id
stringlengths
12
53
messages
listlengths
3
3
code_my-account_67d1406e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/vtex.address-form/index.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.address-form' {\n export const AddressSummary\n export const AddressRules\n}\n\n```" } ]
code_my-account_47243253
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/vtex.my-account-commons/Router.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.my-account-commons/Router' {\n export * from 'react-router-dom'\n}\n\n```" } ]
code_my-account_976c2e8e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/vtex.my-account-commons/index.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.my-account-commons' {\n export const BaseLoading\n export const SkeletonPiece\n export const SkeletonBox\n export const ContentWrapper\n export const GenericError\n}\n\n```" } ]
code_my-account_5b478e14
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/settings.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/settings.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_b94c4307
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/customerGreeting.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/customerGreeting.gql' {\n import type { DocumentNode } from 'graphql'\n import type { Profile } from 'vtex.store-graphql'\n\n export interface Result {\n profile: Pick<\n Profile,\n 'firstName' | 'lastName' | 'profilePicture' | 'cacheId'\n >\n }\n\n const value: DocumentNode\n\n export default value\n}\n\n```" } ]
code_my-account_723494f1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/updateProfile.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/updateProfile.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_13953289
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/getAddresses.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/getAddresses.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_0e381d81
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/saveAddress.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/saveAddress.gql' {\n import type { DocumentNode } from 'graphql'\n import type { Address } from 'vtex.store-graphql'\n import { MutationSaveAddressArgs as Args } from 'vtex.store-graphql'\n\n interface Result {\n saveAddress: Pick<Address, 'id' | 'cacheId'>\n }\n\n const value: DocumentNode\n\n export { Args, Result }\n export default value\n}\n\n```" } ]
code_my-account_2d41b3db
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/deleteAddress.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/deleteAddress.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_1b825a20
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/updateAddress.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/updateAddress.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_f752ed0d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/storeConfigs.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/storeConfigs.gql' {\n import type { DocumentNode } from 'graphql'\n\n export interface Result {\n configs: {\n geolocation: boolean\n googleMapsApiKey?: string\n }\n logistics: {\n shipsTo: string[]\n }\n }\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_b96f47ca
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/getProfile.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/getProfile.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_4d292668
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/setOptInNewsletter.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/setOptInNewsletter.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_7859a6dc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/getPayments.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/getPayments.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_c834b64d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/typings/graphql/getNewsletterOpt.gql.d.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ndeclare module '*/getNewsletterOpt.gql' {\n import type { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```" } ]
code_my-account_12877cd9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/shared/withContentWrapper.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { ComponentType } from 'react'\nimport React from 'react'\nimport { ContentWrapper } from 'vtex.my-account-commons'\nimport { useCssHandles } from 'vtex.css-handles'\n\nexport const withContentWrapper =\n ({\n headerConfig,\n handle,\n }: {\n headerConfig: ContentWrapperProps\n handle?: { contentHandle: string; configHandle: string }\n }) =>\n (WrappedComponent: ComponentType<InjectedContentWrapperProps>) =>\n // eslint-disable-next-line react/display-name\n (props: { [key: string]: unknown }) => {\n const cssHandles = useCssHandles([\n handle?.configHandle,\n handle?.contentHandle,\n ] as const)\n\n const configs = {\n ...headerConfig,\n headerContent: headerConfig?.headerContent?.(handle?.contentHandle),\n namespace: `${headerConfig.namespace ?? ''} ${\n handle ? cssHandles[handle.configHandle] : ''\n }`,\n }\n\n return (\n <ContentWrapper {...configs}>\n {({ handleError }: InjectedContentWrapperProps) => (\n <WrappedComponent {...props} handleError={handleError} />\n )}\n </ContentWrapper>\n )\n }\n\n```" } ]
code_my-account_37e8f96a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/shared/DataEntry.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['dataEntryLabel', 'dataEntryChildren'] as const\n\nconst DataEntry: FunctionComponent<Props> = ({ label, children }) => {\n const cssHandles = useCssHandles(CSS_HANDLES)\n\n return (\n <>\n <label className={`db c-on-base mb3 ${cssHandles.dataEntryLabel}`}>\n {label}\n </label>\n <div className={`light c-on-disabled ${cssHandles.dataEntryChildren}`}>\n {children}\n </div>\n </>\n )\n}\n\ninterface Props {\n label: string\n}\n\nexport default DataEntry\n\n```" } ]
code_my-account_0e27bbcc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/shared/Toast.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Alert } from 'vtex.styleguide'\n\nclass Toast extends Component<Props> {\n public state = {\n isClosing: false,\n }\n\n public static defaultProps = {\n autoClose: 3000,\n }\n\n private openTimeout: any\n private closeTimeout: any\n\n public componentDidMount() {\n this.openTimeout = setTimeout(() => {\n this.setState({ isClosing: true }, () => {\n this.closeTimeout = setTimeout(() => {\n this.props.onClose\n }, 3000)\n })\n }, this.props.autoClose)\n }\n\n public componentWillUnmount() {\n clearTimeout(this.openTimeout)\n clearTimeout(this.closeTimeout)\n }\n\n public render() {\n const { isClosing } = this.state\n const { onClose, messageId } = this.props\n\n return (\n <div\n className={`animated ${\n isClosing ? 'fadeOutDown' : 'fadeInUp'\n } slower bottom--1 fixed z-5 ma7-ns mb5-s left-2-ns w-100-s w-30-ns`}\n >\n <Alert type=\"success\" onClose={onClose}>\n <FormattedMessage id={messageId} />\n </Alert>\n </div>\n )\n }\n}\n\ninterface Props {\n autoClose: number\n onClose: () => void\n messageId: string\n}\n\nexport default Toast\n\n```" } ]
code_my-account_0a12c47a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/shared/withSettings.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { ComponentType } from 'react'\nimport React from 'react'\nimport { Query } from 'react-apollo'\n\nimport QUERY from '../../graphql/settings.gql'\n\nexport function withSettings(\n WrappedComponent: ComponentType<{ settings?: Settings }>\n) {\n return function SettingsApplied(props: any) {\n return (\n <Query query={QUERY}>\n {({\n data: { loading, settings },\n }: {\n data: { settings: Settings; loading: boolean }\n }) => <WrappedComponent {...props} settings={!loading && settings} />}\n </Query>\n )\n }\n}\n\nexport interface Settings {\n showGenders: boolean\n showMyCards: boolean | null\n showMyOrders: boolean | null\n showMyAddresses: boolean | null\n showMyAuthentication: boolean | null\n useMap: boolean\n}\n\n```" } ]
code_my-account_f91dbc14
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/shared/ContentBox.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent, ReactElement } from 'react'\nimport React from 'react'\nimport { Button } from 'vtex.styleguide'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = [\n 'boxContainer',\n 'boxContainerBody',\n 'boxContainerFooter',\n] as const\n\nconst ContentBox: FunctionComponent<Props> = ({\n children,\n maxWidthStep,\n shouldAllowGrowing = false,\n lowerButton,\n onLowerButtonClick,\n}) => {\n const cssHandles = useCssHandles(CSS_HANDLES)\n const widthClass = maxWidthStep ? `mw${maxWidthStep}-ns` : ''\n const flexClass = shouldAllowGrowing ? 'flex-auto' : 'flex-none'\n\n return (\n <div className={`pb5 pr5-ns ${flexClass} ${widthClass}`}>\n <article\n className={`ba bw1 b--muted-4 br2 flex flex-column justify-between ${cssHandles.boxContainer}`}\n >\n <main className={`ph7 pv6 ${cssHandles.boxContainerBody}`}>\n {children}\n </main>\n {lowerButton && (\n <footer\n className={`flex justify-end ph3 pb3 ${cssHandles.boxContainerFooter}`}\n >\n <Button\n variation=\"tertiary\"\n size=\"small\"\n onClick={onLowerButtonClick}\n >\n {lowerButton}\n </Button>\n </footer>\n )}\n </article>\n </div>\n )\n}\n\ninterface Props {\n maxWidthStep?: number\n shouldAllowGrowing?: boolean\n lowerButton?: ReactElement\n onLowerButtonClick?: () => void\n}\n\nexport default ContentBox\n\n```" } ]
code_my-account_ca89f0eb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Profile/ProfileFormBox.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { graphql } from 'react-apollo'\nimport { compose } from 'recompose'\nimport { ExtensionPoint, withRuntimeContext } from 'vtex.render-runtime'\nimport { ProfileRules, ProfileContainer } from 'vtex.profile-form'\nimport { Button } from 'vtex.styleguide'\nimport { withCssHandles } from 'vtex.css-handles'\n\nimport ContentBox from '../shared/ContentBox'\nimport UpdateProfile from '../../graphql/updateProfile.gql'\nimport type { Settings } from '../shared/withSettings'\nimport { withSettings } from '../shared/withSettings'\n\nconst CSS_HANDLES = ['profileFormBoxContainer'] as const\n\nclass ProfileFormBox extends Component<InnerProps & OutterProps, State> {\n private validatorFunctions: any[]\n private submitterFunctions: any[]\n\n constructor(props: InnerProps & OutterProps) {\n super(props)\n this.state = {\n isLoading: false,\n valid: true,\n }\n this.validatorFunctions = []\n this.submitterFunctions = []\n }\n\n public componentDidMount() {\n this.registerValidator(this.validate)\n this.registerSubmitter(this.submit)\n }\n\n private setStateAsync(state: any) {\n return new Promise(resolve => {\n this.setState(state, resolve)\n })\n }\n\n private registerValidator = (validator: any) => {\n this.validatorFunctions.push(validator)\n }\n\n private registerSubmitter = (submitter: any) => {\n this.submitterFunctions.push(submitter)\n }\n\n private handleSubmit = async ({ valid, profile }: any) => {\n const { onDataSave, onError } = this.props\n\n await this.setStateAsync({ isLoading: true, valid, profile })\n try {\n const validation$ = this.validatorFunctions.map(validator => validator())\n const validationResults = await Promise.all(validation$)\n const isValid = validationResults.reduce((acc, cur) => acc && cur, true)\n\n if (!isValid) {\n this.setState({ isLoading: false })\n\n return\n }\n\n const submit$ = this.submitterFunctions.map(submitter =>\n submitter(profile)\n )\n\n await Promise.all(submit$)\n this.setState({ isLoading: false })\n onDataSave()\n } catch (error) {\n onError(error)\n }\n }\n\n private validate = () => {\n return this.state.valid\n }\n\n private submit = (profile: ProfileInput) => {\n const { updateProfile } = this.props\n\n return updateProfile({ variables: { profile } })\n }\n\n public render() {\n const { profile, settings, runtime, cssHandles, blockDocument } = this.props\n const { isLoading } = this.state\n const showGenders = settings?.showGenders\n\n if (!profile) return null\n\n return (\n <div className={cssHandles.profileFormBoxContainer}>\n <ContentBox shouldAllowGrowing maxWidthStep={6}>\n <ProfileRules country={runtime.culture.country} shouldUseIOFetching>\n <ProfileContainer\n defaultProfile={profile}\n onSubmit={this.handleSubmit}\n shouldShowExtendedGenders={showGenders}\n blockDocument={blockDocument}\n SubmitButton={\n <Button type=\"submit\" block size=\"small\" isLoading={isLoading}>\n <FormattedMessage id=\"vtex.profile-form@3.x::profile-form.save-changes\" />\n </Button>\n }\n >\n <ExtensionPoint\n id=\"profile-input-container\"\n registerValidator={this.registerValidator}\n registerSubmitter={this.registerSubmitter}\n />\n </ProfileContainer>\n </ProfileRules>\n </ContentBox>\n </div>\n )\n }\n}\n\ninterface State {\n isLoading: boolean\n valid: boolean\n}\n\ninterface InnerProps {\n settings?: Settings\n runtime: Runtime\n updateProfile: (args: Variables<UpdateProfileArgs>) => void\n cssHandles: CssHandles<typeof CSS_HANDLES>\n}\ninterface OutterProps {\n onDataSave: () => void\n onError: (error: any) => void\n profile: Profile\n blockDocument?: boolean\n}\n\nconst enhance = compose<InnerProps & OutterProps, OutterProps>(\n graphql(UpdateProfile, { name: 'updateProfile' }),\n withRuntimeContext,\n withSettings,\n withCssHandles(CSS_HANDLES)\n)\n\nexport default enhance(ProfileFormBox)\n\n```" } ]
code_my-account_9d1dfc9d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Profile/ProfileBox.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable react/prop-types */\nimport type { FunctionComponent } from 'react'\nimport React, { Fragment } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { ExtensionPoint, withRuntimeContext } from 'vtex.render-runtime'\nimport { ProfileRules, ProfileSummary } from 'vtex.profile-form'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport ContentBox from '../shared/ContentBox'\nimport DataEntry from '../shared/DataEntry'\n\nconst CSS_HANDLES = [\n 'profileBoxContainer',\n 'nameContainer',\n 'firstNameSubContainer',\n 'lastNameSubContainer',\n 'emailContainer',\n 'genderContainer',\n 'documentsSubContainer',\n 'genderSubContainer',\n 'phoneNumberContainer',\n 'dateOfBirthSubContainer',\n 'phoneNumberSubContainer',\n 'corporateName',\n 'tradeName',\n 'corporateDocument',\n 'businessPhoneContainer',\n 'businessPhoneSubContainer',\n 'stateRegistration',\n] as const\n\nconst ProfileBox: FunctionComponent<Props> = ({\n profile,\n onEditClick,\n runtime,\n}) => {\n const cssHandles = useCssHandles(CSS_HANDLES)\n\n if (!profile) return null\n\n return (\n <div className={cssHandles.profileBoxContainer}>\n <ContentBox\n shouldAllowGrowing\n lowerButton={\n <FormattedMessage id=\"vtex.store-messages@0.x::commons.edit\" />\n }\n onLowerButtonClick={onEditClick}\n >\n <ProfileRules country={runtime.culture.country} shouldUseIOFetching>\n <ProfileSummary profile={profile}>\n {({\n personalData: {\n firstName,\n lastName,\n email,\n document,\n gender,\n birthDate,\n homePhone,\n },\n businessData: {\n corporateName,\n tradeName,\n corporateDocument,\n businessPhone,\n stateRegistration,\n },\n isCorporate,\n }: any) => (\n <Fragment>\n <div\n className={`flex-ns flex-wrap ${cssHandles.nameContainer}`}\n >\n <div\n className={`mb8 flex-auto ${cssHandles.firstNameSubContainer}`}\n >\n <DataEntry label={firstName.label}>\n {firstName.value}\n </DataEntry>\n </div>\n <div\n className={`mb8 w-50-ns ${cssHandles.lastNameSubContainer}`}\n >\n <DataEntry label={lastName.label}>\n {lastName.value}\n </DataEntry>\n </div>\n </div>\n <div className={`mb8 ${cssHandles.emailContainer}`}>\n <DataEntry label={email.label}>{email.value}</DataEntry>\n </div>\n <div\n className={`flex-ns flex-wrap ${cssHandles.genderContainer}`}\n >\n {document?.label && (\n <div\n className={`mb8 flex-auto ${cssHandles.documentsSubContainer}`}\n >\n <DataEntry label={document.label}>\n {document.value}\n </DataEntry>\n </div>\n )}\n <div\n className={`mb8 w-50-ns ${cssHandles.genderSubContainer}`}\n >\n <DataEntry label={gender.label}>{gender.value}</DataEntry>\n </div>\n </div>\n <div\n className={`flex-ns flex-wrap ${cssHandles.phoneNumberContainer}`}\n >\n <div\n className={`mb8 flex-auto ${cssHandles.dateOfBirthSubContainer}`}\n >\n <DataEntry label={birthDate.label}>\n {birthDate.value}\n </DataEntry>\n </div>\n <div\n className={`mb8 w-50-ns ${cssHandles.phoneNumberSubContainer}`}\n >\n <DataEntry label={homePhone.label}>\n {homePhone.value}\n </DataEntry>\n </div>\n </div>\n {isCorporate && (\n <Fragment>\n <div className={`mb8 ${cssHandles.corporateName}`}>\n <DataEntry label={corporateName.label}>\n {corporateName.value}\n </DataEntry>\n </div>\n {tradeName?.label && (\n <div className={`mb8 ${cssHandles.tradeName}`}>\n <DataEntry label={tradeName.label}>\n {tradeName.value}\n </DataEntry>\n </div>\n )}\n {corporateDocument?.label && (\n <div className={`mb8 ${cssHandles.corporateDocument}`}>\n <DataEntry label={corporateDocument.label}>\n {corporateDocument.value}\n </DataEntry>\n </div>\n )}\n <div\n className={`flex-ns flex-wrap ${cssHandles.businessPhoneContainer}`}\n >\n <div\n className={`mb8 flex-auto ${cssHandles.businessPhoneSubContainer}`}\n >\n <DataEntry label={businessPhone.label}>\n {businessPhone.value}\n </DataEntry>\n </div>\n {stateRegistration?.label && (\n <div\n className={`mb8 w-50-ns ${cssHandles.stateRegistration}`}\n >\n <DataEntry label={stateRegistration.label}>\n {stateRegistration.value}\n </DataEntry>\n </div>\n )}\n </div>\n </Fragment>\n )}\n </Fragment>\n )}\n </ProfileSummary>\n </ProfileRules>\n <ExtensionPoint\n id=\"profile-display-container\"\n render={(fields: Array<{ label: string; value: string }>) => (\n <div className=\"flex-ns flex-wrap\">\n {fields.map(\n ({ label, value }: { label: string; value: string }) => (\n <div className=\"mb8 w-50-ns\" key={label}>\n <DataEntry label={label}>{value}</DataEntry>\n </div>\n )\n )}\n </div>\n )}\n />\n </ContentBox>\n </div>\n )\n}\n\ninterface Props {\n profile: Profile\n runtime: Runtime\n onEditClick: () => void\n}\n\nexport default withRuntimeContext(ProfileBox)\n\n```" } ]
code_my-account_f613e4c4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Profile/NewsletterBox.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport type { InjectedIntlProps } from 'react-intl'\nimport { defineMessages, injectIntl } from 'react-intl'\nimport { graphql } from 'react-apollo'\nimport { compose } from 'recompose'\nimport { Checkbox } from 'vtex.styleguide'\nimport { withCssHandles } from 'vtex.css-handles'\n\nimport ContentBox from '../shared/ContentBox'\nimport GET_NEWSLETTER from '../../graphql/getNewsletterOpt.gql'\nimport NEWSLETTER_MUTATION from '../../graphql/setOptInNewsletter.gql'\n\nconst CSS_HANDLES = [\n 'newsletterBoxContainer',\n 'newsletterContainerTitle',\n 'newsletterContainerMessage',\n 'passwordBox',\n] as const\n\nconst messages = defineMessages({\n optinNewsLetter: {\n id: 'vtex.store-messages@0.x::personalData.newsletterOptIn',\n defaultMessage: '',\n },\n newsletter: {\n id: 'vtex.store-messages@0.x::personalData.newsletter',\n defaultMessage: '',\n },\n newsletterQuestion: {\n id: 'vtex.store-messages@0.x::personalData.newsletterQuestion',\n defaultMessage: '',\n },\n})\n\nclass NewsletterBox extends Component<Props, State> {\n constructor(props: Props) {\n super(props)\n this.state = {\n checked: props.isNewsletterOptIn,\n }\n }\n\n public componentDidUpdate(oldProps: Props) {\n if (oldProps.isNewsletterOptIn !== this.props.isNewsletterOptIn) {\n this.setState({ checked: this.props.isNewsletterOptIn })\n }\n }\n\n private debounceCall: NodeJS.Timeout | null | number = null\n\n private handleCheck = () => {\n const { setOptInNewsletter, userEmail } = this.props\n const { checked } = this.state\n\n clearInterval(this.debounceCall as NodeJS.Timeout)\n this.debounceCall = setTimeout(\n () =>\n setOptInNewsletter({\n variables: {\n email: userEmail,\n isNewsletterOptIn: !checked,\n },\n }),\n 500\n )\n this.setState({ checked: !checked })\n }\n\n public render() {\n const { checked } = this.state\n const {\n cssHandles,\n intl: { formatMessage },\n } = this.props\n\n return (\n <div className={cssHandles.newsletterBoxContainer}>\n <ContentBox shouldAllowGrowing>\n <div className={cssHandles.newsletterContainerTitle}>\n {formatMessage(messages.newsletter)}\n </div>\n <div\n className={`c-muted-2 pt2 pb6 ${cssHandles.newsletterContainerMessage}`}\n >\n {formatMessage(messages.newsletterQuestion)}\n </div>\n <div className={`${cssHandles.passwordBox} w-100`}>\n <Checkbox\n checked={checked}\n id=\"newsletterOptIn\"\n label={formatMessage(messages.optinNewsLetter)}\n name=\"newsletterOptIn\"\n onChange={this.handleCheck}\n />\n </div>\n </ContentBox>\n </div>\n )\n }\n}\n\ninterface State {\n checked: boolean\n}\n\ninterface QueryData {\n profile: Pick<Profile, 'customFields'>\n}\n\ninterface QueryResult {\n isNewsletterOptIn: boolean\n}\n\ninterface Mutations {\n setOptInNewsletter: (args: Variables<SetOptInNewsletterArgs>) => Promise<void>\n}\n\ninterface OuterProps {\n userEmail: string\n}\ninterface InnerProps extends InjectedIntlProps, QueryResult, Mutations {\n cssHandles: CssHandles<typeof CSS_HANDLES>\n}\n\ntype Props = OuterProps & InnerProps\n\nconst enhance = compose<Props, OuterProps>(\n graphql<Props, QueryData, unknown, QueryResult>(GET_NEWSLETTER, {\n props: ({ data }) => ({\n isNewsletterOptIn: data?.profile?.customFields?.[0].value === 'true',\n }),\n }),\n graphql(NEWSLETTER_MUTATION, {\n name: 'setOptInNewsletter',\n options: {\n refetchQueries: ['NewsletterOpt'],\n },\n }),\n injectIntl,\n withCssHandles(CSS_HANDLES)\n)\n\nexport default enhance(NewsletterBox)\n\n```" } ]
code_my-account_ea8aa7a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Addresses/AddressForm.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component, Fragment } from 'react'\nimport type { InjectedIntlProps } from 'react-intl'\nimport { FormattedMessage, injectIntl } from 'react-intl'\nimport { compose, branch, renderComponent } from 'recompose'\nimport { graphql } from 'react-apollo'\nimport {\n AddressContainer,\n AddressForm as AddressFields,\n AddressRules,\n AddressSubmitter,\n AutoCompletedFields,\n CountrySelector,\n GoogleMapsContainer,\n Map,\n PostalCodeGetter,\n} from 'vtex.address-form/components'\nimport { Button } from 'vtex.styleguide'\nimport { addValidation } from 'vtex.address-form/helpers'\nimport { StyleguideInput, GeolocationInput } from 'vtex.address-form/inputs'\nimport { withRuntimeContext } from 'vtex.render-runtime'\n\nimport type { Result } from '../../graphql/storeConfigs.gql'\nimport STORE_CONFIGS from '../../graphql/storeConfigs.gql'\nimport Loading from '../loaders/FormContent'\nimport getEmptyAddress from './emptyAddress'\n\nconst AUTO_COMPLETABLE_FIELDS = [\n 'city',\n 'geoCoordinates',\n 'neighborhood',\n 'number',\n 'postalCode',\n 'state',\n 'street',\n]\n\nclass AddressForm extends Component<InnerProps & OuterProps, State> {\n constructor(props: InnerProps & OuterProps) {\n super(props)\n\n let address: Address\n\n if (props.address === undefined) {\n const { runtime, shipsTo, receiverName, useGeolocation } = props\n\n let country\n\n if (useGeolocation) {\n country = runtime.culture.country\n } else {\n country = shipsTo.length > 0 ? shipsTo[0] : runtime.culture.country\n }\n\n address = getEmptyAddress(country, receiverName ?? '')\n } else {\n address = props.address\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { __typename, addressName, ...addressValues } = address\n\n const addressWithValidation = addValidation({\n addressQuery: null,\n ...addressValues,\n })\n\n // if editing an existing address (address id exists), all fields start as valid\n if (addressValues.addressId) {\n AUTO_COMPLETABLE_FIELDS.forEach(field => {\n if (addressWithValidation[field].value === null) return\n\n addressWithValidation[field].geolocationAutoCompleted = true\n addressWithValidation[field].postalCodeAutoCompleted = true\n addressWithValidation[field].valid = true\n })\n }\n\n this.state = { address: addressWithValidation }\n }\n\n private handleSubmit = (isValid: boolean, address: Address) => {\n const { onSubmit } = this.props\n\n if (isValid) {\n onSubmit(address)\n }\n }\n\n private handleAddressChange = (newAddress: AddressFormFields) => {\n const curAddress = this.state.address\n\n // allow to edit only with geolocation component\n if (\n this.props.useGeolocation &&\n newAddress.addressQuery &&\n !AUTO_COMPLETABLE_FIELDS.some(\n field => newAddress[field]?.geolocationAutoCompleted\n )\n ) {\n AUTO_COMPLETABLE_FIELDS.forEach(field => {\n newAddress[field].value = null\n delete newAddress[field].valid\n })\n }\n\n const address = { ...curAddress, ...newAddress }\n\n this.setState({ address })\n }\n\n private hasGeoCoords() {\n const { address } = this.state\n\n return (\n address.geoCoordinates.geolocationAutoCompleted ||\n (Array.isArray(address.geoCoordinates.value) &&\n address.geoCoordinates.value.length === 2)\n )\n }\n\n private hasValidPostalCode() {\n const { address } = this.state\n\n return (\n address.postalCode.geolocationAutoCompleted ?? address.postalCode.valid\n )\n }\n\n private hasAutoCompletedFields() {\n const { address } = this.state\n\n return AUTO_COMPLETABLE_FIELDS.some(\n fieldName =>\n address?.[fieldName].geolocationAutoCompleted ??\n address?.[fieldName].postalCodeAutoCompleted\n )\n }\n\n private translateCountries() {\n const { shipsTo, intl } = this.props\n\n return shipsTo.map(code => ({\n label: intl.formatMessage({ id: `country.${code}` }),\n value: code,\n }))\n }\n\n public render() {\n const { address } = this.state\n const {\n intl,\n submitLabelId,\n isLoading,\n googleMapsApiKey,\n useGeolocation,\n isExistingAddress,\n } = this.props\n\n const shipCountries = this.translateCountries()\n const hasGeoCoords = this.hasGeoCoords()\n const hasValidPostalCode = this.hasValidPostalCode()\n const hasAutoCompletedFields = this.hasAutoCompletedFields()\n\n const enhancedAddress = {\n ...address,\n country: {\n ...address.country,\n disabled: !!isExistingAddress,\n },\n }\n\n return (\n <AddressRules\n country={address.country.value}\n shouldUseIOFetching\n useGeolocation={useGeolocation}\n >\n <AddressContainer\n address={enhancedAddress}\n Input={StyleguideInput}\n onChangeAddress={this.handleAddressChange}\n autoCompletePostalCode\n >\n <Fragment>\n <CountrySelector shipsTo={shipCountries} />\n\n {useGeolocation && (\n <GoogleMapsContainer\n apiKey={googleMapsApiKey}\n locale={intl.locale}\n >\n {({ loading, googleMaps }: GoogleMapsContainerArgs) => (\n <Fragment>\n {!hasAutoCompletedFields && (\n <GeolocationInput\n loadingGoogle={loading}\n googleMaps={googleMaps}\n />\n )}\n\n {hasGeoCoords && (\n <Map\n loadingGoogle={loading}\n googleMaps={googleMaps}\n mapProps={{ className: 'mb7 br2 h4' }}\n />\n )}\n </Fragment>\n )}\n </GoogleMapsContainer>\n )}\n\n {useGeolocation === false && <PostalCodeGetter />}\n\n {(hasGeoCoords || hasValidPostalCode) && (\n <Fragment>\n {hasAutoCompletedFields && (\n <div className=\"mb7\">\n <AutoCompletedFields>\n <span className=\"c-link pointer\">\n <FormattedMessage id=\"vtex.address-form@4.x::address-form.edit\" />\n </span>\n </AutoCompletedFields>\n </div>\n )}\n <AddressFields\n address={address}\n Input={StyleguideInput}\n onChangeAddress={this.handleAddressChange}\n notApplicableLabel={intl.formatMessage({\n id: 'vtex.store-messages@0.x::addresses.notApplicable',\n })}\n />\n </Fragment>\n )}\n\n <AddressSubmitter onSubmit={this.handleSubmit}>\n {(handleSubmit: () => void) => (\n <Button\n onClick={handleSubmit}\n block\n size=\"small\"\n isLoading={isLoading}\n disabled={!hasGeoCoords && !hasValidPostalCode}\n >\n <FormattedMessage id={submitLabelId} />\n </Button>\n )}\n </AddressSubmitter>\n </Fragment>\n </AddressContainer>\n </AddressRules>\n )\n }\n}\n\ninterface MappedResult {\n googleMapsApiKey?: string\n useGeolocation: boolean\n shipsTo: string[]\n loading: boolean\n}\n\ninterface InnerProps extends InjectedIntlProps, MappedResult {\n runtime: Runtime\n}\n\ninterface OuterProps {\n isLoading?: boolean\n submitLabelId: string\n address?: Address\n receiverName?: string\n onError: () => void\n onSubmit: (address: Address) => void\n isExistingAddress?: boolean\n}\n\ntype Props = InnerProps & OuterProps\n\ninterface State {\n address: AddressFormFields\n}\n\nexport default compose<Props, OuterProps>(\n graphql<\n Record<string, unknown>,\n Result,\n Record<string, unknown>,\n MappedResult\n >(STORE_CONFIGS, {\n props: ({ data }) => ({\n loading: data?.loading ?? false,\n googleMapsApiKey: data?.configs?.googleMapsApiKey,\n useGeolocation: data?.configs?.geolocation ?? false,\n shipsTo: data?.logistics?.shipsTo ?? [],\n }),\n }),\n branch<Props>(({ loading }) => loading, renderComponent(Loading)),\n withRuntimeContext,\n injectIntl\n)(AddressForm)\n\n```" } ]
code_my-account_5286b106
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Addresses/AddressBox.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { AddressSummary, AddressRules } from 'vtex.address-form'\n\nimport ContentBox from '../shared/ContentBox'\n\nconst AddressBox: FunctionComponent<Props> = ({ address, onEditClick }) => {\n return (\n <ContentBox\n lowerButton={\n <FormattedMessage id=\"vtex.store-messages@0.x::commons.edit\" />\n }\n onLowerButtonClick={onEditClick}\n >\n <div className=\"lighter c-muted-2 lh-copy pv4 w5 h4\">\n <AddressRules country={address.country} shouldUseIOFetching>\n <AddressSummary address={address} />\n </AddressRules>\n </div>\n </ContentBox>\n )\n}\n\ninterface Props {\n address: Address\n onEditClick: () => void\n}\n\nexport default AddressBox\n\n```" } ]
code_my-account_14a94097
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Addresses/emptyAddress.ts from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default function getEmptyAddress(country: string, receiverName: string) {\n return {\n addressId: '',\n addressType: 'residential',\n city: null,\n complement: null,\n country,\n receiverName,\n geoCoordinates: [],\n neighborhood: null,\n number: null,\n postalCode: null,\n reference: null,\n state: null,\n street: null,\n addressQuery: null,\n }\n}\n\n```" } ]
code_my-account_95d0e2c6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Addresses/AddressDeleter.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { graphql } from 'react-apollo'\nimport { Button } from 'vtex.styleguide'\n\nimport MUTATION from '../../graphql/deleteAddress.gql'\n\nclass AddressDeleter extends Component<OutterProps & InnerProps> {\n public state = {\n isLoading: false,\n }\n\n private handleDeleteClick = async () => {\n const { addressId, onAddressDeleted, deleteAddress, onError } = this.props\n\n if (this.state.isLoading) return\n\n try {\n this.setState({ isLoading: true })\n await deleteAddress({ variables: { addressId } })\n onAddressDeleted()\n } catch (error) {\n this.setState({ isLoading: false })\n onError()\n }\n }\n\n public render() {\n const { isLoading } = this.state\n\n return (\n <div className=\"mt5\">\n <Button\n type=\"button\"\n variation=\"danger\"\n block\n size=\"small\"\n onClick={this.handleDeleteClick}\n isLoading={isLoading}\n >\n <FormattedMessage id=\"vtex.store-messages@0.x::addresses.deleteAddress\" />\n </Button>\n </div>\n )\n }\n}\n\ninterface OutterProps {\n /** Callback for address deletion */\n onAddressDeleted: () => void\n /** Callback for error during deletion */\n onError: () => void\n /** Id of the address to be deleted */\n addressId: string\n}\n\ninterface InnerProps {\n /** Mutation for deleting an address */\n deleteAddress: (args: Variables<DeleteAddressArgs>) => void\n}\n\nexport default graphql<\n OutterProps,\n Record<string, unknown>,\n Record<string, unknown>,\n InnerProps\n>(MUTATION, {\n name: 'deleteAddress',\n})(AddressDeleter)\n\n```" } ]
code_my-account_7320a7f2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/MenuLink.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport type { RouteComponentProps } from 'vtex.my-account-commons/Router'\nimport { Link, withRouter } from 'vtex.my-account-commons/Router'\n\nconst MenuLink: FunctionComponent<Props> = ({ path, name, location }) => {\n return (\n <Link\n to={path}\n className={`\n vtex-account_menu-link f6 no-underline db hover-near-black pv5 mv3 pl5 bl bw2 nowrap ${\n location.pathname.indexOf(path) === -1\n ? 'c-muted-1 b--transparent'\n : 'c-on-base b b--action-primary'\n }`}\n >\n {name}\n </Link>\n )\n}\n\ninterface Props extends RouteComponentProps {\n path: string\n name: string\n}\n\nexport default withRouter(MenuLink)\n\n```" } ]
code_my-account_cb7d19b8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/index.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\n/* eslint-disable jsx-a11y/click-events-have-key-events */\n/* eslint-disable jsx-a11y/no-static-element-interactions */\nimport React, { Component, Fragment } from 'react'\nimport type { InjectedIntlProps } from 'react-intl'\nimport { injectIntl, FormattedMessage } from 'react-intl'\nimport { compose } from 'recompose'\nimport { ExtensionPoint, withRuntimeContext } from 'vtex.render-runtime'\nimport { ModalDialog } from 'vtex.styleguide'\nimport { withCssHandles } from 'vtex.css-handles'\n\nimport UserInfo from './UserInfo'\nimport MenuLink from './MenuLink'\nimport type { Settings } from '../shared/withSettings'\nimport { withSettings } from '../shared/withSettings'\nimport getRedirectLogout from '../../utils/getRedirectLogout'\n\nconst CSS_HANDLES = ['css', 'menu', 'menuLinks', 'menuLink'] as const\n\ninterface RenderLinksOptions {\n showMyCards: boolean | null\n showMyOrders: boolean | null\n showMyAddresses: boolean | null\n showMyAuthentication: boolean | null\n}\n\nfunction renderLinks(\n links: Link[],\n {\n showMyCards,\n showMyOrders,\n showMyAddresses,\n showMyAuthentication,\n }: RenderLinksOptions\n) {\n const linksToDisplay = links.filter(link => {\n if (showMyCards === false && link.path === '/cards') {\n return false\n }\n\n if (showMyOrders === false && link.path === '/orders') {\n return false\n }\n\n if (showMyAddresses === false && link.path === '/addresses') {\n return false\n }\n\n if (showMyAuthentication === false && link.path === '/authentication') {\n return false\n }\n\n return true\n })\n\n return linksToDisplay.map(({ name, path }) => (\n <MenuLink path={path} name={name} key={name} />\n ))\n}\n\nclass Menu extends Component<Props, { isModalOpen: boolean }> {\n public state = { isModalOpen: false }\n\n private handleModalToggle = () => {\n this.setState(prevState => ({ isModalOpen: !prevState.isModalOpen }))\n }\n\n public render() {\n const { cssHandles, intl, settings, runtime } = this.props\n const {\n showMyCards = false,\n showMyOrders = false,\n showMyAddresses = false,\n showMyAuthentication = false,\n } = settings || {}\n\n return (\n <aside\n className={`${cssHandles.menu} pv9 pv0-m-2 ph9 ph7-m ph8-l w-20-m w-100`}\n >\n <UserInfo />\n <nav className={cssHandles.menuLinks}>\n <ExtensionPoint\n id=\"my-account-menu\"\n render={(links: Link[]) =>\n renderLinks(links, {\n showMyCards,\n showMyOrders,\n showMyAddresses,\n showMyAuthentication,\n })\n }\n />\n <Fragment>\n <div\n className={`\n ${cssHandles.menuLink}\n f6 no-underline db hover-near-black pv5 mv3 pl5 bl bw2 nowrap c-muted-1 b--transparent pointer\n `}\n onClick={this.handleModalToggle}\n >\n <FormattedMessage id=\"vtex.store-messages@0.x::pages.logout\" />\n </div>\n <ModalDialog\n centered\n confirmation={{\n onClick: getRedirectLogout(runtime),\n label: intl.formatMessage({\n id: 'vtex.store-messages@0.x::pages.logout',\n }),\n }}\n cancelation={{\n onClick: this.handleModalToggle,\n label: intl.formatMessage({\n id: 'vtex.store-messages@0.x::logoutModal.cancel',\n }),\n }}\n isOpen={this.state.isModalOpen}\n onClose={this.handleModalToggle}\n >\n <span className=\"t-heading-5 pa6\">\n <FormattedMessage id=\"vtex.store-messages@0.x::logoutModal.title\" />\n </span>\n </ModalDialog>\n </Fragment>\n </nav>\n </aside>\n )\n }\n}\n\ninterface Link {\n name: string\n path: string\n}\n\ninterface Props extends InjectedIntlProps {\n settings?: Settings\n cssHandles: CssHandles<typeof CSS_HANDLES>\n runtime: Runtime\n}\n\nexport default compose<Props, Record<string, unknown>>(\n injectIntl,\n withSettings,\n withCssHandles(CSS_HANDLES),\n withRuntimeContext\n)(Menu)\n\n```" } ]
code_my-account_f5c64b85
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/UserInfoLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React from 'react'\nimport { SkeletonPiece } from 'vtex.my-account-commons'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['shimmer'] as const\n\nconst UserInfoLoading: FC = () => {\n const cssHandles = useCssHandles(CSS_HANDLES)\n\n return (\n <div className=\"flex items-end mb7\">\n <div className=\"mr5 relative\">\n <div className=\"h3 w3 br-100 bg-light-silver\">\n <div className={cssHandles.shimmer} />\n </div>\n </div>\n <div className=\"flex-auto w3\">\n <div className=\"mb2\">\n <SkeletonPiece width={50} />\n </div>\n <SkeletonPiece />\n </div>\n </div>\n )\n}\n\nexport default UserInfoLoading\n\n```" } ]
code_my-account_edcb8768
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/UserInfo.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose, branch, renderComponent } from 'recompose'\nimport { FormattedMessage } from 'react-intl'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport type { Result } from '../../graphql/customerGreeting.gql'\nimport GREETING from '../../graphql/customerGreeting.gql'\nimport Loading from './UserInfoLoading'\nimport PictureRenderer from './ProfilePicture/PictureRenderer'\n\nconst CSS_HANDLES = [\n 'userInfo',\n 'userImage',\n 'userGreeting',\n 'userName',\n 'userGreeting',\n] as const\n\nconst UserInfo: FunctionComponent<Props> = ({ profilePicture, firstName }) => {\n const cssHandles = useCssHandles(CSS_HANDLES)\n\n return (\n <div className={`${cssHandles.userInfo} flex flex-wrap items-end mb7`}>\n <div className={`${cssHandles.userImage} relative mr5 h3 w3`}>\n <PictureRenderer imagePath={profilePicture} />\n </div>\n {firstName ? (\n <div>\n <div\n className={`\n ${cssHandles.userGreeting} f5 fw3 c-muted-1 mb2 mt0-l mt2-m\n `}\n >\n <FormattedMessage id=\"vtex.store-messages@0.x::userInfo.greeting\" />\n ,\n </div>\n <div className={`${cssHandles.userName} f4 c-on-base fw3 nowrap`}>\n {firstName}!\n </div>\n </div>\n ) : (\n <div className={`${cssHandles.userGreeting} f4 fw3 nowrap`}>\n <FormattedMessage id=\"vtex.store-messages@0.x::userInfo.greeting\" />!\n </div>\n )}\n </div>\n )\n}\n\ninterface Props {\n firstName: string\n profilePicture?: string\n loading: boolean\n}\n\nconst enhance = compose<Props, Record<string, unknown>>(\n graphql<Record<string, unknown>, Result, Record<string, unknown>, Props>(\n GREETING,\n {\n props: ({ data }) => ({\n firstName: data?.profile?.firstName ?? '',\n profilePicture: data?.profile?.profilePicture ?? undefined,\n loading: data ? data.loading : false,\n }),\n }\n ),\n branch<Props>(({ loading }) => loading, renderComponent(Loading))\n)\n\nexport default enhance(UserInfo)\n\n```" } ]
code_my-account_34f514f4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/pages/ProfileEdit.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose, branch, renderComponent, withProps } from 'recompose'\nimport { withRouter } from 'vtex.my-account-commons/Router'\n\nimport { withContentWrapper } from '../shared/withContentWrapper'\nimport ProfileEditLoading from '../loaders/ProfileEditLoading'\nimport ProfileFormBox from '../Profile/ProfileFormBox'\nimport GET_PROFILE from '../../graphql/getProfile.gql'\n\nexport const headerConfig = {\n titleId: 'vtex.store-messages@0.x::pages.profileEdit',\n backButton: {\n titleId: 'vtex.store-messages@0.x::pages.profile',\n path: '/profile',\n },\n}\n\nclass ProfileEdit extends Component<Props> {\n private handleGoBack = () => {\n this.props.history.push('/profile?success=true')\n }\n\n public render() {\n const { profile, handleError, blockDocument } = this.props\n\n return (\n <ProfileFormBox\n profile={profile}\n onDataSave={this.handleGoBack}\n onError={handleError}\n blockDocument={blockDocument}\n />\n )\n }\n}\n\ninterface Props extends InjectedContentWrapperProps {\n data: { profile: Profile }\n profile: Profile\n history: any\n blockDocument?: boolean\n}\n\nconst enhance = compose<Props, { blockDocument?: boolean }>(\n graphql(GET_PROFILE),\n branch<Props>(\n ({ data }) => data.profile == null,\n renderComponent(ProfileEditLoading)\n ),\n withProps(({ data }: Props) => {\n return { profile: data.profile }\n }),\n withRouter,\n withContentWrapper({\n headerConfig,\n handle: { configHandle: 'profileEdit', contentHandle: '' },\n })\n)\n\nexport default enhance(ProfileEdit)\n\n```" } ]
code_my-account_dd8066a3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/pages/AddressEdit.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose, branch, renderComponent, withProps } from 'recompose'\nimport { GenericError } from 'vtex.my-account-commons'\n\nimport AddressEditLoading from '../loaders/AddressEditLoading'\nimport AddressForm from '../Addresses/AddressForm'\nimport AddressDeleter from '../Addresses/AddressDeleter'\nimport { withContentWrapper } from '../shared/withContentWrapper'\nimport ContentBox from '../shared/ContentBox'\nimport GET_ADDRESSES from '../../graphql/getAddresses.gql'\nimport UPDATE_ADDRESS from '../../graphql/updateAddress.gql'\n\nexport const headerConfig = {\n titleId: 'vtex.store-messages@0.x::pages.addressEdit',\n backButton: {\n titleId: 'vtex.store-messages@0.x::pages.addresses',\n path: '/addresses',\n },\n}\n\nclass AddressEdit extends Component<Props> {\n private handleGoBack = () => {\n this.props.history.push('/addresses?success=true')\n }\n\n public state = {\n isLoading: false,\n }\n\n private handleDelete = () => this.handleGoBack()\n\n private handleSave = (address: Address) => {\n const { updateAddress, handleError } = this.props\n const { addressId, addressQuery, ...addressFields } = address\n\n this.setState({ isLoading: true })\n\n updateAddress({\n variables: {\n addressId,\n addressFields: addressFields as AddressInput,\n },\n })\n .then(() => this.handleGoBack())\n .catch(() => {\n handleError()\n this.setState({ isLoading: false })\n })\n }\n\n public render() {\n const { isLoading } = this.state\n const { addresses, addressId } = this.props\n const address = addresses.find(current => current.addressId === addressId)\n\n if (!address) {\n return (\n <GenericError errorId=\"vtex.store-messages@0.x::alert.addressNotFound\" />\n )\n }\n\n const { addressName, ...normalizedAddress } = address\n\n return (\n <ContentBox shouldAllowGrowing maxWidthStep={6}>\n <AddressForm\n isLoading={isLoading}\n submitLabelId=\"vtex.store-messages@0.x::addresses.saveAddress\"\n address={normalizedAddress}\n isExistingAddress={!!addressId}\n onSubmit={this.handleSave}\n onError={this.props.handleError}\n />\n <AddressDeleter\n addressId={addressId}\n onAddressDeleted={this.handleDelete}\n onError={this.props.handleError}\n />\n </ContentBox>\n )\n }\n}\n\ninterface Data {\n profile: {\n addresses: Address[]\n }\n}\n\ninterface Props extends InjectedContentWrapperProps {\n history: any\n addresses: Address[]\n addressId: string\n shipsTo: string[]\n updateAddress: (args: Variables<UpdateAddressArgs>) => Promise<void>\n}\n\nconst enhance = compose<Props, void>(\n graphql(GET_ADDRESSES),\n graphql(UPDATE_ADDRESS, { name: 'updateAddress' }),\n branch(\n ({ data }: { data: Data }) => data.profile == null,\n renderComponent(AddressEditLoading)\n ),\n withProps(({ data, match }: { data: Data; match: any }) => ({\n addresses: data.profile.addresses,\n addressId: match.params.id,\n })),\n withContentWrapper({\n headerConfig,\n handle: { contentHandle: '', configHandle: 'addressEdit' },\n })\n)\n\nexport default enhance(AddressEdit)\n\n```" } ]
code_my-account_164bceb2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/pages/Profile.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { withRouter } from 'vtex.my-account-commons/Router'\nimport { compose, branch, renderComponent, withProps } from 'recompose'\n\nimport { withContentWrapper } from '../shared/withContentWrapper'\nimport ProfileLoading from '../loaders/ProfileLoading'\nimport ProfileBox from '../Profile/ProfileBox'\nimport Toast from '../shared/Toast'\nimport GET_PROFILE from '../../graphql/getProfile.gql'\nimport NewsletterBox from '../Profile/NewsletterBox'\n\nexport const headerConfig = {\n titleId: 'vtex.store-messages@0.x::pages.profile',\n hideBackButton: true,\n}\n\nclass ProfileContainer extends Component<Props> {\n public state = {\n showToast: false,\n }\n\n public componentDidMount = () => {\n const { location } = this.props\n\n this.setState({ showToast: location.search.indexOf('success=true') > -1 })\n }\n\n private handleCloseToast = () => {\n this.setState({ showToast: false })\n }\n\n private handleGoToEdit = () => {\n this.props.history.push('/profile/edit')\n }\n\n public render() {\n const { profile } = this.props\n const { showToast } = this.state\n\n return (\n <main className=\"flex flex-column-s flex-row-ns\">\n <div className=\"w-60-ns w-100-s\">\n <ProfileBox profile={profile} onEditClick={this.handleGoToEdit} />\n </div>\n <div className=\"w-40-ns w-100-s\">\n <NewsletterBox userEmail={profile.email} />\n </div>\n {showToast && (\n <Toast\n messageId=\"vtex.store-messages@0.x::alert.success\"\n onClose={this.handleCloseToast}\n />\n )}\n </main>\n )\n }\n}\n\ninterface Props {\n location: any\n history: any\n profile: Profile\n data: {\n profile: Profile\n }\n}\n\nconst enhance = compose<Props, void>(\n graphql(GET_PROFILE),\n branch<Props>(\n ({ data }) => data.profile == null,\n renderComponent(ProfileLoading)\n ),\n withContentWrapper({\n headerConfig,\n handle: { configHandle: 'profile', contentHandle: '' },\n }),\n withProps(({ data }: Props) => ({ profile: data.profile })),\n withRouter\n)\n\nexport default enhance(ProfileContainer)\n\n```" } ]
code_my-account_fac24c5e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/pages/AddressCreate.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport type { MutationResult, DataValue } from 'react-apollo'\nimport { graphql } from 'react-apollo'\nimport { compose, branch, renderComponent } from 'recompose'\nimport queryString from 'query-string'\nimport type { RouteComponentProps } from 'vtex.my-account-commons/Router'\nimport { withRouter } from 'vtex.my-account-commons/Router'\n\nimport { withContentWrapper } from '../shared/withContentWrapper'\nimport AddressCreateLoading from '../loaders/AddressCreateLoading'\nimport AddressForm from '../Addresses/AddressForm'\nimport ContentBox from '../shared/ContentBox'\nimport type {\n Args,\n Result as SaveAddressResult,\n} from '../../graphql/saveAddress.gql'\nimport SAVE_ADDRESS from '../../graphql/saveAddress.gql'\nimport type { Result as CustomerInfo } from '../../graphql/customerGreeting.gql'\nimport CREATE_ADDRESS_INFO from '../../graphql/customerGreeting.gql'\n\nexport const headerConfig = {\n titleId: 'vtex.store-messages@0.x::pages.addressCreate',\n backButton: {\n titleId: 'vtex.store-messages@0.x::pages.addresses',\n path: '/addresses',\n },\n}\n\nfunction buildReceiverName(profile: CustomerInfo['profile']): string {\n const lastName = profile.lastName ? ` ${profile.lastName}` : ''\n\n return `${profile.firstName ?? ''}${lastName}`\n}\n\nclass AddressCreate extends Component<Props> {\n public state = {\n isLoading: false,\n }\n\n private handleCreate = (address: Address) => {\n const { saveAddress, handleError, history, location } = this.props\n const { addressId, addressQuery, ...addressFields } = address\n\n this.setState({ isLoading: true })\n\n saveAddress({\n variables: {\n address: { ...addressFields } as AddressInput,\n },\n })\n .then(({ data }) => {\n const parsed = queryString.parse(location.search)\n\n if (parsed.returnUrl && data) {\n history.push({\n pathname: parsed.returnUrl,\n search: queryString.stringify({\n newAddressId: data.saveAddress.id,\n }),\n })\n } else {\n history.goBack()\n }\n })\n .catch(() => {\n handleError()\n this.setState({ isLoading: false })\n })\n }\n\n public render() {\n const { isLoading } = this.state\n const { receiverName } = this.props\n\n return (\n <ContentBox shouldAllowGrowing maxWidthStep={6}>\n <AddressForm\n receiverName={receiverName}\n isLoading={isLoading}\n submitLabelId=\"vtex.store-messages@0.x::addresses.addAddress\"\n onSubmit={this.handleCreate}\n onError={this.props.handleError}\n />\n </ContentBox>\n )\n }\n}\n\ninterface MappedResult {\n loading: boolean\n receiverName: string\n data: DataValue<unknown>\n}\n\ntype Props = MappedResult &\n RouteComponentProps &\n InjectedContentWrapperProps & {\n saveAddress: (\n args: Variables<Args>\n ) => Promise<MutationResult<SaveAddressResult>>\n }\n\nconst enhance = compose<Props, void>(\n graphql<\n Record<string, unknown>,\n CustomerInfo,\n Record<string, unknown>,\n MappedResult\n >(CREATE_ADDRESS_INFO, {\n props: props => ({\n loading: props.data?.loading ?? true,\n data: props.data as DataValue<unknown>,\n receiverName: props.data?.profile\n ? buildReceiverName(props.data?.profile)\n : '',\n }),\n }),\n branch(\n ({ loading }: Props) => loading,\n renderComponent(AddressCreateLoading)\n ),\n graphql(SAVE_ADDRESS, { name: 'saveAddress' }),\n withContentWrapper({\n headerConfig,\n handle: { configHandle: 'addressCreate', contentHandle: '' },\n }),\n withRouter\n)\n\nexport default enhance(AddressCreate)\n\n```" } ]
code_my-account_c13b98ce
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/pages/Addresses.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { Component } from 'react'\nimport { graphql } from 'react-apollo'\nimport { compose, branch, renderComponent, withProps } from 'recompose'\nimport { FormattedMessage } from 'react-intl'\nimport { EmptyState, Button } from 'vtex.styleguide'\nimport { withRouter, Link } from 'vtex.my-account-commons/Router'\nimport { withCssHandles } from 'vtex.css-handles'\n\nimport { withContentWrapper } from '../shared/withContentWrapper'\nimport AddressesLoading from '../loaders/AddressesLoading'\nimport AddressBox from '../Addresses/AddressBox'\nimport Toast from '../shared/Toast'\nimport GET_ADRESSES from '../../graphql/getAddresses.gql'\n\nconst CSS_HANDLES = ['addressBox'] as const\n\nexport const headerConfig = {\n titleId: 'vtex.store-messages@0.x::pages.addresses',\n headerContent(handle: any) {\n return (\n <Link className={handle} to=\"/addresses/new\">\n <Button variation=\"primary\" block size=\"small\">\n <FormattedMessage id=\"vtex.store-messages@0.x::addresses.addAddress\" />\n </Button>\n </Link>\n )\n },\n}\n\nfunction EmptyAddresses() {\n const title = (\n <FormattedMessage id=\"vtex.store-messages@0.x::addresses.notFound\" />\n )\n\n return <EmptyState title={title} />\n}\n\nclass Addresses extends Component<Props> {\n public state = {\n showToast: false,\n }\n\n public componentDidMount = () => {\n const { location } = this.props\n\n this.setState({ showToast: location.search.indexOf('success=true') > -1 })\n }\n\n private handleCloseToast = () => {\n this.setState({ showToast: false })\n }\n\n private handleStartEditing = (address: Address) => {\n window.scroll({ top: 0, left: 0, behavior: 'auto' })\n this.props.history.push(`/addresses/edit/${address.addressId}`)\n }\n\n public render() {\n const { cssHandles } = this.props\n\n return (\n <div\n className={`${cssHandles.addressBox} flex flex-wrap-ns items-start-ns relative tl`}\n >\n {this.props.addresses.map(address => (\n <AddressBox\n key={address.addressId}\n address={address}\n onEditClick={() => this.handleStartEditing(address)}\n />\n ))}\n\n {this.state.showToast && (\n <Toast\n messageId=\"vtex.store-messages@0.x::alert.success\"\n onClose={this.handleCloseToast}\n />\n )}\n </div>\n )\n }\n}\n\ninterface Data {\n loading: boolean\n profile: {\n addresses: Address[]\n } | null\n}\n\ninterface Props {\n location: any\n history: any\n addresses: Address[]\n cssHandles: CssHandles<typeof CSS_HANDLES>\n}\n\nconst enhance = compose<Props, void>(\n graphql(GET_ADRESSES, { options: { fetchPolicy: 'network-only' } }),\n branch(\n ({ data }: { data: Data }) => data.loading,\n renderComponent(AddressesLoading)\n ),\n withContentWrapper({\n headerConfig,\n handle: { configHandle: 'addressList', contentHandle: 'newAddressButton' },\n }),\n branch(\n ({ data }: { data: { profile: { addresses: Address[] } } }) =>\n data.profile == null || data.profile.addresses.length === 0,\n renderComponent(EmptyAddresses)\n ),\n withProps(({ data }: { data: Data }) => ({\n addresses: data.profile && data.profile.addresses,\n })),\n withRouter,\n withCssHandles(CSS_HANDLES)\n)\n\nexport default enhance(Addresses)\n\n```" } ]
code_my-account_9056bed7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/AddressEditLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { BaseLoading } from 'vtex.my-account-commons'\n\nimport { headerConfig } from '../pages/AddressEdit'\nimport FormLoader from './FormLoader'\n\nconst AddressEditLoading: FunctionComponent<Props> = ({ data }) => {\n return (\n <BaseLoading queryData={data} headerConfig={headerConfig}>\n <FormLoader />\n </BaseLoading>\n )\n}\n\ninterface Props {\n data: unknown\n}\n\nexport default AddressEditLoading\n\n```" } ]
code_my-account_8a1f5cc7
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/ProfileLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport {\n SkeletonPiece,\n SkeletonBox,\n BaseLoading,\n} from 'vtex.my-account-commons'\n\nimport { headerConfig } from '../pages/Profile'\n\nconst ProfileLoading: FunctionComponent<Props> = ({ data }) => {\n return (\n <BaseLoading queryData={data} headerConfig={headerConfig}>\n <main className=\"flex flex-column-s flex-row-ns\">\n <div className=\"w-60-ns w-100-s\">\n <SkeletonBox shouldAllowGrowing shouldShowLowerButton>\n <div className=\"flex flex-wrap mb8 justify-between w5\">\n <SkeletonPiece width=\"40\" size=\"4\" />\n <SkeletonPiece width=\"50\" size=\"4\" />\n </div>\n <div className=\"mb8\">\n <SkeletonPiece size=\"4\" />\n </div>\n <div className=\"flex flex-wrap mb8 justify-between\">\n <SkeletonPiece width=\"30\" size=\"4\" />\n <SkeletonPiece width=\"50\" size=\"4\" />\n </div>\n <div className=\"flex flex-wrap mb8 justify-between\">\n <SkeletonPiece width=\"40\" size=\"4\" />\n <SkeletonPiece width=\"50\" size=\"4\" />\n </div>\n </SkeletonBox>\n </div>\n <div className=\"w-40-ns w-100-s\">\n <SkeletonBox shouldAllowGrowing shouldShowLowerButton>\n <SkeletonPiece size=\"4\" />\n </SkeletonBox>\n <SkeletonBox shouldAllowGrowing shouldShowLowerButton>\n <SkeletonPiece size=\"4\" />\n </SkeletonBox>\n </div>\n </main>\n </BaseLoading>\n )\n}\n\ninterface Props {\n data: any\n}\n\nexport default ProfileLoading\n\n```" } ]
code_my-account_465a7503
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/AddressesLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport {\n SkeletonPiece,\n SkeletonBox,\n BaseLoading,\n} from 'vtex.my-account-commons'\n\nimport { headerConfig } from '../pages/Addresses'\n\nconst AddressesLoading: FunctionComponent<Props> = ({ data }) => {\n return (\n <BaseLoading queryData={data} headerConfig={headerConfig}>\n <main className=\"mt7 flex-ns flex-wrap-ns items-start-ns\">\n {[0, 1].map(i => (\n <SkeletonBox shouldShowLowerButton key={i}>\n <div className=\"pv4 w5 h4\">\n <div className=\"mb4\">\n <SkeletonPiece width=\"70\" size=\"3\" />\n </div>\n <div className=\"mb4\">\n <SkeletonPiece width=\"40\" size=\"3\" />\n </div>\n <SkeletonPiece width=\"30\" size=\"3\" />\n </div>\n </SkeletonBox>\n ))}\n </main>\n </BaseLoading>\n )\n}\n\ninterface Props {\n data: unknown\n}\n\nexport default AddressesLoading\n\n```" } ]
code_my-account_249cc070
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/AddressCreateLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { BaseLoading } from 'vtex.my-account-commons'\nimport type { DataValue } from 'react-apollo'\n\nimport { headerConfig } from '../pages/AddressCreate'\nimport FormLoader from './FormLoader'\n\nconst AddressCreateLoading: FunctionComponent<Props> = ({ data }) => {\n return (\n <BaseLoading queryData={data} headerConfig={headerConfig}>\n <FormLoader />\n </BaseLoading>\n )\n}\n\ninterface Props {\n data: DataValue<unknown>\n}\n\nexport default AddressCreateLoading\n\n```" } ]
code_my-account_19d09603
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/ProfileEditLoading.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\nimport { BaseLoading } from 'vtex.my-account-commons'\n\nimport { headerConfig } from '../pages/ProfileEdit'\nimport FormLoader from './FormLoader'\n\nconst ProfileEditLoading: FunctionComponent<Props> = ({ data }) => {\n return (\n <BaseLoading queryData={data} headerConfig={headerConfig}>\n <FormLoader />\n </BaseLoading>\n )\n}\n\ninterface Props {\n data: any\n}\n\nexport default ProfileEditLoading\n\n```" } ]
code_my-account_ded26991
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/FormLoader.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { SkeletonBox } from 'vtex.my-account-commons'\n\nimport Content from './FormContent'\n\nconst FormLoader = () => (\n <SkeletonBox shouldAllowGrowing maxWidthStep={6}>\n <Content />\n </SkeletonBox>\n)\n\nexport default FormLoader\n\n```" } ]
code_my-account_8fbaf98d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/loaders/FormContent.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React, { PureComponent } from 'react'\nimport { SkeletonPiece } from 'vtex.my-account-commons'\n\n// eslint-disable-next-line react/prefer-stateless-function\nclass FormContent extends PureComponent {\n public render() {\n return (\n <>\n <div className=\"mb8 mt4\">\n <SkeletonPiece width=\"100\" size=\"3\" />\n <SkeletonPiece width=\"100\" size=\"3\" />\n </div>\n <div className=\"mb9\">\n <SkeletonPiece width=\"100\" size=\"3\" />\n <SkeletonPiece width=\"100\" size=\"3\" />\n </div>\n <div className=\"mb8\">\n <SkeletonPiece width=\"40\" size=\"3\" />\n <SkeletonPiece width=\"40\" size=\"3\" />\n </div>\n </>\n )\n }\n}\n\nexport default FormContent\n\n```" } ]
code_my-account_edf6e592
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/ProfilePicture/UserPlaceholderPicture.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nconst UserPlaceholderPicture = () => {\n return (\n <svg\n className=\"h-100 w-auto\"\n width=\"110\"\n height=\"110\"\n viewBox=\"0 0 110 110\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <rect width=\"110\" height=\"110\" fill=\"black\" fillOpacity=\"0\" />\n <rect width=\"110\" height=\"110\" fill=\"black\" fillOpacity=\"0\" />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M55 110C85.3757 110 110 85.3757 110 55C110 24.6243 85.3757 0 55 0C24.6243 0 0 24.6243 0 55C0 85.3757 24.6243 110 55 110Z\"\n fill=\"#D8D8D8\"\n />\n <mask\n id=\"mask0\"\n maskUnits=\"userSpaceOnUse\"\n x=\"0\"\n y=\"0\"\n width=\"110\"\n height=\"110\"\n >\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M55 110C85.3757 110 110 85.3757 110 55C110 24.6243 85.3757 0 55 0C24.6243 0 0 24.6243 0 55C0 85.3757 24.6243 110 55 110Z\"\n fill=\"white\"\n />\n </mask>\n <g mask=\"url(#mask0)\">\n <rect\n width=\"85.3731\"\n height=\"96.8655\"\n fill=\"black\"\n fillOpacity=\"0\"\n transform=\"translate(13.1367 21.3433)\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M66.4949 78.5818H45.1516C27.4705 78.5818 13.1367 93.0978 13.1367 111.004C13.1367 111.004 29.1442 118.209 55.8233 118.209C82.5024 118.209 98.5098 111.004 98.5098 111.004C98.5098 93.0978 84.1761 78.5818 66.4949 78.5818Z\"\n fill=\"#979797\"\n />\n <path\n fillRule=\"evenodd\"\n clipRule=\"evenodd\"\n d=\"M30.7969 46C30.7969 32.3824 42.0001 21.3433 55.82 21.3433C69.64 21.3433 80.8432 32.3824 80.8432 46C80.8432 59.6175 69.64 74.1791 55.82 74.1791C42.0001 74.1791 30.7969 59.6175 30.7969 46Z\"\n fill=\"#979797\"\n />\n </g>\n </svg>\n )\n}\n\nexport default UserPlaceholderPicture\n\n```" } ]
code_my-account_3af4453b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of my-account/react/components/Menu/ProfilePicture/PictureRenderer.tsx from the my-account VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React from 'react'\n\nimport UserPlaceholderPicture from './UserPlaceholderPicture'\n\nconst PictureRenderer: FunctionComponent<Props> = ({ imagePath }) => {\n const imageStyle = { backgroundImage: `url(${imagePath})` }\n\n return imagePath ? (\n <div className=\"h-100 w-100 br-100 cover\" style={imageStyle} />\n ) : (\n <UserPlaceholderPicture />\n )\n}\n\ninterface Props {\n imagePath?: string\n}\n\nexport default PictureRenderer\n\n```" } ]
code_vega-graphql_1bc27c12
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/graphql/schema.graphql from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype SpecLocator {\n appId: String\n specName: String\n}\n\ntype Query {\n spec (\n specName: String!,\n appId: String\n ): String\n\n specs: [SpecLocator]\n}\n\n```" } ]
code_vega-graphql_f70093a2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/typings.d.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Apps, ServiceContext, VBase } from '@vtex/api'\nimport { StoreDashDataSource } from './dataSources/storedash'\n\ndeclare global {\n interface Context extends ServiceContext {\n dataSources: DataSources\n }\n \n interface DataSources {\n storeDash: StoreDashDataSource\n apps: Apps\n vbase: VBase\n }\n \n type Resolver<P, A, I, R> = (root: P, args: A, ctx: Context, info: I) => Promise<R>\n\n interface StoreDashInput {\n aggregateBy?: string[]\n fields?: string[]\n from: string\n interval?: string\n operation?: string\n size?: number\n timezone?: string\n to?: string\n }\n\n type Maybe<T> = T | void \n\n interface Specs {\n [name: string]: string\n }\n\n interface SpecLocator {\n appId: string\n specName: string\n }\n\n interface Layout {\n specLocator: SpecLocator\n spec: string\n }\n\n interface LayoutContainer {\n cacheId: string\n layout: Layout[]\n }\n}\n\nexport {}\n```" } ]
code_vega-graphql_fd79bb7d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/package.json from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"dependencies\": {\n \"@vtex/api\": \"1.4.0\",\n \"apollo-datasource-rest\": \"^0.1.5\",\n \"apollo-server\": \"^2.1.0\",\n \"apollo-server-errors\": \"^2.0.2\",\n \"ramda\": \"^0.25.0\"\n },\n \"devDependencies\": {\n \"@types/bluebird\": \"^3.5.24\",\n \"@types/bluebird-global\": \"^3.5.9\",\n \"@types/node\": \"^10.7.1\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"tslint\": \"^5.11.0\",\n \"tslint-config-vtex\": \"^2.0.0\",\n \"typescript\": \"^3.1.3\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```" } ]
code_vega-graphql_d70a0f1b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/index.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport * as Bluebird from 'bluebird'\n\nglobal.Promise = Bluebird\n\nimport { cache, dataSources } from './dataSources'\nimport { resolvers } from './resolvers'\n\nexport default {\n graphql: {\n cache,\n dataSources,\n resolvers,\n }\n}\n```" } ]
code_vega-graphql_4b8f87a9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/dataSources/index.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Apps, DiskCache, LRUCache, MultilayeredCache } from '@vtex/api'\n\nimport { CACHE_PATH } from '../common/globals'\n\nconst cacheStorage = new MultilayeredCache([\n new LRUCache<string, any>({\n max: 1000\n }),\n new DiskCache(CACHE_PATH)\n])\n\nexport const dataSources = () => ({\n apps: new Apps(),\n})\n\nexport const cache = () => cacheStorage\n```" } ]
code_vega-graphql_a112a5a4
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/resolvers/spec.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isValidAppIdOrLocator } from '@vtex/api'\nimport { ApolloError } from 'apollo-server-errors'\nimport { compose, flatten, keys, map, mapObjIndexed, partial, values, zipObj } from 'ramda'\n\nimport { appsWithSpecs, getSpec, getSpecs } from '../common/spec'\n\nconst maybeSpecsToSpecLocators = (maybeSpecs: Maybe<Specs>, appId: string) => maybeSpecs \n ? compose(\n map((specName: string) => ({specName, appId})),\n keys\n )(maybeSpecs) as SpecLocator[]\n : [] \n\nexport const specs = async (root, args: void, ctx: Context, info): Promise<SpecLocator[]> => {\n const {dataSources: {apps}} = ctx\n const appIdsWithStats = await appsWithSpecs(apps)\n const getSpecsForAppId = partial(getSpecs, [apps])\n const appSpecs = await Promise.map(appIdsWithStats, getSpecsForAppId)\n const specsByAppId = zipObj(appIdsWithStats, appSpecs)\n return compose(\n flatten,\n values,\n mapObjIndexed(maybeSpecsToSpecLocators)\n )(specsByAppId) as SpecLocator[]\n}\n\ninterface SpecArgs {\n specName: string\n appId?: string\n}\n\nexport const spec = async (root, args: SpecArgs, ctx: Context, info) => {\n const {dataSources: {apps}} = ctx\n const {specName, appId} = args\n\n if (appId && isValidAppIdOrLocator(appId)) {\n return getSpec(apps, appId, specName).then(JSON.stringify)\n } \n \n throw new ApolloError(`Vega spec ${specName} was not found for app ${appId}`)\n}\n\n```" } ]
code_vega-graphql_38b0324d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/resolvers/index.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { spec, specs } from './spec'\n\nexport const resolvers = {\n Query: {\n spec,\n specs,\n },\n}\n```" } ]
code_vega-graphql_2b7629a6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/common/utils.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SPEC_PATH } from './globals'\n\nexport const cacheKey = (app: string) => `${app}/${SPEC_PATH}`.replace(/\\W/g, '_')\n\nexport const toString = ({data}: {data: Buffer}) => data.toString()\n\n\n```" } ]
code_vega-graphql_bbaed09c
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/common/spec.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { Apps, DiskCache, LRUCache, MultilayeredCache, removeBuild } from '@vtex/api'\nimport { find, keys, prop } from 'ramda'\n\nimport { CACHE_PATH, SPEC_PATH, VEGA_GRAPHQL } from './globals'\nimport { ignoreNotFound } from './notFound'\nimport { cacheKey, toString } from './utils'\n\nconst specStorage = new MultilayeredCache<string, Maybe<Specs>>([\n new LRUCache({\n max: 100\n }),\n new DiskCache(CACHE_PATH)\n])\n\nconst equalsNoBuild = (appIdNoBuild: string) => (appId: string) => removeBuild(appIdNoBuild) === removeBuild(appId)\n\nconst findAppInDeps = (apps: Apps, appIdNoBuild: string): Promise<Maybe<string>> => \n apps.getDependencies()\n .then(keys)\n .then(find(equalsNoBuild(appIdNoBuild)))\n\nconst fetchSpec = (apps: Apps, appId: string) => (): Promise<Maybe<Specs>> => \n apps.getAppFile(appId, SPEC_PATH)\n .then(toString)\n .then(JSON.parse)\n .catch(ignoreNotFound(null))\n\nexport const getSpecs = async (apps: Apps, appId: string) => {\n const appIdWithBuild = await findAppInDeps(apps, removeBuild(appId))\n return appIdWithBuild && specStorage.get(cacheKey(appIdWithBuild), fetchSpec(apps, appIdWithBuild))\n}\n\nexport const getSpec = (apps: Apps, appId: string, specName: string): Promise<string> => \n getSpecs(apps, appId).then(prop(specName))\n\nexport const appsWithSpecs = (apps: Apps) => apps.getDependencies(VEGA_GRAPHQL).then(keys)\n```" } ]
code_vega-graphql_a060c164
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/common/globals.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const CACHE_PATH = '/cache/v0'\n\nexport const SPEC_PATH = 'dist/vtex.vega-graphql/spec0x.vega.json'\n\nexport const VEGA_GRAPHQL = 'vtex.vega-graphql@0.x'\n\n```" } ]
code_vega-graphql_b124ccbc
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of vega-graphql/node/common/notFound.ts from the vega-graphql VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport const ignoreNotFound = <T>(fallback: T) => (error: any): T => {\n if (error.response && error.response.status === 404) {\n return fallback\n }\n throw error\n }\n```" } ]
code_component-library_ae56e918
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of component-library/messages/pt.json from the component-library VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n```" } ]
code_component-library_171b272e
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of component-library/messages/en.json from the component-library VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"test\",\n \"store/test\": \"test\"\n}\n\n```" } ]
code_component-library_0c2d2d20
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of component-library/messages/es.json from the component-library VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"admin/test\": \"teste\",\n \"store/test\": \"teste\"\n}\n```" } ]
code_component-library_6bff50f3
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of component-library/react/package.json from the component-library 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 \"apollo-client\": \"^2.6.3\",\n \"react\": \"^16.8.6\",\n \"react-apollo\": \"^2.5.8\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"^2.9.0\"\n },\n \"devDependencies\": {\n \"@types/graphql\": \"^14.2.2\",\n \"@types/react\": \"^16.8.22\",\n \"@types/react-intl\": \"^2.3.18\",\n \"@vtex/test-tools\": \"^0.3.2\",\n \"eslint\": \"5.x\",\n \"eslint-config-vtex-react\": \"4.x\",\n \"prettier\": \"^1.18.2\",\n \"prop-types\": \"^15.7.2\",\n \"typescript\": \"3.5.2\"\n }\n}\n\n```" } ]
code_component-library_f614b7d0
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms." }, { "role": "user", "content": "Show me the implementation of component-library/react/__tests__/index.test.tsx from the component-library 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_storefront-permissions_36227469
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/configuration/schema.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\"\n },\n \"features\": {\n \"type\": \"array\",\n \"items\": [\n {\n \"type\": \"object\",\n \"properties\": {\n \"label\": {\n \"type\": \"string\"\n },\n \"value\": {\n \"type\": \"string\"\n },\n \"roles\": {\n \"type\": \"array\",\n \"items\": [\n {\n \"type\": \"string\"\n }\n ]\n }\n },\n \"required\": [\"label\", \"value\", \"roles\"]\n }\n ]\n }\n },\n \"required\": [\"name\", \"features\"]\n}\n\n```" } ]
code_storefront-permissions_ee4f3008
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/docs/README.md from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```markdown\n# Storefront Permissions\n\n<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->\n\n[![All Contributors](https://img.shields.io/badge/all_contributors-0-orange.svg?style=flat-square)](#contributors-)\n\n<!-- ALL-CONTRIBUTORS-BADGE:END -->\n\n> ℹ The **Storefront Permissions** app is part of VTEX’s [B2B Suite](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-suite) solution, which is a collection of apps that allow stores to manage organizations, storefront roles and permissions, and checkout settings for B2B commerce relationships. We recommend that you use it alongside the other apps in this suite for all functionalities to work as expected.\n\nWhen navigating a B2B store as a customer, it is common for a main user from an organization to have other people under their structure, each with their own information and access privileges.\n\nWithin an organization, each user can have different roles, such as a professional buyer that places orders with budget limits from a predefined cost center or a manager in charge of reviewing and approving orders. These roles can be associated with multiple permissions, depending on the actions this user needs to perform.\n\nThe **Storefront Permissions** app stores a predefined set of roles and app permissions related to what B2B users can access and do in your storefront, making this information available for other integrated apps to check. This is useful for stores who want to set specific app permissions for users with different roles in an organization.\n\n\n## Available storefront roles\n\nIn the following table, you can see the available storefront roles, their key used for identification in the app’s code, and their description.\n\n| **Role** | **Key** | **Description** |\n|---|---|---|\n| Store Admin | `store-admin` | Store administrator, also known as a user who has access to the VTEX Admin, including the permission to impersonate any company/buyer. |\n| Sales Admin | `sales-admin` | Sales administrator user who can manage all sales users. |\n| Sales Manager | `sales-manager` | Sales manager user who can manage sales users in the same organization, as well as assist or impersonate buyers during navigation or purchase. |\n| Sales Representative | `sales-representative` | Sales representative user who can assist or impersonate buyers in the same cost center during navigation or purchase. |\n| Organization Admin | `customer-admin` | Main organization user who manages the organization information, as well as its members and cost centers. |\n| Organization Approver | `customer-approver` | Organization user who can take a saved cart or quote that was created by an **Organization Buyer** and use it to place an order. |\n| Organization Buyer | `customer-buyer` | Organization user who has the ability to add items to cart. If the **B2B Quotes** app is installed, they are also able to save their cart for future use or create a quote. |\n\n\n## How it works\n\n**Storefront Permissions** communicates automatically with other [B2B Suite](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-suite) apps, such as [B2B Organizations](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations), where it enables different organization management capabilities depending on each user’s role.\n\nIt also allows you to configure available permissions when developing your own app, associate them with the predefined roles, and have these permissions checked by other applications – if you perform the steps described in the [Advanced app integration](#advanced-app-integration-optional) section.\n\nThe **Storefront Permissions** app does not contain an interface – it operates “backstage”, storing the predefined roles and serving as a bridge to communicate with other apps in order to check user permissions. If you would like to manage roles and app permissions using the VTEX Admin interface, you must also install the [Storefront Permissions UI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-storefront-permissions-ui) app. As an optional feature, you can install the [Admin Customers](https://developers.vtex.com/vtex-developer-docs/docs/vtex-admin-customers) app for additional customer management capabilities.\n\n\n## Before you start\n\nMake sure you have the [VTEX IO CLI (Command Line Interface)](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-install) installed in your machine.\n\nIf you opt to develop your own app and [integrate](#advanced-app-integration-optional) it with **Storefront Permissions**, read our documentation on [Developing an app](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-developing-an-app).\n\n\n## Installation\n\nYou can install the app by running `vtex install vtex.storefront-permissions` in your terminal, using the [VTEX IO CLI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-vtex-io-cli-installation-and-command-reference).\n\n\n## Advanced app integration [optional]\n\nIf you would like to develop your own app and integrate it with **Storefront Permissions**, follow the steps below.\n\n1. Open your app’s repository.\n2. In the `manifest.json` file, add `vtex.storefront-permissions` under the `builders` property, as follows.\n\n ```json\n \"builders\": {\n \"vtex.storefront-permissions\": \"1.x\"\n }\n ```\n\n3. In the root folder, create a new folder named `vtex.storefront-permissions`.\n4. In the `vtex.storefront-permissions` folder, create a `configuration.json` file. The content of this file should follow the format below. Keep in mind that you must replace the example information with the `name` of your app and its `features`.\n\n ```json\n {\n \"name\": \"My awesome app\",\n \"features\": [\n {\n \"label\": \"View\",\n \"value\": \"view-awesome-things\",\n \"roles\": [\"store-admin\",\"sales-admin\",\"sales-manager\",\"sales-representative\",\"customer-admin\",\"customer-approver\",\"customer-buyer\"]\n },\n {\n \"label\": \"Create\",\n \"value\": \"create-awesome-things\",\n \"roles\": [\"store-admin\",\"sales-admin\",\"sales-manager\",\"sales-representative\"]\n },\n {\n \"label\": \"Delete\",\n \"value\": \"delete-awesome-things\",\n \"roles\": [\"store-admin\",\"sales-admin\",\"sales-manager\",\"sales-representative\"]\n },\n {\n \"label\": \"Special Access\",\n \"value\": \"allow-special-access\",\n \"roles\": [\"store-admin\",\"sales-admin\"]\n }\n ]\n }\n ```\n\n Below you can find a description of each property.\n\n | **Property** | **Type** | **Description** |\n |---|---|---|\n | `name` | string | Name of your app. |\n | `features` | array of objects | List of features related to your app – the functionalities of your app that you want to set permissions for users to be able to access or not. |\n | ⤷ | object | Object containing information about each feature of your app. |\n | ⤷ `label` | string | Name or description of the feature. |\n | ⤷ `value` | string | Identifier key you want to use for the feature, as used in your app’s [custom storefront components](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-developing-custom-storefront-components). Do not use space or special characters in this field. |\n | ⤷ `roles` | array of strings | List with the keys for all the roles you want to associate with the permission to use the feature by default. You can find more information about each role and its key in the [Available Storefront Roles section](#available-storefront-roles) of this documentation. |\n\n5. Make sure you refer to the `value` – the identifier key – for each feature you want to set permissions for in your [custom storefront components](https://developers.vtex.com/vtex-developer-docs/docs/vtex-io-documentation-developing-custom-storefront-components)’ code, when developing your app.\n\n Example: in the B2B Organizations app, one of the permissions created is represented by the following object.\n\n ```json\n {\n \"label\": \"Create Cost Center\",\n \"value\": \"create-cost-center-organization\",\n \"roles\": [\"store-admin\",\"sales-admin\",\"customer-admin\"]\n }\n ```\n\n Therefore, in a [custom storefront component’s code](https://github.com/vtex-apps/b2b-organizations/blob/366a28add226eac5d9b104bb13a9f2cd1d574f02/react/components/CostCenterDetails.tsx) in TypeScript, whenever referring to this feature, it uses `create-cost-center-organization`.\n\n\nOnce you are done developing and installing your own app, if you have [Storefront Permissions UI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-storefront-permissions-ui), the features of your app associated with each role will be automatically loaded on the **Storefront Permissions** page. For more details on this, read our documentation on the [Storefront Permissions UI](https://developers.vtex.com/vtex-developer-docs/docs/vtex-storefront-permissions-ui) app.\n\n### Session Watcher\n\nThe session watcher is based in the [session transformation feature](https://developers.vtex.com/docs/guides/vtex-io-documentation-collecting-user-session-data#configuring-vtexsession) to update the cart fields with Buyer [Organization data](https://github.com/vtex-apps/b2b-organizations): `Shipping Address`, `Profile` and `Marketdata` ( `utmCampaign` with `organization.id` and `utmMedium` with `costCenter.id` )\n\nTo activate it, [use the mutation](#setSessionWatcher).\n\n### GraphQL queries\n\nNow that your app is integrated, you can write a GraphQL query on your app to check the current user's permission within the context of your app.\n\nFirst, you need to associate your test user to a Role containing your app's permission by following the [B2B Organizations documentation](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations#users).\n\nIt is not necessary to declare your app name nor user credentials, the query will take care of these details.\n\n\n#### checkUserPermission\n\nThis query allows you to check which permissions a user has in the context of your app. When the query is performed, **Storefront Permissions** checks which app the request is coming from, and returns the current user's permissions for that specific app.\n\nThe response will be a list with all the permissions the current user has on the app.\n\nSample query:\n\n```graphql\nquery permissions {\n checkUserPermission @context(provider: \"vtex.storefront-permissions\") {\n role {\n id\n name\n slug\n }\n permissions\n }\n}\n```\n\n\nSample response:\n\n\n```graphql\n{\n \"data\":{\n \"checkUserPermission\": {\n \"role\": {\n \"id\": \"00549c22-f39d-11eb-82ac-0a55b612700f\",\n \"name\": \"Admin\",\n \"slug\": \"customer-admin\"\n },\n \"permissions\": [\"view-awesome-things\",\"create-awesome-things\",\"delete-awesome-things\"]\n }\n }\n}\n```\n\n\n\n#### hasUsers\n\nThis query allows you to check if there are any users associated with a specific role. The response will be a boolean, with `\"hasUsers\": true` if there are users with this role or `false` if there are not.\n\nSample query:\n\n\n```graphql\nquery hasUsers {\n hasUsers(slug: \"sales-admin\")\n @context(provider: \"vtex.storefront-permissions\")\n}\n```\n\n\nSample response:\n\n\n```graphql\n{\n \"data\": {\n \"hasUsers\": true\n }\n}\n```\n\n\n\n#### checkImpersonation\n\nThis query allows you to check if the current user is [impersonating](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations#impersonate-users) another user, and retrieve information on the impersonated user.\n\nSample query:\n\n\n```graphql\nquery checkImpersonation {\n checkImpersonation {\n firstName\n lastName\n email\n userId\n error\n }\n}\n```\n\n\nSample response:\n\n\n```graphql\n{\n \"data\": {\n \"checkImpersonation\": {\n \"firstName\": \"Andrew\",\n \"lastName\": \"Smith\",\n \"email\": \"testemail@mail.com\",\n \"userId\": \"aaaaa-bbbb-cccc-dddd-eeeee\",\n \"error\": null\n }\n }\n}\n```\n\n#### getSessionWatcher\n\nUsing Session Watcher, **Storefront Permissions** detects changes to the user authentication to trigger changes to its cart and navigation, based on associated price tables, collections, profile information and shipping options.\n\nThis query fetches Session Watcher’s status, that is, whether it is active or not. The response will be a boolean, with `true` meaning that it is enabled or `false` meaning it is disabled.\n\nSample query:\n\n```graphql\nquery getSessionWatcher {\n getSessionWatcher\n}\n```\n\n\nSample response:\n\n\n```graphql\n{\n \"data\": {\n \"getSessionWatcher\": false\n }\n}\n```\n\n#### getOrganizationsPaginatedByEmail\n\nThis query allows you to retrieve a paginated list of organizations associated with a specific email. The response includes the organization data along with pagination details such as the current page, page size, and total number of results.\n\nSample query:\n\n```graphql\nquery 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\nSample response:\n\n{\n \"data\": {\n \"getOrganizationsPaginatedByEmail\": {\n \"data\": [\n {\n \"id\": \"00000000-0000-0000-0000-000000000000\",\n \"clId\": \"00000000-0000-0000-0000-000000000000\",\n \"costId\": \"00000000-0000-0000-0000-000000000000\",\n \"orgId\": \"00000000-0000-0000-0000-000000000000\"\n },\n {\n \"id\": \"00000000-0000-0000-0000-000000000000\",\n \"clId\": \"00000000-0000-0000-0000-000000000000\",\n \"costId\": \"00000000-0000-0000-0000-000000000000\",\n \"orgId\": \"00000000-0000-0000-0000-000000000000\"\n }\n ],\n \"pagination\": {\n \"page\": 1,\n \"pageSize\": 25,\n \"total\": 2\n }\n }\n }\n}\n\n\n\n### GraphQL mutation\n\n\n#### impersonateUser\n\nUsing this mutation, you can inform the `userId` to [impersonate an user](https://developers.vtex.com/vtex-developer-docs/docs/vtex-b2b-organizations#impersonate-users). To remove impersonation, send an empty `userId` instead.\n\nSample mutation:\n\n\n```graphql\nmutation impersonateUser($userId: ID)\n@context(provider: \"vtex.storefront-permissions\") {\n impersonateUser(userId: $userId) {\n status\n message\n }\n}\n```\n\n#### <a href=\"#setSessionWatcher\"></a> setSessionWatcher\n\nIf your account is not using `vtex.b2b-organizations` you may want to disable the Session Watcher to avoid unnecessary operations. To do so, set the `active` property to `false` in the mutation exemplified below.\n\nThe response will be a boolean, with `true` for a successful operation or `false` for a failure.\n\nSample mutation:\n\n```graphql\nmutation setSessionWatcher {\n sessionWatcher(active: false)\n}\n```\n\nSample response:\n\n```graphql\n{\n \"data\": {\n \"sessionWatcher\": true\n }\n}\n```\n\n```" } ]
code_storefront-permissions_8bbf2c72
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/vtex.session/configuration.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"storefront-permissions\": {\n \"input\": {\n \"authentication\": [\"storeUserEmail\"],\n \"checkout\": [\"orderFormId\"],\n \"impersonate\": [\"storeUserEmail\", \"storeUserId\"],\n \"public\": [\"impersonate\", \"removeB2B\", \"b2bCurrentCostCenter\"],\n \"storefront-permissions\": [\"hash\"]\n },\n \"output\": {\n \"public\": [\"facets\", \"sc\", \"regionId\"],\n \"storefront-permissions\": [\n \"storeUserId\",\n \"storeUserEmail\",\n \"organization\",\n \"costcenter\",\n \"priceTables\",\n \"collections\",\n \"userId\",\n \"hash\"\n ]\n }\n }\n}\n\n```" } ]
code_storefront-permissions_cd620f9f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/schema.graphql from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ntype Query {\n getAppSettings: SettingsResponse\n @cacheControl(scope: PRIVATE)\n @settings(settingsType: \"workspace\")\n @withSender\n\n getRole(id: ID!): Role @cacheControl(scope: PRIVATE, maxAge: SHORT)\n\n hasUsers(slug: String!): Boolean @cacheControl(scope: PRIVATE, maxAge: SHORT)\n\n listRoles: [Role]\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n @settings(settingsType: \"workspace\")\n @withSession\n @withSender\n\n getFeaturesByModule(module: String!): Feature\n @settings(settingsType: \"workspace\")\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n\n listFeatures: [FullFeature]\n @settings(settingsType: \"workspace\")\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n @withSender\n\n getUser(id: ID!): User @cacheControl(scope: PRIVATE) @validateStoreUserAccess\n getB2BUser(id: ID!): User @cacheControl(scope: PRIVATE)\n\n checkCustomerSchema: Boolean @cacheControl(scope: PRIVATE) @withSender\n\n getUserByEmail(email: String!): [User]\n @cacheControl(scope: PRIVATE)\n @withSender\n @validateStoreUserAccess\n\n listAllUsers: [User]\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n @withSender\n @validateStoreUserAccess\n\n listUsers(organizationId: ID, costCenterId: ID, roleId: ID): [User]\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n @deprecated(\n reason: \"This query is deprecated, use listUsersPaginated query instead.\"\n )\n @validateStoreUserAccess\n\n listUsersPaginated(\n organizationId: ID\n costCenterId: ID\n roleId: ID\n page: Int\n pageSize: Int\n search: String\n sortOrder: String\n sortedBy: String\n ): UserPagination\n @cacheControl(scope: PRIVATE, maxAge: SHORT)\n @validateStoreUserAccess\n\n checkImpersonation: UserImpersonation\n @settings(settingsType: \"workspace\")\n @withSession\n @cacheControl(scope: PRIVATE)\n\n checkUserPermission: UserPermissions\n @settings(settingsType: \"workspace\")\n @withSession\n @withSender\n @cacheControl(scope: PRIVATE)\n\n getSessionWatcher: Boolean @cacheControl(scope: PRIVATE)\n\n getUsersByEmail(email: String!, orgId: ID, costId: ID): [User]\n @cacheControl(scope: PRIVATE)\n @validateStoreUserAccess\n\n getActiveUserByEmail(email: String!): User\n @cacheControl(scope: PRIVATE)\n @validateStoreUserAccess\n\n getOrganizationsByEmail(email: String!): [Organization]\n @cacheControl(scope: PRIVATE)\n @validateStoreUserAccess\n\n getOrganizationsPaginatedByEmail(\n email: String!\n page: Int = 1\n pageSize: Int = 25\n ): OrganizationPaginated\n @cacheControl(scope: PRIVATE)\n @validateStoreUserAccess\n}\n\ntype Mutation {\n sessionWatcher(active: Boolean!): Boolean @cacheControl(scope: PRIVATE)\n\n saveRole(\n id: ID\n name: String!\n slug: String\n features: [FeatureInput]\n ): MutationResponse\n @cacheControl(scope: PRIVATE)\n @withSender\n @validateStoreUserAccess\n\n deleteRole(id: ID!): MutationResponse\n @cacheControl(scope: PRIVATE)\n @withSender\n @validateStoreUserAccess\n\n saveUser(\n id: ID\n roleId: ID!\n userId: ID\n orgId: ID\n costId: ID\n clId: ID\n canImpersonate: Boolean = false\n name: String!\n email: String!\n ): MutationResponse\n @validateAdminUserAccess(adminPermission: \"B2B_ORGANIZATIONS_EDIT\")\n @cacheControl(scope: PRIVATE)\n\n updateUser(\n id: ID\n roleId: ID!\n userId: ID\n orgId: ID\n costId: ID\n clId: ID\n canImpersonate: Boolean = false\n email: String\n name: String\n ): MutationResponse\n @validateAdminUserAccess(adminPermission: \"B2B_ORGANIZATIONS_EDIT\")\n @cacheControl(scope: PRIVATE)\n\n addUser(\n id: ID\n roleId: ID!\n userId: ID\n orgId: ID\n costId: ID\n canImpersonate: Boolean = false\n name: String!\n email: String!\n ): MutationResponse\n @validateAdminUserAccess(adminPermission: \"B2B_ORGANIZATIONS_EDIT\")\n @cacheControl(scope: PRIVATE)\n\n addCostCenterToUser(costId: ID!, userId: ID!): MutationResponse\n @validateStoreUserAccess\n @cacheControl(scope: PRIVATE)\n\n addOrganizationToUser(\n orgId: ID!\n userId: ID!\n costId: ID!\n roleId: ID\n ): MutationResponse\n @validateAdminUserAccess(adminPermission: \"B2B_ORGANIZATIONS_EDIT\")\n @cacheControl(scope: PRIVATE)\n\n setActiveUserByOrganization(userId: ID): MutationResponse\n @validateStoreUserAccess\n @cacheControl(scope: PRIVATE)\n\n impersonateUser(userId: ID): MutationResponse\n @validateStoreUserAccess\n @cacheControl(scope: PRIVATE)\n\n deleteUser(id: ID!, userId: ID, email: String!): MutationResponse\n @validateAdminUserAccess(adminPermission: \"B2B_ORGANIZATIONS_EDIT\")\n @cacheControl(scope: PRIVATE)\n\n setCurrentOrganization(orgId: ID!, costId: ID!): MutationResponse\n @withSession\n @cacheControl(scope: PRIVATE)\n @withSender\n\n ignoreB2BSessionData(enabled: Boolean!): MutationResponse\n @withSession\n @cacheControl(scope: PRIVATE)\n\n setCurrentPriceTable(priceTable: String): MutationResponse\n @withSession\n @cacheControl(scope: PRIVATE)\n @withSender\n @validateStoreUserAccess\n}\n\ntype UserImpersonation {\n firstName: String\n lastName: String\n email: String\n userId: ID\n error: String\n}\n\ntype UserPermissions {\n role: SimpleRole\n permissions: [String]\n}\n\ntype Pagination {\n page: Int\n pageSize: Int\n total: Int\n}\n\ntype UserPagination {\n data: [User]\n pagination: Pagination\n}\n\ntype User {\n id: ID\n roleId: ID\n userId: ID\n clId: ID\n orgId: ID\n costId: ID\n name: String!\n email: String!\n canImpersonate: Boolean\n active: Boolean\n selectedPriceTable: String\n}\n\ntype Organization {\n id: ID\n clId: ID\n costId: ID\n orgId: ID\n roleId: ID\n}\n\ntype OrganizationPaginated {\n data: [Organization]\n pagination: Pagination\n}\n\ntype Profile {\n id: ID\n name: String\n features: [Feature]!\n roleId: ID!\n scoped: Boolean\n}\n\ninput FeatureInput {\n module: String!\n features: [String]!\n}\n\ntype FeatureType {\n module: String!\n features: [String]!\n}\n\ntype FullFeature {\n module: String!\n name: String!\n features: [SingleFeature]!\n}\n\ntype Feature {\n module: String!\n name: String!\n features: [String]!\n}\n\ntype SingleFeature {\n label: String!\n value: String!\n}\n\ntype Role {\n id: ID\n name: String!\n locked: Boolean\n slug: String\n features: [FeatureType]\n}\n\ntype SimpleRole {\n id: ID\n name: String!\n slug: String\n}\n\ntype MutationResponse {\n id: String\n status: String\n message: String\n}\n\ntype SettingsResponse {\n adminSetup: Data\n}\n\nscalar Data\n\n```" } ]
code_storefront-permissions_accc6bf6
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/graphql/directives.graphql from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```graphql\ndirective @checkUserAccess on FIELD | FIELD_DEFINITION\ndirective @validateStoreUserAccess(\n adminPermission: String\n) on FIELD | FIELD_DEFINITION\ndirective @checkAdminAccess on FIELD | FIELD_DEFINITION\ndirective @validateAdminUserAccess(\n adminPermission: String\n) on FIELD | FIELD_DEFINITION\ndirective @withSession on FIELD_DEFINITION\ndirective @withSender on FIELD_DEFINITION\ndirective @withUserPermissions on FIELD_DEFINITION\ndirective @auditAccess on FIELD | FIELD_DEFINITION\n\n```" } ]
code_storefront-permissions_7a6fdaf8
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/service.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"stack\": \"nodejs\",\n \"memory\": 256,\n \"ttl\": 60,\n \"timeout\": 45,\n \"cpu\": {\n \"type\": \"shared\",\n \"value\": 5,\n \"scalingPercentage\": 20\n },\n \"minReplicas\": 8,\n \"maxReplicas\": 80,\n \"workers\": 1,\n \"routes\": {\n \"setProfile\": {\n \"path\": \"/_v/storefront-permissions/session/transform\",\n \"public\": true\n },\n \"checkPermissions\": {\n \"path\": \"/_v/storefront-permissions/check-permissions\",\n \"public\": false\n }\n }\n}\n\n```" } ]
code_storefront-permissions_5f952cf9
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typings.d.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface ReqContext {\n account: string\n workspace: string\n authToken: string\n region: string\n production: boolean\n userAgent: string\n}\n\ninterface Logger {\n log(\n content: string,\n level: LogLevel,\n details?: Record<string, unknown>\n ): PromiseLike<void>\n}\n\ninterface OperationState {\n orderFormId: string\n ctx: ReqContext\n data?: OperationData\n logger: Logger\n}\n\ninterface OperationData {\n orderForm?: any\n userProfileId: string\n cookie: string\n}\n\ntype ProcessPaymentStep = (\n state: OperationState,\n next: () => Promise<void>\n) => Promise<void>\n\ntype LogLevel = 'info' | 'error' | 'warning'\n\ntype Timings = { [middleware: string]: [number, number] }\n\ndeclare module '*.json' {\n const value: any\n export default value\n}\n\ninterface RegionsResponse {\n id: string\n sellers: Sellers[]\n}\n\n```" } ]
code_storefront-permissions_eec79649
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/package.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"vtex.checkout-ui-custom\",\n \"version\": \"3.2.1\",\n \"dependencies\": {\n \"@vtex/api\": \"6.50.1\",\n \"atob\": \"^2.1.2\",\n \"co-body\": \"^6.0.0\",\n \"cookie\": \"^0.3.1\",\n \"graphql\": \"^14.5.0\",\n \"graphql-tools\": \"^4.0.6\",\n \"qs\": \"^6.9.4\",\n \"ramda\": \"^0.25.0\",\n \"slugify\": \"^1.2.6\"\n },\n \"devDependencies\": {\n \"@types/atob\": \"^2.1.2\",\n \"@types/bluebird\": \"^3.5.25\",\n \"@types/co-body\": \"0.0.3\",\n \"@types/cookie\": \"^0.3.2\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jsonwebtoken\": \"^8.5.0\",\n \"@types/node\": \"^12.0.0\",\n \"@types/ramda\": \"types/npm-ramda#dist\",\n \"@vtex/api\": \"6.50.1\",\n \"@vtex/prettier-config\": \"^0.3.1\",\n \"tslint\": \"^5.12.0\",\n \"tslint-config-prettier\": \"^1.18.0\",\n \"tslint-config-vtex\": \"^2.1.0\",\n \"typescript\": \"3.9.7\",\n \"vtex.graphql-server\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.graphql-server@1.67.6/public/_types/react\",\n \"vtex.profile-session\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.profile-session@0.8.5/public/_types/react\",\n \"vtex.search-session\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.search-session@0.2.10/public/_types/react\",\n \"vtex.storefront-permissions\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.storefront-permissions@1.29.8/public/@types/vtex.storefront-permissions\",\n \"vtex.styleguide\": \"http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.3/public/@types/vtex.styleguide\"\n },\n \"scripts\": {\n \"lint\": \"tsc --noEmit && tslint -c tslint.json './**/*.ts'\"\n }\n}\n\n```" } ]
code_storefront-permissions_f8d08fe1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/index.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 {\n ClientsConfig,\n ServiceContext,\n ParamsContext,\n RecorderState,\n EventContext,\n IOContext,\n SegmentData,\n} from '@vtex/api'\nimport { method, Service, AuthType, LRUCache } from '@vtex/api'\n\nimport { schemaDirectives } from './directives'\nimport { Clients } from './clients'\nimport { resolvers } from './resolvers'\n\nconst TIMEOUT_MS = 5000\n\nconst defaultClientOptions = {\n retries: 1,\n timeout: TIMEOUT_MS,\n}\n\nconst memoryCache = new LRUCache<string, any>({ max: 1000 })\n\nconst clients: ClientsConfig<Clients> = {\n implementation: Clients,\n options: {\n default: defaultClientOptions,\n settings: {\n memoryCache,\n },\n b2bAdmin: {\n authType: AuthType.bearer,\n memoryCache,\n },\n },\n}\n\ndeclare global {\n type Context = ServiceContext<Clients>\n interface CustomIOContext extends IOContext {\n currentProfile: CurrentProfile\n segment?: SegmentData\n orderFormId?: string\n }\n\n interface CurrentProfile {\n email: string\n userId: string\n }\n interface StatusChangeContext extends EventContext<Clients> {\n body: {\n domain: string\n orderId: string\n currentState: string\n lastState: string\n currentChangeDate: string\n lastChangeDate: string\n }\n }\n\n interface State {\n code: number\n }\n}\n\nexport default new Service<Clients, RecorderState, ParamsContext>({\n clients,\n graphql: {\n resolvers: {\n Mutation: resolvers.Mutation,\n Query: resolvers.Query,\n },\n schemaDirectives,\n },\n routes: {\n checkPermissions: method({\n GET: resolvers.Routes.checkPermissions,\n }),\n setProfile: method({\n POST: resolvers.Routes.setProfile,\n }),\n },\n})\n\n```" } ]
code_storefront-permissions_ec372826
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/mdSchema.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport default [\n {\n name: 'b2b_roles',\n version: 'v0.0.3',\n body: {\n properties: {\n name: {\n type: 'string',\n title: 'Role Name',\n },\n slug: {\n type: ['null', 'string'],\n title: 'Role Slug',\n },\n locked: {\n type: ['null', 'boolean'],\n title: 'Can delete',\n default: false,\n },\n features: {\n type: 'array',\n items: {\n type: 'object',\n },\n title: 'Features',\n },\n },\n 'v-indexed': ['name', 'slug'],\n 'v-cache': false,\n },\n },\n {\n name: 'b2b_profiles',\n version: 'v0.0.2',\n body: {\n properties: {\n roleId: {\n type: 'string',\n title: 'Role ID',\n },\n features: {\n type: 'array',\n items: {\n type: 'string',\n },\n title: 'Features',\n },\n },\n 'v-indexed': ['roleId'],\n 'v-cache': false,\n },\n },\n {\n name: 'b2b_users',\n version: 'v0.1.2',\n body: {\n properties: {\n roleId: {\n type: 'string',\n title: 'Role ID',\n },\n name: {\n type: 'string',\n title: 'Name',\n },\n email: {\n type: 'string',\n title: 'Email',\n },\n userId: {\n type: ['null', 'string'],\n title: 'User ID',\n },\n clId: {\n type: ['null', 'string'],\n title: 'CL ID',\n },\n orgId: {\n type: ['null', 'string'],\n title: 'Organization ID',\n },\n costId: {\n type: ['null', 'string'],\n title: 'Cost Center ID',\n },\n canImpersonate: {\n type: 'boolean',\n title: 'Can impersonate',\n },\n active: {\n type: 'boolean',\n title: 'Current Profile active',\n },\n selectedPriceTable: {\n type: ['null', 'string'],\n title: 'Selected Price Table',\n },\n },\n 'v-immediate-indexing': true,\n 'v-indexed': [\n 'userId',\n 'clId',\n 'roleId',\n 'orgId',\n 'costId',\n 'email',\n 'canImpersonate',\n 'active',\n 'selectedPriceTable',\n ],\n 'v-cache': false,\n },\n },\n]\n\n```" } ]
code_storefront-permissions_7e234151
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/roleNames.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nconst roleNames: any = {\n 'en-US': {\n 'customer-admin': 'Organization Admin',\n 'customer-approver': 'Organization Approver',\n 'customer-buyer': 'Organization Buyer',\n 'sales-admin': 'Sales Admin',\n 'sales-manager': 'Sales Manager',\n 'sales-representative': 'Sales Representative',\n 'store-admin': 'Store Admin',\n },\n}\n\nexport default roleNames\n\n```" } ]
code_storefront-permissions_481734c1
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/public/metadata/messages/es-AR.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Admin\",\n \"headline\": \"B2B Admin\",\n \"overview\": \"B2B Admin\",\n \"features\": [\"B2B Admin\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_storefront-permissions_615b813f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/public/metadata/messages/pt-BR.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Admin\",\n \"headline\": \"B2B Admin\",\n \"overview\": \"B2B Admin\",\n \"features\": [\"B2B Admin\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_storefront-permissions_411e19cd
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/public/metadata/messages/en-US.json from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```json\n{\n \"name\": \"B2B Admin\",\n \"headline\": \"B2B Admin\",\n \"overview\": \"B2B Admin\",\n \"features\": [\"B2B Admin\"],\n \"websiteURL\": \"https://vtex.com/\",\n \"support\": {\n \"url\": \"https://support.vtex.com/hc/requests\"\n }\n}\n\n```" } ]
code_storefront-permissions_a6732677
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/auditAccess.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport sendAuthMetric, { AuthMetric } from '../metrics/auth'\n\nexport class AuditAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n this.sendAuthMetric(field, context)\n\n return resolve(root, args, context, info)\n }\n }\n\n private async sendAuthMetric(field: GraphQLField<any, any>, context: any) {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, account, logger },\n request,\n } = context\n\n const operation = field.astNode?.name?.value ?? request.url\n const userAgent = request.headers['user-agent'] as string\n const forwardedHost = request.headers['x-forwarded-host'] as string\n const caller =\n context.vtex.sender ?? (request.headers['x-vtex-caller'] as string)\n\n const hasAdminToken = !!(\n adminUserAuthToken ?? (context?.headers.vtexidclientautcookie as string)\n )\n\n const hasStoreToken = !!storeUserAuthToken\n const hasApiToken = !!request.headers['vtex-api-apptoken']\n\n const authMetric = new AuthMetric(account, {\n caller,\n userAgent,\n forwardedHost,\n hasAdminToken,\n hasApiToken,\n hasStoreToken,\n operation,\n })\n\n await sendAuthMetric(logger, authMetric)\n }\n}\n\n```" } ]
code_storefront-permissions_748f05ab
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/checkUserAccess.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport sendAuthMetric, { AuthMetric } from '../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n validateStoreToken,\n} from './helper'\n\nexport class CheckUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n // now we emit a metric with all the collected data before we proceed\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n const metricFields = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken, hasCurrentValidAdminToken } =\n await validateAdminToken(\n context,\n adminUserAuthToken as string,\n metricFields\n )\n\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasCurrentValidAdminTokenOnHeader,\n } = await validateAdminTokenOnHeader(context, metricFields)\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(\n context,\n metricFields\n )\n\n const { hasStoreToken, hasValidStoreToken, hasCurrentValidStoreToken } =\n await validateStoreToken(context, storeUserAuthToken as string)\n\n const auditMetric = new AuthMetric(\n context?.vtex?.account,\n {\n operation,\n forwardedHost,\n caller,\n userAgent,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasCurrentValidStoreToken,\n hasValidStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n },\n 'CheckUserAccessAudit'\n )\n\n sendAuthMetric(logger, auditMetric)\n\n if (\n !hasAdminToken &&\n !hasApiToken &&\n !hasStoreToken &&\n !hasAdminTokenOnHeader\n ) {\n logger.warn({\n message: 'CheckUserAccess: No token provided',\n userAgent,\n caller,\n forwardedHost,\n operation,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n if (\n !hasCurrentValidAdminToken &&\n !hasValidApiToken &&\n !hasCurrentValidStoreToken &&\n !hasCurrentValidAdminTokenOnHeader\n ) {\n logger.warn({\n message: `CheckUserAccess: Invalid token`,\n userAgent,\n caller,\n forwardedHost,\n operation,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasCurrentValidStoreToken,\n hasValidStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```" } ]
code_storefront-permissions_68992e27
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/withSender.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable max-params */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nexport class WithSender extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n context.vtex.sender =\n context?.graphql?.query?.senderApp ??\n context?.graphql?.query?.extensions?.persistedQuery?.sender ??\n context?.request?.header['x-b2b-senderapp'] ??\n null\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```" } ]
code_storefront-permissions_ae86f90f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/helper.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { isUserPartOfBuyerOrg } from '../resolvers/Queries/Users'\nimport { LICENSE_MANAGER_ROLES, B2B_LM_PRODUCT_CODE } from '../utils/constants'\n\nexport const validateAdminToken = async (\n context: Context,\n adminUserAuthToken: string,\n metricFields: any = {},\n requiredRole: string = LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n): Promise<{\n hasAdminToken: boolean\n hasValidAdminToken: boolean\n hasCurrentValidAdminToken: boolean\n hasValidAdminRole: boolean\n}> => {\n const {\n clients: { identity, lm },\n vtex: { account, logger },\n } = context\n\n // check if has admin token and if it is valid\n const hasAdminToken = !!adminUserAuthToken\n let hasValidAdminToken = false\n // this is used to check if the token is valid by current standards\n let hasCurrentValidAdminToken = false\n let hasValidAdminRole = false\n\n if (hasAdminToken) {\n try {\n const authUser = await identity.validateToken({\n token: adminUserAuthToken,\n })\n\n // we set this flag to true if the token is valid by current standards\n // in the future we should remove this line\n hasCurrentValidAdminToken = true\n\n if (\n authUser?.audience === 'admin' &&\n authUser &&\n authUser.account !== account\n ) {\n logger.warn({\n message: 'validateAdminToken: Token from another account',\n ...metricFields,\n authUserAccount: authUser.account,\n account,\n user: authUser.user,\n })\n }\n\n if (authUser?.audience === 'admin' && authUser?.account === account) {\n const hasAdminPermissions = await lm.getUserAdminPermissions(\n account,\n authUser.id\n )\n\n // Check for specific role using the new endpoint\n const roleCheckResponse = await lm.checkUserSpecificRole(\n account,\n authUser.id,\n B2B_LM_PRODUCT_CODE,\n requiredRole\n )\n\n hasValidAdminRole = !!roleCheckResponse\n\n // Only set hasValidAdminToken to true if BOTH admin permissions AND role are valid\n hasValidAdminToken = hasAdminPermissions && hasValidAdminRole\n }\n } catch (err) {\n // noop so we leave hasValidAdminToken as false\n logger.warn({\n message: 'Error validating admin token',\n err,\n })\n }\n }\n\n return {\n hasAdminToken,\n hasValidAdminToken,\n hasCurrentValidAdminToken,\n hasValidAdminRole,\n }\n}\n\nexport const validateApiToken = async (\n context: Context,\n metricFields: any = {},\n requiredRole: string = LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n): Promise<{\n hasApiToken: boolean\n hasValidApiToken: boolean\n hasValidApiRole: boolean\n}> => {\n const {\n clients: { identity, lm },\n vtex: { account, logger },\n } = context\n\n // check if has api token and if it is valid\n const apiToken = context?.headers['vtex-api-apptoken'] as string\n const appKey = context?.headers['vtex-api-appkey'] as string\n const hasApiToken = !!(apiToken?.length && appKey?.length)\n let hasValidApiToken = false\n\n let hasValidApiRole = false\n\n if (hasApiToken) {\n try {\n const { token } = await identity.getToken({\n appkey: appKey,\n apptoken: apiToken,\n })\n\n const authUser = await identity.validateToken({\n token,\n })\n\n // keeping this behavior for now, but we should remove it in the future as well\n context.cookies.set('VtexIdclientAutCookie', token)\n context.vtex.adminUserAuthToken = token\n\n if (\n authUser?.audience === 'admin' &&\n authUser &&\n authUser.account !== account\n ) {\n logger.warn({\n message: 'validateApiToken: Token from another account',\n ...metricFields,\n authUserAccount: authUser.account,\n account,\n user: authUser.user,\n })\n }\n\n if (authUser?.audience === 'admin' && authUser?.account === account) {\n const hasAdminPermissions = await lm.getUserAdminPermissions(\n account,\n authUser.id\n )\n\n // Check for specific role using the new endpoint\n const roleCheckResponse = await lm.checkUserSpecificRole(\n account,\n authUser.id,\n B2B_LM_PRODUCT_CODE,\n requiredRole\n )\n\n hasValidApiRole = !!roleCheckResponse\n\n // Only set hasValidApiToken to true if BOTH admin permissions AND role are valid\n hasValidApiToken = hasAdminPermissions && hasValidApiRole\n }\n } catch (err) {\n // noop so we leave hasValidApiToken as false\n logger.warn({\n message: 'Error validating API token',\n err,\n })\n }\n }\n\n return {\n hasApiToken,\n hasValidApiToken,\n hasValidApiRole,\n }\n}\n\nexport const validateStoreToken = async (\n context: Context,\n storeUserAuthToken: string\n): Promise<{\n hasStoreToken: boolean\n hasValidStoreToken: boolean\n hasCurrentValidStoreToken: boolean\n}> => {\n const {\n clients: { vtexId },\n vtex: { logger },\n } = context\n\n // check if has store token and if it is valid\n const hasStoreToken = !!storeUserAuthToken\n let hasValidStoreToken = false\n // this is used to check if the token is valid by current standards\n let hasCurrentValidStoreToken = false\n\n if (hasStoreToken) {\n try {\n const authUser = await vtexId.getAuthenticatedUser(storeUserAuthToken)\n\n if (authUser?.user) {\n // we set this flag to true if the token is valid by current standards\n // in the future we should remove this line\n hasCurrentValidStoreToken = true\n\n const userIsPartOfBuyerOrg = await isUserPartOfBuyerOrg(\n authUser?.user,\n context\n )\n\n if (userIsPartOfBuyerOrg) {\n hasValidStoreToken = true\n }\n }\n } catch (err) {\n // noop so we leave hasValidStoreToken as false\n logger.warn({\n message: 'Error validating store token:',\n err,\n })\n }\n }\n\n return { hasStoreToken, hasValidStoreToken, hasCurrentValidStoreToken }\n}\n\nexport const validateAdminTokenOnHeader = async (\n context: Context,\n metricFields: any = {},\n requiredRole: string = LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n): Promise<{\n hasAdminTokenOnHeader: boolean\n hasValidAdminTokenOnHeader: boolean\n hasCurrentValidAdminTokenOnHeader: boolean\n hasValidAdminRoleOnHeader: boolean\n}> => {\n const adminUserAuthToken = context?.headers.vtexidclientautcookie as string\n const hasAdminTokenOnHeader = !!adminUserAuthToken?.length\n\n if (!hasAdminTokenOnHeader) {\n return {\n hasAdminTokenOnHeader: false,\n hasValidAdminTokenOnHeader: false,\n hasCurrentValidAdminTokenOnHeader: false,\n hasValidAdminRoleOnHeader: false,\n }\n }\n\n const {\n hasAdminToken,\n hasCurrentValidAdminToken,\n hasValidAdminToken,\n hasValidAdminRole,\n } = await validateAdminToken(\n context,\n adminUserAuthToken,\n metricFields,\n requiredRole\n )\n\n return {\n hasAdminTokenOnHeader: hasAdminToken,\n hasValidAdminTokenOnHeader: hasValidAdminToken,\n hasCurrentValidAdminTokenOnHeader: hasCurrentValidAdminToken,\n hasValidAdminRoleOnHeader: hasValidAdminRole,\n }\n}\n\n```" } ]
code_storefront-permissions_d31001fe
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/validateAdminUserAccess.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport type { AuthAuditMetric } from '../metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n} from './helper'\nimport { LICENSE_MANAGER_ROLES } from '../utils/constants'\n\nexport class ValidateAdminUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n const { adminPermission } = this.args\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, logger },\n } = context\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n // Choose role based on parameter\n const requiredRole =\n adminPermission === 'B2B_ORGANIZATIONS_EDIT'\n ? LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_EDIT\n : LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n\n const { hasAdminToken, hasValidAdminToken } = await validateAdminToken(\n context,\n adminUserAuthToken as string,\n metricFields,\n requiredRole\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminToken) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const { hasAdminTokenOnHeader, hasValidAdminTokenOnHeader } =\n await validateAdminTokenOnHeader(context, metricFields, requiredRole)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminTokenOnHeader) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(\n context,\n metricFields,\n requiredRole\n )\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n }\n\n // allow access if has valid API token\n if (hasValidApiToken) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateAdminUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasAdminTokenOnHeader && !hasApiToken) {\n logger.warn({\n message: 'ValidateAdminUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided\n logger.warn({\n message: 'ValidateAdminUserAccess: Invalid token',\n ...metricFields,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n }\n}\n\n```" } ]
code_storefront-permissions_f52a519b
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/validateStoreUserAccess.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport type { AuthAuditMetric } from '../metrics/auth'\nimport sendAuthMetric, { AuthMetric } from '../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n validateStoreToken,\n} from './helper'\nimport { LICENSE_MANAGER_ROLES } from '../utils/constants'\n\nexport class ValidateStoreUserAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n const { adminPermission } = this.args\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n // get metrics data\n const operation = field?.astNode?.name?.value ?? context?.request?.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n // set metric fields with initial data\n let metricFields: AuthAuditMetric = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n // Choose role based on parameter\n const requiredRole =\n adminPermission === 'B2B_ORGANIZATIONS_EDIT'\n ? LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_EDIT\n : LICENSE_MANAGER_ROLES.B2B_ORGANIZATIONS_VIEW\n\n const { hasAdminToken, hasValidAdminToken } = await validateAdminToken(\n context,\n adminUserAuthToken as string,\n metricFields,\n requiredRole\n )\n\n // add admin token metrics\n metricFields = {\n ...metricFields,\n hasAdminToken,\n hasValidAdminToken,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminToken) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // If there's no valid admin token on context, search for it on header\n const { hasAdminTokenOnHeader, hasValidAdminTokenOnHeader } =\n await validateAdminTokenOnHeader(context, metricFields, requiredRole)\n\n // add admin header token metrics\n metricFields = {\n ...metricFields,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n }\n\n // allow access if has valid admin token\n if (hasValidAdminTokenOnHeader) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(\n context,\n metricFields,\n requiredRole\n )\n\n // add API token metrics\n metricFields = {\n ...metricFields,\n hasApiToken,\n hasValidApiToken,\n }\n\n // allow access if has valid API token\n if (hasValidApiToken) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n const { hasStoreToken, hasValidStoreToken } = await validateStoreToken(\n context,\n storeUserAuthToken as string\n )\n\n // add store token metrics\n metricFields = {\n ...metricFields,\n hasStoreToken,\n hasValidStoreToken,\n }\n\n // allow access if has valid store token\n if (hasValidStoreToken) {\n sendAuthMetric(\n logger,\n new AuthMetric(\n context?.vtex?.account,\n metricFields,\n 'ValidateStoreUserAccessAudit'\n )\n )\n\n return resolve(root, args, context, info)\n }\n\n // deny access if no tokens were provided\n if (!hasAdminToken && !hasApiToken && !hasStoreToken) {\n logger.warn({\n message: 'ValidateStoreUserAccess: No token provided',\n ...metricFields,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n // deny access if no valid tokens were provided\n logger.warn({\n message: `ValidateStoreUserAccess: Invalid token`,\n ...metricFields,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n }\n}\n\n```" } ]
code_storefront-permissions_0beabf3a
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/checkAdminAccess.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\nimport { AuthenticationError, ForbiddenError } from '@vtex/api'\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\n\nimport sendAuthMetric, { AuthMetric } from '../metrics/auth'\nimport {\n validateAdminToken,\n validateAdminTokenOnHeader,\n validateApiToken,\n} from './helper'\n\nexport class CheckAdminAccess extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (\n root: any,\n args: any,\n context: Context,\n info: any\n ) => {\n const {\n vtex: { adminUserAuthToken, storeUserAuthToken, logger },\n } = context\n\n // now we emit a metric with all the collected data before we proceed\n const operation = field.astNode?.name?.value ?? context.request.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n const metricFields = {\n operation,\n forwardedHost,\n caller,\n userAgent,\n }\n\n const { hasAdminToken, hasValidAdminToken, hasCurrentValidAdminToken } =\n await validateAdminToken(\n context,\n adminUserAuthToken as string,\n metricFields\n )\n\n const {\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n hasCurrentValidAdminTokenOnHeader,\n } = await validateAdminTokenOnHeader(context, metricFields)\n\n const { hasApiToken, hasValidApiToken } = await validateApiToken(\n context,\n metricFields\n )\n\n const hasStoreToken = !!storeUserAuthToken // we don't need to validate store token\n\n const auditMetric = new AuthMetric(\n context?.vtex?.account,\n {\n operation,\n forwardedHost,\n caller,\n userAgent,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n },\n 'CheckAdminAccessAudit'\n )\n\n sendAuthMetric(logger, auditMetric)\n\n if (!hasAdminToken && !hasApiToken && !hasAdminTokenOnHeader) {\n logger.warn({\n message: 'CheckAdminAccess: No token provided',\n userAgent,\n caller,\n forwardedHost,\n operation,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n })\n throw new AuthenticationError('No token was provided')\n }\n\n if (\n !hasCurrentValidAdminToken &&\n !hasValidApiToken &&\n !hasCurrentValidAdminTokenOnHeader\n ) {\n logger.warn({\n message: 'CheckAdminAccess: Invalid token',\n userAgent,\n caller,\n forwardedHost,\n operation,\n hasAdminToken,\n hasValidAdminToken,\n hasApiToken,\n hasValidApiToken,\n hasStoreToken,\n hasAdminTokenOnHeader,\n hasValidAdminTokenOnHeader,\n })\n throw new ForbiddenError('Unauthorized Access')\n }\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```" } ]
code_storefront-permissions_4b5335ee
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/index.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport { WithSession } from './withSession'\nimport { WithSender } from './withSender'\nimport { WithUserPermissions } from './withUserPermissions'\nimport { CheckAdminAccess } from './checkAdminAccess'\nimport { CheckUserAccess } from './checkUserAccess'\nimport { ValidateAdminUserAccess } from './validateAdminUserAccess'\nimport { ValidateStoreUserAccess } from './validateStoreUserAccess'\nimport { AuditAccess } from './auditAccess'\n\nexport const schemaDirectives = {\n checkAdminAccess: CheckAdminAccess as any,\n checkUserAccess: CheckUserAccess as any,\n validateAdminUserAccess: ValidateAdminUserAccess as any,\n validateStoreUserAccess: ValidateStoreUserAccess as any,\n withSession: WithSession,\n withSender: WithSender,\n withUserPermissions: WithUserPermissions,\n auditAccess: AuditAccess as any,\n}\n\n```" } ]
code_storefront-permissions_7a2c2ef2
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/withSession.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 */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport sendSessionMetric, { SessionMetric } from '../metrics/session'\n\nexport class WithSession extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { session, logger },\n } = context\n\n const token =\n context.vtex.sessionToken ?? context.request.header?.sessiontoken\n\n context.vtex.sessionData = await session\n .getSession(token as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch(() => null)\n\n // we emit a metric for cases where the sessionData is null\n // so we can identify use cases that are supposed to have sessionData\n // but do not have it. We currently have a high volume of logs generated\n // by such cases, so we need to identify and fix them.\n const operation = field.astNode?.name?.value ?? context.request.url\n const userAgent = context?.request?.headers['user-agent'] as string\n const caller = context?.request?.headers['x-vtex-caller'] as string\n const forwardedHost = context?.request?.headers[\n 'x-forwarded-host'\n ] as string\n\n const hasSessionToken = !!context.vtex.sessionToken\n const hasSessionTokenOnHeader = !!context.request.header?.sessiontoken\n const hasSessionData = !!context.vtex.sessionData\n\n const auditMetric = new SessionMetric(context?.vtex?.account, {\n operation,\n forwardedHost,\n caller,\n userAgent,\n hasSessionToken,\n hasSessionTokenOnHeader,\n hasSessionData,\n })\n\n sendSessionMetric(logger, auditMetric)\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```" } ]
code_storefront-permissions_be4ba736
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/directives/withUserPermissions.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 */\n/* eslint-disable max-params */\nimport type { GraphQLField } from 'graphql'\nimport { defaultFieldResolver } from 'graphql'\nimport { SchemaDirectiveVisitor } from 'graphql-tools'\n\nimport { checkUserPermission } from '../resolvers/Queries/Users'\n\nexport class WithUserPermissions extends SchemaDirectiveVisitor {\n public visitFieldDefinition(field: GraphQLField<any, any>) {\n const { resolve = defaultFieldResolver } = field\n\n field.resolve = async (root: any, args: any, context: any, info: any) => {\n const {\n clients: { session },\n } = context\n\n context.vtex.sender = context?.graphql?.query?.senderApp ?? null\n context.vtex.sessionData = await session\n .getSession(context.vtex.sessionToken as string, ['*'])\n .then((currentSession: any) => {\n return currentSession.sessionData\n })\n .catch(() => null)\n\n context.vtex.userPermissions = await checkUserPermission(\n null,\n { skipError: true },\n context\n )\n\n return resolve(root, args, context, info)\n }\n }\n}\n\n```" } ]
code_storefront-permissions_de518657
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/metrics/session.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api/lib/service/logger/logger'\n\nimport type { Metric } from '../clients/metrics'\nimport { B2B_METRIC_NAME, sendMetric } from '../clients/metrics'\n\nexport interface SessionAuditMetric {\n operation: string\n forwardedHost: string\n caller: string\n userAgent: string\n hasSessionToken: boolean\n hasSessionTokenOnHeader: boolean\n hasSessionData: boolean\n}\n\nexport class SessionMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: SessionAuditMetric\n public readonly name = B2B_METRIC_NAME\n public error?: string\n\n constructor(account: string, fields: SessionAuditMetric) {\n this.account = account\n this.fields = fields\n this.kind = 'b2b-storefront-permissions-session-event'\n this.description = 'Session metric event'\n }\n}\n\nconst sendSessionMetric = async (\n logger: Logger,\n sessionMetric: SessionMetric\n) => {\n try {\n await sendMetric(sessionMetric)\n } catch (error) {\n logger.error({\n error,\n message: `Error to send metrics from session metric`,\n })\n }\n}\n\nexport default sendSessionMetric\n\n```" } ]
code_storefront-permissions_71e2389f
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/metrics/auth.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { Logger } from '@vtex/api/lib/service/logger/logger'\n\nimport type { Metric } from '../clients/metrics'\nimport { B2B_METRIC_NAME, sendMetric } from '../clients/metrics'\n\nexport interface AuthAuditMetric {\n operation: string\n forwardedHost: string\n caller: string\n userAgent: string\n role?: string\n permissions?: string[]\n hasAdminToken?: boolean\n hasValidAdminToken?: boolean\n hasStoreToken?: boolean\n hasCurrentValidStoreToken?: boolean\n hasValidStoreToken?: boolean\n hasApiToken?: boolean\n hasValidApiToken?: boolean\n hasAdminTokenOnHeader?: boolean\n hasValidAdminTokenOnHeader?: boolean\n}\n\nexport class AuthMetric implements Metric {\n public readonly description: string\n public readonly kind: string\n public readonly account: string\n public readonly fields: AuthAuditMetric\n public readonly name = B2B_METRIC_NAME\n public error?: string\n\n constructor(account: string, fields: AuthAuditMetric, description?: string) {\n this.account = account\n this.fields = fields\n this.kind = 'b2b-storefront-permissions-auth-event'\n this.description = description ?? 'Auth metric event'\n }\n}\n\nconst sendAuthMetric = async (logger: Logger, authMetric: AuthMetric) => {\n try {\n await sendMetric(authMetric)\n } catch (error) {\n logger.error({\n error,\n message: `Error to send metrics from auth metric`,\n })\n }\n}\n\nexport default sendAuthMetric\n\n```" } ]
code_storefront-permissions_83406f16
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/schema.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nimport { getTokenToHeader } from './index'\n\nconst getRouteSchema = (dataEntity: string) =>\n `/api/dataentities/${dataEntity}/schemas`\n\nexport class Schema extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...getTokenToHeader(ctx),\n 'x-vtex-user-agent': ctx.userAgent,\n },\n })\n }\n\n public async getLatestSchema(entityName: string) {\n const schemas = await this.http.get(getRouteSchema(entityName))\n\n return schemas && schemas.length > 0 ? schemas[schemas.length - 1] : null\n }\n}\n\n```" } ]
code_storefront-permissions_00322a71
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/Organizations.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { GraphQLResponse, InstanceOptions, IOContext } from '@vtex/api'\nimport { AppGraphQLClient } from '@vtex/api'\n\nimport { QUERIES } from '../resolvers/Routes/utils'\nimport { getTokenToHeader } from './index'\nimport type {\n GetCostCenterType,\n GetOrganizationsByEmailResponse,\n GetOrganizationsPaginatedByEmailResponse,\n} from '../typings/custom'\n\nconst getPersistedQuery = () => {\n return {\n persistedQuery: {\n provider: 'vtex.b2b-organizations-graphql@2.x',\n sender: 'vtex.storefront-permissions@3.x',\n },\n }\n}\n\nexport class OrganizationsGraphQLClient extends AppGraphQLClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super('vtex.b2b-organizations-graphql@2.x', ctx, options)\n }\n\n public getOrganizationById = async (orgId: string): Promise<unknown> => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getOrganizationById,\n variables: {\n id: orgId,\n },\n })\n }\n\n public getB2BSettings = async (): Promise<unknown> => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getB2BSettings,\n variables: {},\n })\n }\n\n public getCostCenterById = async (costId: string) => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getCostCenterById,\n variables: {\n id: costId,\n },\n }) as Promise<GraphQLResponse<GetCostCenterType>>\n }\n\n public getMarketingTags = async (costId: string): Promise<unknown> => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getMarketingTags,\n variables: {\n costId,\n },\n })\n }\n\n public getOrganizationsByEmail = async (email: string) => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getOrganizationsByEmail,\n variables: { email },\n }) as Promise<GetOrganizationsByEmailResponse>\n }\n\n public getOrganizationsPaginatedByEmail = async (\n email: string,\n page: number,\n pageSize: number\n ) => {\n return this.query({\n extensions: getPersistedQuery(),\n query: QUERIES.getOrganizationsPaginatedByEmail,\n variables: {\n email,\n page,\n pageSize,\n },\n }) as Promise<{\n data: {\n getOrganizationsPaginatedByEmail: GetOrganizationsPaginatedByEmailResponse\n }\n }>\n }\n\n private query = async (param: {\n query: string\n variables: any\n extensions: any\n }) => {\n const { query, variables, extensions } = param\n\n return this.graphql.query(\n { query, variables, extensions },\n {\n headers: getTokenToHeader(this.context),\n params: {\n locale: this.context.locale,\n },\n }\n )\n }\n}\n\n```" } ]
code_storefront-permissions_00efb7ea
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/checkout.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/* eslint-disable max-params */\nimport type {\n InstanceOptions,\n IOContext,\n IOResponse,\n RequestConfig,\n} from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\nimport type { AxiosError } from 'axios'\n\nimport { checkoutCookieFormat, statusToError } from '../utils'\n\nexport class Checkout extends JanusClient {\n private get routes() {\n const base = '/api/checkout/pub'\n\n return {\n addItem: (orderFormId: string, queryString: string) =>\n `${base}/orderForm/${orderFormId}/items${queryString}`,\n cancelOrder: (orderFormId: string) =>\n `${base}/orders/${orderFormId}/user-cancel-request`,\n orderFormCustomData: (\n orderFormId: string,\n appId: string,\n field: string\n ) => `${base}/orderForm/${orderFormId}/customData/${appId}/${field}`,\n updateItems: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/items/update`,\n profile: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/profile`,\n attachmentsData: (orderFormId: string, field: string) =>\n `${base}/orderForm/${orderFormId}/attachments/${field}`,\n attachmentItem: (\n orderFormId: string,\n field: string,\n index: string | number\n ) =>\n `${base}/orderForm/${orderFormId}/items/${index}/attachments/${field}`,\n assemblyOptions: (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string\n ) =>\n `${base}/orderForm/${orderFormId}/items/${itemId}/assemblyOptions/${assemblyOptionsId}`,\n checkin: (orderFormId: string) =>\n `${base}/orderForm/${orderFormId}/checkIn`,\n orderForm: (orderFormId?: string) =>\n `${base}/orderForm/${orderFormId ?? ''}`,\n orders: `${base}/orders`,\n simulation: (queryString: string) =>\n `${base}/orderForms/simulation${queryString}`,\n changeToAnonymousUser: (orderFormId: string) =>\n `/checkout/changeToAnonymousUser/${orderFormId}`,\n }\n }\n\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n ...(ctx.storeUserAuthToken\n ? { VtexIdclientAutCookie: ctx.storeUserAuthToken }\n : { VtexIdclientAutCookie: ctx.authToken }),\n 'x-vtex-user-agent': ctx.userAgent,\n },\n })\n }\n\n public addItem = (orderFormId: string, items: any) =>\n this.post<OrderForm>(\n this.routes.addItem(orderFormId, this.getChannelQueryString()),\n { orderItems: items },\n { metric: 'checkout-addItem' }\n )\n\n public cancelOrder = (orderFormId: string, reason: string) =>\n this.post(\n this.routes.cancelOrder(orderFormId),\n { reason },\n { metric: 'checkout-cancelOrder' }\n )\n\n public setOrderFormCustomData = (\n orderFormId: string,\n appId: string,\n field: string,\n value: any\n ) =>\n this.put(\n this.routes.orderFormCustomData(orderFormId, appId, field),\n { value },\n { metric: 'checkout-setOrderFormCustomData' }\n )\n\n public updateItems = (orderFormId: string, orderItems: any) =>\n this.post(\n this.routes.updateItems(orderFormId),\n { orderItems },\n { metric: 'checkout-updateItems' }\n )\n\n public updateOrderFormIgnoreProfile = (\n orderFormId: string,\n ignoreProfileData: boolean\n ) =>\n this.patch(\n this.routes.profile(orderFormId),\n { ignoreProfileData },\n { metric: 'checkout-updateOrderFormIgnoreProfile' }\n )\n\n public updateOrderFormPayment = (orderFormId: string, payments: any) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'paymentData'),\n { payments },\n { metric: 'checkout-updateOrderFormPayment' }\n )\n\n public updateOrderFormProfile = (orderFormId: string, fields: any) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'clientProfileData'),\n fields,\n { metric: 'checkout-updateOrderFormProfile' }\n )\n\n public updateOrderFormShipping = (orderFormId: string, shipping: any) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'shippingData'),\n shipping,\n { metric: 'checkout-updateOrderFormShipping' }\n )\n\n public updateOrderFormMarketingData = (\n orderFormId: string,\n marketingData: any\n ) =>\n this.post(\n this.routes.attachmentsData(orderFormId, 'marketingData'),\n marketingData,\n { metric: 'checkout-updateOrderFormMarketingData' }\n )\n\n public async clearCart(orderFormId: string) {\n return this.post(\n `${this.routes.orderForm(orderFormId)}/items/removeAll`,\n {}\n )\n }\n\n public updateSalesChannel = async (\n orderFormId: string,\n salesChannel: any\n ) => {\n const orderForm = await this.get(this.routes.orderForm(orderFormId))\n\n const { items, salesChannel: sc }: any = orderForm\n\n if (String(salesChannel) !== String(sc) && items?.length) {\n await this.clearCart(orderFormId)\n\n await this.post(\n `${this.routes.orderForm(orderFormId)}/items?sc=${salesChannel}`,\n {\n orderItems: items.map((item: any) => ({\n id: item.id,\n index: item.index,\n price: item.price,\n quantity: item.quantity,\n seller: item.seller,\n })),\n }\n )\n\n // Check attachments\n const attachmentPromise: any[] = []\n\n items.forEach((item: { attachments: any[] }, index: string | number) => {\n if (item.attachments?.length) {\n item.attachments.forEach(\n (attachment: { name: string; content: any }) => {\n attachmentPromise.push(\n this.post(\n this.routes.attachmentItem(\n orderFormId,\n attachment.name,\n index\n ),\n {\n content: attachment.content,\n }\n )\n )\n }\n )\n }\n })\n if (attachmentPromise.length) {\n await Promise.all(attachmentPromise)\n }\n }\n\n return orderForm\n }\n\n public updateOrderFormClientPreferencesData = (\n orderFormId: string,\n clientPreferencesData: OrderFormClientPreferencesData\n ) => {\n // The API default value of `optinNewsLetter` is `null`, but it doesn't accept a POST with its value as `null`\n const filteredClientPreferencesData =\n clientPreferencesData.optinNewsLetter === null\n ? { locale: clientPreferencesData.locale }\n : clientPreferencesData\n\n return this.post(\n this.routes.attachmentsData(orderFormId, 'clientPreferencesData'),\n filteredClientPreferencesData,\n { metric: 'checkout-updateOrderFormClientPreferencesData' }\n )\n }\n\n public addAssemblyOptions = async (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string,\n body: any\n ) =>\n this.post<OrderForm>(\n this.routes.assemblyOptions(orderFormId, itemId, assemblyOptionsId),\n body,\n { metric: 'checkout-addAssemblyOptions' }\n )\n\n public removeAssemblyOptions = async (\n orderFormId: string,\n itemId: string | number,\n assemblyOptionsId: string,\n body: any\n ) =>\n this.delete<OrderForm>(\n this.routes.assemblyOptions(orderFormId, itemId, assemblyOptionsId),\n { metric: 'checkout-removeAssemblyOptions', data: body }\n )\n\n public updateOrderFormCheckin = (orderFormId: string, checkinPayload: any) =>\n this.post(this.routes.checkin(orderFormId), checkinPayload, {\n metric: 'checkout-updateOrderFormCheckin',\n })\n\n public orderForm = (orderFormId?: string) => {\n return this.get<OrderForm>(this.routes.orderForm(orderFormId), {\n metric: 'checkout-orderForm',\n })\n }\n\n public orderFormRaw = () => {\n return this.postRaw<OrderForm>(\n this.routes.orderForm(),\n { expectedOrderFormSections: ['items'] },\n { metric: 'checkout-orderForm' }\n )\n }\n\n public newOrderForm = (orderFormId?: string) => {\n return this.http\n .postRaw<OrderForm>(this.routes.orderForm(orderFormId), undefined, {\n metric: 'checkout-newOrderForm',\n })\n .catch(statusToError) as Promise<IOResponse<OrderForm>>\n }\n\n public changeToAnonymousUser = (orderFormId: string) => {\n return this.get(this.routes.changeToAnonymousUser(orderFormId), {\n metric: 'checkout-change-to-anonymous',\n }).catch((err) => {\n // This endpoint is expected to return a redirect to\n // the user, so we can ignore the error if it is a 3xx\n if (!err.response || /^3..$/.test((err as AxiosError).code ?? '')) {\n throw err\n }\n })\n }\n\n public orders = () =>\n this.get(this.routes.orders, { metric: 'checkout-orders' })\n\n public simulation = (simulation: SimulationPayload) =>\n this.post<SimulationOrderForm>(\n this.routes.simulation(this.getChannelQueryString()),\n simulation,\n {\n metric: 'checkout-simulation',\n }\n )\n\n public getRegionId = (\n country: string,\n postalCode: string | null,\n salesChannel: string,\n geoCoordinates: [number, number] | null\n ): Promise<RegionsResponse[]> => {\n const baseUrl = '/api/checkout/pub/regions'\n const params = new URLSearchParams({\n country,\n sc: salesChannel,\n })\n\n if (postalCode) {\n params.append('postalCode', postalCode)\n }\n\n if (geoCoordinates) {\n params.append('geoCoordinates', geoCoordinates.join(';'))\n }\n\n const url = `${baseUrl}?${params.toString()}`\n\n return this.get(url)\n }\n\n protected get = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.get<T>(url, config).catch(statusToError) as Promise<T>\n }\n\n protected post = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .post<T>(url, data, config)\n .catch(statusToError) as Promise<T>\n }\n\n protected postRaw = async <T>(\n url: string,\n data?: any,\n config: RequestConfig = {}\n ) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .postRaw<T>(url, data, config)\n .catch(statusToError) as Promise<IOResponse<T>>\n }\n\n protected delete = <T>(url: string, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http.delete<T>(url, config).catch(statusToError) as Promise<\n IOResponse<T>\n >\n }\n\n protected patch = <T>(\n url: string,\n data?: any,\n config: RequestConfig = {}\n ) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .patch<T>(url, data, config)\n .catch(statusToError) as Promise<T>\n }\n\n protected put = <T>(url: string, data?: any, config: RequestConfig = {}) => {\n config.headers = {\n ...config.headers,\n ...this.getCommonHeaders(),\n }\n\n return this.http\n .put<T>(url, data, config)\n .catch(statusToError) as Promise<T>\n }\n\n private getCommonHeaders = () => {\n const { orderFormId, segmentToken, sessionToken } = this\n .context as CustomIOContext\n\n const checkoutCookie = orderFormId ? checkoutCookieFormat(orderFormId) : ''\n const segmentTokenCookie = segmentToken\n ? `vtex_segment=${segmentToken};`\n : ''\n\n const sessionTokenCookie = sessionToken\n ? `vtex_session=${sessionToken};`\n : ''\n\n return {\n Cookie: `${checkoutCookie}${segmentTokenCookie}${sessionTokenCookie}`,\n }\n }\n\n private getChannelQueryString = () => {\n const { segment } = this.context as CustomIOContext\n const channel = segment?.channel\n const queryString = channel ? `?sc=${channel}` : ''\n\n return queryString\n }\n}\n\n```" } ]
code_storefront-permissions_3573134d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/vtexId.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\ninterface AuthenticatedUser {\n user: string\n}\n\nexport default class VtexId extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, { ...options })\n }\n\n public async getAuthenticatedUser(\n authToken: string\n ): Promise<AuthenticatedUser> {\n return this.http.get('/api/vtexid/pub/authenticated/user/', {\n params: { authToken },\n metric: 'authenticated-user-get',\n })\n }\n}\n\n```" } ]
code_storefront-permissions_b32c42df
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/masterDataExtended.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\n/*\n The default Master Data client was causing higher response times compared\n to calling Master Data directly from the app using this custom client.\n*/\n\nexport class MasterDataExtended extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n VtexIdClientAutCookie: context.authToken,\n },\n })\n }\n\n public getDocumentById = async (\n dataEntity: string,\n id: string,\n fields: string[]\n ) =>\n this.http.get(\n `/api/dataentities/${dataEntity}/documents/${id}?_fields=${fields.join(\n ','\n )}`\n )\n}\n\n```" } ]
code_storefront-permissions_78adcf85
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/salesChannel.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport interface SalesChannelResponse {\n Id: string\n Name: string\n CurrencyCode: string\n CurrencySymbol: string\n IsActive: boolean\n CultureInfo: string\n}\n\nexport class SalesChannel extends JanusClient {\n constructor(context: IOContext, options?: InstanceOptions) {\n super(context, {\n ...options,\n headers: {\n VtexIdClientAutCookie: context.authToken,\n },\n })\n }\n\n public getSalesChannel = async () => ({\n data: await this.http.get<SalesChannelResponse>(\n '/api/catalog_system/pvt/saleschannel/list'\n ),\n })\n}\n\n```" } ]
code_storefront-permissions_951bba92
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/FullSessions.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport default class FullSessions extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n })\n }\n\n public async getSessions({ headers }: any): Promise<any> {\n return this.http.get('/api/sessions?items=*', {\n headers,\n })\n }\n}\n\n```" } ]
code_storefront-permissions_56660107
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/index.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { IOContext } from '@vtex/api'\nimport { IOClients } from '@vtex/api'\n\nimport { LMClient } from '../utils/LicenseManager'\nimport { ProfileSystemClient } from '../utils/ProfileSystem'\nimport { Checkout } from './checkout'\nimport FullSessions from './FullSessions'\nimport IdentityClient from './IdentityClient'\nimport { OrganizationsGraphQLClient } from './Organizations'\nimport { SalesChannel } from './salesChannel'\nimport { Schema } from './schema'\nimport VtexId from './vtexId'\nimport { MasterDataExtended } from './masterDataExtended'\n\nexport const getTokenToHeader = (ctx: IOContext) => {\n const adminToken = ctx.authToken\n const userToken = ctx.storeUserAuthToken\n const { sessionToken, account } = ctx\n\n let allCookies = `VtexIdclientAutCookie=${adminToken}`\n\n if (userToken) {\n allCookies += `; VtexIdclientAutCookie_${account}=${userToken}`\n }\n\n return {\n 'x-vtex-credential': ctx.authToken,\n VtexIdclientAutCookie: adminToken,\n cookie: allCookies,\n ...(sessionToken && {\n 'x-vtex-session': sessionToken,\n }),\n }\n}\n\n// Extend the default IOClients implementation with our own custom clients.\nexport class Clients extends IOClients {\n public get lm() {\n return this.getOrSet('lm', LMClient)\n }\n\n public get profileSystem() {\n return this.getOrSet('profileSystem', ProfileSystemClient)\n }\n\n public get checkout() {\n return this.getOrSet('checkout', Checkout)\n }\n\n public get organizations() {\n return this.getOrSet('organizations', OrganizationsGraphQLClient)\n }\n\n public get schema() {\n return this.getOrSet('schema', Schema)\n }\n\n public get vtexId() {\n return this.getOrSet('vtexId', VtexId)\n }\n\n public get identity() {\n return this.getOrSet('identity', IdentityClient)\n }\n\n public get salesChannel() {\n return this.getOrSet('salesChannel', SalesChannel)\n }\n\n public get fullSessions() {\n return this.getOrSet('fullSessions', FullSessions)\n }\n\n public get masterDataExtended() {\n return this.getOrSet('masterDataExtended', MasterDataExtended)\n }\n}\n\n```" } ]
code_storefront-permissions_abd49327
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/IdentityClient.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport type { InstanceOptions, IOContext } from '@vtex/api'\nimport { JanusClient } from '@vtex/api'\n\nexport default class IdentityClient extends JanusClient {\n constructor(ctx: IOContext, options?: InstanceOptions) {\n super(ctx, {\n ...options,\n headers: {\n ...options?.headers,\n },\n })\n }\n\n public async validateToken({ token }: { token: string }): Promise<any> {\n return this.http.post('/api/vtexid/credential/validate', { token })\n }\n\n public async getToken({\n appkey,\n apptoken,\n }: {\n appkey: string\n apptoken: string\n }): Promise<any> {\n return this.http.post('/api/vtexid/apptoken/login', { appkey, apptoken })\n }\n}\n\n```" } ]
code_storefront-permissions_1e3d63ac
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/clients/metrics.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nimport axios from 'axios'\n\nconst ANALYTICS_URL = 'https://rc.vtex.com/api/analytics/schemaless-events'\n\nexport const B2B_METRIC_NAME = 'b2b-suite-buyerorg-data'\n\nexport interface Metric {\n readonly account: string\n readonly kind: string\n readonly description: string\n readonly name: typeof B2B_METRIC_NAME\n}\n\nexport const sendMetric = async (metric: Metric) => {\n await axios.post(ANALYTICS_URL, metric)\n}\n\n```" } ]
code_storefront-permissions_3ca25b00
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typings/Checkout.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\ninterface OrderFormMarketingData {\n utmCampaign?: string\n utmMedium?: string\n utmSource?: string\n utmiCampaign?: string\n utmiPart?: string\n utmipage?: string\n marketingTags?: string | string[]\n}\n\ninterface CheckoutAddress {\n addressType: string\n receiverName: string | null\n addressId: string\n postalCode: string\n city: string\n state: string\n country: string\n street: string\n number: string\n neighborhood: string\n complement: string\n reference: string | null\n geoCoordinates: [number, number]\n}\n\ninterface CheckoutAssemblyItem {\n id: string\n inputValues: Record<string, string>\n}\n\ninterface CheckoutAttachmentOffering {\n name: string\n required: boolean\n schema: Record<string, unknown>\n}\n\ninterface OrderFormItem {\n id: string\n name: string\n detailUrl: string\n imageUrl: string\n productRefId: string\n skuName: string\n quantity: number\n uniqueId: string\n productId: string\n refId: string\n ean: string\n priceValidUntil: string\n price: number\n tax: number\n listPrice: number\n sellingPrice: number\n rewardValue: number\n isGift: boolean\n parentItemIndex: number | null\n parentAssemblyBinding: string | null\n productCategoryIds: string\n priceTags: string[]\n measurementUnit: string\n additionalInfo: {\n brandName: string\n brandId: string\n offeringInfo: any | null\n offeringType: any | null\n offeringTypeId: any | null\n }\n productCategories: Record<string, string>\n seller: string\n sellerChain: string[]\n availability: string\n unitMultiplier: number\n assemblies: CheckoutAssemblyItem[]\n attachmentOfferings: CheckoutAttachmentOffering[]\n priceDefinition: {\n calculatedSellingPrice: number\n sellingPrices: SellingPrice[]\n total: number\n } | null\n}\n\ninterface SellingPrice {\n quantity: number\n value: number\n}\n\ninterface InstallmentOption {\n paymentSystem: string\n paymentName: string\n paymentGroupName: string\n value: number\n bin: string | null\n installments: SimulationInstallment[]\n}\n\ninterface SimulationInstallment {\n value: number\n interestRate: number\n total: number\n count: number\n}\n\ninterface PaymentData {\n installmentOptions: InstallmentOption[]\n paymentSystems: Array<{\n id: string\n name: string\n groupName: string\n validator: {\n regex: string\n mask: string\n cardCodeRegex: string\n cardCodeMask: string\n weights: number[]\n useCvv: boolean\n useExpirationDate: boolean\n useCardHolderName: boolean\n useBillingAddress: boolean\n }\n stringId: string\n template: string\n requiresDocument: boolean\n isCustom: boolean\n description: string | null\n requiresAuthentication: boolean\n dueDate: string\n availablePayments: any | null\n }>\n payments: any[]\n giftCards: any[]\n giftCardMessages: any[]\n availableAccounts: any[]\n availableTokens: any[]\n}\n\ninterface OrderForm {\n orderFormId: string\n salesChannel: string\n loggedIn: boolean\n isCheckedIn: boolean\n storeId: string | null\n checkedInPickupPointId: string | null\n allowManualPrice: boolean\n canEditData: boolean\n userProfileId: string | null\n userType: string | null\n ignoreProfileData: boolean\n value: number\n messages: any[]\n items: OrderFormItem[]\n selectableGifts: any[]\n totalizers: Array<{ id: string; name: string; value: number }>\n shippingData: {\n address: CheckoutAddress\n logisticsInfo: LogisticsInfo[]\n selectedAddresses: CheckoutAddress[]\n availableAddresses: CheckoutAddress[]\n pickupPoints: Array<{\n friendlyName: string\n address: CheckoutAddress\n additionalInfo: string\n id: string\n businessHours: Array<{\n DayOfWeek: number\n OpeningTime: string\n ClosingTime: string\n }>\n }>\n }\n clientProfileData: any | null\n paymentData: PaymentData\n marketingData: OrderFormMarketingData | null\n sellers: Array<{\n id: string\n name: string\n logo: string\n }>\n clientPreferencesData: OrderFormClientPreferencesData\n commercialConditionData: any | null\n storePreferencesData: {\n countryCode: string\n saveUserData: boolean\n timeZone: string\n currencyCode: string\n currencyLocale: number\n currencySymbol: string\n currencyFormatInfo: {\n currencyDecimalDigits: number\n currencyDecimalSeparator: string\n currencyGroupSeparator: string\n currencyGroupSize: number\n startsWithCurrencySymbol: boolean\n }\n }\n giftRegistryData: any | null\n openTextField: any | null\n invoiceData: any | null\n customData: any | null\n itemMetadata: {\n items: MetadataItem[]\n }\n hooksData: any | null\n ratesAndBenefitsData: {\n rateAndBenefitsIdentifiers: any[]\n teaser: any[]\n }\n subscriptionData: any | null\n itemsOrdination: any | null\n}\n\ninterface OrderFormClientPreferencesData {\n locale: string\n optinNewsLetter: boolean | null\n}\n\ninterface OrderFormItemInput {\n id?: number\n index?: number\n quantity?: number\n seller?: string\n inputValues: Record<string, string>\n options?: AssemblyOptionInput[]\n}\n\ninterface AssemblyOptionInput {\n id: string\n quantity: number\n assemblyId: string\n seller: string\n inputValues: Record<string, string>\n options?: AssemblyOptionInput[]\n}\n\ninterface PayloadItem {\n id: string\n quantity: number\n seller: string\n parentItemIndex?: number | null\n parentAssemblyBinding?: string | null\n}\n\ninterface SimulationPayload {\n country?: string\n items: PayloadItem[]\n postalCode?: string\n isCheckedIn?: boolean\n priceTables?: string[]\n marketingData?: Record<string, string>\n geoCoordinates?: [string | number, string | number]\n shippingData?: any\n}\n\ninterface SLAItem {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: Array<{\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }>\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n}\n\ninterface LogisticsInfo {\n itemIndex: number\n selectedSla: string | null\n selectedDeliveryChannel: string | null\n addressId: string\n slas: SLAItem[]\n shipsTo: string[]\n itemId: string\n deliveryChannels: Array<{ id: string }>\n}\n\ninterface SimulationOrderForm extends OrderForm {\n logisticsInfo?: LogisticsInfo[]\n}\n\ninterface SLA {\n id: string\n deliveryChannel: string\n name: string\n deliveryIds: Array<{\n courierId: string\n warehouseId: string\n dockId: string\n courierName: string\n quantity: number\n }>\n shippingEstimate: string\n shippingEstimateDate: string | null\n lockTTL: string | null\n availableDeliveryWindows: any[]\n deliveryWindow: string | null\n price: number\n listPrice: number\n tax: number\n pickupStoreInfo: {\n isPickupStore: boolean\n friendlyName: string | null\n address: CheckoutAddress | null\n additionalInfo: any | null\n dockId: string | null\n }\n pickupPointId: string | null\n pickupDistance: number\n polygonName: string | null\n}\n\ninterface ItemWithSimulationInput {\n itemId: string\n sellers: Array<{\n sellerId: string\n }>\n}\n\ninterface RatesAndBenefitsData {\n rateAndBenefitsIdentifiers: Array<{\n id: string\n name: string\n featured: boolean\n description: string\n }>\n teaser: Array<{\n featured: boolean\n id: string\n name: string\n conditions: {\n parameters: Array<{\n name: string\n value: string\n }>\n minimumQuantity: number\n }\n effects: {\n parameters: Array<{\n name: string\n value: string\n }>\n }\n teaserType: string\n }>\n}\n\n```" } ]
code_storefront-permissions_fd7430cb
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typings/ItemMetadata.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\n/**\n * Assembly options related types\n */\n\ninterface CompositionItem {\n id: string\n minQuantity: number\n maxQuantity: number\n initialQuantity: number\n priceTable: string\n seller: string\n}\n\ninterface Composition {\n minQuantity: number\n maxQuantity: number\n items: CompositionItem[]\n}\n\ninterface AssemblyOption {\n id: string\n name: string\n composition: Composition | null\n}\n\ninterface CatalogMetadataItem {\n Name: string\n NameComplete: string\n MainImage: string\n BrandName: string\n CategoryId: number\n ProductId: number\n id: string\n seller: string\n assemblyOptions: AssemblyOption[]\n}\n\ninterface MetadataItem {\n id: string\n name: string\n imageUrl: string\n detailUrl: string\n seller: string\n assemblyOptions: AssemblyOption[]\n skuName: string\n productId: string\n refId: string\n ean: string | null\n}\ninterface AddedItem {\n choiceType: string\n compositionItem: CompositionItem\n extraQuantity: number\n item: OrderFormItem\n normalizedQuantity: number\n}\n\ninterface RemovedItem {\n initialQuantity: number\n name: string\n removedQuantity: number\n}\n\n```" } ]
code_storefront-permissions_507ab13d
[ { "role": "system", "content": "You are an expert VTEX IO developer. You specialize in building 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/typings/custom.d.ts from the storefront-permissions VTEX app." }, { "role": "assistant", "content": "Here's the implementation:\n\n```typescript\nexport interface Order {\n orderId: string\n clientProfileData: ClientProfileData | null\n creationDate: string\n clientName: string\n items: Item[] | null\n comments: Comment[] | null\n totalValue: number\n status: string\n statusDescription: string | null\n sequence: string | null\n salesChannel: string\n affiliateId: string | null\n origin: string | null\n workflowInErrorState: boolean | null\n workflowInRetry: boolean | null\n ShippingEstimatedDate: string | null\n ShippingEstimatedDateMax: string\n ShippingEstimatedDateMin: string\n orderIsComplete: boolean | null\n authorizedDate: string | null\n callCenterOperatorName: string | null\n totalItems: number | null\n currencyCode: string | null\n hostname: string\n checkedInPickupPointId: string\n shippingData: ShippingData | null\n paymentData: PaymentData | null\n storePreferencesData: StorePreferencesData | null\n fulfillment?: Fulfillment\n}\n\nexport interface StorePreferencesData {\n countryCode: string\n currencyCode: string\n}\n\nexport interface PaymentData {\n transactions: Transaction[]\n}\n\nexport interface Transaction {\n isActive: boolean\n payments: Payment[]\n}\n\nexport interface Payment {\n id: string | null\n paymentSystem: string\n paymentSystemName: string\n value: number\n installments: number | null\n referenceValue: number | null\n}\n\nexport interface ClientProfileData {\n corporateDocument: string | null\n corporateName: string | null\n corporatePhone: string | null\n customerClass: string | null\n document: string | null\n documentType: string | null\n email: string\n firstName: string | null\n id: string\n isCorporate: boolean\n lastName: string | null\n phone: string | null\n stateInscription: string | null\n tradeName: string | null\n userProfileId: string | null\n}\n\nexport type ProductCategory = {\n id: string\n name: string\n}\n\nexport type ItemAdditionalInfo = {\n categories: ProductCategory[]\n}\n\nexport interface Item {\n seller: string\n quantity: number\n description: string | null\n ean: string | null\n refId: string | null\n id: string | null\n productId: string | null\n sellingPrice: number\n price: number\n imageUrl: string | null\n skuName: string | null\n name: string\n additionalInfo: ItemAdditionalInfo\n}\n\nexport interface Comment {\n createdBy: CommentCreatedBy | null\n creationDate: string\n description: string\n domain: string\n id: string\n lastUpdate: string | null\n owner: string | null\n target: CommentTarget | null\n}\n\nexport interface CommentCreatedBy {\n id: string\n name: string\n email: string | null\n key: string | null\n}\n\nexport interface CommentTarget {\n id: string\n type: string | null\n url: string | null\n}\n\nexport interface ShippingData {\n id: string | null\n logisticsInfo: LogisticsInfoItem[]\n selectedAddresses: Address[]\n}\n\nexport interface LogisticsInfoItem {\n itemIndex: number\n selectedSla: string\n lockTTL: string | null\n price: number\n listPrice: number\n sellingPrice: number\n deliveryCompany: string | null\n shippingEstimate: string\n shippingEstimateDate: string | null\n deliveryChannel: string\n addressId: string\n pickupStoreInfo: PickupStoreInfo\n pickupPointId: string | null\n slas: SLA[]\n}\n\nexport interface PickupStoreInfo {\n additionalInfo: string | null\n address: Address | null\n dockId: string | null\n friendlyName: string | null\n isPickupStore: boolean\n}\n\nexport interface Address {\n addressId: string\n addressType: string\n receiverName: string | null\n street: string\n number: string\n complement: string | null\n neighborhood: string\n postalCode: string\n city: string\n state: string\n country: string\n reference: string | null\n geoCoordinates: number[] | null\n}\n\nexport interface SLA {\n id: string | null\n deliveryChannel: string | null\n name: string | null\n deliveryIds: DeliveryId[]\n shippingEstimate: string | null\n shippingEstimateDate: string | null\n lockTTL: string | null\n price: number | null\n listPrice: number | null\n tax: number | null\n pickupStoreInfo: PickupStoreInfo | null\n pickupPointId: string | null\n pickupDistance: number | null\n polygonName: string | null\n}\n\nexport interface DeliveryId {\n courierId: string | null\n warehouseId: string | null\n dockId: string | null\n courierName: string | null\n quantity: number | null\n}\nexport interface GetOrganizationByEmailBase {\n id: string\n organizationStatus: string\n orgId: string\n costId: string\n costCenterName: string | null\n}\n\nexport interface GetOrganizationsByEmailResponse {\n data: {\n getOrganizationsByEmail: GetOrganizationByEmailBase[]\n }\n}\nexport interface GetOrganizationsPaginatedByEmailResponse {\n data: GetOrganizationByEmailBase[]\n pagination: {\n page: number\n pageSize: number\n total: number\n }\n}\nexport interface GetCostCenterType {\n getCostCenterById: {\n name: string | null\n organization: string | null\n paymentTerms: {\n id: string | null\n name: string | null\n } | null\n address: Address\n phoneNumber: string | null\n businessDocument: string | null\n stateRegistration: string | null\n sellers: {\n id: string | null\n name: string | null\n }\n }\n}\n\n```" } ]