id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_return-app_fdf4c64f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/createReturn.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport { json } from 'co-body'\n\nimport { createReturnRequestService } from '../services/createReturnRequestService'\n\nexport async function createReturn(ctx: Context) {\n const { req } = ctx\n\n const body = await json(req)\n\n const { locale } = body\n\n if (!locale) {\n throw new UserInputError('Locale is required.')\n }\n\n ctx.vtex.locale = locale\n\n ctx.body = await createReturnRequestService(ctx, body)\n ctx.status = 201\n}\n\n```"
}
] |
code_return-app_8bdfb0b7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/errorHandler.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport async function errorHandler(ctx: Context, next: () => Promise<void>) {\n const {\n vtex: { logger },\n } = ctx\n\n try {\n await next()\n } catch (error) {\n logger.error({\n message: error.message,\n error,\n })\n\n ctx.status = error.status || error.response?.status || 500\n ctx.body = { error: error.message }\n ctx.app.emit('error', error, ctx)\n }\n}\n\n```"
}
] |
code_return-app_cbe3e55c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/updateRequestStatus.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { json } from 'co-body'\n\nimport { updateRequestStatusService } from '../services/updateRequestStatusService'\n\nexport async function updateRequestStatus(ctx: Context) {\n const {\n req,\n vtex: {\n route: { params },\n },\n } = ctx\n\n const { requestId } = params as { requestId: string }\n\n const body = await json(req)\n\n const updatedRequest = await updateRequestStatusService(ctx, {\n ...body,\n requestId,\n })\n\n ctx.body = updatedRequest\n}\n\n```"
}
] |
code_return-app_ed6375e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/getRequest.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { returnRequestService } from '../services/returnRequestService'\n\nexport async function getRequest(ctx: Context) {\n const { requestId } = ctx.vtex.route.params as { requestId: string }\n\n ctx.set('Cache-Control', 'no-cache')\n\n ctx.body = await returnRequestService(ctx, requestId)\n}\n\n```"
}
] |
code_return-app_78c23aac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/getRequestList.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Status } from 'vtex.return-app'\n\nimport { returnRequestListService } from '../services/returnRequestListService'\n\nexport async function getRequestList(ctx: Context) {\n const { query } = ctx\n\n const {\n _page,\n _perPage,\n _status,\n _sequenceNumber,\n _id,\n _dateSubmitted,\n _orderId,\n _userEmail,\n _allFields,\n } = query\n\n const [from, to] = (_dateSubmitted as string | undefined)?.split(',') ?? []\n\n const getAllFields = Boolean(_allFields)\n\n ctx.set('Cache-Control', 'no-cache')\n\n ctx.body = await returnRequestListService(\n ctx,\n {\n page: _page ? Number(_page) : 1,\n perPage: _perPage ? Number(_perPage) : 25,\n filter: {\n status: _status as Status | undefined,\n sequenceNumber: _sequenceNumber as string | undefined,\n id: _id as string | undefined,\n createdIn: _dateSubmitted ? { from, to } : undefined,\n orderId: _orderId as string | undefined,\n userEmail: _userEmail as string | undefined,\n },\n },\n getAllFields\n )\n}\n\n```"
}
] |
code_return-app_5fe3df69
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/middlewares/auth.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { AuthenticationError } from '@vtex/api'\n\nexport async function auth(ctx: Context, next: () => Promise<void>) {\n const {\n header,\n clients: { vtexId, sphinx },\n state,\n } = ctx\n\n const appkey = header['x-vtex-api-appkey'] as string | undefined\n const apptoken = header['x-vtex-api-apptoken'] as string | undefined\n const authCookie = header.vtexidclientautcookie as string | undefined\n\n if (authCookie) {\n const authenticatedUser = await vtexId.getAuthenticatedUser(authCookie)\n\n // When the auth cookie is invalid, the API returns null\n if (authenticatedUser) {\n const isAdmin = await sphinx.isAdmin(authenticatedUser.user)\n\n const { user, userId } = authenticatedUser\n\n state.userProfile = {\n userId,\n email: user,\n role: isAdmin ? 'admin' : 'store-user',\n }\n\n if (isAdmin) {\n ctx.vtex.adminUserAuthToken = authCookie\n }\n }\n }\n\n if (appkey && apptoken) {\n // If appkey and apptoken are not valid, the method throws a 401 error\n const { token } = await vtexId.login({ appkey, apptoken })\n\n state.appkey = appkey\n ctx.vtex.adminUserAuthToken = token\n }\n\n const { userProfile, appkey: appKeyState } = state\n\n // Either userProfile or appKeyState must be on state to continue\n if (!userProfile && !appKeyState) {\n throw new AuthenticationError('Request failed with status code 401')\n }\n\n await next()\n}\n\n```"
}
] |
code_return-app_0b07f2ac
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/canReturnAllItems.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { OrderDetailResponse } from '@vtex/clients'\nimport type { MasterDataEntity } from '@vtex/clients/build/clients/masterData/MasterDataEntity'\nimport type {\n ReturnRequestItemInput,\n ReturnAppSettings,\n ReturnRequest,\n} from 'vtex.return-app'\nimport { ResolverError } from '@vtex/api'\n\nimport { createOrdersToReturnSummary } from './createOrdersToReturnSummary'\nimport type { CatalogGQL } from '../clients/catalogGQL'\n\ninterface CanReturnAllItemsSetup {\n order: OrderDetailResponse\n excludedCategories: ReturnAppSettings['excludedCategories']\n returnRequestClient: MasterDataEntity<ReturnRequest>\n catalogGQL: CatalogGQL\n}\n\nexport const canReturnAllItems = async (\n itemsToReturn: ReturnRequestItemInput[],\n {\n order,\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n }: CanReturnAllItemsSetup\n) => {\n // we pass email as email because we won't use the email form the return object here\n const { invoicedItems, excludedItems, processedItems } =\n await createOrdersToReturnSummary(order, 'email', {\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n })\n\n const excludedItemsIndexMap = new Map<number, boolean>()\n\n for (const excludedItem of excludedItems) {\n excludedItemsIndexMap.set(excludedItem.itemIndex, true)\n }\n\n const processedItemsQuantityIndexMap = new Map<number, number>()\n\n for (const processedItem of processedItems) {\n processedItemsQuantityIndexMap.set(\n processedItem.itemIndex,\n processedItem.quantity\n )\n }\n\n const itemAvailableMap = new Map<number, number>()\n\n for (let i = 0; i < invoicedItems.length; i++) {\n const { orderItemIndex, quantity } = invoicedItems[i]\n const isExcluded = excludedItemsIndexMap.get(i) ?? false\n const quantityAvailable = isExcluded\n ? 0\n : quantity - (processedItemsQuantityIndexMap.get(i) ?? 0)\n\n itemAvailableMap.set(orderItemIndex, quantityAvailable)\n }\n\n const cannotReturn = []\n\n for (const itemToReturn of itemsToReturn) {\n const { quantity, orderItemIndex } = itemToReturn\n const availableToReturn = itemAvailableMap.get(orderItemIndex)\n\n // if quantity available to return is undefined or zero or less than the quantity requested, throw error\n if (!availableToReturn || availableToReturn < quantity) {\n cannotReturn.push(orderItemIndex)\n }\n }\n\n if (cannotReturn.length > 0) {\n throw new ResolverError(\n `Items with index ${cannotReturn.join(\n ', '\n )} are not available to be returned`,\n 400\n )\n }\n}\n\n```"
}
] |
code_return-app_80b43ee7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/mapItemIndexAndQuantity.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ItemPackage } from '@vtex/clients'\n\nexport const mapItemIndexAndQuantity = (\n itemPackages: Array<\n Omit<ItemPackage, 'description' | 'price' | 'unitMultiplier'>\n >\n): Map<number, number> => {\n const itemIndexAndQuantityMap = new Map<number, number>()\n\n for (const invoicedItem of itemPackages) {\n const { itemIndex, quantity } = invoicedItem\n\n if (itemIndexAndQuantityMap.has(itemIndex)) {\n const currentQuantity = itemIndexAndQuantityMap.get(itemIndex) as number\n\n itemIndexAndQuantityMap.set(itemIndex, currentQuantity + quantity)\n } else {\n itemIndexAndQuantityMap.set(itemIndex, quantity)\n }\n }\n\n return itemIndexAndQuantityMap\n}\n\n```"
}
] |
code_return-app_bbbced2d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/validateReturnReason.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n ReturnRequestItemInput,\n CustomReturnReason,\n} from 'vtex.return-app'\nimport { ResolverError, UserInputError } from '@vtex/api'\n\nimport { isWithinMaxDaysToReturn } from './dateHelpers'\n\nexport const validateReturnReason = (\n itemsToReturn: ReturnRequestItemInput[],\n orderCreationDate: string,\n customReturnReasons?: CustomReturnReason[] | null\n) => {\n itemsToReturn.forEach(({ returnReason: { reason }, orderItemIndex }) => {\n if (!reason) {\n throw new UserInputError(\n `Item index ${orderItemIndex} has no return reason. Reason cannot be empty.`\n )\n }\n })\n\n if (!customReturnReasons || customReturnReasons.length === 0) {\n return\n }\n\n const maxDaysPercustomReasonMap = new Map<string, number>()\n\n for (const customReason of customReturnReasons) {\n const { maxDays, reason, translations } = customReason\n\n maxDaysPercustomReasonMap.set(reason, maxDays)\n\n for (const { translation } of translations ?? []) {\n maxDaysPercustomReasonMap.set(translation, maxDays)\n }\n }\n\n for (const item of itemsToReturn) {\n const {\n orderItemIndex,\n returnReason: { reason },\n } = item\n\n if (reason === 'otherReason') {\n continue\n }\n\n const maxDayForReason = maxDaysPercustomReasonMap.get(reason)\n\n if (!maxDayForReason) {\n throw new ResolverError(\n `Order Item index ${orderItemIndex} doesn't have a valid return reason`,\n 400\n )\n }\n\n if (!isWithinMaxDaysToReturn(orderCreationDate, maxDayForReason)) {\n throw new ResolverError(\n `Order Item index ${orderItemIndex} is not within max days for the reason ${reason}`,\n 400\n )\n }\n }\n}\n\n```"
}
] |
code_return-app_4d793771
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/getUserProfileFromSession.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Session } from '@vtex/api'\nimport { ResolverError } from '@vtex/api'\n\nconst createUserProfile = (sessionData: SessionData): UserProfile => {\n const {\n namespaces: { profile, authentication },\n } = sessionData\n\n const email = profile.email?.value ?? authentication.adminUserEmail?.value\n const userId = profile.id?.value ?? authentication.adminUserId?.value\n\n const role = authentication.adminUserId ? 'admin' : 'store-user'\n\n if (!email || !userId) {\n throw new ResolverError('Invalid session data')\n }\n\n const { firstName, lastName } = profile\n\n const firstNameValue = firstName?.value ?? ''\n const lastNameValue = lastName?.value ?? ''\n\n return {\n email,\n userId,\n role,\n firstName: firstNameValue,\n lastName: lastNameValue,\n }\n}\n\nexport const getUserProfileFromSession = async (\n session: Session,\n sessionCookie: string | undefined\n) => {\n if (!sessionCookie) throw new Error('No session cookie provided')\n\n const { sessionData } = (await session.getSession(sessionCookie, [\n 'profile.id',\n 'profile.email',\n 'profile.firstName',\n 'profile.lastName',\n 'authentication.adminUserEmail',\n 'authentication.adminUserId',\n ])) as {\n sessionData: SessionData\n sessionToken: string\n }\n\n return createUserProfile(sessionData)\n}\n\n```"
}
] |
code_return-app_19f7541b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/validateItemCondition.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ReturnRequestItemInput } from 'vtex.return-app'\nimport { UserInputError } from '@vtex/api'\n\nexport const validateItemCondition = (\n itemsToReturn: ReturnRequestItemInput[],\n considerCondition?: boolean | null\n) => {\n considerCondition &&\n itemsToReturn.forEach(({ condition }, orderItemIndex) => {\n if (!condition || condition === 'unspecified') {\n throw new UserInputError(\n `Item index ${orderItemIndex} has no Item condition. Account settings state that Item condition cannot be unspecified.`\n )\n }\n })\n}\n\n```"
}
] |
code_return-app_edebdcd5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/createItemsToReturn.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { UserInputError } from '@vtex/api'\nimport type {\n OrderItemDetailResponse,\n PriceTag,\n SellerDetail,\n} from '@vtex/clients'\nimport type { ReturnRequestItemInput, ReturnRequestItem } from 'vtex.return-app'\n\nimport type { CatalogGQL } from '../clients/catalogGQL'\nimport { translateItemName } from './translateItems'\n\ninterface ItemMetadata {\n Items: Array<{\n Id: string\n ImageUrl: string\n }>\n}\n\nconst calculateItemTax = ({\n tax,\n priceTags,\n quantity,\n sellingPrice,\n}: {\n tax: number\n priceTags: PriceTag[]\n quantity: number\n sellingPrice: number\n}): number => {\n if (tax) return tax\n\n const taxHubItems = priceTags.filter((priceTag) =>\n priceTag.name.includes('TAXHUB')\n )\n\n if (taxHubItems.length === 0) return 0\n\n const taxValueFromTaxHub = taxHubItems.reduce((acc, priceTag) => {\n const { isPercentual, value, rawValue } = priceTag\n // value for TAXHUB is total (not per unit).\n // When it's percentual, the rawValue is the % to be applied. Since we divide the total ammount per quantity in the return, we\n const taxValue = isPercentual ? rawValue * sellingPrice * quantity : value\n\n return acc + taxValue\n }, 0)\n\n return parseFloat((taxValueFromTaxHub / quantity).toFixed(0))\n}\n\nexport const createItemsToReturn = async ({\n itemsToReturn,\n orderItems,\n sellers,\n itemMetadata,\n catalogGQL,\n}: {\n itemsToReturn: ReturnRequestItemInput[]\n orderItems: OrderItemDetailResponse[]\n sellers: SellerDetail[]\n itemMetadata: ItemMetadata\n catalogGQL: CatalogGQL\n}): Promise<ReturnRequestItem[]> => {\n return Promise.all(\n itemsToReturn.map(async (item) => {\n const orderItem = orderItems[item.orderItemIndex]\n\n if (!orderItem) {\n throw new UserInputError(\n `Item index ${item.orderItemIndex} doesn't exist on order`\n )\n }\n\n const {\n id,\n sellingPrice,\n tax,\n priceTags,\n quantity,\n name,\n imageUrl,\n unitMultiplier,\n seller,\n refId,\n productId,\n } = orderItem\n\n const sellerName =\n sellers.find((sellerInfo) => sellerInfo.id === seller)?.name ?? ''\n\n const productImage =\n imageUrl ??\n itemMetadata.Items.find((itemMeta) => itemMeta.Id === id)?.ImageUrl ??\n ''\n\n return {\n ...item,\n id,\n sellingPrice,\n tax: calculateItemTax({ tax, priceTags, quantity, sellingPrice }),\n name,\n localizedName: await translateItemName(id, name, catalogGQL),\n imageUrl: productImage,\n unitMultiplier,\n sellerId: seller,\n refId: refId ?? '',\n productId,\n sellerName,\n condition: item.condition ? item.condition : 'unspecified',\n }\n })\n )\n}\n\n```"
}
] |
code_return-app_52d8c29f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/validateCanUseDropoffPoints.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { PickupReturnDataInput } from 'vtex.return-app'\nimport { ResolverError, UserInputError } from '@vtex/api'\n\nexport const validateCanUsedropoffPoints = (\n pickupReturnData: PickupReturnDataInput,\n isPickupPointsEnabled?: boolean | null\n) => {\n if (!pickupReturnData) {\n throw new UserInputError('Missing pickupReturnData')\n }\n\n const { addressType } = pickupReturnData\n\n if (addressType === 'PICKUP_POINT' && !isPickupPointsEnabled) {\n throw new ResolverError('Dropoff points are not enabled')\n }\n}\n\n```"
}
] |
code_return-app_de4acd8d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/getInvoicedItems.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ItemPackage, PackageDetail } from '@vtex/clients'\n\ntype InvoiceType = 'Output' | 'Input'\n\nexport const getInvoicedItems = (\n packageDetails: PackageDetail[],\n invoiceType: InvoiceType\n): ItemPackage[] => {\n const invoices = packageDetails.filter(({ type }) => type === invoiceType)\n\n const invoicedItemsRaw = invoices.map(\n ({ items: invoicedItems }) => invoicedItems\n )\n\n const invoicedItemsFlatten = invoicedItemsRaw.reduce((acc, invoicedItems) => {\n return [...acc, ...invoicedItems]\n }, [])\n\n return invoicedItemsFlatten\n}\n\n```"
}
] |
code_return-app_f676251d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/handleRefund.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Status, Maybe, ReturnRequest, GiftCard } from 'vtex.return-app'\nimport { ResolverError } from '@vtex/api'\n\nimport type { OMSCustom } from '../clients/oms'\nimport type { GiftCard as GiftCardClient } from '../clients/giftCard'\n\nconst getOneYearLaterDate = (createdAt: string) => {\n const date = new Date(createdAt)\n const year = date.getFullYear()\n const month = date.getMonth()\n const day = date.getDate()\n const oneYearLater = new Date(year + 1, month, day)\n\n return oneYearLater.toISOString()\n}\n\ninterface HandleRefundProps {\n currentStatus: Status\n previousStatus?: Status\n refundPaymentData: ReturnRequest['refundPaymentData']\n orderId: string\n createdAt: string\n userEmail: string\n refundInvoice: ReturnRequest['refundData']\n clients: {\n omsClient: OMSCustom\n giftCardClient: GiftCardClient\n }\n}\n\nexport const handleRefund = async ({\n currentStatus,\n previousStatus,\n refundPaymentData,\n orderId,\n createdAt,\n refundInvoice,\n clients,\n userEmail,\n}: HandleRefundProps): Promise<Maybe<{ giftCard: GiftCard }>> => {\n // To avoid handling the amountRefunded after it has been already done, we check the previous status.\n // If the current status is already amountRefunded, it means the refund has already been done and we don't need to do it again.\n const shouldHandle =\n currentStatus === 'amountRefunded' &&\n previousStatus !== 'amountRefunded' &&\n refundInvoice\n\n if (!shouldHandle) {\n return null\n }\n\n const { omsClient, giftCardClient } = clients\n\n const { refundPaymentMethod, automaticallyRefundPaymentMethod } =\n refundPaymentData ?? {}\n\n if (refundPaymentMethod === 'giftCard') {\n try {\n const { id, redemptionCode } = await giftCardClient.createGiftCard({\n relationName: refundInvoice?.invoiceNumber as string,\n caption: 'Gift Card from Return Request',\n expiringDate: getOneYearLaterDate(createdAt),\n balance: 0,\n profileId: userEmail,\n discount: true,\n })\n\n const giftCardIdSplit = id.split('_')\n\n const giftCardId = giftCardIdSplit[giftCardIdSplit.length - 1]\n\n await giftCardClient.updateGiftCard(giftCardId, {\n description: 'Initial Charge',\n value: refundInvoice?.invoiceValue as number,\n })\n\n return {\n giftCard: { id: giftCardId, redemptionCode },\n }\n } catch (error) {\n throw new ResolverError('Error creating/updating gift card')\n }\n }\n\n const refundPayment =\n refundPaymentMethod === 'card' ||\n (refundPaymentMethod === 'sameAsPurchase' &&\n automaticallyRefundPaymentMethod)\n\n if (refundPayment) {\n try {\n await omsClient.createInvoice(orderId, {\n type: 'Input',\n issuanceDate: createdAt,\n invoiceNumber: refundInvoice?.invoiceNumber as string,\n invoiceValue: refundInvoice?.invoiceValue as number,\n items:\n refundInvoice?.items?.map((item) => {\n return {\n id: item.id as string,\n price: (item.price as number) - (item.restockFee as number),\n quantity: item.quantity as number,\n }\n }) ?? [],\n })\n\n return null\n } catch (error) {\n throw new ResolverError('Error creating refund invoice')\n }\n }\n\n return null\n}\n\n```"
}
] |
code_return-app_bee09674
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/transformShippingData.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ShippingDetail } from '@vtex/clients'\nimport type { ShippingData } from 'vtex.return-app'\n\nexport const transformShippingData = (\n shippingData: ShippingDetail\n): ShippingData => {\n const { address } = shippingData\n\n const complement = address.complement ?? ''\n\n /**\n * Order has type pickup for pickup orders.\n * Orders delivered into the customer address has type `residential`\n * TODO: Map other address types\n */\n const addressType =\n address.addressType === 'pickup' ? 'PICKUP_POINT' : 'CUSTOMER_ADDRESS'\n\n return {\n addressId: address.addressId ?? '',\n country: address.country,\n city: address.city,\n address: `${address.street}, ${address.number ?? ''} ${complement}`.trim(),\n state: address.state,\n zipCode: address.postalCode,\n addressType,\n // @ts-expect-error geoCoordinates is not typed in the OMS client project\n geoCoordinates: address.geoCoordinates,\n }\n}\n\n```"
}
] |
code_return-app_83a4261f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/translateItems.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { InvoicedItem } from 'vtex.return-app'\n\nimport type { CatalogGQL } from '../clients/catalogGQL'\n\n/**\n * @returns the most up to date SKU translations, if it exist\n */\nexport const translateItemName = async (\n id: string,\n originalName: string,\n catalogClient: CatalogGQL\n) => {\n try {\n const skuName = await catalogClient.getSKUTranslation(id)\n const isLocalized = skuName && skuName !== originalName\n\n return isLocalized ? skuName : null\n } catch (error) {\n error.message = 'Error translating item name'\n throw error\n }\n}\n\nexport function handleTranlateItems(\n items: InvoicedItem[],\n catalogClient: CatalogGQL\n): Promise<InvoicedItem[]> {\n return Promise.all(\n items.map(async (item: InvoicedItem) => {\n return {\n ...item,\n localizedName: await translateItemName(\n item.id,\n item.name,\n catalogClient\n ),\n }\n })\n )\n}\n\n```"
}
] |
code_return-app_7bcbdaf8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/getCostumerEmail.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientProfileDetail } from '@vtex/clients'\nimport type { Logger } from '@vtex/api'\nimport { ResolverError } from '@vtex/api'\n\n/**\n * Why not ALWAYS using email for userProfile?\n * userProfile is parsed from session cookie or created when a request is made using AuthCookie token.\n * When submitting a request via GraphQL IDE or calling the endpoint using APP-KEY and APP-TOKEN, we don't have the userProfile.\n * Also, we cannot use the email in the order because it might be masked.\n */\nexport const getCustomerEmail = (\n clientProfileData: ClientProfileDetail,\n {\n userProfile,\n appkey,\n inputEmail,\n }: {\n userProfile?: UserProfile\n appkey?: string\n /**\n * Email sent via args, either via GraphQL or request body in REST\n * @type {string}\n */\n inputEmail?: string | null\n },\n {\n logger,\n }: {\n logger: Logger\n }\n): string => {\n const requesterIsStoreUser =\n clientProfileData.userProfileId === userProfile?.userId\n\n // when the requester is the owner of the order, we can use the email parsed from the session cookie\n if (userProfile && requesterIsStoreUser) return userProfile.email\n\n // Case: Request made by an admin user for a store user (e.g. via GraphQL IDE or endpoint using auth cookie)\n if (userProfile && userProfile.role === 'admin' && !requesterIsStoreUser) {\n if (!inputEmail) {\n throw new ResolverError(\n 'Missing Store user email. Store user email is required when using admin user makes the request',\n 400\n )\n }\n\n return inputEmail\n }\n\n // When the request is made via integration using the endpoint, store user email is a required param.\n if (appkey) {\n if (!inputEmail) {\n throw new ResolverError(\n 'Missing Store user email. Store user email is required when using appkey',\n 400\n )\n }\n\n return inputEmail\n }\n\n logger.error({\n message: 'Could not parse store user email',\n params: {\n customerOrderId: clientProfileData.userProfileId,\n appkey,\n inputEmail,\n userProfile,\n },\n })\n\n throw new ResolverError('Missing costumer email', 400)\n}\n\n```"
}
] |
code_return-app_d20ba3e8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/validatePaymentMethod.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { RefundPaymentDataInput, PaymentOptions } from 'vtex.return-app'\nimport { ResolverError } from '@vtex/api'\n\nimport { isValidIBANNumber } from './isValidIBANNumber'\n\nexport const validatePaymentMethod = (\n refundPaymentData: RefundPaymentDataInput,\n paymentSettings: PaymentOptions\n) => {\n const {\n enablePaymentMethodSelection,\n allowedPaymentTypes,\n automaticallyRefundPaymentMethod,\n } = paymentSettings\n\n const { refundPaymentMethod, iban, accountHolderName } = refundPaymentData\n\n // When admin doesn't allow selection, PM request has to be sameAsPurchase\n if (\n !enablePaymentMethodSelection &&\n refundPaymentMethod !== 'sameAsPurchase'\n ) {\n throw new ResolverError(\n `Payment method ${refundPaymentMethod} is not allowed`,\n 400\n )\n }\n\n if (refundPaymentMethod === 'sameAsPurchase') {\n if (typeof automaticallyRefundPaymentMethod !== 'boolean') {\n throw new ResolverError(\n `automaticallyRefundPaymentMethod field isn't set on settings. It has to be a boolean when refundPaymentMethod is sameAsPurchase`,\n 500\n )\n }\n\n // sameAsPurchase isn't a field on allowedPaymentTypes. Return here to satisfy TS.\n return\n }\n\n // The PM in the request has to be true in the allowedPaymentTypes on the settings.\n if (!allowedPaymentTypes[refundPaymentMethod]) {\n throw new ResolverError(\n `Payment method ${refundPaymentMethod} is not allowed`,\n 400\n )\n }\n\n // eslint-disable-next-line vtex/prefer-early-return\n if (refundPaymentMethod === 'bank') {\n if (!iban) {\n throw new ResolverError('IBAN is required', 400)\n }\n\n if (!accountHolderName) {\n throw new ResolverError('Account holder name is required', 400)\n }\n\n if (!isValidIBANNumber(iban)) {\n throw new ResolverError('IBAN is not valid', 400)\n }\n }\n}\n\n```"
}
] |
code_return-app_58079510
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/transformOrderClientProfileData.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientProfileDetail } from '@vtex/clients'\nimport type { ClientProfileData } from 'vtex.return-app'\n\nexport const transformOrderClientProfileData = (\n clientProfileData: ClientProfileDetail,\n email: string\n): ClientProfileData => {\n return {\n name: `${clientProfileData.firstName} ${clientProfileData.lastName}`,\n email,\n phoneNumber: clientProfileData.phone,\n }\n}\n\n```"
}
] |
code_return-app_28138b9c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/createOrUpdateStatusPayload.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport type {\n Maybe,\n ReturnRequest,\n ReturnRequestCommentInput,\n Status,\n} from 'vtex.return-app'\n\nexport const createOrUpdateStatusPayload = ({\n refundStatusData,\n requestStatus,\n comment,\n submittedBy,\n createdAt,\n}: {\n refundStatusData: ReturnRequest['refundStatusData']\n requestStatus: Status\n comment: Maybe<ReturnRequestCommentInput> | undefined\n submittedBy: string\n createdAt: string\n}): ReturnRequest['refundStatusData'] => {\n if (!refundStatusData) {\n throw new ResolverError('Request does not have refundStatusData')\n }\n\n const newComment = comment\n ? {\n comment: comment.value,\n createdAt,\n submittedBy,\n visibleForCustomer: Boolean(comment.visibleForCustomer),\n role: 'adminUser' as const,\n }\n : null\n\n const hasRefundStatus = refundStatusData.find(\n ({ status }) => status === requestStatus\n )\n\n const statusPayload = hasRefundStatus\n ? refundStatusData.map((statusObject) => {\n if (statusObject.status !== requestStatus) return statusObject\n const updatedStatusObject = {\n ...statusObject,\n comments: [\n ...(statusObject?.comments ?? []),\n ...(newComment ? [newComment] : []),\n ],\n }\n\n return updatedStatusObject\n })\n : [\n ...refundStatusData,\n {\n status: requestStatus,\n submittedBy,\n createdAt,\n comments: [...(newComment ? [newComment] : [])],\n },\n ]\n\n return statusPayload\n}\n\n```"
}
] |
code_return-app_5f4741d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/canOrderBeReturned.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\n\nimport { isWithinMaxDaysToReturn } from './dateHelpers'\nimport { ORDER_TO_RETURN_VALIDATON } from './constants'\n\nconst { ORDER_NOT_INVOICED, OUT_OF_MAX_DAYS } = ORDER_TO_RETURN_VALIDATON\n\nexport const canOrderBeReturned = ({\n creationDate,\n maxDays,\n status,\n}: {\n creationDate: string\n maxDays: number\n status: string\n}) => {\n if (!isWithinMaxDaysToReturn(creationDate, maxDays)) {\n throw new ResolverError(\n 'Order is not within max days to return',\n 400,\n OUT_OF_MAX_DAYS\n )\n }\n\n if (status !== 'invoiced') {\n throw new ResolverError('Order is not invoiced', 400, ORDER_NOT_INVOICED)\n }\n}\n\n```"
}
] |
code_return-app_8747ab63
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/createRefundData.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Maybe, RefundDataInput, ReturnRequest } from 'vtex.return-app'\nimport { UserInputError } from '@vtex/api'\n\nexport const createRefundData = ({\n requestId,\n refundData,\n requestItems,\n refundableShipping,\n}: {\n requestId: string\n refundData?: Maybe<RefundDataInput>\n requestItems: ReturnRequest['items']\n refundableShipping: number\n}): ReturnRequest['refundData'] => {\n const requestItemsMap = new Map<number, ReturnRequest['items'][number]>()\n\n for (const requestedItem of requestItems ?? []) {\n requestItemsMap.set(requestedItem.orderItemIndex as number, requestedItem)\n }\n\n const items = []\n\n for (const refundItem of refundData?.items ?? []) {\n if (refundItem.quantity === 0) continue\n const requestedItem = requestItemsMap.get(refundItem.orderItemIndex)\n\n if (!requestedItem) {\n throw new UserInputError(\n `Item index ${refundItem.orderItemIndex} isn't in the return request`\n )\n }\n\n if (requestedItem.quantity < refundItem.quantity) {\n throw new UserInputError(\n `Item index ${refundItem.orderItemIndex} has a quantity of ${requestedItem.quantity} but ${refundItem.quantity} was requested to return`\n )\n }\n\n const { orderItemIndex, sellingPrice, tax, id } = requestedItem\n\n if (typeof refundItem.restockFee !== 'number') {\n throw new UserInputError(\n `Item index ${refundItem.orderItemIndex} has a invalid restockFee. It must be a number. Pass 0 if there is no restock fee.`\n )\n }\n\n items.push({\n orderItemIndex,\n id,\n price: (Number(sellingPrice) ?? 0) + (Number(tax) ?? 0),\n quantity: refundItem.quantity,\n restockFee: refundItem.restockFee,\n })\n }\n\n const refundedItemsValue = items.reduce(\n (total, item) => total + (item.price * item.quantity - item.restockFee),\n 0\n )\n\n if (typeof refundData?.refundedShippingValue !== 'number') {\n throw new UserInputError(\n 'Missing refundedShippingValue or not a valid number'\n )\n }\n\n const refundedShippingValue = refundData?.refundedShippingValue ?? 0\n\n if (refundableShipping < refundedShippingValue) {\n throw new UserInputError(\n `Refundable shipping value (${refundableShipping}) is less than the shipping value sent (${refundedShippingValue})`\n )\n }\n\n return {\n // invoiceNumber has to match the requestId.\n // This values is used to filter the invoices created via Return app when calculating the items available to be returned.\n invoiceNumber: requestId,\n invoiceValue: refundedItemsValue + refundedShippingValue,\n refundedItemsValue,\n refundedShippingValue,\n items,\n }\n}\n\n```"
}
] |
code_return-app_8efff6b3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/constants.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { OrderToReturnValidation } from 'vtex.return-app'\n\nimport type {\n ReturnRequestConfirmation,\n ReturnRequestStatusUpdate,\n} from '../typings/mailClient'\n\nexport const SETTINGS_PATH = 'app-settings'\n\nexport const ORDER_TO_RETURN_VALIDATON: Record<\n OrderToReturnValidation,\n OrderToReturnValidation\n> = {\n OUT_OF_MAX_DAYS: 'OUT_OF_MAX_DAYS',\n ORDER_NOT_INVOICED: 'ORDER_NOT_INVOICED',\n}\n\nexport const OMS_RETURN_REQUEST_CONFIRMATION = (\n locale = 'en-GB'\n): ReturnRequestConfirmation => `oms-return-request-confirmation_${locale}`\nexport const OMS_RETURN_REQUEST_CONFIRMATION_FRIENDLY_NAME = (\n locale = 'en-GB'\n) => `[OMS] Return Request Confirmation_${locale}`\n\nexport const OMS_RETURN_REQUEST_STATUS_UPDATE = (\n locale = 'en-GB'\n): ReturnRequestStatusUpdate => `oms-return-request-status-update_${locale}`\nexport const OMS_RETURN_REQUEST_STATUS_UPDATE_FRIENDLY_NAME = (\n locale = 'en-GB'\n) => `[OMS] Return Request Status Update_${locale}`\n\n```"
}
] |
code_return-app_30f4b2c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/canRefundCard.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { TransactionDetail } from '@vtex/clients'\n\nexport const canRefundCard = (\n orderTransactions: TransactionDetail[]\n): boolean =>\n orderTransactions.some((transactions) =>\n transactions.payments.some((transaction) => transaction.lastDigits)\n )\n\n```"
}
] |
code_return-app_21c43626
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/dateHelpers.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const getCurrentDate = () => new Date().toISOString()\n\nexport const substractDays = (currentDate: string, maxDays: number) => {\n const date = new Date(currentDate)\n\n date.setDate(date.getDate() - maxDays)\n date.setUTCHours(0, 0, 0)\n\n return date.toISOString()\n}\n\nexport const isWithinMaxDaysToReturn = (\n orderCreationDate: string,\n maxDays: number\n) => {\n const currentDate = getCurrentDate()\n\n const limitDateToReturn = substractDays(currentDate, maxDays)\n\n return new Date(orderCreationDate) > new Date(limitDateToReturn)\n}\n\n```"
}
] |
code_return-app_c72add09
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/appSettingsValidation.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n PaymentOptionsInput,\n PaymentTypeInput,\n CustomReturnReasonInput,\n PaymentOptions,\n} from 'vtex.return-app'\n\nexport const validatePaymentOptions = (\n paymentOptions: PaymentOptionsInput\n): PaymentOptions => {\n const {\n enablePaymentMethodSelection,\n allowedPaymentTypes,\n automaticallyRefundPaymentMethod,\n } = paymentOptions\n\n // If the user has not enabled the payment method selection, then the allowed payment types can be any available. The automaticallyRefundPaymentMethod needs to have a value.\n if (!enablePaymentMethodSelection) {\n if (typeof automaticallyRefundPaymentMethod !== 'boolean') {\n throw new Error(\n 'When payment method selection is disabled, the automaticallyRefundPaymentMethod needs to be a boolean'\n )\n }\n\n return paymentOptions\n }\n\n // Make automaticallyRefundPaymentMethod null when enablePaymentMethodSelection is true. This way we avoid confusion. We cannot have this value as true when payment method selection is eneble.\n const adjustedPaymentOptions = {\n ...paymentOptions,\n automaticallyRefundPaymentMethod: null,\n }\n\n for (const paymentType of Object.keys(allowedPaymentTypes)) {\n // If we have at least one payment method selected, then the payment options are valid.\n if (allowedPaymentTypes[paymentType as keyof PaymentTypeInput]) {\n return adjustedPaymentOptions\n }\n }\n\n // if we got here, all the alloed payment types are unselected.\n throw new Error('At least one payment method must be selected')\n}\n\nexport const validateMaxDaysCustomReasons = (\n maxDays: number,\n customReturnReasons: CustomReturnReasonInput[] | undefined | null\n) => {\n if (!customReturnReasons) return\n\n if (customReturnReasons.length === 0) return\n\n const maxCustomOptionsDays = customReturnReasons.reduce(\n (maxDay, option) => (maxDay > option.maxDays ? maxDay : option.maxDays),\n 0\n )\n\n if (maxCustomOptionsDays && maxCustomOptionsDays < maxDays) {\n throw new Error(\n `No custom reason found having max days equal or greater than the general max days of ${maxDays}`\n )\n }\n\n for (const customReason of customReturnReasons) {\n if (customReason.maxDays > maxDays) {\n throw new Error(\n `Custom reason ${customReason.reason} cannot have a max days (${customReason.maxDays}) greater than the general max days ${maxDays}`\n )\n }\n }\n}\n\nexport const valideteUniqueCustomReasonsPerLocale = (\n customReturnReasons: CustomReturnReasonInput[] | undefined | null\n) => {\n if (!customReturnReasons) return\n\n if (customReturnReasons.length === 0) return\n\n for (const customReturn of customReturnReasons) {\n const { translations } = customReturn\n\n if (!translations) continue\n\n const uniqueLocales = new Set()\n\n for (const translation of translations) {\n if (uniqueLocales.has(translation.locale)) {\n throw new Error(\n `Reason ${customReturn.reason} has duplicate translation for locale ${translation.locale}`\n )\n }\n\n uniqueLocales.add(translation.locale)\n }\n }\n}\n\n```"
}
] |
code_return-app_695f9dd1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/createRefundableTotals.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { RefundableAmountTotal, ReturnRequest } from 'vtex.return-app'\nimport type { ItemTotal } from '@vtex/clients'\n\nexport const createRefundableTotals = (\n itemsToReturn: ReturnRequest['items'],\n totals: ItemTotal[],\n proportionalShippingSetting?: boolean | null\n): RefundableAmountTotal[] => {\n const orderShippingTotal =\n totals.find(({ id }) => id === 'Shipping')?.value ?? 0\n\n const orderItemsTotal = totals.find(({ id }) => id === 'Items')?.value ?? 0\n const orderDiscountsTotal =\n totals.find(({ id }) => id === 'Discounts')?.value ?? 0\n\n const itemsAmount =\n itemsToReturn?.reduce((total, item) => {\n const { quantity, sellingPrice } = item\n\n return total + (quantity ?? 0) * (sellingPrice ?? 0)\n }, 0) ?? 0\n\n const itemsTotal = { id: 'items' as const, value: itemsAmount }\n\n const taxAmount =\n itemsToReturn?.reduce((total, item) => {\n const { quantity, tax } = item\n\n return total + (quantity ?? 0) * (tax ?? 0)\n }, 0) ?? 0\n\n const taxTotal = { id: 'tax' as const, value: taxAmount }\n\n const orderItemsValue = orderItemsTotal + orderDiscountsTotal\n\n // This handles the case where the items returned are all gifts (net value = 0)\n const areAllItemsGift = orderItemsValue === 0\n\n // If all items are gifts, we split the shipping value proportionally\n const proportionalShippingValue = areAllItemsGift\n ? orderShippingTotal / itemsToReturn.length\n : parseFloat(\n ((itemsAmount * orderShippingTotal) / orderItemsValue).toFixed(0)\n )\n\n const shippingAmount = proportionalShippingSetting\n ? proportionalShippingValue\n : orderShippingTotal\n\n const shippingTotal = { id: 'shipping' as const, value: shippingAmount }\n\n return [itemsTotal, shippingTotal, taxTotal]\n}\n\n```"
}
] |
code_return-app_11e14552
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/createOrdersToReturnSummary.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { OrderDetailResponse } from '@vtex/clients'\nimport type { MasterDataEntity } from '@vtex/clients/build/clients/masterData/MasterDataEntity'\nimport type {\n OrderToReturnSummary,\n InvoicedItem,\n ExcludedItem,\n ProcessedItem,\n ReturnAppSettings,\n ReturnRequest,\n} from 'vtex.return-app'\n\nimport { getInvoicedItems } from './getInvoicedItems'\nimport { mapItemIndexAndQuantity } from './mapItemIndexAndQuantity'\nimport { transformOrderClientProfileData } from './transformOrderClientProfileData'\nimport { transformShippingData } from './transformShippingData'\nimport { canRefundCard } from './canRefundCard'\nimport type { CatalogGQL } from '../clients/catalogGQL'\nimport { handleTranlateItems } from './translateItems'\n\ninterface CreateOrdersToReturnSummarySetup {\n excludedCategories: ReturnAppSettings['excludedCategories']\n returnRequestClient: MasterDataEntity<ReturnRequest>\n catalogGQL: CatalogGQL\n}\n\nexport const createOrdersToReturnSummary = async (\n order: OrderDetailResponse,\n email: string,\n {\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n }: CreateOrdersToReturnSummarySetup\n): Promise<OrderToReturnSummary> => {\n const { items, orderId, creationDate } = order\n\n const returnRequestSameOrder = await returnRequestClient.search(\n { page: 1, pageSize: 100 },\n ['items', 'refundData', 'refundPaymentData'],\n undefined,\n `orderId=${orderId} AND status <> cancelled`\n )\n\n const invoicesCreatedByReturnApp: string[] = []\n const committedItemsToReturn: Array<{ itemIndex: number; quantity: number }> =\n []\n\n for (const returnRequest of returnRequestSameOrder) {\n const { refundData, items: rmaItems } =\n (returnRequest as Pick<\n ReturnRequest,\n 'items' | 'refundData' | 'refundPaymentData'\n >) ?? {}\n\n const { invoiceNumber } = refundData ?? {}\n\n /**\n * Colect all invoices created by the return app.\n * The app creates invoices type Input on object only when refunding a card.\n * It's necessary to remove all the invoices from OMS Order object to avoid considering the items twice.\n */\n // Use\n if (invoiceNumber) {\n invoicesCreatedByReturnApp.push(invoiceNumber)\n }\n\n for (const item of rmaItems ?? []) {\n const { orderItemIndex, quantity } = item\n\n if (orderItemIndex === undefined || quantity === undefined) continue\n\n const committedItem = {\n itemIndex: orderItemIndex,\n quantity,\n }\n\n committedItemsToReturn.push(committedItem)\n }\n }\n\n // get all items (based on index on order.items) that were invoiced and sent to customer.\n // By the documentation: The Output type should be used when the invoice you are sending is a selling invoice\n // https://developers.vtex.com/vtex-rest-api/reference/invoicenotification\n const outputInvoicedItems = getInvoicedItems(\n order.packageAttachment.packages,\n 'Output'\n )\n\n // Keep only the invoices created outside the return app. Otherwise, an item could be cosidered twice.\n const invoicedOutsideRMAApp = order.packageAttachment.packages.filter(\n ({ invoiceNumber }) => {\n return !invoicesCreatedByReturnApp.includes(invoiceNumber)\n }\n )\n\n // get all items (based on index on order.items) that were send a return invoice.\n // By the documentation: The Input type should be used when you send a return invoice.\n // https://developers.vtex.com/vtex-rest-api/reference/invoicenotification\n const inputIvoicedItems = getInvoicedItems(invoicedOutsideRMAApp, 'Input')\n\n // Create a map to get quantity invoiced with Output type for an item (based on its index)\n const quantityInvoiced = mapItemIndexAndQuantity(outputInvoicedItems)\n\n // Create a map to get quantity invoiced with Input type for an item (based on its index)\n const returnedQuantityInvoiced = mapItemIndexAndQuantity(inputIvoicedItems)\n\n // Create a map to get quantity committed (added in other RMA) for an item (based on its index)\n const committedQuantityMap = mapItemIndexAndQuantity(committedItemsToReturn)\n\n const invoicedItems: InvoicedItem[] = []\n const excludedItems: ExcludedItem[] = []\n const processedItems: ProcessedItem[] = []\n\n // Associate itemIndex with the correspondent item in the order.item\n for (const [index, quantity] of quantityInvoiced.entries()) {\n const {\n id,\n productId,\n name,\n imageUrl,\n additionalInfo: { categoriesIds },\n } = items[index]\n\n // Here we can add the fields we want to have in the final item array. TBD the needed ones\n const currentLength = invoicedItems.push({\n id,\n productId,\n quantity,\n name,\n imageUrl,\n orderItemIndex: index,\n })\n\n const categoryIdList = categoriesIds.split('/').filter(Boolean)\n const excludedCategory = excludedCategories.filter((categoryId) =>\n categoryIdList.includes(categoryId)\n )\n\n // If item is in a category that is forbidden to be returned by admin, add it to the control array\n if (excludedCategory.length) {\n excludedItems.push({\n itemIndex: currentLength - 1,\n reason: {\n key: 'EXCLUDED_CATEGORY',\n value: JSON.stringify(excludedCategory),\n },\n })\n }\n\n // A item could have been refunded via RMA (committedQuantity) app or OMS interface or manually via API order/{orderId}/invoice (returnedQuantity)\n const returnedQuantity = returnedQuantityInvoiced.get(index) ?? 0\n const committedQuantity = committedQuantityMap.get(index) ?? 0\n\n const processedQuantity = returnedQuantity + committedQuantity\n\n if (processedQuantity) {\n processedItems.push({\n itemIndex: currentLength - 1,\n quantity: processedQuantity,\n })\n }\n }\n\n return {\n orderId,\n creationDate,\n invoicedItems: await handleTranlateItems(invoicedItems, catalogGQL),\n processedItems,\n excludedItems,\n clientProfileData: transformOrderClientProfileData(\n order.clientProfileData,\n email\n ),\n shippingData: transformShippingData(order.shippingData),\n paymentData: {\n canRefundCard: canRefundCard(order.paymentData.transactions),\n },\n }\n}\n\n```"
}
] |
code_return-app_c00b6265
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/isValidIBANNumber.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nfunction mod97(string: string) {\n let checksum = string.slice(0, 2) as string | number\n let fragment\n\n for (let offset = 2; offset < string.length; offset += 7) {\n fragment = `${String(checksum)}${string.substring(offset, offset + 7)}`\n checksum = parseInt(fragment, 10) % 97\n }\n\n return checksum\n}\n\nexport function isValidIBANNumber(input: string) {\n type CodeLengths = {\n [key: string]: number\n }\n\n const CODE_LENGTHS: CodeLengths = {\n AD: 24,\n AE: 23,\n AT: 20,\n AZ: 28,\n BA: 20,\n BE: 16,\n BG: 22,\n BH: 22,\n BR: 29,\n CH: 21,\n CR: 21,\n CY: 28,\n CZ: 24,\n DE: 22,\n DK: 18,\n DO: 28,\n EE: 20,\n ES: 24,\n FI: 18,\n FO: 18,\n FR: 27,\n GB: 22,\n GI: 23,\n GL: 18,\n GR: 27,\n GT: 28,\n HR: 21,\n HU: 28,\n IE: 22,\n IL: 23,\n IS: 26,\n IT: 27,\n JO: 30,\n KW: 30,\n KZ: 20,\n LB: 28,\n LI: 21,\n LT: 20,\n LU: 20,\n LV: 21,\n MC: 27,\n MD: 24,\n ME: 22,\n MK: 19,\n MR: 27,\n MT: 31,\n MU: 30,\n NL: 18,\n NO: 15,\n PK: 24,\n PL: 28,\n PS: 29,\n PT: 25,\n QA: 29,\n RO: 24,\n RS: 22,\n SA: 24,\n SE: 24,\n SI: 19,\n SK: 24,\n SM: 27,\n TN: 24,\n TR: 26,\n AL: 28,\n BY: 28,\n EG: 29,\n GE: 22,\n IQ: 23,\n LC: 32,\n SC: 31,\n ST: 25,\n SV: 28,\n TL: 23,\n UA: 29,\n VA: 22,\n VG: 24,\n XK: 20,\n }\n\n const iban = String(input)\n .toUpperCase()\n .replace(/[^A-Z0-9]/g, '')\n\n const code = iban.match(/^([A-Z]{2})(\\d{2})([A-Z\\d]+)$/)\n\n if (!code || iban.length !== CODE_LENGTHS[code[1]]) {\n return false\n }\n\n const dig = code[3] + code[1] + code[2]\n const digits = dig.replace(/[A-Z]/g, (letter) => {\n const returnVar = letter.charCodeAt(0) - 55\n\n return returnVar.toString()\n })\n\n // If the IBAN is correct the result should be 1 if not any number higher than 1.\n return mod97(digits) === 1\n}\n\n```"
}
] |
code_return-app_c58d7168
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/isUserAllowed.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ClientProfileDetail } from '@vtex/clients'\nimport { ForbiddenError, ResolverError } from '@vtex/api'\n\nexport const isUserAllowed = ({\n requesterUser,\n clientProfile,\n appkey,\n}: {\n requesterUser?: UserProfile\n clientProfile: ClientProfileDetail\n appkey?: string\n}) => {\n // If appkey is in the request, it means that the request was authenticated with appkey and apptoken\n if (appkey) return\n\n // if appkey doesn't exist, we need a UserProfile\n if (!requesterUser) {\n throw new ResolverError('Missing User Profile data')\n }\n\n const { userId, role } = requesterUser\n const { userProfileId } = clientProfile\n\n const orderBelongsToUser = userId === userProfileId\n const userIsAdmin = role === 'admin'\n\n // User should only be able to see / use their order.\n if (!orderBelongsToUser && !userIsAdmin) {\n throw new ForbiddenError('User cannot access this order')\n }\n}\n\n```"
}
] |
code_return-app_73600303
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/validateStatusUpdate.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError, UserInputError } from '@vtex/api'\nimport type { Status } from 'vtex.return-app'\n\nconst statusAllowed: Record<Status, Status[]> = {\n new: ['new', 'processing', 'denied', 'cancelled'],\n processing: ['processing', 'pickedUpFromClient', 'denied', 'cancelled'],\n pickedUpFromClient: ['pickedUpFromClient', 'pendingVerification', 'denied'],\n pendingVerification: ['pendingVerification', 'packageVerified'],\n // In this step, when sending the items to the resolver, it will assign the status denied or packageVerified based on the items sent.\n packageVerified: ['packageVerified', 'amountRefunded'],\n amountRefunded: ['amountRefunded'],\n denied: ['denied'],\n cancelled: ['cancelled'],\n}\n\nexport const validateStatusUpdate = (\n newStatus: Status,\n currentStatus: Status\n) => {\n if (!newStatus) {\n throw new UserInputError('Missing status')\n }\n\n if (!statusAllowed[newStatus]) {\n throw new UserInputError(\n `Invalid status: ${newStatus}. Valid values: ${Object.keys(\n statusAllowed\n ).join(', ')}`\n )\n }\n\n if (!statusAllowed[currentStatus].includes(newStatus)) {\n throw new ResolverError(\n `Status transition from ${currentStatus} to ${newStatus} is not allowed. Valid status: ${statusAllowed[\n currentStatus\n ].join(', ')}`\n )\n }\n}\n\n```"
}
] |
code_return-app_701d03e5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/returnRequestList.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { QueryReturnRequestListArgs } from 'vtex.return-app'\n\nimport { returnRequestListService } from '../services/returnRequestListService'\n\nexport const returnRequestList = (\n _: unknown,\n args: QueryReturnRequestListArgs,\n ctx: Context\n) => {\n return returnRequestListService(ctx, args)\n}\n\n```"
}
] |
code_return-app_a01e0e2c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/appSettings.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n ReturnAppSettings,\n MutationSaveReturnAppSettingsArgs,\n} from 'vtex.return-app'\n\nimport {\n validateMaxDaysCustomReasons,\n validatePaymentOptions,\n valideteUniqueCustomReasonsPerLocale,\n} from '../utils/appSettingsValidation'\nimport { SETTINGS_PATH } from '../utils/constants'\n\nconst returnAppSettings = async (\n _root: unknown,\n _args: unknown,\n ctx: Context\n): Promise<ReturnAppSettings | null> => {\n const {\n clients: { appSettings },\n } = ctx\n\n const settings = await appSettings.get(SETTINGS_PATH, true)\n\n if (!settings) return null\n\n return settings\n}\n\nconst saveReturnAppSettings = async (\n _root: unknown,\n args: MutationSaveReturnAppSettingsArgs,\n ctx: Context\n) => {\n const {\n clients: { appSettings },\n } = ctx\n\n // validate if all custom reasons have max days smaller than the general max days\n validateMaxDaysCustomReasons(\n args.settings.maxDays,\n args.settings.customReturnReasons\n )\n\n // validate if all custom reasons have unique locales for their translations\n valideteUniqueCustomReasonsPerLocale(args.settings.customReturnReasons)\n\n const settings = {\n ...args.settings,\n // validate that there is at least one payment method selected or user has to use the same as in the order\n paymentOptions: validatePaymentOptions(args.settings.paymentOptions),\n }\n\n await appSettings.save(SETTINGS_PATH, settings)\n\n return true\n}\n\nexport const queries = { returnAppSettings }\nexport const mutations = { saveReturnAppSettings }\n\n```"
}
] |
code_return-app_5080ed39
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/orderToReturnSummary.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError, UserInputError } from '@vtex/api'\nimport type { OrderToReturnSummary } from 'vtex.return-app'\n\nimport { SETTINGS_PATH } from '../utils/constants'\nimport { createOrdersToReturnSummary } from '../utils/createOrdersToReturnSummary'\nimport { isUserAllowed } from '../utils/isUserAllowed'\nimport { canOrderBeReturned } from '../utils/canOrderBeReturned'\nimport { getCustomerEmail } from '../utils/getCostumerEmail'\n\nexport const orderToReturnSummary = async (\n _: unknown,\n args: { orderId: string; storeUserEmail?: string },\n ctx: Context\n): Promise<OrderToReturnSummary> => {\n const { orderId, storeUserEmail } = args\n const {\n state: { userProfile, appkey },\n clients: {\n appSettings,\n oms,\n returnRequest: returnRequestClient,\n catalogGQL,\n },\n vtex: { logger },\n } = ctx\n\n const settings = await appSettings.get(SETTINGS_PATH, true)\n\n if (!settings) {\n throw new ResolverError('Return App settings is not configured', 500)\n }\n\n const { maxDays, excludedCategories } = settings\n\n // For requests where orderId is an empty string\n if (!orderId) {\n throw new UserInputError('Order ID is missing')\n }\n\n const order = await oms.order(orderId)\n\n const { creationDate, clientProfileData, status } = order\n\n isUserAllowed({\n requesterUser: userProfile,\n clientProfile: clientProfileData,\n appkey,\n })\n\n canOrderBeReturned({\n creationDate,\n maxDays,\n status,\n })\n\n const customerEmail = getCustomerEmail(\n clientProfileData,\n {\n userProfile,\n appkey,\n inputEmail: storeUserEmail,\n },\n {\n logger,\n }\n )\n\n return createOrdersToReturnSummary(order, customerEmail, {\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n })\n}\n\n```"
}
] |
code_return-app_5454804b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/nearestPickupPoints.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n QueryNearestPickupPointsArgs,\n NearPickupPointQueryResponse,\n} from 'vtex.return-app'\n\nexport const nearestPickupPoints = async (\n _: unknown,\n { lat, long }: QueryNearestPickupPointsArgs,\n ctx: Context\n): Promise<NearPickupPointQueryResponse> => {\n const {\n clients: { checkout },\n } = ctx\n\n const closestPickupPointsData = await checkout.getNearestPickupPoints(\n lat,\n long\n )\n\n return closestPickupPointsData\n}\n\n```"
}
] |
code_return-app_3bc72b16
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/createReturnRequest.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { MutationCreateReturnRequestArgs } from 'vtex.return-app'\n\nimport { createReturnRequestService } from '../services/createReturnRequestService'\n\nexport const createReturnRequest = async (\n _: unknown,\n args: MutationCreateReturnRequestArgs,\n ctx: Context\n) => {\n const { returnRequest } = args\n\n return createReturnRequestService(ctx, returnRequest)\n}\n\n```"
}
] |
code_return-app_fbe13f61
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/updateReturnRequestStatus.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n MutationUpdateReturnRequestStatusArgs,\n ReturnRequest,\n} from 'vtex.return-app'\n\nimport { updateRequestStatusService } from '../services/updateRequestStatusService'\n\nexport const updateReturnRequestStatus = (\n _: unknown,\n args: MutationUpdateReturnRequestStatusArgs,\n ctx: Context\n): Promise<ReturnRequest> => updateRequestStatusService(ctx, args)\n\n```"
}
] |
code_return-app_a51ff175
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/returnRequest.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { QueryReturnRequestArgs } from 'vtex.return-app'\n\nimport { returnRequestService } from '../services/returnRequestService'\n\nexport const returnRequest = async (\n _: unknown,\n { requestId }: QueryReturnRequestArgs,\n ctx: Context\n) => {\n return returnRequestService(ctx, requestId)\n}\n\n```"
}
] |
code_return-app_17c842bc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/categoryTreeName.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { CategoryInfo } from 'vtex.return-app'\n\nconst transformCategoryTree = (\n categoryTree: CategoryTree[],\n parentName = ''\n): CategoryInfo[] => {\n const categoryInfoFlatten = []\n\n for (const category of categoryTree) {\n if (!category.hasChildren) {\n categoryInfoFlatten.push({\n id: category.id,\n name: parentName ? `${parentName} > ${category.name}` : category.name,\n })\n } else {\n const categoryTreeName = parentName\n ? `${parentName} > ${category.name}`\n : category.name\n\n const group = transformCategoryTree(category.children, categoryTreeName)\n\n categoryInfoFlatten.push(...group, {\n id: category.id,\n name: categoryTreeName,\n })\n }\n }\n\n return categoryInfoFlatten\n}\n\nexport const categoryTreeName = async (\n _: unknown,\n _args: unknown,\n ctx: Context\n): Promise<CategoryInfo[]> => {\n const {\n clients: { catalog },\n } = ctx\n\n const categoryTree = await catalog.getCategoryTree()\n\n return transformCategoryTree(categoryTree)\n}\n\n```"
}
] |
code_return-app_e06e6227
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/ReturnRequestResponse.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ReturnRequest } from 'vtex.return-app'\n\ntype VtexProduct = 'admin' | 'store' | undefined\n\nconst removeSubmittedByForStoreUser = (\n statusData: ReturnRequest['refundStatusData'][number],\n vtexProduct: VtexProduct\n) => {\n if (vtexProduct === 'store') {\n return {\n ...statusData,\n submittedBy: undefined,\n }\n }\n\n return statusData\n}\n\n// This function hides the submittedBy field and removes the comments that should not be visible to the store user\nconst transformStatusForStoreUser = (\n refundStatusDataList: ReturnRequest['refundStatusData'],\n vtexProduct: VtexProduct\n) => {\n return (\n refundStatusDataList?.map((statusData) => {\n return {\n ...removeSubmittedByForStoreUser(statusData, vtexProduct),\n comments: statusData.comments?.filter((comment) => {\n return vtexProduct !== 'store' || comment.visibleForCustomer\n }),\n }\n }) ?? []\n )\n}\n\n// This resolver allows the parent one to fetch just the root fields for a ReturnRequest.\n// This stategy can save some kb when transfering data, since that in a search, we don't need all the fields.\nexport const ReturnRequestResponse = {\n refundableAmount: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, refundableAmount } = root\n\n if (refundableAmount) return refundableAmount\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { refundableAmount: refundableAmountValue } =\n await returnRequestClient.get(id as string, ['refundableAmount'])\n\n return refundableAmountValue\n },\n customerProfileData: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, customerProfileData } = root\n\n if (customerProfileData) return customerProfileData\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { customerProfileData: customerProfile } =\n await returnRequestClient.get(id as string, ['customerProfileData'])\n\n return customerProfile\n },\n refundableAmountTotals: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, refundableAmountTotals } = root\n\n if (refundableAmountTotals) return refundableAmountTotals\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { refundableAmountTotals: refundableAmountTotalsData } =\n await returnRequestClient.get(id as string, ['refundableAmountTotals'])\n\n return refundableAmountTotalsData\n },\n pickupReturnData: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, pickupReturnData } = root\n\n if (pickupReturnData) return pickupReturnData\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { pickupReturnData: pickupData } = await returnRequestClient.get(\n id as string,\n ['pickupReturnData']\n )\n\n return pickupData\n },\n refundPaymentData: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, refundPaymentData } = root\n\n if (refundPaymentData) return refundPaymentData\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { refundPaymentData: refundData } = await returnRequestClient.get(\n id as string,\n ['refundPaymentData']\n )\n\n return refundData\n },\n items: async (root: ReturnRequest, _args: unknown, ctx: Context) => {\n const { id, items } = root\n\n if (items) return items\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { items: itemsList } = await returnRequestClient.get(id as string, [\n 'items',\n ])\n\n return itemsList\n },\n refundData: async (root: ReturnRequest, _args: unknown, ctx: Context) => {\n const { id, refundData } = root\n\n if (refundData) return refundData\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { refundData: refundDataList } = await returnRequestClient.get(\n id as string,\n ['refundData']\n )\n\n return refundDataList\n },\n refundStatusData: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, refundStatusData } = root\n const {\n clients: { returnRequest: returnRequestClient },\n request: { header },\n } = ctx\n\n const vtexProduct = header['x-vtex-product'] as VtexProduct\n\n const { refundStatusData: refundStatusDataList } = refundStatusData\n ? { refundStatusData }\n : await returnRequestClient.get(id as string, ['refundStatusData'])\n\n return transformStatusForStoreUser(refundStatusDataList, vtexProduct)\n },\n cultureInfoData: async (\n root: ReturnRequest,\n _args: unknown,\n ctx: Context\n ) => {\n const { id, cultureInfoData } = root\n\n if (cultureInfoData) return cultureInfoData\n\n const {\n clients: { returnRequest: returnRequestClient },\n } = ctx\n\n const { cultureInfoData: cultureInfo } = await returnRequestClient.get(\n id as string,\n ['cultureInfoData']\n )\n\n return cultureInfo\n },\n // Resolve dateSubmitted value into createdIn field because we lost the original value of createdIn (migration data from v2 to v3).\n createdIn: async (root: ReturnRequest) => {\n const { dateSubmitted } = root\n\n return dateSubmitted\n },\n}\n\n```"
}
] |
code_return-app_3704d6ef
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/ordersAvailableToReturn.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError } from '@vtex/api'\nimport type { OrdersToReturnList, OrderToReturnSummary } from 'vtex.return-app'\n\nimport { SETTINGS_PATH } from '../utils/constants'\nimport { createOrdersToReturnSummary } from '../utils/createOrdersToReturnSummary'\nimport { getCurrentDate, substractDays } from '../utils/dateHelpers'\n\nconst ONE_MINUTE = 60 * 1000\n\nfunction pacer(callsPerMinute: number) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve('done')\n }, ONE_MINUTE / callsPerMinute)\n })\n}\n\nconst createParams = ({\n maxDays,\n userEmail,\n page = 1,\n}: {\n maxDays: number\n userEmail: string\n page: number\n}) => {\n const currentDate = getCurrentDate()\n\n return {\n clientEmail: userEmail,\n orderBy: 'creationDate,desc' as const,\n f_status: 'invoiced' as const,\n f_creationDate: `creationDate:[${substractDays(\n currentDate,\n maxDays\n )} TO ${currentDate}]`,\n page,\n per_page: 10 as const,\n }\n}\n\nexport const ordersAvailableToReturn = async (\n _: unknown,\n args: { page: number; storeUserEmail?: string },\n ctx: Context\n): Promise<OrdersToReturnList> => {\n const {\n state: { userProfile },\n clients: {\n appSettings,\n oms,\n returnRequest: returnRequestClient,\n catalogGQL,\n },\n } = ctx\n\n const { page, storeUserEmail } = args\n\n const settings = await appSettings.get(SETTINGS_PATH, true)\n\n if (!settings) {\n throw new ResolverError('Return App settings is not configured')\n }\n\n const { maxDays, excludedCategories } = settings\n const { email } = userProfile ?? {}\n\n const userEmail = storeUserEmail ?? email\n\n if (!userEmail) {\n throw new ResolverError('Missing user email', 400)\n }\n\n // Fetch order associated to the user email\n const { list, paging } = await oms.listOrdersWithParams(\n createParams({ maxDays, userEmail, page })\n )\n\n const orderListPromises = []\n\n for (const order of list) {\n // Fetch order details to get items and packages\n const orderPromise = oms.order(order.orderId)\n\n orderListPromises.push(orderPromise)\n\n // eslint-disable-next-line no-await-in-loop\n await pacer(2000)\n }\n\n const orders = await Promise.all(orderListPromises)\n\n const orderSummaryPromises: Array<Promise<OrderToReturnSummary>> = []\n\n for (const order of orders) {\n const orderToReturnSummary = createOrdersToReturnSummary(order, userEmail, {\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n })\n\n orderSummaryPromises.push(orderToReturnSummary)\n }\n\n const orderList = await Promise.all(orderSummaryPromises)\n\n return { list: orderList, paging }\n}\n\n```"
}
] |
code_return-app_41b6fb59
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/resolvers/index.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { createReturnRequest } from './createReturnRequest'\nimport {\n queries as settingsQuery,\n mutations as settingsMutation,\n} from './appSettings'\nimport { categoryTreeName } from './categoryTreeName'\nimport { ordersAvailableToReturn } from './ordersAvailableToReturn'\nimport { orderToReturnSummary } from './orderToReturnSummary'\nimport { returnRequest } from './returnRequest'\nimport { returnRequestList } from './returnRequestList'\nimport { ReturnRequestResponse } from './ReturnRequestResponse'\nimport { updateReturnRequestStatus } from './updateReturnRequestStatus'\nimport { nearestPickupPoints } from './nearestPickupPoints'\n\nexport const mutations = {\n createReturnRequest,\n updateReturnRequestStatus,\n ...settingsMutation,\n}\n\nexport const queries = {\n ...settingsQuery,\n categoryTreeName,\n ordersAvailableToReturn,\n orderToReturnSummary,\n returnRequest,\n returnRequestList,\n nearestPickupPoints,\n}\n\nexport const resolvers = { ReturnRequestResponse }\n\n```"
}
] |
code_return-app_95f074fa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/__tests__/simple.test.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n// You can import your files here for testing them\n//\n// More info: https://github.com/sapegin/jest-cheat-sheet\n\ndescribe('simpleTest', () => {\n it('one test case', async () => {\n expect(0.2 + 0.1).not.toBe(0.3)\n })\n})\n\n```"
}
] |
code_return-app_9f92fca9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/services/createReturnRequestService.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { ReturnRequestCreated, ReturnRequestInput } from 'vtex.return-app'\nimport { UserInputError, ResolverError } from '@vtex/api'\nimport type { DocumentResponse } from '@vtex/clients/build/clients/masterData/MasterDataEntity'\n\nimport {\n SETTINGS_PATH,\n OMS_RETURN_REQUEST_CONFIRMATION,\n} from '../utils/constants'\nimport { isUserAllowed } from '../utils/isUserAllowed'\nimport { canOrderBeReturned } from '../utils/canOrderBeReturned'\nimport { canReturnAllItems } from '../utils/canReturnAllItems'\nimport { validateReturnReason } from '../utils/validateReturnReason'\nimport { validatePaymentMethod } from '../utils/validatePaymentMethod'\nimport { validateCanUsedropoffPoints } from '../utils/validateCanUseDropoffPoints'\nimport { createItemsToReturn } from '../utils/createItemsToReturn'\nimport { createRefundableTotals } from '../utils/createRefundableTotals'\nimport { OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE } from '../utils/templates'\nimport type { ConfirmationMailData } from '../typings/mailClient'\nimport { getCustomerEmail } from '../utils/getCostumerEmail'\nimport { validateItemCondition } from '../utils/validateItemCondition'\n\nexport const createReturnRequestService = async (\n ctx: Context,\n args: ReturnRequestInput\n): Promise<ReturnRequestCreated> => {\n const {\n clients: {\n oms,\n returnRequest: returnRequestClient,\n appSettings,\n mail,\n catalogGQL,\n },\n state: { userProfile, appkey },\n vtex: { logger },\n } = ctx\n\n const {\n orderId,\n items,\n customerProfileData,\n pickupReturnData,\n refundPaymentData,\n userComment,\n locale,\n } = args\n\n if (!appkey && !userProfile) {\n throw new ResolverError('Missing appkey or userProfile')\n }\n\n const { firstName, lastName, email } = userProfile ?? {}\n\n const submittedByNameOrEmail =\n firstName || lastName ? `${firstName} ${lastName}` : email\n\n // If request was validated using appkey and apptoken, we assign the appkey as a sender\n // Otherwise, we try to use requester name. Email is the last resort.\n const submittedBy = appkey ?? submittedByNameOrEmail\n\n if (!submittedBy) {\n throw new ResolverError(\n 'Unable to get submittedBy from context. The request is missing the userProfile info or the appkey'\n )\n }\n\n const requestDate = new Date().toISOString()\n\n // Check items since a request via endpoint might not have it.\n // Graphql validation doesn't prevent user to send empty items\n if (!items || items.length === 0) {\n throw new UserInputError('There are no items in the request')\n }\n\n // For requests where orderId is an empty string\n if (!orderId) {\n throw new UserInputError('Order ID is missing')\n }\n\n const orderPromise = oms.order(orderId, 'AUTH_TOKEN')\n\n const searchRMAPromise = returnRequestClient.searchRaw(\n { page: 1, pageSize: 1 },\n ['id'],\n undefined,\n `orderId=${orderId}`\n )\n\n const settingsPromise = appSettings.get(SETTINGS_PATH, true)\n\n // If order doesn't exist, it throws an error and stop the process.\n // If there is no request created for that order, request searchRMA will be an empty array.\n const [order, searchRMA, settings] = await Promise.all([\n orderPromise,\n searchRMAPromise,\n settingsPromise,\n ])\n\n if (!settings) {\n throw new ResolverError('Return App settings is not configured', 500)\n }\n\n const {\n pagination: { total },\n } = searchRMA\n\n const {\n sequence,\n clientProfileData,\n items: orderItems,\n totals,\n creationDate,\n status,\n sellers,\n // @ts-expect-error itemMetadata is not typed in the OMS client project\n itemMetadata,\n shippingData,\n storePreferencesData: { currencyCode },\n } = order\n\n const {\n maxDays,\n excludedCategories,\n customReturnReasons,\n paymentOptions,\n options: settingsOptions,\n } = settings\n\n isUserAllowed({\n requesterUser: userProfile,\n clientProfile: clientProfileData,\n appkey,\n })\n\n canOrderBeReturned({\n creationDate,\n maxDays,\n status,\n })\n\n // Validate if all items are available to be returned\n await canReturnAllItems(items, {\n order,\n excludedCategories,\n returnRequestClient,\n catalogGQL,\n })\n\n // Validate maxDays for custom reasons.\n validateReturnReason(items, creationDate, customReturnReasons)\n\n // Validate payment methods\n validatePaymentMethod(refundPaymentData, paymentOptions)\n\n // validate address type\n validateCanUsedropoffPoints(\n pickupReturnData,\n settingsOptions?.enablePickupPoints\n )\n\n // validate item condition\n validateItemCondition(items, settingsOptions?.enableSelectItemCondition)\n\n // Possible bug here: If someone deletes a request, it can lead to a duplicated sequence number.\n // Possible alternative: Save a key value pair in to VBase where key is the orderId and value is either the latest sequence (as number) or an array with all Ids, so we can use the length to calcualate the next seuqence number.\n const sequenceNumber = `${sequence}-${total + 1}`\n\n const itemsToReturn = await createItemsToReturn({\n itemsToReturn: items,\n orderItems,\n sellers,\n itemMetadata,\n catalogGQL,\n })\n\n const refundableAmountTotals = createRefundableTotals(\n itemsToReturn,\n totals,\n settings?.options?.enableProportionalShippingValue\n )\n\n const refundableAmount = refundableAmountTotals.reduce(\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (amount, cur) => amount + cur.value,\n 0\n )\n\n const userCommentData = userComment\n ? [\n {\n comment: userComment,\n createdAt: requestDate,\n submittedBy,\n visibleForCustomer: true,\n role: 'storeUser' as const,\n },\n ]\n : []\n\n // customerProfileData can be undefined when coming from a endpoint request\n const { email: inputEmail } = customerProfileData ?? {}\n\n const customerEmail = getCustomerEmail(\n clientProfileData,\n {\n userProfile,\n appkey,\n inputEmail,\n },\n {\n logger,\n }\n )\n\n const { refundPaymentMethod } = refundPaymentData\n\n const { iban, accountHolderName, ...refundPaymentMethodSubset } =\n refundPaymentData\n\n const refundPaymentDataResult =\n refundPaymentMethod === 'bank'\n ? refundPaymentData\n : refundPaymentMethodSubset\n\n const { automaticallyRefundPaymentMethod } = paymentOptions\n\n const createInvoiceTypeInput =\n refundPaymentMethod === 'sameAsPurchase'\n ? Boolean(automaticallyRefundPaymentMethod)\n : null\n\n let rmaDocument: DocumentResponse\n\n try {\n rmaDocument = await returnRequestClient.save({\n orderId,\n refundableAmount,\n sequenceNumber,\n status: 'new',\n refundableAmountTotals,\n customerProfileData: {\n userId: clientProfileData.userProfileId,\n name: customerProfileData.name,\n email: customerEmail,\n phoneNumber: customerProfileData.phoneNumber,\n },\n pickupReturnData,\n refundPaymentData: {\n ...refundPaymentDataResult,\n automaticallyRefundPaymentMethod: createInvoiceTypeInput,\n },\n items: itemsToReturn,\n dateSubmitted: requestDate,\n refundData: null,\n refundStatusData: [\n {\n status: 'new',\n submittedBy,\n createdAt: requestDate,\n comments: userCommentData,\n },\n ],\n cultureInfoData: {\n currencyCode,\n locale,\n },\n })\n } catch (error) {\n const mdValidationErrors = error?.response?.data?.errors[0]?.errors\n\n const errorMessageString = mdValidationErrors\n ? JSON.stringify(\n {\n message: 'Schema Validation error',\n errors: mdValidationErrors,\n },\n null,\n 2\n )\n : error.message\n\n throw new ResolverError(errorMessageString, error.response?.status || 500)\n }\n\n // We add a try/catch here so we avoid sending an error to the browser only if the email fails.\n try {\n const templateExists = await mail.getTemplate(\n OMS_RETURN_REQUEST_CONFIRMATION(locale)\n )\n\n if (!templateExists) {\n await mail.publishTemplate(\n OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE(locale)\n )\n }\n\n const {\n firstName: clientFirstName,\n lastName: clientLastName,\n phone,\n } = clientProfileData\n\n const {\n address: { country, city, street },\n } = shippingData\n\n const mailData: ConfirmationMailData = {\n templateName: OMS_RETURN_REQUEST_CONFIRMATION(locale),\n jsonData: {\n data: {\n status: 'new',\n name: `${clientFirstName} ${clientLastName}`,\n DocumentId: rmaDocument.DocumentId,\n email: customerEmail,\n phoneNumber: phone,\n country,\n locality: city,\n address: street,\n paymentMethod: refundPaymentData.refundPaymentMethod,\n },\n products: [...itemsToReturn],\n refundStatusData: [\n {\n status: 'new',\n submittedBy,\n createdAt: requestDate,\n comments: userCommentData,\n },\n ],\n },\n }\n\n await mail.sendMail(mailData)\n } catch (error) {\n logger.warn({\n message: `Failed to send email for return request ${rmaDocument.DocumentId}`,\n error,\n })\n }\n\n return { returnRequestId: rmaDocument.DocumentId }\n}\n\n```"
}
] |
code_return-app_d93e8264
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/services/updateRequestStatusService.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n MutationUpdateReturnRequestStatusArgs,\n ReturnRequest,\n Status,\n RefundItemInput,\n} from 'vtex.return-app'\nimport {\n ResolverError,\n ForbiddenError,\n NotFoundError,\n UserInputError,\n} from '@vtex/api'\n\nimport { validateStatusUpdate } from '../utils/validateStatusUpdate'\nimport { createOrUpdateStatusPayload } from '../utils/createOrUpdateStatusPayload'\nimport { createRefundData } from '../utils/createRefundData'\nimport { handleRefund } from '../utils/handleRefund'\nimport { OMS_RETURN_REQUEST_STATUS_UPDATE } from '../utils/constants'\nimport { OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE } from '../utils/templates'\nimport type { StatusUpdateMailData } from '../typings/mailClient'\n\n// A partial update on MD requires all required field to be sent. https://vtex.slack.com/archives/C8EE14F1C/p1644422359807929\n// And the request to update fails when we pass the auto generated ones.\n// If any new field is added to the ReturnRequest as required, it has to be added here too.\nconst formatRequestToPartialUpdate = (\n request: ReturnRequest\n): ReturnRequest => {\n const {\n orderId,\n refundableAmount,\n sequenceNumber,\n status,\n customerProfileData,\n pickupReturnData,\n refundPaymentData,\n items,\n refundData,\n refundableAmountTotals,\n refundStatusData,\n cultureInfoData,\n dateSubmitted,\n } = request\n\n const partialUpdate = {\n orderId,\n refundableAmount,\n sequenceNumber,\n status,\n customerProfileData,\n pickupReturnData,\n refundPaymentData,\n items,\n refundData,\n refundableAmountTotals,\n refundStatusData,\n cultureInfoData,\n dateSubmitted,\n }\n\n return partialUpdate\n}\n\nconst acceptOrDenyPackage = (refundItemList?: RefundItemInput[]) => {\n if (!refundItemList) {\n throw new UserInputError(\n 'Missing items inside refundData object. It is necessary to pass a list of items to refund. To deny all items, pass a empty array.'\n )\n }\n\n if (!Array.isArray(refundItemList)) {\n throw new UserInputError(\n 'Item has to be an array. To deny all items, pass a empty array.'\n )\n }\n\n return refundItemList.some(({ quantity, orderItemIndex }) => {\n if (typeof quantity !== 'number') {\n throw new UserInputError(\n `Not a valid quantity for item index ${orderItemIndex}`\n )\n }\n\n return quantity > 0\n })\n ? 'packageVerified'\n : 'denied'\n}\n\nexport const updateRequestStatusService = async (\n ctx: Context,\n args: MutationUpdateReturnRequestStatusArgs\n): Promise<ReturnRequest> => {\n const {\n state: { userProfile, appkey },\n clients: {\n returnRequest: returnRequestClient,\n oms,\n giftCard: giftCardClient,\n mail,\n },\n vtex: { logger },\n } = ctx\n\n const { status, requestId, comment, refundData } = args\n\n const { role, firstName, lastName, email, userId } = userProfile ?? {}\n\n const requestDate = new Date().toISOString()\n const submittedByNameOrEmail =\n firstName || lastName ? `${firstName} ${lastName}` : email\n\n const submittedBy = appkey ?? submittedByNameOrEmail\n\n if (!submittedBy) {\n throw new ResolverError(\n 'Unable to get submittedBy from context. The request is missing the userProfile info or the appkey'\n )\n }\n\n const returnRequest = (await returnRequestClient.get(requestId, [\n '_all',\n ])) as ReturnRequest\n\n if (!returnRequest) {\n throw new NotFoundError(`Request ${requestId} not found`)\n }\n\n const userIsAdmin = Boolean(appkey) || role === 'admin'\n\n const belongsToStoreUser =\n returnRequest.customerProfileData.userId === userId &&\n returnRequest.status === 'new'\n\n if (!userIsAdmin && !belongsToStoreUser) {\n throw new ForbiddenError('Not authorized')\n }\n\n validateStatusUpdate(status, returnRequest.status as Status)\n\n // when a request is made for the same status, it means admin user is adding a new comment\n if (status === returnRequest.status && !comment) {\n throw new UserInputError(\n 'Missing comment. Comment is needed when status sent is equal the current status.'\n )\n }\n\n const isPackageVerified = status === 'packageVerified'\n\n // This is need in case a user wants to add a comment when status is packageVerified.\n // It avoids recreating a new refundData object and updating the request status\n const createRefundInvoice = isPackageVerified && !returnRequest.refundData\n\n if (createRefundInvoice && !refundData) {\n throw new UserInputError(\n 'Missing refundData property. To update status to packageVerified it is necessary to send items verification object.'\n )\n }\n\n // When status is packageVerified, the final status is based on the quantity of items. If none is approved, status is denied.\n const requestStatus = createRefundInvoice\n ? acceptOrDenyPackage(refundData?.items)\n : status\n\n const refundStatusData = createOrUpdateStatusPayload({\n refundStatusData: returnRequest.refundStatusData,\n requestStatus,\n comment,\n submittedBy,\n createdAt: requestDate,\n })\n\n const maxRefundableShipping =\n returnRequest.refundableAmountTotals.find(({ id }) => id === 'shipping')\n ?.value ?? 0\n\n const refundInvoice =\n createRefundInvoice && requestStatus !== 'denied'\n ? createRefundData({\n requestId,\n refundData,\n requestItems: returnRequest.items,\n refundableShipping: maxRefundableShipping,\n })\n : returnRequest.refundData\n\n const refundReturn = await handleRefund({\n currentStatus: requestStatus,\n previousStatus: returnRequest.status,\n refundPaymentData: returnRequest.refundPaymentData ?? {},\n orderId: returnRequest.orderId as string,\n createdAt: requestDate,\n refundInvoice,\n userEmail: returnRequest.customerProfileData?.email as string,\n clients: {\n omsClient: oms,\n giftCardClient,\n },\n })\n\n const giftCard = refundReturn?.giftCard\n\n const updatedRequest = {\n ...formatRequestToPartialUpdate(returnRequest),\n status: requestStatus,\n refundStatusData,\n refundData: refundInvoice\n ? { ...refundInvoice, ...(giftCard ? { giftCard } : null) }\n : null,\n }\n\n try {\n await returnRequestClient.update(requestId, updatedRequest)\n } catch (error) {\n const mdValidationErrors = error?.response?.data?.errors[0]?.errors\n\n const errorMessageString = mdValidationErrors\n ? JSON.stringify(\n {\n message: 'Schema Validation error',\n errors: mdValidationErrors,\n },\n null,\n 2\n )\n : error.message\n\n throw new ResolverError(errorMessageString, error.response?.status || 500)\n }\n\n const { cultureInfoData } = updatedRequest\n\n // We add a try/catch here so we avoid sending an error to the browser only if the email fails.\n try {\n const templateExists = await mail.getTemplate(\n OMS_RETURN_REQUEST_STATUS_UPDATE(cultureInfoData?.locale)\n )\n\n if (!templateExists) {\n await mail.publishTemplate(\n OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE(cultureInfoData?.locale)\n )\n }\n\n const {\n status: updatedStatus,\n items,\n customerProfileData,\n refundStatusData: updatedRefundStatusData,\n refundPaymentData,\n refundData: updatedRefundData,\n } = updatedRequest\n\n const mailData: StatusUpdateMailData = {\n templateName: OMS_RETURN_REQUEST_STATUS_UPDATE(cultureInfoData?.locale),\n jsonData: {\n data: {\n status: updatedStatus,\n name: customerProfileData?.name ?? '',\n DocumentId: requestId,\n email: customerProfileData?.email ?? '',\n paymentMethod: refundPaymentData?.refundPaymentMethod ?? '',\n iban: refundPaymentData?.iban ?? '',\n refundedAmount:\n Number(updatedRefundData?.refundedItemsValue) +\n Number(updatedRefundData?.refundedShippingValue),\n },\n products: items,\n refundStatusData: updatedRefundStatusData,\n },\n }\n\n await mail.sendMail(mailData)\n } catch (error) {\n logger.warn({\n message: `Failed to send email for return request ${requestId}`,\n error,\n })\n }\n\n return { id: requestId, ...updatedRequest }\n}\n\n```"
}
] |
code_return-app_374336a7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/services/returnRequestListService.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n QueryReturnRequestListArgs,\n ReturnRequestFilters,\n Maybe,\n} from 'vtex.return-app'\nimport { ForbiddenError } from '@vtex/api'\n\nconst filterDate = (date: string): string => {\n const newDate = new Date(date)\n const day = newDate.getDate()\n const month = newDate.getMonth() + 1\n const year = newDate.getFullYear()\n\n return `${year}-${month < 10 ? `0${month}` : `${month}`}-${\n day < 10 ? `0${day}` : `${day}`\n }`\n}\n\nconst buildWhereClause = (filter: Maybe<ReturnRequestFilters> | undefined) => {\n if (!filter) return\n\n const returnFilters = Object.entries(filter)\n const whereFilter = returnFilters.reduce((where, [key, value]) => {\n if (!value) return where\n\n if (where.length) {\n where += ` AND `\n }\n\n if (key === 'userId') {\n where += `customerProfileData.userId = \"${value}\"`\n\n return where\n }\n\n if (key === 'userEmail') {\n where += `customerProfileData.email = \"${value}\"`\n\n return where\n }\n\n if (key === 'createdIn' && typeof value !== 'string') {\n where += `dateSubmitted between ${filterDate(\n value.from\n )} AND ${filterDate(value.to)}`\n\n return where\n }\n\n where += `${key}=${value}`\n\n return where\n }, '')\n\n return whereFilter\n}\n\nexport const returnRequestListService = async (\n ctx: Context,\n args: QueryReturnRequestListArgs,\n getAllFields = false\n) => {\n const {\n clients: { returnRequest: returnRequestClient },\n request: { header },\n state: { userProfile, appkey },\n } = ctx\n\n const { page, perPage, filter } = args\n const {\n userId: userIdProfile,\n email: userEmailProfile,\n role,\n } = userProfile ?? {}\n\n const { userId: userIdArg, userEmail: userEmailArg } = filter ?? {}\n\n const userIsAdmin = Boolean(appkey) || role === 'admin'\n\n // only admin users can pass userId or userEmail in the request.\n // For non admin users, the userId or userEmail must be gotten from cookie session.\n // Otherwise, a non admin user could search for another user's return requests\n const userId = userIsAdmin ? userIdArg || userIdProfile : userIdProfile\n const userEmail = userIsAdmin\n ? userEmailArg || userEmailProfile\n : userEmailProfile\n\n // vtexProduct is undefined when coming from GraphQL IDE or from a external request\n const vtexProduct = header['x-vtex-product'] as 'admin' | 'store' | undefined\n\n // When the user is not admin or the request is coming from the store, we need to apply the user filter to get the right requests\n const requireFilterByUser =\n !userIsAdmin || vtexProduct === 'store' || role === 'store-user'\n\n const hasUserIdOrEmail = Boolean(userId || userEmail)\n\n if (requireFilterByUser && !hasUserIdOrEmail) {\n throw new ForbiddenError('Missing params to filter by store user')\n }\n\n const adjustedFilter = requireFilterByUser\n ? { ...filter, userId, userEmail }\n : filter\n\n const resultFields = getAllFields\n ? ['_all']\n : [\n 'id',\n 'orderId',\n 'sequenceNumber',\n 'createdIn',\n 'status',\n 'dateSubmitted',\n ]\n\n const rmaSearchResult = await returnRequestClient.searchRaw(\n {\n page,\n pageSize: perPage && perPage <= 100 ? perPage : 25,\n },\n resultFields,\n 'dateSubmitted DESC',\n buildWhereClause(adjustedFilter)\n )\n\n const { data, pagination } = rmaSearchResult\n const { page: currentPage, pageSize, total } = pagination\n\n return {\n list: data,\n paging: {\n total,\n perPage: pageSize,\n currentPage,\n pages: Math.ceil(total / pageSize),\n },\n }\n}\n\n```"
}
] |
code_return-app_4621b69c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/services/returnRequestService.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ResolverError, ForbiddenError } from '@vtex/api'\nimport type { ReturnRequest } from 'vtex.return-app'\n\nexport const returnRequestService = async (ctx: Context, requestId: string) => {\n const {\n clients: { returnRequest: returnRequestClient },\n state: { userProfile, appkey },\n } = ctx\n\n const { userId, role } = userProfile ?? {}\n const userIsAdmin = Boolean(appkey) || role === 'admin'\n\n const returnRequestResult = await returnRequestClient.get(requestId, ['_all'])\n\n if (!returnRequestResult) {\n // Code error 'E_HTTP_404' to match the one when failing to find and order by OMS\n throw new ResolverError(`Request ${requestId} not found`, 404, 'E_HTTP_404')\n }\n\n const { customerProfileData } = returnRequestResult as ReturnRequest\n\n const requestBelongsToUser = userId === customerProfileData?.userId\n\n if (!requestBelongsToUser && !userIsAdmin) {\n throw new ForbiddenError('User cannot access this request')\n }\n\n return returnRequestResult\n}\n\n```"
}
] |
code_return-app_e1ff08d2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/templates/templateMessages.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport html from 'html-template-tag'\n\nconst HEAD_AND_STYLE = html`\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>{{_accountInfo.TradingName}}</title>\n <!--[if gte mso 9]>\n <xml>\n <o:OfficeDocumentSettings>\n <o:AllowPNG />\n <o:PixelsPerInch>96</o:PixelsPerInch>\n </o:OfficeDocumentSettings>\n </xml>\n <![endif]-->\n <style>\n .statusIcon {\n width: 30px;\n height: 30px;\n border: 1px solid #134cd8;\n border-radius: 50%;\n display: inline-block;\n box-sizing: border-box;\n padding-top: 3px;\n padding-left: 3px;\n background: #fff;\n margin-right: 20px;\n }\n\n .statusIconChecked {\n background: #134cd8;\n }\n\n .statusLine {\n display: flex;\n align-items: center;\n }\n\n .statusUl {\n background-image: linear-gradient(gray 33%, rgba(255, 255, 255, 0) 0%);\n background-position: left;\n background-size: 2px 6px;\n background-repeat: repeat-y;\n list-style-type: none;\n margin-left: 15px;\n min-height: 20px;\n padding-top: 0;\n padding-bottom: 0;\n }\n\n .statusUl li {\n padding-bottom: 5px;\n }\n\n .statusUlLast {\n background-image: none;\n }\n\n a[x-apple-data-detectors] {\n color: inherit !important;\n text-decoration: none !important;\n font-size: inherit !important;\n font-family: inherit !important;\n font-weight: inherit !important;\n line-height: inherit !important;\n }\n </style>\n <style>\n @media (max-width: 600px) {\n img {\n max-width: 100% !important;\n height: auto !important;\n }\n }\n </style>\n <style>\n @media screen and (min-width: 30em) {\n .w-50-ns {\n width: 50% !important;\n }\n\n .pr4-ns {\n padding-right: 2rem !important;\n }\n\n .ph4-ns {\n padding-left: 2rem !important;\n padding-right: 2rem !important;\n }\n\n .mv1-ns {\n margin-top: 0.25rem !important;\n margin-bottom: 0.25rem !important;\n }\n\n .mv4-ns {\n margin-top: 2rem !important;\n margin-bottom: 2rem !important;\n }\n }\n </style>\n </head>\n`\n\nconst HEADER = html`\n <tr style=\"box-sizing: border-box !important;\">\n <td class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; width: 100%; padding-bottom: 2rem; text-align: center !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"center\">\n <div style=\"box-sizing: border-box; width: 8rem; margin-bottom: 1rem; margin-top: 2rem; margin-right: auto; margin-left: auto !important;\">\n <a href=\"http://{{_accountInfo.HostName}}.com.br\"\n style=\"box-sizing: border-box !important;\">\n <img alt=\"\" border=\"0\" width=\"auto\"\n src=\"http://licensemanager.vtex.com.br/api/site/pub/accounts/{{_accountInfo.Id}}/logos/show\"\n style=\"vertical-align: top; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; max-width: 100%; border: none; max-height: 80px !important;\">\n </img>\n </a>\n </div>\n <h1 style=\"margin: 0; font-size: 25px; line-height: 35px; box-sizing: border-box !important;\">\n {{#if data.status}}\n {{#compare data.status \"==\" 'new'}}\n New return request <br/>{{data.DocumentId}}\n {{else}}\n Return request <br/>{{data.DocumentId}}\n {{/compare}}\n {{/if}}\n </h1>\n </td>\n </tr>\n`\n\nconst PRODUCTS = html`\n {{#compare products.length \">\" 0}}\n\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Products\n </h3>\n\n <table style=\"border-collapse:collapse;font-size:14px;width: 36rem\">\n <thead style=\"text-align:left\">\n <tr>\n <th>Products</th>\n <th>Quantity</th>\n <th>Unit price</th>\n </tr>\n\n <tr></tr>\n </thead>\n\n <tbody>\n {{#each products}} {{#compare quantity '>' 0}}\n <tr>\n <td>{{name}}</td>\n <td>{{quantity}}</td>\n <td>{{formatCurrency sellingPrice}}</td>\n </tr>\n {{/compare}} {{/each}}\n </tbody>\n </table>\n </td>\n </tr>\n\n {{/compare}}\n`\n\nconst CONTACT_DETAILS = html`\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <table style=\"border-collapse:collapse;font-size:14px;width: 36rem\">\n <tr>\n <td>\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Contact Details\n </h3>\n <div>\n Name: {{data.name}}<br />\n E-mail: {{data.email}}<br />\n Phone: {{data.phoneNumber}}\n </div>\n </td>\n\n <td>\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Address\n </h3>\n <div>\n Country: {{data.country}}<br />\n Locality: {{data.locality}}<br />\n Address: {{data.address}}\n </div>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n`\n\nconst PAYMENT_METHOD = html`\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Refund payment method\n </h3>\n Method: {{#eq data.paymentMethod 'card'}} Credit or debit card used when\n placing the order {{/eq}} {{#eq data.paymentMethod 'bank'}} Bank\n transfer<br />\n IBAN: {{data.iban}} {{/eq}} {{#eq data.paymentMethod 'giftCard'}} Gift\n Card {{/eq}} {{#eq data.paymentMethod 'sameAsPurchase'}} Same as purchase\n {{/eq}}\n </td>\n </tr>\n`\n\nconst STATUS_UPDATE = html`\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Return request status\n </h3>\n The current status for your return request is now: <br />\n <b>\n {{#eq data.status 'new'}} New {{/eq}} {{#eq data.status 'processing'}}\n Processing {{/eq}} {{#eq data.status 'pickedUpFromClient'}} Picked up\n from client {{/eq}} {{#eq data.status 'pendingVerification'}} Pending\n verification {{/eq}} {{#eq data.status 'packageVerified'}} Package\n verified {{/eq}} {{#eq data.status 'amountRefunded'}} Amount refunded\n {{/eq}} {{#eq data.status 'denied'}} Denied {{/eq}} {{#eq data.status\n 'cancelled'}} Cancelled {{/eq}}\n </b>\n </td>\n </tr>\n`\n\nconst REFUNDED_MESSAGE = html`\n {{#eq data.status 'refunded'}}\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <div>\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Refund details\n </h3>\n Refunded value {{#eq data.paymentMethod 'giftCard'}} in the form of a\n gift card worth {{formatCurrency data.refundedAmount}}$\n <br /><br />\n {{/eq}} {{#eq data.paymentMethod 'card'}} by bank card in the amount of\n {{formatCurrency data.refundedAmount}}$<br /><br />\n {{/eq}} {{#eq data.paymentMethod 'bank'}} by bank transfer in the amount\n of {{formatCurrency data.refundedAmount}}$<br />\n <b>IBAN: {{data.iban}}</b>\n {{/eq}}\n </div>\n </td>\n </tr>\n {{/eq}}\n`\n\nconst DENIED_MESSSAGE = html`\n {{#eq data.status 'denied'}}\n\n <tr style=\"box-sizing: border-box !important;\">\n <td\n class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\"\n >\n <div>\n <h3\n style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\"\n >\n Final state\n </h3>\n <b>Return request rejected</b>\n </div>\n </td>\n </tr>\n {{/eq}}\n`\n\nconst STATUS_TIMELINE = html`\n{{#compare refundStatusData.length \">\" 0}}\n\n<tr style=\"box-sizing: border-box !important;\">\n <td class=\"ph4-ns\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left; border-top-style: solid; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px; border-color: #eee; border-width: .5rem; width: 100%; padding-top: 2rem; padding-bottom: 2rem !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n align=\"left\">\n <h3 style=\"margin: 0; font-size: 20px; line-height: 36px; text-transform: uppercase; letter-spacing: 1.2pt; font-weight: 300; box-sizing: border-box; margin-top: 0 !important;\">\n Request status timeline</h3>\n <table style=\"border-collapse:collapse;font-size:14px;width: 36rem\">\n <tr>\n <td>\n <div>\n {{#each refundStatusData}}\n <div>\n <p class=\"statusLine\">\n {{#unless @last}}\n\n <span class=\"statusIcon statusIconChecked\">\n <span style=\"color: #fff; display: block; width: 1.3rem; height: 1.3rem; text-align: center;\"><b>✓</b></span>\n </span>\n <span>Status: \n <b>\n {{#eq status 'new'}} New {{/eq}}\n {{#eq status 'processing'}} Processing {{/eq}}\n {{#eq status 'pickedUpFromClient'}} Picked up from client {{/eq}}\n {{#eq status 'pendingVerification'}} Pending verification {{/eq}}\n {{#eq status 'packageVerified'}} Package verified {{/eq}}\n {{#eq status 'amountRefunded'}} Amount refunded {{/eq}}\n {{#eq status 'denied'}} Denied {{/eq}} {{#eq status\n 'cancelled'}} Cancelled {{/eq}}\n </b>\n </span>\n <ul class=\"statusUl\">\n {{#each comments}} \n {{#if visibleForCustomer}}\n <li>Comment: {{comment}}</li>\n {{/if}}\n {{/each}}\n </ul>\n \n {{else}}\n \n <span class=\"statusIcon statusIconChecked\">\n <span style=\"color: #fff; display: block; width: 1.3rem; height: 1.3rem; text-align: center;\"><b>✓</b></span>\n </span>\n <span>Status: \n <b>\n {{#eq status 'new'}} New {{/eq}}\n {{#eq status 'processing'}} Processing {{/eq}}\n {{#eq status 'pickedUpFromClient'}} Picked up from client {{/eq}}\n {{#eq status 'pendingVerification'}} Pending verification {{/eq}}\n {{#eq status 'packageVerified'}} Package verified {{/eq}}\n {{#eq status 'amountRefunded'}} Amount refunded {{/eq}}\n {{#eq status 'denied'}} Denied {{/eq}} {{#eq status\n 'cancelled'}} Cancelled {{/eq}}\n </b>\n </span>\n <ul class=\"statusUl statusUlLast\">\n {{#each comments}} \n {{#if visibleForCustomer}}\n <li>Comment: {{comment}}</li>\n {{/if}}\n {{/each}}\n </ul>\n\n {{#compare status '!=' 'amountRefunded'}}\n {{#compare status '!=' 'denied'}}\n {{#compare status '!=' 'cancelled'}}\n <span class=\"statusIcon\">\n <span style=\"color: #fff; display: block; width: 1.3rem; height: 1.3rem; text-align: center;\"><b>✓</b></span>\n </span>\n <span>Status: \n <b>\n {{#eq status 'new'}} Processing {{/eq}} \n {{#eq status 'processing'}} Picked up from client {{/eq}}\n {{#eq status 'pickedUpFromClient'}} Pending verification {{/eq}}\n {{#eq status 'pendingVerification'}} Package verified {{/eq}}\n {{#eq status 'packageVerified'}} Amount refunded {{/eq}}\n </b>\n </span>\n {{/compare}}\n {{/compare}}\n {{/compare}}\n {{/unless}}\n </p>\n </div>\n {{/each}}\n </div>\n </td>\n </tr>\n </table>\n\n </td>\n</tr>\n{{/compare}}\n`\n\nconst createTemplate = (headAndStyle: string, ...bodyBlocks: string[]) => {\n return `<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional //EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html\n xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n xmlns:v=\"urn:schemas-microsoft-com:vml\"\n style=\"-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; box-sizing: border-box; width: 100%; height: 100%; margin: 0; padding: 0; background: #f1f1f1 !important;\"\n >\n ${headAndStyle}\n <body\n style=\"-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; box-sizing: border-box; width: 100%; height: 100%; margin: 0; padding: 0; background: #f1f1f1 !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n >\n <table\n width=\"100%\"\n border=\"0\"\n cellpadding=\"0\"\n cellspacing=\"0\"\n style=\"box-sizing: border-box; margin: 0; padding: 0; background: #f1f1f1; border-collapse: collapse; border-spacing: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; width: 100%; height: 100%; line-height: 100% !important;\"\n >\n <tr style=\"box-sizing: border-box !important;\">\n <td\n align=\"left\"\n valign=\"top\"\n style=\"font-size: 14px; line-height: 20px; box-sizing: border-box; border-collapse: collapse; text-align: left !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n >\n <table\n class=\"mv4-ns\"\n width=\"100%\"\n align=\"center\"\n border=\"0\"\n cellpadding=\"0\"\n cellspacing=\"0\"\n style=\"box-sizing: border-box; max-width: 40rem; width: 100%; background-color: #fff; border-collapse: collapse; border-spacing: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt !important; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;\"\n bgcolor=\"#fff\"\n >\n ${bodyBlocks.join('\\n')}\n </table>\n </td>\n </tr>\n </table>\n </body>\n </html>\n `\n}\n\nexport const OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE_MESSAGE = createTemplate(\n HEAD_AND_STYLE,\n HEADER,\n PRODUCTS,\n CONTACT_DETAILS,\n PAYMENT_METHOD\n)\n\nexport const OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE_MESSAGE = createTemplate(\n HEAD_AND_STYLE,\n HEADER,\n STATUS_UPDATE,\n REFUNDED_MESSAGE,\n DENIED_MESSSAGE,\n STATUS_TIMELINE\n)\n\n```"
}
] |
code_return-app_7d6eb41d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/node/utils/templates/index.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { Template } from '../../typings/mailClient'\nimport {\n OMS_RETURN_REQUEST_CONFIRMATION,\n OMS_RETURN_REQUEST_CONFIRMATION_FRIENDLY_NAME,\n OMS_RETURN_REQUEST_STATUS_UPDATE,\n OMS_RETURN_REQUEST_STATUS_UPDATE_FRIENDLY_NAME,\n} from '../constants'\nimport {\n OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE_MESSAGE,\n OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE_MESSAGE,\n} from './templateMessages'\n\nexport const OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE = (\n locale = 'en-GB'\n): Template => ({\n Name: OMS_RETURN_REQUEST_CONFIRMATION(locale),\n FriendlyName: OMS_RETURN_REQUEST_CONFIRMATION_FRIENDLY_NAME(locale),\n Description: '[OMS] Return requests confirmation message',\n IsDefaultTemplate: false,\n AccountId: null,\n AccountName: null,\n ApplicationId: null,\n IsPersisted: true,\n IsRemoved: false,\n Type: '',\n Templates: {\n email: {\n To: '{{data.email}}',\n CC: null,\n BCC: '{{#compare data.status \"==\" \\'new\\'}}{{/compare}}',\n Subject: 'New Return request {{data.DocumentId}}',\n Message: OMS_RETURN_REQUEST_CONFIRMATION_TEMPLATE_MESSAGE,\n Type: 'E',\n ProviderId: '00000000-0000-0000-0000-000000000000',\n ProviderName: null,\n IsActive: true,\n withError: false,\n },\n sms: {\n Type: 'S',\n ProviderId: null,\n ProviderName: null,\n IsActive: false,\n withError: false,\n Parameters: [],\n },\n },\n})\n\nexport const OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE = (\n locale = 'en-GB'\n): Template => ({\n Name: OMS_RETURN_REQUEST_STATUS_UPDATE(locale),\n FriendlyName: OMS_RETURN_REQUEST_STATUS_UPDATE_FRIENDLY_NAME(locale),\n Description: '[OMS] Return requests status update message',\n IsDefaultTemplate: false,\n AccountId: null,\n AccountName: null,\n ApplicationId: null,\n IsPersisted: true,\n IsRemoved: false,\n Type: '',\n Templates: {\n email: {\n To: '{{data.email}}',\n CC: null,\n BCC: '{{#compare data.status \"==\" \\'new\\'}}{{/compare}}',\n Subject: 'Return request status update {{data.DocumentId}}',\n Message: OMS_RETURN_REQUEST_STATUS_UPDATE_TEMPLATE_MESSAGE,\n Type: 'E',\n ProviderId: '00000000-0000-0000-0000-000000000000',\n ProviderName: null,\n IsActive: true,\n withError: false,\n },\n sms: {\n Type: 'S',\n ProviderId: null,\n ProviderName: null,\n IsActive: false,\n withError: false,\n Parameters: [],\n },\n },\n})\n\n```"
}
] |
code_return-app_63589eba
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/typings/vtex.render-runtime.d.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.render-runtime' {\n import type { ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: unknown\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n\n [key: string]: any\n }\n\n interface ChildBlock<BlockProps> {\n props: BlockProps\n }\n\n export const ExtensionPoint: ComponentType<ExtensionPointProps>\n export const useChildBlock: <BlockProps>({\n id,\n }: {\n id: string\n }) => ChildBlock<BlockProps> | null\n export const Helmet: ReactElement\n export const Link: ReactType\n export const NoSSR: ReactElement\n export const RenderContextConsumer: unknown\n export const TreePathContextConsumer: unknown\n export const useTreePath: unknown\n export const useRuntime: unknown\n export const canUseDOM: boolean\n export const withRuntimeContext: <\n TOriginalProps extends Record<string, unknown>\n >(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const withSession: <TOriginalProps extends Record<string, unknown>>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n interface KeyValue {\n value: string\n }\n\n interface Session {\n id: string\n namespaces: {\n store: {\n channel: KeyValue\n }\n profile: {\n isAuthenticated: KeyValue\n email: string\n }\n }\n }\n\n interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n }\n\n interface SessionForbidden {\n type: 'Forbidden'\n message: string\n }\n\n type SessionResponse = Session | SessionUnauthorized | SessionForbidden\n\n export interface RenderSession {\n sessionPromise: Promise<SessionPromise>\n }\n\n export interface SessionPromise {\n response: Session | SessionUnauthorized | SessionForbidden\n }\n\n export function useRuntime()\n}\n\n```"
}
] |
code_return-app_6743d82a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/typings/vtex.return-app.d.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ninterface ItemToReturn {\n id: string\n quantity: number\n quantityAvailable: number\n isExcluded: boolean\n name: string\n localizedName?: string | null\n imageUrl: string\n orderItemIndex: number\n}\n\ntype MaybeGlobal<T> = T | null\n\ntype GeoCoordinates = Array<MaybeGlobal<number>>\n\n```"
}
] |
code_return-app_3ebb2a70
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/AdminLoader.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { FC, ReactElement } from 'react'\nimport type { ApolloError } from 'apollo-client'\nimport { EmptyState, Spinner } from 'vtex.styleguide'\n\ninterface Props {\n error?: ApolloError\n loading: boolean\n data?: unknown\n errorMessages: {\n errorTitle: ReactElement\n errorDescription?: ReactElement\n }\n}\n\nexport const AdminLoader: FC<Props> = ({\n error,\n loading,\n data,\n errorMessages,\n children,\n}) => {\n if (error) {\n return (\n <EmptyState title={errorMessages.errorTitle}>\n {errorMessages.errorDescription}\n </EmptyState>\n )\n }\n\n if (loading || !data) {\n return <Spinner />\n }\n\n return <>{children}</>\n}\n\n```"
}
] |
code_return-app_ffbebd58
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/AdminReturnDetails.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { ReturnDetailsContainer } from './ReturnDetails/ReturnDetailsContainer'\nimport { AlertProvider } from './provider/AlertProvider'\nimport { ReturnDetailsProvider } from '../common/provider/ReturnDetailsProvider'\nimport { UpdateRequestStatusProvider } from './provider/UpdateRequestStatusProvider'\n\ninterface CustomRouteProps {\n params: {\n id: string\n }\n}\n\nexport const AdminReturnDetails = ({ params }: CustomRouteProps) => {\n return (\n <AlertProvider>\n <ReturnDetailsProvider requestId={params.id}>\n <UpdateRequestStatusProvider>\n <ReturnDetailsContainer />\n </UpdateRequestStatusProvider>\n </ReturnDetailsProvider>\n </AlertProvider>\n )\n}\n\n```"
}
] |
code_return-app_2b7c6e9c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/AdminReturnSettings.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { RMASettings } from './settings/RMASettings'\nimport { SettingsProvider } from './settings/provider/SettingsProvider'\nimport { AlertProvider } from './provider/AlertProvider'\n\nexport const RMASettingsWrapper = () => {\n return (\n <AlertProvider>\n <SettingsProvider>\n <RMASettings />\n </SettingsProvider>\n </AlertProvider>\n )\n}\n\n```"
}
] |
code_return-app_c0399bcb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/AdminReturnList.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { AdminReturnList } from './ReturnList/ReturnListContainer'\n\nexport default AdminReturnList\n\n```"
}
] |
code_return-app_a0a5430c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/utils/requestStatus.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n Status,\n RefundStatusData,\n RefundStatusComment,\n} from 'vtex.return-app'\nimport { defineMessages } from 'react-intl'\n\nconst statusSequence: Status[] = [\n 'new',\n 'processing',\n 'pickedUpFromClient',\n 'pendingVerification',\n 'packageVerified',\n 'amountRefunded',\n]\n\nexport const statusAllowed: Record<Status, Status[]> = {\n new: ['new', 'processing', 'denied', 'cancelled'],\n processing: ['processing', 'pickedUpFromClient', 'denied', 'cancelled'],\n pickedUpFromClient: ['pickedUpFromClient', 'pendingVerification', 'denied'],\n // In this step, when sending the items to the resolver, it will assign the status denied or packageVerified based on the items sent.\n pendingVerification: ['pendingVerification'],\n packageVerified: ['packageVerified', 'amountRefunded'],\n amountRefunded: ['amountRefunded'],\n denied: ['denied'],\n cancelled: ['cancelled'],\n}\n\nexport const statusMessageIdAdmin = defineMessages({\n new: { id: 'store/return-app-status.new' },\n processing: { id: 'store/return-app-status.processing' },\n pickedUpFromClient: { id: 'store/return-app-status.pickedup-from-client' },\n pendingVerification: { id: 'store/return-app-status.pending-verification' },\n packageVerified: { id: 'store/return-app-status.package-verified' },\n amountRefunded: { id: 'store/return-app-status.refunded' },\n denied: { id: 'store/return-app-status.denied' },\n cancelled: { id: 'store/return-app-status.cancelled' },\n})\n\nexport const timelineStatusMessageId = defineMessages({\n new: { id: 'store/return-app-status.timeline.new' },\n processing: { id: 'store/return-app-status.timeline.processing' },\n pickedUpFromClient: {\n id: 'store/return-app-status.timeline.pickedup-from-client',\n },\n pendingVerification: {\n id: 'store/return-app-status.timeline.pending-verification',\n },\n packageVerified: { id: 'store/return-app-status.timeline.package-verified' },\n amountRefunded: { id: 'store/return-app-status.timeline.refunded' },\n denied: { id: 'store/return-app-status.timeline.denied' },\n cancelled: { id: 'store/return-app-status.timeline.cancelled' },\n})\n\ntype Comments = RefundStatusComment[]\ninterface VisitedStatus {\n status: Status\n visited: boolean\n comments?: Comments\n createdAt?: string\n submittedBy?: string | null\n}\n\nexport const createStatusTimeline = (\n currentStatus: Status,\n refundStatusData: RefundStatusData[]\n): VisitedStatus[] => {\n const refundStatusMap = new Map<Status, VisitedStatus>()\n\n for (const status of refundStatusData ?? []) {\n const { status: statusName, comments, createdAt, submittedBy } = status\n\n refundStatusMap.set(statusName as Status, {\n status: statusName as Status,\n visited: true,\n comments,\n createdAt,\n submittedBy,\n })\n }\n\n const statusTimeline: VisitedStatus[] = []\n\n const isDenied = currentStatus === 'denied'\n const isCancelled = currentStatus === 'cancelled'\n\n for (const statusName of statusSequence) {\n const status = refundStatusMap.get(statusName)\n\n if (!status && !isDenied && !isCancelled) {\n statusTimeline.push({ status: statusName, visited: false })\n continue\n }\n\n if (status) {\n statusTimeline.push(status as VisitedStatus)\n }\n }\n\n if (isDenied || isCancelled) {\n const status = refundStatusMap.get(isDenied ? 'denied' : 'cancelled')\n\n if (status) {\n statusTimeline.push(status)\n }\n }\n\n return statusTimeline\n}\n\n```"
}
] |
code_return-app_a876d502
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/graphql/getReturnRequestList.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getReturnRequestList($filter: ReturnRequestFilters, $page: Int!) {\n returnRequestList(filter: $filter, page: $page)\n @context(provider: \"vtex.return-app\") {\n list {\n id\n sequenceNumber\n createdIn\n status\n orderId\n items {\n id\n imageUrl\n }\n }\n paging {\n total\n pages\n currentPage\n perPage\n }\n }\n}\n\n```"
}
] |
code_return-app_1bfa699e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/graphql/createLabel.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation CreateLabel(\n $street1: String\n $street2: String\n $city: String\n $state: String\n $zip: String\n $country: String\n $name: String\n $phone: String\n) {\n createLabel(\n street1: $street1\n street2: $street2\n city: $city\n state: $state\n zip: $zip\n country: $country\n name: $name\n phone: $phone\n ) @context(provider: \"vtex.easypost\") {\n labelUrl\n }\n}\n\n```"
}
] |
code_return-app_c74c09a9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/hooks/useReturnRequestList.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useQuery } from 'react-apollo'\nimport type {\n ReturnRequestList as ReturnRequestListResponse,\n QueryReturnRequestListArgs,\n} from 'vtex.return-app'\n\nimport RETURN_REQUEST_LIST from '../graphql/getReturnRequestList.gql'\n\nexport const useReturnRequestList = () => {\n const { data, loading, error, refetch } = useQuery<\n {\n returnRequestList: ReturnRequestListResponse\n },\n QueryReturnRequestListArgs\n >(RETURN_REQUEST_LIST, {\n variables: {\n page: 1,\n },\n notifyOnNetworkStatusChange: true,\n fetchPolicy: 'no-cache',\n })\n\n return { returnRequestData: { data, loading, error, refetch } }\n}\n\n```"
}
] |
code_return-app_1dfc064a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/store/StoreMyReturnsPage.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nexport { StoreReturnList } from './ReturnRequest/StoreReturnList'\nexport { StoreReturnDetailsContainer } from './ReturnRequest/StoreReturnDetails'\n\n```"
}
] |
code_return-app_34bf24b5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/store/StoreReturnAppRouter.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Route, Switch } from 'vtex.my-account-commons/Router'\n\nimport {\n StoreReturnList,\n StoreReturnDetailsContainer,\n} from './StoreMyReturnsPage'\nimport {\n OrderListContainer,\n CreateReturnRequestContainer,\n} from './StoreMyReturnsAdd'\n\nexport const AppRouter = () => {\n return (\n <Switch>\n <Route exact path=\"/my-returns\" component={StoreReturnList} />\n <Route\n exact\n path=\"/my-returns/details/:id\"\n component={StoreReturnDetailsContainer}\n />\n <Route exact path=\"/my-returns/add\" component={OrderListContainer} />\n <Route\n exact\n path=\"/my-returns/add/:orderId\"\n component={CreateReturnRequestContainer}\n />\n </Switch>\n )\n}\n\nexport default AppRouter\n\n```"
}
] |
code_return-app_42a808ae
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/store/StoreMyReturnsAdd.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport { OrderListContainer } from './createReturnRequest/OrderListContainer'\nexport { CreateReturnRequestContainer } from './createReturnRequest/CreateReturnRequest'\n\n```"
}
] |
code_return-app_10237f71
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/typings/vtex.my-account-commons/index.d.ts from the return-app 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_return-app_012703bb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/RMASettings.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect, useRef } from 'react'\nimport type { FormEvent, ReactElement } from 'react'\nimport type {\n PaymentOptions as PaymentOptionsInterface,\n PaymentType,\n} from 'vtex.return-app'\nimport { FormattedMessage } from 'react-intl'\nimport {\n Layout,\n PageHeader,\n PageBlock,\n Divider,\n Button,\n Spinner,\n EmptyState,\n} from 'vtex.styleguide'\n\nimport { CustomReasons } from './components/CustomReasons'\nimport { ExcludedCategories } from './components/ExcludedCategories'\nimport { GeneralOptions } from './components/GeneralOptions'\nimport { PaymentOptions } from './components/PaymentOptions'\nimport { RequiredOptions } from './components/RequiredOptions'\nimport { WarningModal } from './components/WarningModal'\nimport { useSettings } from './hooks/useSettings'\n\nexport interface ModalWarningState {\n openModal: boolean\n customMaxDays: number\n attemptNewSave: boolean\n}\n\nexport interface CheckboxProps {\n label: ReactElement\n checked: boolean\n name: string\n}\n\nconst validateOptions = (paymentOptions: PaymentOptionsInterface) => {\n const { enablePaymentMethodSelection, allowedPaymentTypes } = paymentOptions\n\n // If the user has not enabled the payment method selection, then the allowed payment types can be all unselected.\n if (!enablePaymentMethodSelection) return true\n\n let result = false\n\n for (const paymentType of Object.keys(allowedPaymentTypes)) {\n // If we have at least one payment method selected, then the payment options are valid.\n if (allowedPaymentTypes[paymentType] && paymentType !== '__typename') {\n result = true\n break\n }\n }\n\n return result\n}\n\nexport const RMASettings = () => {\n const {\n appSettings,\n loading,\n error,\n savingAppSettings,\n actions: { handleSaveAppSettings, dispatch },\n } = useSettings()\n\n const [maxDaysWarning, setWarning] = useState<ModalWarningState>({\n openModal: false,\n customMaxDays: 0,\n attemptNewSave: false,\n })\n\n const [hasPaymentMethodError, setHasPaymentMethodError] = useState(false)\n\n const paymentMethodsRef = useRef<HTMLDivElement>(null)\n\n useEffect(() => {\n if (!maxDaysWarning.attemptNewSave) return\n\n handleSaveAppSettings()\n\n setWarning({\n ...maxDaysWarning,\n attemptNewSave: false,\n })\n }, [handleSaveAppSettings, maxDaysWarning])\n\n const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault()\n\n const { customReturnReasons, maxDays, paymentOptions } = appSettings\n\n const maxCustomOptionsDays = customReturnReasons?.reduce(\n (maxDay, option) => (maxDay > option.maxDays ? maxDay : option.maxDays),\n 0\n )\n\n if (maxCustomOptionsDays && maxCustomOptionsDays < maxDays) {\n setWarning({\n ...maxDaysWarning,\n openModal: true,\n customMaxDays: maxCustomOptionsDays,\n })\n\n return\n }\n\n if (!validateOptions(paymentOptions)) {\n setHasPaymentMethodError(true)\n paymentMethodsRef.current?.scrollIntoView()\n\n return\n }\n\n setHasPaymentMethodError(false)\n\n handleSaveAppSettings()\n }\n\n const handleOptionSelection = (options: { string: CheckboxProps }) => {\n const paymentOptions = Object.keys(options)\n\n const updatedPaymentOptions = paymentOptions.reduce<PaymentType>(\n (acc, paymentOption) => {\n return {\n ...acc,\n [paymentOption]: options[paymentOption].checked,\n }\n },\n {}\n )\n\n const paymentOptionsPayload = {\n ...appSettings.paymentOptions,\n allowedPaymentTypes: updatedPaymentOptions,\n }\n\n dispatch({\n type: 'updatePaymentOptions',\n payload: {\n ...appSettings.paymentOptions,\n allowedPaymentTypes: updatedPaymentOptions,\n },\n })\n\n if (!validateOptions(paymentOptionsPayload)) {\n setHasPaymentMethodError(true)\n\n return\n }\n\n setHasPaymentMethodError(false)\n }\n\n return (\n <Layout\n pageHeader={\n <PageHeader\n title={\n <FormattedMessage id=\"admin/return-app.settings.navigation.label\" />\n }\n />\n }\n >\n <PageBlock variation=\"full\">\n {error ? (\n <EmptyState\n title={\n <FormattedMessage id=\"admin/return-app.settings.error.header\" />\n }\n >\n <p>\n <FormattedMessage id=\"admin/return-app.settings.error.description\" />\n </p>\n </EmptyState>\n ) : loading ? (\n <Spinner />\n ) : (\n <>\n {maxDaysWarning.openModal && (\n <WarningModal\n setWarning={setWarning}\n customMaxDays={maxDaysWarning.customMaxDays}\n />\n )}\n <form onSubmit={handleSubmit}>\n <RequiredOptions />\n <Divider />\n <ExcludedCategories />\n <Divider />\n <PaymentOptions\n handleOptionSelection={handleOptionSelection}\n hasError={hasPaymentMethodError}\n ref={paymentMethodsRef}\n />\n <Divider />\n <CustomReasons />\n <Divider />\n <GeneralOptions />\n <Divider />\n <div className=\"flex flex-column mt6\">\n <Button\n disabled={savingAppSettings}\n variation=\"primary\"\n type=\"submit\"\n >\n {savingAppSettings ? (\n <Spinner size={20} />\n ) : (\n <FormattedMessage id=\"admin/return-app.settings.save.button\" />\n )}\n </Button>\n </div>\n </form>\n </>\n )}\n </PageBlock>\n </Layout>\n )\n}\n\n```"
}
] |
code_return-app_8c6b71d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/provider/AlertProvider.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FC, ReactElement } from 'react'\nimport React, { createContext, useState, useCallback, useEffect } from 'react'\nimport { Alert } from 'vtex.styleguide'\n\ntype AlertStatus = 'success' | 'error'\n\ninterface AlertContextInterface {\n openAlert: (status: AlertStatus, message: string | ReactElement) => void\n}\n\nexport const AlertContext = createContext<AlertContextInterface>(\n {} as AlertContextInterface\n)\n\nexport const AlertProvider: FC = ({ children }) => {\n const [alertStatus, setAlertStatus] = useState<AlertStatus | ''>('')\n const [message, setMessage] = useState<string | ReactElement>('')\n\n const openAlert = (\n status: AlertStatus,\n alertMessage: string | ReactElement\n ) => {\n setAlertStatus(status)\n setMessage(alertMessage)\n }\n\n const handleClose = useCallback(() => {\n if (alertStatus) {\n setAlertStatus('')\n setMessage('')\n }\n }, [alertStatus])\n\n useEffect(() => {\n const timeout = setTimeout(() => {\n handleClose()\n }, 5000)\n\n return () => {\n clearTimeout(timeout)\n }\n }, [handleClose, alertStatus])\n\n return (\n <AlertContext.Provider value={{ openAlert }}>\n {alertStatus ? (\n <div className=\"w-100 fixed z-max overflow-hidden\">\n <div\n className=\"mt7\"\n style={{ maxWidth: '520px', margin: '2rem auto' }}\n >\n <Alert type={alertStatus} onClose={handleClose}>\n {message}\n </Alert>\n </div>\n </div>\n ) : null}\n {children}\n </AlertContext.Provider>\n )\n}\n\n```"
}
] |
code_return-app_03aebb3f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/provider/UpdateRequestStatusProvider.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { createContext } from 'react'\nimport type {\n Status,\n ReturnRequestCommentInput,\n RefundDataInput,\n ReturnRequestResponse,\n MutationUpdateReturnRequestStatusArgs,\n} from 'vtex.return-app'\nimport { useMutation } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\n\nimport UPDATE_RETURN_STATUS from '../graphql/updateReturnRequestStatus.gql'\nimport { useAlert } from '../hooks/userAlert'\nimport { useReturnDetails } from '../../common/hooks/useReturnDetails'\n\ninterface HandleStatusUpdateArgs {\n status: Status\n id: string\n comment?: ReturnRequestCommentInput\n cleanUp?: () => void\n refundData?: RefundDataInput\n}\n\ninterface UpdateRequestInterface {\n handleStatusUpdate: (args: HandleStatusUpdateArgs) => Promise<void>\n submitting: boolean\n}\n\nexport const UpdateRequestStatusContext = createContext<UpdateRequestInterface>(\n {} as UpdateRequestInterface\n)\n\nexport const UpdateRequestStatusProvider: FC = ({ children }) => {\n const { openAlert } = useAlert()\n const { _handleUpdateQuery } = useReturnDetails()\n\n const [updateReturnStatus, { loading: submitting }] = useMutation<\n {\n updateReturnRequestStatus: ReturnRequestResponse\n },\n MutationUpdateReturnRequestStatusArgs\n >(UPDATE_RETURN_STATUS)\n\n const handleStatusUpdate = async (args: HandleStatusUpdateArgs) => {\n const { id, status, comment, cleanUp, refundData } = args\n\n try {\n const { errors, data: mutationData } = await updateReturnStatus({\n variables: {\n requestId: id,\n status,\n ...(comment ? { comment } : {}),\n ...(refundData ? { refundData } : {}),\n },\n })\n\n if (errors) {\n throw new Error('Error updating return request status')\n }\n\n openAlert(\n 'success',\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.alert.success\" />\n )\n\n cleanUp?.()\n if (!mutationData) return\n _handleUpdateQuery(mutationData.updateReturnRequestStatus)\n } catch {\n openAlert(\n 'error',\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.alert.error\" />\n )\n }\n }\n\n return (\n <UpdateRequestStatusContext.Provider\n value={{ handleStatusUpdate, submitting }}\n >\n {children}\n </UpdateRequestStatusContext.Provider>\n )\n}\n\n```"
}
] |
code_return-app_43356d86
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/ReturnDetailsContainer.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { Layout, PageHeader, PageBlock } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport { UpdateRequestStatus } from './components/UpdateRequestStatus'\nimport { useReturnDetails } from '../../common/hooks/useReturnDetails'\nimport { VerifyItemsPage } from './components/VerifyItems/VerifyItemsPage'\nimport { ItemDetailsList } from '../../common/components/ReturnDetails/ItemDetails/ItemDetailsList'\nimport { ContactDetails } from '../../common/components/ContactDetails'\nimport { PickupAddress } from '../../common/components/ReturnDetails/PickupAddress'\nimport { RefundMethodDetail } from '../../common/components/ReturnDetails/RefundMethodDetail'\nimport { AdminLoader } from '../AdminLoader'\nimport { ReturnValues } from '../../common/components/ReturnDetails/ReturnValues/ReturnValues'\nimport { StatusTimeline } from '../../common/components/ReturnDetails/StatusTimeline/StatusTimeline'\nimport { StatusHistory } from '../../common/components/ReturnDetails/StatusHistory'\nimport { OrderLink } from '../../common/components/ReturnDetails/OrderLink'\nimport { CurrentRequestStatus } from '../../common/components/ReturnDetails/CurrentRequestStatus'\nimport RequestCancellation from '../../common/components/ReturnDetails/RequestCancellation'\n\ntype Pages = 'return-details' | 'verify-items'\n\nexport const ReturnDetailsContainer = () => {\n const [detailsPage, setDetailsPage] = useState<Pages>('return-details')\n const returnDetails = useReturnDetails()\n\n const { navigate } = useRuntime()\n\n const handleViewVerifyItems = (page: Pages) => {\n setDetailsPage(page)\n }\n\n return (\n <Layout\n fullWidth\n pageHeader={\n <PageHeader\n title={\n <FormattedMessage id=\"admin/return-app.return-request-details.page-header.title\" />\n }\n linkLabel={\n <FormattedMessage id=\"admin/return-app.return-request-details.page-header.link-label\" />\n }\n onLinkClick={() => {\n navigate({\n to: '/admin/app/returns/requests',\n })\n }}\n >\n <RequestCancellation />\n </PageHeader>\n }\n >\n <PageBlock variation=\"full\" fit=\"fill\">\n <AdminLoader\n {...returnDetails}\n errorMessages={{\n errorTitle: (\n <FormattedMessage id=\"admin/return-app.return-request-details.error.title\" />\n ),\n errorDescription: (\n <FormattedMessage id=\"admin/return-app.return-request-details.error.description\" />\n ),\n }}\n >\n <>\n {detailsPage !== 'return-details' ? null : (\n <>\n <CurrentRequestStatus />\n <OrderLink />\n <ItemDetailsList />\n <ReturnValues />\n <div className=\"flex-ns flex-wrap flex-row\">\n <ContactDetails />\n <PickupAddress />\n </div>\n <RefundMethodDetail />\n <StatusTimeline />\n <UpdateRequestStatus\n onViewVerifyItems={() =>\n handleViewVerifyItems('verify-items')\n }\n />\n <StatusHistory />\n </>\n )}\n {detailsPage !== 'verify-items' ? null : (\n <VerifyItemsPage\n onViewVerifyItems={() =>\n handleViewVerifyItems('return-details')\n }\n />\n )}\n </>\n </AdminLoader>\n </PageBlock>\n </Layout>\n )\n}\n\n```"
}
] |
code_return-app_00007f15
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/graphql/updateReturnRequestStatus.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\n#import '../../common/graphql/returnDetailsFragment.gql'\n\nmutation updateReturnRequestStatus(\n $requestId: ID!\n $status: Status!\n $comment: ReturnRequestCommentInput\n $refundData: RefundDataInput\n) {\n updateReturnRequestStatus(\n requestId: $requestId\n status: $status\n comment: $comment\n refundData: $refundData\n ) @context(provider: \"vtex.return-app\") {\n ...ReturnDetailsAdminFragment\n }\n}\n\n```"
}
] |
code_return-app_9395bbbe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/hooks/userAlert.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport { AlertContext } from '../provider/AlertProvider'\n\nexport const useAlert = () => useContext(AlertContext)\n\n```"
}
] |
code_return-app_442e62bf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/hooks/useUpdateRequestStatus.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport { UpdateRequestStatusContext } from '../provider/UpdateRequestStatusProvider'\n\nexport const useUpdateRequestStatus = () =>\n useContext(UpdateRequestStatusContext)\n\n```"
}
] |
code_return-app_43f41b35
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnList/ReturnListContainer.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Layout, PageHeader, PageBlock } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport ListTable from '../../common/components/returnList/ListTable'\n\nexport const AdminReturnList = () => {\n return (\n <Layout\n fullWidth\n pageHeader={\n <PageHeader\n title={\n <FormattedMessage id=\"admin/return-app.return-request-list.page-header.title\" />\n }\n subtitle={\n <FormattedMessage id=\"admin/return-app.return-request-list.page-header.subTitle\" />\n }\n />\n }\n >\n <PageBlock variation=\"full\" fit=\"fill\">\n <ListTable />\n </PageBlock>\n </Layout>\n )\n}\n\n```"
}
] |
code_return-app_069b318b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/provider/SettingsProvider.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ApolloError } from 'apollo-client'\nimport type { FC, Dispatch } from 'react'\nimport React, { createContext, useReducer, useEffect } from 'react'\nimport { useQuery, useMutation } from 'react-apollo'\nimport { FormattedMessage } from 'react-intl'\nimport type { ReturnAppSettings, ReturnAppSettingsInput } from 'vtex.return-app'\n\nimport APP_SETTINGS from '../graphql/getAppSettings.gql'\nimport SAVE_APP_SETTINGS from '../graphql/saveAppSettings.gql'\nimport { useAlert } from '../../hooks/userAlert'\nimport type { Actions } from './settingsReducer'\nimport { settingsReducer, initialSettingsState } from './settingsReducer'\n\ninterface SettingsContextInterface {\n appSettings: ReturnAppSettings\n actions: {\n dispatch: Dispatch<Actions>\n handleSaveAppSettings: () => Promise<void>\n }\n loading: boolean\n error?: ApolloError\n savingAppSettings: boolean\n}\n\nexport const SettingsContext = createContext<SettingsContextInterface>(\n {} as SettingsContextInterface\n)\n\nexport const SettingsProvider: FC = ({ children }) => {\n const [appSettings, dispatch] = useReducer(\n settingsReducer,\n initialSettingsState\n )\n\n const { openAlert } = useAlert()\n\n const { data, loading, error } = useQuery<{\n returnAppSettings: ReturnAppSettings\n }>(APP_SETTINGS)\n\n const [saveAppSettings, { loading: savingAppSettings }] = useMutation<\n { saveReturnAppSettings: boolean },\n { settings: ReturnAppSettingsInput }\n >(SAVE_APP_SETTINGS)\n\n useEffect(() => {\n if (data?.returnAppSettings) {\n dispatch({\n type: 'updateInitialState',\n payload: data.returnAppSettings,\n })\n }\n }, [data])\n\n const handleSaveAppSettings = async () => {\n try {\n const { paymentOptions } = appSettings\n\n const { automaticallyRefundPaymentMethod } = paymentOptions\n\n const adjustedPaymentOptions = paymentOptions.enablePaymentMethodSelection\n ? paymentOptions\n : {\n ...paymentOptions,\n automaticallyRefundPaymentMethod: Boolean(\n automaticallyRefundPaymentMethod\n ),\n }\n\n const { data: mutationResult, errors } = await saveAppSettings({\n variables: {\n settings: { ...appSettings, paymentOptions: adjustedPaymentOptions },\n },\n })\n\n if (errors) {\n throw new Error('Error saving app settings')\n }\n\n if (mutationResult?.saveReturnAppSettings) {\n openAlert(\n 'success',\n <FormattedMessage id=\"admin/return-app.settings.alert.save.success\" />\n )\n }\n } catch {\n openAlert(\n 'error',\n <FormattedMessage id=\"admin/return-app.settings.alert.save.error\" />\n )\n }\n }\n\n return (\n <SettingsContext.Provider\n value={{\n appSettings,\n loading,\n error,\n savingAppSettings,\n actions: { dispatch, handleSaveAppSettings },\n }}\n >\n {children}\n </SettingsContext.Provider>\n )\n}\n\n```"
}
] |
code_return-app_405d1fd0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/provider/settingsReducer.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type {\n CustomReturnReason,\n PaymentOptions,\n ReturnAppSettings,\n ReturnOption,\n} from 'vtex.return-app'\n\nexport const initialSettingsState: ReturnAppSettings = {\n maxDays: 0,\n excludedCategories: [],\n termsUrl: '',\n paymentOptions: {\n enablePaymentMethodSelection: false,\n allowedPaymentTypes: {\n bank: false,\n card: false,\n giftCard: false,\n },\n },\n customReturnReasons: [],\n options: {\n enableOtherOptionSelection: false,\n enablePickupPoints: false,\n enableProportionalShippingValue: false,\n enableSelectItemCondition: false,\n },\n}\n\nexport const maxDaysAction = (maxDays: number) => {\n return {\n type: 'updateMaxDays' as const,\n payload: maxDays,\n }\n}\n\nexport const excludedCategoriesAction = (excludedCategories: string[]) => {\n return {\n type: 'updateExcludedCategories' as const,\n payload: excludedCategories,\n }\n}\n\nexport const termsUrlAction = (termsUrl: string) => {\n return {\n type: 'updateTermsUrl' as const,\n payload: termsUrl,\n }\n}\n\nexport const paymentOptionsAction = (paymentOptions: PaymentOptions) => {\n return {\n type: 'updatePaymentOptions' as const,\n payload: paymentOptions,\n }\n}\n\nexport const customReturnReasonsAction = (\n customReturnReasons: CustomReturnReason[]\n) => {\n return {\n type: 'updateCustomReturnReasons' as const,\n payload: customReturnReasons,\n }\n}\n\nexport const optionsAction = (options: ReturnOption) => {\n return {\n type: 'updateOptions' as const,\n payload: options,\n }\n}\n\nexport const initialStateAction = (initialState: ReturnAppSettings) => {\n return {\n type: 'updateInitialState' as const,\n payload: initialState,\n }\n}\n\nexport type Actions =\n | ReturnType<typeof maxDaysAction>\n | ReturnType<typeof excludedCategoriesAction>\n | ReturnType<typeof termsUrlAction>\n | ReturnType<typeof paymentOptionsAction>\n | ReturnType<typeof customReturnReasonsAction>\n | ReturnType<typeof optionsAction>\n | ReturnType<typeof initialStateAction>\n\nexport const settingsReducer = (state: ReturnAppSettings, action: Actions) => {\n switch (action.type) {\n case 'updateMaxDays': {\n return {\n ...state,\n maxDays: action.payload,\n }\n }\n\n case 'updateExcludedCategories': {\n return {\n ...state,\n excludedCategories: action.payload,\n }\n }\n\n case 'updateTermsUrl': {\n return {\n ...state,\n termsUrl: action.payload,\n }\n }\n\n case 'updatePaymentOptions': {\n return {\n ...state,\n paymentOptions: action.payload,\n }\n }\n\n case 'updateCustomReturnReasons': {\n return {\n ...state,\n customReturnReasons: action.payload,\n }\n }\n\n case 'updateOptions': {\n return {\n ...state,\n options: action.payload,\n }\n }\n\n case 'updateInitialState': {\n return action.payload\n }\n\n default: {\n return state\n }\n }\n}\n\n```"
}
] |
code_return-app_b2f6d5eb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/WarningModal.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ReactElement } from 'react'\nimport React from 'react'\nimport { ModalDialog } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport { useSettings } from '../hooks/useSettings'\nimport type { ModalWarningState } from '../RMASettings'\n\ninterface WarningModalContentProps {\n maxDays: number\n customMaxDays: number\n}\n\ninterface WarningModalProps {\n setWarning: React.Dispatch<React.SetStateAction<ModalWarningState>>\n customMaxDays: number\n}\n\nconst StrongChunk = (chunks: ReactElement) => <b>{chunks}</b>\n\nconst WarningModalContent = (props: WarningModalContentProps) => {\n const { maxDays, customMaxDays } = props\n\n return (\n <div>\n <p className=\"f3 f3-ns fw3 gray\">\n <FormattedMessage id=\"admin/return-app.settings.modal-warning.title\" />\n </p>\n <p>\n <FormattedMessage\n id=\"admin/return-app.settings.modal-warning.first-paragraph\"\n values={{\n b: StrongChunk,\n maxDays,\n }}\n />\n </p>\n <p>\n <FormattedMessage id=\"admin/return-app.settings.modal-warning.second-paragraph\" />\n </p>\n <p>\n <FormattedMessage\n id=\"admin/return-app.settings.modal-warning.third-paragraph\"\n values={{\n b: StrongChunk,\n maxDays,\n customMaxDays,\n }}\n />\n </p>\n </div>\n )\n}\n\nexport const WarningModal = (props: WarningModalProps) => {\n const { customMaxDays, setWarning } = props\n\n const {\n appSettings,\n actions: { dispatch },\n } = useSettings()\n\n const handleWarningModal = (overrideAndSave: boolean) => {\n overrideAndSave &&\n dispatch({\n type: 'updateMaxDays',\n payload: customMaxDays,\n })\n\n setWarning({\n openModal: false,\n customMaxDays: 0,\n attemptNewSave: overrideAndSave,\n })\n }\n\n return (\n <ModalDialog\n centered\n confirmation={{\n onClick: () => {\n handleWarningModal(true)\n },\n label: (\n <FormattedMessage id=\"admin/return-app.settings.modal-warning.confirm\" />\n ),\n isDangerous: true,\n }}\n cancelation={{\n onClick: () => {\n handleWarningModal(false)\n },\n label: (\n <FormattedMessage id=\"admin/return-app.settings.modal-warning.cancel\" />\n ),\n }}\n isOpen\n onClose={() => {\n handleWarningModal(false)\n }}\n >\n <WarningModalContent\n maxDays={appSettings.maxDays}\n customMaxDays={customMaxDays}\n />\n </ModalDialog>\n )\n}\n\nexport default WarningModal\n\n```"
}
] |
code_return-app_734b7430
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/ExcludedCategories.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useMemo } from 'react'\nimport { useQuery } from 'react-apollo'\nimport { useIntl, FormattedMessage } from 'react-intl'\nimport { AutocompleteInput, IconWarning, IconDeny } from 'vtex.styleguide'\nimport type { CategoryInfo } from 'vtex.return-app'\n\nimport GET_CATEGORY_TREE_INFO from '../graphql/getCategoryTreeName.gql'\nimport { useSettings } from '../hooks/useSettings'\n\ninterface FilterSearchCategoriesArgs {\n categoryList?: CategoryInfo[]\n term: string\n excludedCategories: string[]\n}\n\ninterface LabelFormat {\n /**\n * The category name.\n */\n label: string\n /**\n * The category id.\n */\n value: string\n}\n\nconst AUTO_COMPLETE_LIST_SIZE = 10\n\nconst filterSearchCategories = ({\n categoryList,\n term,\n excludedCategories,\n}: FilterSearchCategoriesArgs): LabelFormat[] => {\n if (!categoryList) {\n return []\n }\n\n const removeExcluded = categoryList.filter(({ id }) => {\n if (!id) return false\n\n return !excludedCategories.includes(id)\n })\n\n const formattedLabels = removeExcluded.map(({ id, name }) => {\n return {\n label: `${id} - ${name}`,\n value: id as string,\n }\n })\n\n return formattedLabels.filter(({ label }) =>\n label.toLowerCase().includes(term.toLowerCase())\n )\n}\n\nexport const ExcludedCategories = () => {\n const [searchedCategory, setSearchedCategory] = React.useState('')\n const {\n appSettings: { excludedCategories },\n actions: { dispatch },\n } = useSettings()\n\n const intl = useIntl()\n const { data, loading, error } = useQuery<{\n categoryTreeName: CategoryInfo[]\n }>(GET_CATEGORY_TREE_INFO)\n\n const categoryNamesMap = useMemo(() => {\n if (!data) {\n return {}\n }\n\n const { categoryTreeName } = data\n\n return categoryTreeName.reduce((categoryMap, { id, name }) => {\n if (id) {\n categoryMap[id] = name\n }\n\n return categoryMap\n }, {})\n }, [data])\n\n const listOfOptions = filterSearchCategories({\n categoryList: data?.categoryTreeName,\n term: searchedCategory,\n excludedCategories,\n })\n\n const handleCategorySelection = (e: LabelFormat) => {\n dispatch({\n type: 'updateExcludedCategories',\n payload: [...excludedCategories, e.value],\n })\n setSearchedCategory('')\n }\n\n const handleDeleteExcludedCategory = (categoryId: string) => {\n dispatch({\n type: 'updateExcludedCategories',\n payload: excludedCategories.filter((id) => id !== categoryId),\n })\n }\n\n return (\n <div className=\"flex flex-column mb6\">\n <div className=\"flex flex-column w-100\">\n <h3>\n <FormattedMessage id=\"admin/return-app.settings.excluded-categories.label\" />\n </h3>\n <AutocompleteInput\n id=\"excluded-categories\"\n input={{\n placeholder: intl.formatMessage({\n id: 'admin/return-app.settings.search-categories.placeholder',\n }),\n onChange: (term: string) => setSearchedCategory(term),\n onClear: () => setSearchedCategory(''),\n value: searchedCategory,\n }}\n options={{\n onSelect: handleCategorySelection,\n value: !searchedCategory.length\n ? []\n : listOfOptions.slice(0, AUTO_COMPLETE_LIST_SIZE),\n loading:\n loading ||\n (searchedCategory.length > 0 &&\n listOfOptions.length > AUTO_COMPLETE_LIST_SIZE),\n customMessage: !error ? null : (\n <div className=\"w-100 pa4 f6 br2 br--bottom bg-base flex items-center\">\n <div className=\"ph3 c-danger flex\">\n <IconWarning />\n </div>\n <p className=\"c-danger\">\n <FormattedMessage id=\"admin/return-app.settings.section-excluded-categories.fetch-data-error\" />\n </p>\n </div>\n ),\n }}\n />\n </div>\n\n {!excludedCategories.length ? null : (\n <ul>\n {excludedCategories.map((categoryId) => {\n const categoryName = categoryNamesMap[categoryId]\n\n return (\n <li key={categoryId}>\n <span className=\"flex items-center\">\n <p>{`${categoryId} - ${categoryName}`}</p>\n <button\n className=\"pointer mh4 bg-transparent c-danger\"\n style={{\n border: 'none',\n }}\n type=\"button\"\n onClick={() => handleDeleteExcludedCategory(categoryId)}\n >\n <IconDeny size={12} />\n </button>\n </span>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n )\n}\n\n```"
}
] |
code_return-app_79b9d09b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/GeneralOptions.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent } from 'react'\nimport React from 'react'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport { Toggle, Divider } from 'vtex.styleguide'\n\nimport { useSettings } from '../hooks/useSettings'\n\nconst generalOptions = [\n 'enableOtherOptionSelection',\n 'enablePickupPoints',\n 'enableProportionalShippingValue',\n 'enableSelectItemCondition',\n 'enableHighlightFormMessage',\n] as const\n\nconst messages = defineMessages({\n 'enableOtherOptionSelection-label': {\n id: 'admin/return-app.settings.section.general-options.enable-other-option-selection.label',\n },\n 'enableOtherOptionSelection-description': {\n id: 'admin/return-app.settings.section.general-options.enable-other-option-selection.description',\n },\n 'enablePickupPoints-label': {\n id: 'admin/return-app.settings.section.general-options.enable-pickup-points.label',\n },\n 'enablePickupPoints-description': {\n id: 'admin/return-app.settings.section.general-options.enable-pickup-points.description',\n },\n 'enableProportionalShippingValue-label': {\n id: 'admin/return-app.settings.section.general-options.enable-proportional-shipping-value.label',\n },\n 'enableProportionalShippingValue-description': {\n id: 'admin/return-app.settings.section.general-options.enable-proportional-shipping-value.description',\n },\n 'enableSelectItemCondition-label': {\n id: 'admin/return-app.settings.section.general-options.enable-select-item-condition.label',\n },\n 'enableSelectItemCondition-description': {\n id: 'admin/return-app.settings.section.general-options.enable-select-item-condition.description',\n },\n 'enableHighlightFormMessage-label': {\n id: 'admin/return-app.settings.section.general-options.enable-highlight-form-message.label',\n },\n 'enableHighlightFormMessage-description': {\n id: 'admin/return-app.settings.section.general-options.enable-highlight-form-message.description',\n },\n})\n\nexport const GeneralOptions = () => {\n const {\n appSettings,\n actions: { dispatch },\n } = useSettings()\n\n const intl = useIntl()\n\n const handleToggle = (e: ChangeEvent<HTMLInputElement>) => {\n const { name, checked } = e.target\n\n const selectedOption = appSettings.options ?? {}\n const updatedSelection = { ...selectedOption, [name]: checked }\n\n dispatch({ type: 'updateOptions', payload: updatedSelection })\n }\n\n return (\n <section>\n <h3>\n <FormattedMessage id=\"admin/return-app.settings.section.general-options.header\" />\n </h3>\n <div className=\"mb4 mh4\">\n {generalOptions.map((option, i, self) => {\n return (\n <div className=\"mt4\" key={option}>\n <Toggle\n name={option}\n semantic\n label={intl.formatMessage(messages[`${option}-label`])}\n helpText={intl.formatMessage(messages[`${option}-description`])}\n onChange={handleToggle}\n checked={appSettings.options?.[option]}\n />\n {i === self.length - 1 ? null : (\n <div className=\"mv4\">\n <Divider />\n </div>\n )}\n </div>\n )\n })}\n </div>\n </section>\n )\n}\n\n```"
}
] |
code_return-app_597a542f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/RequiredOptions.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent } from 'react'\nimport React from 'react'\nimport { Input } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\nimport { useSettings } from '../hooks/useSettings'\n\nexport const RequiredOptions = () => {\n const {\n appSettings,\n actions: { dispatch },\n } = useSettings()\n\n const handleMaxDaysInput = (e: ChangeEvent<HTMLInputElement>) => {\n const { value } = e.target\n const maxDays = Number(value)\n\n if (Number.isNaN(maxDays) || maxDays < 0) {\n return\n }\n\n dispatch({ type: 'updateMaxDays', payload: maxDays })\n }\n\n const handleTermsAndConditionInput = (e: ChangeEvent<HTMLInputElement>) => {\n const { value } = e.target\n\n dispatch({ type: 'updateTermsUrl', payload: value })\n }\n\n return (\n <section className=\"mb6 flex flex-column\">\n <div className=\"flex flex-row\">\n <div className=\"w-50 ph1\">\n <Input\n // logic to avoid leading zero to be persistent in the input\n value={appSettings.maxDays === 0 ? '' : appSettings.maxDays}\n type=\"number\"\n size=\"regular\"\n label={\n <FormattedMessage id=\"admin/return-app.settings.max-days.label\" />\n }\n onChange={handleMaxDaysInput}\n errorMessage=\"\"\n required\n />\n </div>\n <div className=\"w-50 ph1\">\n <Input\n value={appSettings.termsUrl}\n type=\"url\"\n size=\"regular\"\n label={\n <FormattedMessage id=\"admin/return-app.settings.terms.label\" />\n }\n onChange={handleTermsAndConditionInput}\n errorMessage=\"\"\n required\n />\n </div>\n </div>\n </section>\n )\n}\n\n```"
}
] |
code_return-app_1291324f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/PaymentOptions.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent, ComponentPropsWithoutRef } from 'react'\nimport React, { forwardRef } from 'react'\nimport type { IntlShape } from 'react-intl'\nimport { defineMessages, FormattedMessage, useIntl } from 'react-intl'\nimport type { PaymentType } from 'vtex.return-app'\nimport { Toggle, CheckboxGroup } from 'vtex.styleguide'\n\nimport { useSettings } from '../hooks/useSettings'\nimport type { CheckboxProps } from '../RMASettings'\n\nconst messages = defineMessages({\n bank: {\n id: 'admin/return-app.settings.section.payment-options.available-payment-methods.bank',\n },\n card: {\n id: 'admin/return-app.settings.section.payment-options.available-payment-methods.card',\n },\n giftCard: {\n id: 'admin/return-app.settings.section.payment-options.available-payment-methods.gift-card',\n },\n})\n\nconst createOptionsLabel = (\n paymentsTypeOptions: PaymentType,\n intl: IntlShape\n) => {\n if (!paymentsTypeOptions) return null\n\n const paymentTypes = Object.keys(paymentsTypeOptions)\n const createCheckoutOptions = paymentTypes.reduce(\n (checkoutOptions, paymentType) => {\n // This handles the field __typename that comes from the GraphQL query\n if (!messages[paymentType]) return checkoutOptions\n\n return {\n ...checkoutOptions,\n [paymentType]: {\n label: intl.formatMessage(messages[paymentType]),\n checked: paymentsTypeOptions[paymentType],\n name: paymentType,\n },\n }\n },\n {} as { string: CheckboxProps }\n )\n\n return createCheckoutOptions\n}\n\ninterface PaymentOptionsProps extends ComponentPropsWithoutRef<'div'> {\n handleOptionSelection: (options: { string: CheckboxProps }) => void\n hasError: boolean\n}\n\nexport const PaymentOptions = forwardRef<HTMLDivElement, PaymentOptionsProps>(\n ({ handleOptionSelection, hasError }, ref) => {\n const {\n appSettings,\n actions: { dispatch },\n } = useSettings()\n\n const intl = useIntl()\n\n const optionsLabel = createOptionsLabel(\n appSettings?.paymentOptions?.allowedPaymentTypes,\n intl\n )\n\n const handleEnablePaymentMethodSelection = (\n e: ChangeEvent<HTMLInputElement>\n ) => {\n const { checked } = e.target\n\n dispatch({\n type: 'updatePaymentOptions',\n payload: {\n ...appSettings?.paymentOptions,\n enablePaymentMethodSelection: checked,\n allowedPaymentTypes: appSettings.paymentOptions.allowedPaymentTypes,\n // Always return to the default state when use checks / unchecks the checkbox. This way we avaiod a confusing state where buttons is disable but set to on.\n automaticallyRefundPaymentMethod: false,\n },\n })\n }\n\n const handleAutomaticallyRefundOption = (\n e: ChangeEvent<HTMLInputElement>\n ) => {\n const { checked } = e.target\n\n dispatch({\n type: 'updatePaymentOptions',\n payload: {\n ...appSettings?.paymentOptions,\n automaticallyRefundPaymentMethod: checked,\n },\n })\n }\n\n const { enablePaymentMethodSelection, automaticallyRefundPaymentMethod } =\n appSettings.paymentOptions ?? {}\n\n return (\n <section>\n <h3>\n <FormattedMessage id=\"admin/return-app.settings.section.return-payment-options.header\" />\n </h3>\n <div className=\"mb4 mh4\">\n <div className=\"mb4\">\n <Toggle\n label={\n enablePaymentMethodSelection ? (\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.enable-payment-method-selection.label.check\" />\n ) : (\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.enable-payment-method-selection.label.uncheck\" />\n )\n }\n checked={enablePaymentMethodSelection}\n semantic\n onChange={handleEnablePaymentMethodSelection}\n helpText={\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.enable-payment-method-selection.description\" />\n }\n />\n </div>\n <div className=\"mb4\">\n <Toggle\n label={\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.refund-method-strategy.checkbox.label\" />\n }\n checked={automaticallyRefundPaymentMethod}\n semantic\n helpText={\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.refund-method-strategy.checkbox.description\" />\n }\n onChange={handleAutomaticallyRefundOption}\n disabled={enablePaymentMethodSelection}\n />\n </div>\n {enablePaymentMethodSelection && optionsLabel ? (\n <div ref={ref}>\n <h4>\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.available-payment-methods.header\" />\n </h4>\n <CheckboxGroup\n name=\"paymentMethods\"\n label={\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.available-payment-methods.label\" />\n }\n checkedMap={optionsLabel}\n onGroupChange={handleOptionSelection}\n />\n {!hasError ? null : (\n <p className=\"c-danger i t-small mt3 lh-title\">\n <FormattedMessage id=\"admin/return-app.settings.section.payment-options.enable-payment-method-selection.error\" />\n </p>\n )}\n </div>\n ) : null}\n </div>\n </section>\n )\n }\n)\n\n```"
}
] |
code_return-app_3de8e6c5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/graphql/getCategoryTreeName.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery categoryTreeName {\n categoryTreeName @context(provider: \"vtex.return-app\") {\n id\n name\n }\n}\n\n```"
}
] |
code_return-app_18dc6f16
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/graphql/getAppSettings.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery returnAppSettings {\n returnAppSettings @context(provider: \"vtex.return-app\") {\n maxDays\n excludedCategories\n paymentOptions {\n enablePaymentMethodSelection\n allowedPaymentTypes {\n bank\n card\n giftCard\n }\n automaticallyRefundPaymentMethod\n }\n termsUrl\n customReturnReasons {\n reason\n maxDays\n translations {\n locale\n translation\n }\n }\n options {\n enableOtherOptionSelection\n enablePickupPoints\n enableProportionalShippingValue\n enableSelectItemCondition\n enableHighlightFormMessage\n }\n }\n}\n\n```"
}
] |
code_return-app_c65854ea
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/graphql/saveAppSettings.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation saveAppSettings($settings: ReturnAppSettingsInput!) {\n saveReturnAppSettings(settings: $settings)\n @context(provider: \"vtex.return-app\")\n}\n\n```"
}
] |
code_return-app_5a89bda4
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/hooks/useSettings.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\n\nimport { SettingsContext } from '../provider/SettingsProvider'\n\nexport const useSettings = () => useContext(SettingsContext)\n\n```"
}
] |
code_return-app_4fed86c9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/CustomReasons/CustomReasons.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ReactElement } from 'react'\nimport React, { useState } from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport type { CustomReturnReason } from 'vtex.return-app'\nimport {\n ButtonWithIcon,\n IconPlusLines,\n Table,\n ModalDialog,\n} from 'vtex.styleguide'\n\nimport { useSettings } from '../../hooks/useSettings'\nimport { CustomReasonModal } from './CustomReasonModal'\nimport { TranslationsModal } from './TranslationsModal'\n\nconst addIndexToCustomReason = (\n customReturnReasons: CustomReturnReason[] | undefined | null\n) =>\n customReturnReasons?.map((reason, i) => ({\n ...reason,\n index: i,\n })) ?? []\n\nconst tableSchema = {\n properties: {\n reason: {\n title: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.table.header.reason\" />\n ),\n },\n maxDays: {\n title: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.table.header.max-days\" />\n ),\n },\n },\n}\n\ninterface LineActionsArgs {\n handleDeleteCustomReason: (reason: number) => void\n handleEditCustomReason: (customReason: CustomReasonWithIndex) => void\n handleOpenTranslations: (customReason: CustomReasonWithIndex) => void\n}\n\nexport type CustomReasonWithIndex = ReturnType<\n typeof addIndexToCustomReason\n>[number]\n\ninterface RowData {\n rowData: CustomReasonWithIndex\n}\n\nconst lineActions = ({\n handleDeleteCustomReason,\n handleEditCustomReason,\n handleOpenTranslations,\n}: LineActionsArgs) => {\n return [\n {\n label: () => 'Edit',\n onClick: ({ rowData }: RowData) => {\n handleEditCustomReason(rowData)\n },\n },\n {\n label: () => 'Delete',\n isDangerous: true,\n onClick: ({ rowData }: RowData) => {\n handleDeleteCustomReason(rowData.index)\n },\n },\n {\n label: () => 'Translations',\n onClick: ({ rowData }: RowData) => {\n handleOpenTranslations(rowData)\n },\n },\n ]\n}\n\nexport const CustomReasons = () => {\n const [modalOpen, setModalOpen] = useState<\n 'add' | 'edit' | 'translations' | ''\n >('')\n\n const [indexToDelete, setIndexToDelete] = useState<number | null>(null)\n const [customReasonToEdit, setCustomReasonToEdit] =\n useState<CustomReasonWithIndex | null>(null)\n\n const {\n appSettings: { customReturnReasons },\n actions: { dispatch },\n } = useSettings()\n\n const handleDeleteCustomReason = (reasonIndex: number) => {\n setIndexToDelete(reasonIndex)\n }\n\n const handleEditCustomReason = (customReason: CustomReasonWithIndex) => {\n setCustomReasonToEdit(customReason)\n setModalOpen('edit')\n }\n\n const handleOpenTranslations = (customReason: CustomReasonWithIndex) => {\n setCustomReasonToEdit(customReason)\n setModalOpen('translations')\n }\n\n const handleStateCleanup = () => {\n setCustomReasonToEdit(null)\n setModalOpen('')\n }\n\n const confirmDelete = () => {\n const newCustomReturnReasons = customReturnReasons?.filter(\n (_, i) => i !== indexToDelete\n )\n\n setIndexToDelete(null)\n\n dispatch({\n type: 'updateCustomReturnReasons',\n payload: newCustomReturnReasons ?? [],\n })\n }\n\n return (\n <section>\n <div className=\"flex items-end justify-between\">\n <h3>\n <FormattedMessage id=\"admin/return-app.settings.section.custom-return-reasons.header\" />\n </h3>\n <span>\n <ButtonWithIcon\n onClick={() => setModalOpen('add')}\n icon={<IconPlusLines />}\n >\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.add.button\" />\n </ButtonWithIcon>\n </span>\n </div>\n <div>\n <Table\n fullWidth\n schema={tableSchema}\n // Add index to custom reasons so it can be used on edit and delete operations\n items={addIndexToCustomReason(customReturnReasons)}\n lineActions={lineActions({\n handleDeleteCustomReason,\n handleEditCustomReason,\n handleOpenTranslations,\n })}\n emptyStateLabel={\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.empty-custom-reasons\" />\n }\n emptyStateChildren={\n <>\n <p>\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.empty-custom-reasons.how-to\" />\n </p>\n <p>\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.empty-custom-reasons.reasons.disclaimer\" />\n </p>\n </>\n }\n />\n </div>\n <CustomReasonModal\n isOpen={modalOpen === 'add' || modalOpen === 'edit'}\n modalOpen={modalOpen}\n onClose={handleStateCleanup}\n customReasonOnFocus={customReasonToEdit}\n />\n {/* Modal to confirm delete operation. It has to check === null because indexToDelete can be zero */}\n {indexToDelete === null ? null : (\n <ModalDialog\n centered\n isOpen={indexToDelete !== null}\n onClose={() => setIndexToDelete(null)}\n confirmation={{\n label: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.confirm\" />\n ),\n onClick: confirmDelete,\n isDangerous: true,\n }}\n cancelation={{\n label: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.cancel\" />\n ),\n onClick: () => setIndexToDelete(null),\n }}\n >\n <p className=\"f3 fw3 f3-ns\">\n <FormattedMessage\n id=\"admin/return-app.settings.section.custom-reasons.modal.delete.custom-reason.message\"\n values={{\n reason: customReturnReasons?.[indexToDelete]?.reason,\n // eslint-disable-next-line react/display-name\n b: (chunks: ReactElement) => <b>{chunks}</b>,\n }}\n />\n </p>\n </ModalDialog>\n )}\n <TranslationsModal\n customReasonOnFocus={customReasonToEdit}\n isOpen={modalOpen === 'translations'}\n onClose={handleStateCleanup}\n />\n </section>\n )\n}\n\n```"
}
] |
code_return-app_92505efe
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/CustomReasons/CustomReasonModal.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent, FormEvent } from 'react'\nimport React, { useState, useEffect } from 'react'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport type { CustomReturnReason } from 'vtex.return-app'\nimport { Modal, Input, Button } from 'vtex.styleguide'\n\nimport { useSettings } from '../../hooks/useSettings'\nimport type { CustomReasonWithIndex } from './CustomReasons'\n\ninterface CustomReasonModalProps {\n isOpen: boolean\n modalOpen: 'add' | 'edit' | 'translations' | ''\n onClose: () => void\n customReasonOnFocus: CustomReasonWithIndex | null\n}\n\nexport const CustomReasonModal = ({\n isOpen,\n modalOpen,\n onClose,\n customReasonOnFocus,\n}: CustomReasonModalProps) => {\n const {\n appSettings: { maxDays, customReturnReasons },\n actions: { dispatch },\n } = useSettings()\n\n const [tempReason, setTempReason] = useState<CustomReturnReason>(\n {} as CustomReturnReason\n )\n\n const intl = useIntl()\n\n useEffect(() => {\n if (customReasonOnFocus && modalOpen === 'edit') {\n // customReasonOnFocus has index property, not accepted by Graphql.\n setTempReason({\n reason: customReasonOnFocus.reason,\n maxDays: customReasonOnFocus.maxDays,\n translations: customReasonOnFocus.translations,\n })\n }\n }, [modalOpen, customReasonOnFocus])\n\n const handleTempReasonChange = (e: ChangeEvent<HTMLInputElement>) => {\n const { value, name } = e.target\n\n setTempReason({\n ...tempReason,\n [name]: name === 'maxDays' ? Number(value) : value,\n })\n }\n\n const handleCloseModal = () => {\n setTempReason({} as CustomReturnReason)\n onClose()\n }\n\n const handleAddNewReason = (e: FormEvent) => {\n e.preventDefault()\n e.stopPropagation()\n\n let payload: CustomReturnReason[]\n\n if (modalOpen === 'edit' && customReasonOnFocus) {\n payload =\n customReturnReasons?.map((reason, i) => {\n if (i === customReasonOnFocus.index) {\n return tempReason\n }\n\n return reason\n }) ?? []\n } else {\n // Adding new one\n payload = customReturnReasons\n ? [...customReturnReasons, tempReason]\n : [tempReason]\n }\n\n dispatch({\n type: 'updateCustomReturnReasons',\n payload,\n })\n handleCloseModal()\n }\n\n return (\n <Modal isOpen={isOpen} onClose={handleCloseModal}>\n <div className=\"flex flex-column\">\n <div className=\"w-100\">\n <h4 className=\"f3 fw3 gray mt6 mb2\">\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.custom-reason.header\" />\n </h4>\n </div>\n <div className=\"w-100 mv4\">\n <form\n onSubmit={handleAddNewReason}\n className=\"flex flex-column items-baseline\"\n >\n <div className=\"w-100 mv3\">\n <Input\n placeholder={intl.formatMessage({\n id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.placeholder',\n })}\n label={intl.formatMessage({\n id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.label',\n })}\n name=\"reason\"\n size=\"large\"\n required\n value={tempReason.reason ?? ''}\n onChange={handleTempReasonChange}\n />\n </div>\n <div className=\"w-100 mt3 mb6\">\n <Input\n placeholder={intl.formatMessage({\n id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.max-days.placeholder',\n })}\n label={intl.formatMessage({\n id: 'admin/return-app.settings.section.custom-reasons.modal.custom-reason.max-days.label',\n })}\n name=\"maxDays\"\n size=\"large\"\n type=\"number\"\n min=\"1\"\n max={maxDays}\n required\n value={tempReason.maxDays ?? ''}\n onChange={handleTempReasonChange}\n />\n </div>\n <Button type=\"submit\">\n {modalOpen === 'edit' ? (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.custom-reason.edit.button\" />\n ) : null}\n {modalOpen === 'add' ? (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.custom-reason.add-new.button\" />\n ) : null}\n </Button>\n </form>\n </div>\n </div>\n </Modal>\n )\n}\n\n```"
}
] |
code_return-app_fbf55c15
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/CustomReasons/TranslationsModal.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent, ReactElement } from 'react'\nimport React, { useEffect, useState } from 'react'\nimport { useQuery } from 'react-apollo'\nimport type { Tenant, Binding } from 'vtex.tenant-graphql'\nimport { ModalDialog, Table, Input, Spinner, EmptyState } from 'vtex.styleguide'\nimport type { CustomReturnReasonTranslation } from 'vtex.return-app'\nimport { FormattedMessage } from 'react-intl'\n\nimport TENANT_INFO from './graphql/tenant.gql'\nimport type { CustomReasonWithIndex } from './CustomReasons'\nimport { useSettings } from '../../hooks/useSettings'\n\nconst localesAvailable = (bindings: Binding[]): string[] => {\n const storefrontBindings = bindings.filter(\n (binding) => binding.targetProduct === 'vtex-storefront'\n )\n\n const localesMap = new Map()\n\n for (const binding of storefrontBindings) {\n const { defaultLocale, supportedLocales } = binding\n\n if (!localesMap.has(defaultLocale)) {\n localesMap.set(defaultLocale, true)\n }\n\n for (const locale of supportedLocales) {\n if (locale && !localesMap.has(locale)) {\n localesMap.set(locale, true)\n }\n }\n }\n\n return Array.from(localesMap.keys())\n}\n\nconst createTranslationOptions = (\n availableLocales: string[],\n translation?: CustomReturnReasonTranslation[] | null\n): CustomReturnReasonTranslation[] => {\n return availableLocales.map((availableLocale) => {\n const currentTranslation = translation?.find(\n ({ locale }) => locale === availableLocale\n )\n\n return currentTranslation ?? { locale: availableLocale, translation: '' }\n })\n}\n\nconst tableSchema = (\n handleTranslationInput: (e: ChangeEvent<HTMLInputElement>) => void\n) => ({\n properties: {\n locale: {\n title: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.table.header.custom-reason-translation.locale\" />\n ),\n },\n translation: {\n title: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.table.header.custom-reason-translation.translation\" />\n ),\n // eslint-disable-next-line react/display-name\n cellRenderer: ({\n rowData,\n }: {\n rowData: CustomReturnReasonTranslation\n }) => {\n const { translation, locale } = rowData\n\n return (\n <Input\n size=\"small\"\n value={translation}\n name={locale}\n onChange={handleTranslationInput}\n />\n )\n },\n },\n },\n})\n\ninterface TranslationsModalProps {\n isOpen: boolean\n onClose: () => void\n customReasonOnFocus: CustomReasonWithIndex | null\n}\n\nexport const TranslationsModal = ({\n customReasonOnFocus,\n isOpen,\n onClose,\n}: TranslationsModalProps) => {\n const [tempTranslations, setTempTranslations] = useState<\n CustomReturnReasonTranslation[]\n >([])\n\n const {\n appSettings: { customReturnReasons },\n actions: { dispatch },\n } = useSettings()\n\n const { data, loading, error } = useQuery<{ tenantInfo: Tenant }>(TENANT_INFO)\n\n useEffect(() => {\n if (customReasonOnFocus?.translations) {\n setTempTranslations(customReasonOnFocus.translations)\n }\n }, [customReasonOnFocus])\n\n const handleTranslationInput = (e: ChangeEvent<HTMLInputElement>) => {\n const { value, name } = e.target\n const hasLocale = tempTranslations.find(\n (translation) => translation.locale === name\n )\n\n if (hasLocale) {\n const newTranslations = tempTranslations.map((translation) => {\n if (translation.locale === name) {\n return { ...translation, translation: value }\n }\n\n return translation\n })\n\n setTempTranslations(newTranslations)\n\n return\n }\n\n const newTranslations = [\n ...tempTranslations,\n { locale: name, translation: value },\n ]\n\n setTempTranslations(newTranslations)\n }\n\n const handleCloseModal = () => {\n setTempTranslations([])\n onClose()\n }\n\n const handleConfirmation = () => {\n const updatedCustomReturnReasons = customReturnReasons?.map(\n (customReason, i) => {\n if (i === customReasonOnFocus?.index) {\n // filters our the ones where the translation is empty to avoid rendering an empty string to final user\n const translations = tempTranslations.filter(({ translation }) =>\n Boolean(translation)\n )\n\n return {\n ...customReason,\n translations,\n }\n }\n\n return customReason\n }\n )\n\n if (updatedCustomReturnReasons) {\n dispatch({\n type: 'updateCustomReturnReasons',\n payload: updatedCustomReturnReasons,\n })\n }\n\n handleCloseModal()\n }\n\n const availableLocales = localesAvailable(data?.tenantInfo?.bindings ?? [])\n\n return (\n <ModalDialog\n centered\n isOpen={isOpen}\n onClose={handleCloseModal}\n confirmation={{\n label: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.confirm\" />\n ),\n onClick: handleConfirmation,\n }}\n cancelation={{\n label: (\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.cancel\" />\n ),\n onClick: handleCloseModal,\n }}\n >\n <div>\n <div>\n <h4 className=\"f3 fw3 gray mt6 mb2\">\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.header.custom-reason-translation\" />\n </h4>\n <p>\n <FormattedMessage\n id=\"admin/return-app.settings.section.custom-reasons.modal.translations.sub-header.custom-reason-translation\"\n values={{\n reason: customReasonOnFocus?.reason,\n // eslint-disable-next-line react/display-name\n b: (chunks: ReactElement) => <b>{chunks}</b>,\n }}\n />\n </p>\n </div>\n {error ? (\n <EmptyState\n title={\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.error.header\" />\n }\n >\n <p>\n <FormattedMessage id=\"admin/return-app.settings.section.custom-reasons.modal.translations.error.description\" />\n </p>\n </EmptyState>\n ) : loading ? (\n <Spinner />\n ) : (\n <div>\n <Table\n schema={tableSchema(handleTranslationInput)}\n items={createTranslationOptions(\n availableLocales,\n tempTranslations\n )}\n fullWidth\n />\n </div>\n )}\n </div>\n </ModalDialog>\n )\n}\n\n```"
}
] |
code_return-app_7f8e361f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/settings/components/CustomReasons/graphql/tenant.gql from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery tenantInfo {\n tenantInfo @context(provider: \"vtex.tenant-graphql\") {\n bindings {\n defaultLocale\n supportedLocales\n targetProduct\n }\n }\n}\n\n```"
}
] |
code_return-app_1062d4b5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/UpdateRequestStatus.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FormEvent, ChangeEvent } from 'react'\nimport React, { useState } from 'react'\nimport type { IntlFormatters } from 'react-intl'\nimport { FormattedMessage, useIntl } from 'react-intl'\nimport {\n Dropdown,\n Textarea,\n Checkbox,\n Button,\n Tooltip,\n IconInfo,\n} from 'vtex.styleguide'\nimport type { Status } from 'vtex.return-app'\n\nimport { useReturnDetails } from '../../../common/hooks/useReturnDetails'\nimport {\n statusAllowed,\n statusMessageIdAdmin,\n} from '../../../utils/requestStatus'\nimport { useUpdateRequestStatus } from '../../hooks/useUpdateRequestStatus'\n\nconst createStatusOptions = (\n currentStatus: Status,\n formatMessage: IntlFormatters['formatMessage']\n): Array<{ value: string; label: string }> => {\n const allowedStatus = statusAllowed[currentStatus]\n\n return allowedStatus.map((status) => ({\n value: status,\n label: formatMessage(statusMessageIdAdmin[status]),\n }))\n}\n\ninterface Props {\n onViewVerifyItems: () => void\n}\n\nexport const UpdateRequestStatus = ({ onViewVerifyItems }: Props) => {\n const [selectedStatus, setSelectedStatus] = useState<Status | ''>('')\n const [comment, setComment] = useState('')\n const [visibleForCustomer, setVisibleForCustomer] = useState(false)\n const { formatMessage } = useIntl()\n const { data } = useReturnDetails()\n const { submitting, handleStatusUpdate } = useUpdateRequestStatus()\n\n const cleanUp = () => {\n setComment('')\n setVisibleForCustomer(false)\n }\n\n const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {\n event.preventDefault()\n if (submitting || selectedStatus === '' || !data?.returnRequestDetails) {\n return\n }\n\n const newComment = !comment\n ? undefined\n : {\n value: comment,\n visibleForCustomer,\n }\n\n handleStatusUpdate({\n id: data.returnRequestDetails?.id,\n status: selectedStatus,\n comment: newComment,\n cleanUp,\n })\n }\n\n const handleStatusChange = (event: ChangeEvent<HTMLInputElement>) => {\n const { value } = event.target\n\n setSelectedStatus(value as Status)\n }\n\n const handleCommentsChange = (event: ChangeEvent<HTMLInputElement>) => {\n const { value } = event.target\n\n setComment(value)\n }\n\n const handleVisibleToCustomerChange = (\n event: ChangeEvent<HTMLInputElement>\n ) => {\n const { checked } = event.target\n\n setVisibleForCustomer(checked)\n }\n\n const updateStatus =\n selectedStatus && selectedStatus !== data?.returnRequestDetails.status\n\n if (!data) return null\n\n return (\n <section className=\"mv4\">\n <div className=\"flex items-center\">\n <h3>\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.title\" />\n </h3>\n <Tooltip\n label={\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.tooltip\" />\n }\n >\n <span className=\"yellow pointer ml3 flex\">\n <IconInfo />\n </span>\n </Tooltip>\n </div>\n <form\n className=\"flex flex-column items-stretch w-50\"\n onSubmit={handleSubmit}\n >\n <div className=\"mb6\">\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.dropdown.placeholder\">\n {(placeholder) => (\n <Dropdown\n size=\"small\"\n placeholder={placeholder}\n options={createStatusOptions(\n data.returnRequestDetails.status,\n formatMessage\n )}\n value={selectedStatus}\n onChange={handleStatusChange}\n />\n )}\n </FormattedMessage>\n </div>\n <div className=\"mb6\">\n <Textarea\n label={\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.textarea.label\" />\n }\n value={comment}\n onChange={handleCommentsChange}\n />\n </div>\n <div className=\"mb6\">\n <Checkbox\n checked={visibleForCustomer}\n label={\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.checkbox.label\" />\n }\n onChange={handleVisibleToCustomerChange}\n />\n </div>\n <div className=\"mb6\">\n <Button\n type=\"submit\"\n variation=\"primary\"\n size=\"small\"\n disabled={\n !selectedStatus ||\n (selectedStatus === data.returnRequestDetails.status && !comment)\n }\n isLoading={submitting}\n >\n {updateStatus ? (\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.button.update-status\" />\n ) : (\n <FormattedMessage id=\"admin/return-app.return-request-details.update-status.button.comment\" />\n )}\n </Button>\n {data.returnRequestDetails.status === 'pendingVerification' ? (\n <span className=\"ml4\">\n <Button type=\"button\" onClick={onViewVerifyItems} size=\"small\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.button\" />\n </Button>\n </span>\n ) : null}\n </div>\n </form>\n </section>\n )\n}\n\n```"
}
] |
code_return-app_91fae43a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/AlignItemRight.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { FC } from 'react'\n\nexport const AlignItemRight: FC = ({ children }) => (\n <span className=\"flex justify-end w-100\">{children}</span>\n)\n\n```"
}
] |
code_return-app_ae9e7a46
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/VerifyTotalsTable.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Table } from 'vtex.styleguide'\n\nimport { verifyTotalsTableSchema } from './verifyTotalsTableSchema'\nimport type { UpdateRefundShipping } from './VerifyItemsPage'\nimport { useReturnDetails } from '../../../../common/hooks/useReturnDetails'\n\ninterface Props {\n refundableShipping: number\n shippingToRefund: number\n totalRefundItems: number\n onRefundShippingChange: UpdateRefundShipping\n}\n\nexport const VerifyTotalsTable = ({\n refundableShipping,\n shippingToRefund,\n totalRefundItems,\n onRefundShippingChange,\n}: Props) => {\n const { data } = useReturnDetails()\n\n if (!data) return null\n\n const { cultureInfoData } = data.returnRequestDetails\n\n return (\n <div>\n <h3>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.title.totals\" />\n </h3>\n <Table\n fullWidth\n schema={verifyTotalsTableSchema(\n onRefundShippingChange,\n cultureInfoData\n )}\n items={[\n {\n refundableShipping,\n shippingToRefund,\n totalRefundItems,\n totalRefund: shippingToRefund + totalRefundItems,\n },\n ]}\n />\n </div>\n )\n}\n\n```"
}
] |
code_return-app_5cd7b150
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/ProductActionStatus.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { IconSuccess, IconFailure, IconWarning } from 'vtex.styleguide'\nimport { FormattedMessage } from 'react-intl'\n\ntype ActionStatus = 'deny' | 'approve' | 'partially-approve'\n\nconst getActionStatus = ({\n quantity,\n selectedQuantity,\n}: {\n quantity: number\n selectedQuantity: number\n}): ActionStatus =>\n selectedQuantity === 0\n ? 'deny'\n : selectedQuantity === quantity\n ? 'approve'\n : 'partially-approve'\n\nexport const ProductActionStatus = ({\n quantity,\n selectedQuantity,\n}: {\n quantity: number\n selectedQuantity: number\n}) => {\n const actionStatus = getActionStatus({ quantity, selectedQuantity })\n\n return (\n <>\n {actionStatus !== 'approve' ? null : (\n <div className=\"c-success flex items-center\">\n <span className=\"mr2 flex\">\n <IconSuccess size={14} />\n </span>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.action.approve\" />\n </div>\n )}\n {actionStatus !== 'deny' ? null : (\n <div className=\"c-danger flex items-center\">\n <span className=\"mr2 flex\">\n <IconFailure size={14} />\n </span>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.action.deny\" />\n </div>\n )}\n {actionStatus !== 'partially-approve' ? null : (\n <div className=\"c-warning flex items-center\">\n <span className=\"mr2 flex\">\n <IconWarning size={14} />\n </span>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.action.partially-approve\" />\n </div>\n )}\n </>\n )\n}\n\n```"
}
] |
code_return-app_dafcbc19
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/verifyItemsTableSchema.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent } from 'react'\nimport React from 'react'\nimport { FormattedMessage, FormattedNumber } from 'react-intl'\nimport type { ReturnRequestItem, CultureInfoData } from 'vtex.return-app'\nimport { NumericStepper, InputCurrency } from 'vtex.styleguide'\n\nimport type { RefundItemMap, UpdateItemsChange } from './VerifyItemsPage'\nimport { AlignItemRight } from '../AlignItemRight'\nimport { ProductActionStatus } from './ProductActionStatus'\n\nexport const verifyItemsTableSchema = (\n refundItemMap: RefundItemMap,\n updateChanges: UpdateItemsChange,\n cultureInfoData: CultureInfoData\n) => ({\n properties: {\n name: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.product\" />\n ),\n minWidth: 320,\n },\n sellingPrice: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.price\" />\n ),\n width: 90,\n headerRight: true,\n cellRenderer: function SellingPriceHeader({\n cellData,\n }: {\n rowData: ReturnRequestItem\n cellData: ReturnRequestItem['sellingPrice']\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n tax: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.tax\" />\n ),\n width: 90,\n headerRight: true,\n cellRenderer: function TaxHeader({\n cellData,\n }: {\n rowData: ReturnRequestItem\n cellData: ReturnRequestItem['tax']\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n totalPrice: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.total\" />\n ),\n width: 90,\n headerRight: true,\n cellRenderer: function TotalPriceHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { sellingPrice, tax } = rowData\n\n return (\n <AlignItemRight>\n <FormattedNumber\n value={(sellingPrice + tax) / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n quantity: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.quantity\" />\n ),\n width: 80,\n cellRenderer: function QuantityHeader({\n cellData,\n }: {\n rowData: ReturnRequestItem\n cellData: ReturnRequestItem['quantity']\n }) {\n return <span className=\"w-100 flex justify-center\">{cellData}</span>\n },\n },\n verified: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.verified\" />\n ),\n width: 160,\n cellRenderer: function VerifiedPQuantityHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { orderItemIndex, quantity } = rowData\n\n const handleChange = ({ value }: { value: number }) => {\n updateChanges({ quantity: value, orderItemIndex })\n }\n\n const selectedQuantity =\n refundItemMap.get(orderItemIndex)?.quantity ?? 0\n\n return (\n <NumericStepper\n value={selectedQuantity}\n maxValue={quantity}\n onChange={handleChange}\n />\n )\n },\n },\n restockFee: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.restock-fee\" />\n ),\n width: 150,\n cellRenderer: function RestockFeeHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { sellingPrice, tax, orderItemIndex } = rowData\n\n const refundItem = refundItemMap.get(orderItemIndex)\n const restockFee = refundItem?.restockFee ?? 0\n const selectedQuantity = refundItem?.quantity ?? 0\n\n const handleChange = (event: ChangeEvent<HTMLInputElement>) => {\n const { value } = event.target\n const restockFeeInput = Number(value)\n\n const restockFeeInputParsed = Number.isNaN(restockFeeInput)\n ? 0\n : restockFeeInput\n\n const restockFeeCents = parseFloat(\n (restockFeeInputParsed * 100).toFixed(0)\n )\n\n const maxRestockFee = (sellingPrice + tax) * selectedQuantity\n\n const restockFeeChecked =\n restockFeeCents > maxRestockFee ? maxRestockFee : restockFeeCents\n\n updateChanges({ restockFee: restockFeeChecked, orderItemIndex })\n }\n\n return (\n <InputCurrency\n value={restockFee / 100}\n currencyCode={cultureInfoData.currencyCode}\n locale={cultureInfoData.locale}\n onChange={handleChange}\n readOnly={selectedQuantity === 0}\n />\n )\n },\n },\n totalRefund: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.refund-product-total\" />\n ),\n headerRight: true,\n width: 90,\n cellRenderer: function TotalProductRefundHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { sellingPrice, tax, orderItemIndex } = rowData\n\n const refundItem = refundItemMap.get(orderItemIndex)\n const selectedQuantity = refundItem?.quantity ?? 0\n const restockFee = refundItem?.restockFee ?? 0\n\n return (\n <AlignItemRight>\n <FormattedNumber\n value={\n ((sellingPrice + tax) * selectedQuantity - restockFee) / 100\n }\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n action: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.action\" />\n ),\n cellRenderer: function VerifyActionHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { quantity, orderItemIndex } = rowData\n\n const selectedQuantity =\n refundItemMap.get(orderItemIndex)?.quantity ?? 0\n\n return (\n <ProductActionStatus\n quantity={quantity}\n selectedQuantity={selectedQuantity}\n />\n )\n },\n },\n },\n})\n\n```"
}
] |
code_return-app_5809fb49
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/VerifyItemsPage.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport {\n FloatingActionBar,\n ModalDialog,\n Table,\n Tooltip,\n IconInfo,\n} from 'vtex.styleguide'\nimport { FormattedMessage, FormattedNumber } from 'react-intl'\nimport type { RefundItemInput } from 'vtex.return-app'\n\nimport { useReturnDetails } from '../../../../common/hooks/useReturnDetails'\nimport { VerifyItemsTable } from './VerifyItemsTable'\nimport { VerifyTotalsTable } from './VerifyTotalsTable'\nimport { useUpdateRequestStatus } from '../../../hooks/useUpdateRequestStatus'\nimport { verifyItemsModalSchema } from './verifyItemsModalSchema'\n\nexport type RefundItemMap = Map<\n number,\n { quantity: number; restockFee: number }\n>\n\nexport type UpdateItemsChange = (args: {\n orderItemIndex: number\n restockFee?: number\n quantity?: number\n}) => void\n\nexport type UpdateRefundShipping = (shippingToRefundInput: number) => void\n\ninterface Props {\n onViewVerifyItems: () => void\n}\n\nexport const VerifyItemsPage = ({ onViewVerifyItems }: Props) => {\n const { data } = useReturnDetails()\n const { submitting, handleStatusUpdate } = useUpdateRequestStatus()\n\n const [refundItemsInput, setRefundItemsInput] = useState<RefundItemMap>(\n new Map()\n )\n\n const [isModalOpen, setIsModalOpen] = useState(false)\n const [shippingToRefund, setShippingToRefund] = useState(0)\n\n if (!data) return null\n\n const {\n id: requestId,\n items = [],\n refundableAmountTotals = [],\n cultureInfoData,\n } = data?.returnRequestDetails\n\n const handleItemChanges = ({\n orderItemIndex,\n restockFee,\n quantity,\n }: {\n orderItemIndex: number\n restockFee?: number\n quantity?: number\n }) => {\n const updatedRefundItemMap = new Map(refundItemsInput)\n const item = updatedRefundItemMap.get(orderItemIndex)\n const itemQuantity = quantity ?? item?.quantity ?? 0\n const itemRestockFee = restockFee ?? item?.restockFee ?? 0\n\n updatedRefundItemMap.set(orderItemIndex, {\n quantity: itemQuantity,\n restockFee: itemQuantity === 0 ? 0 : itemRestockFee,\n })\n\n setRefundItemsInput(updatedRefundItemMap)\n }\n\n const handleShippingChanges = (shippingToRefundInput: number) => {\n setShippingToRefund(shippingToRefundInput)\n }\n\n const onSave = async () => {\n if (!requestId || submitting) return\n\n const itemsToRefund: RefundItemInput[] = []\n\n for (const [\n orderItemIndex,\n { quantity, restockFee },\n ] of refundItemsInput.entries()) {\n itemsToRefund.push({\n orderItemIndex,\n quantity,\n restockFee,\n })\n }\n\n handleStatusUpdate({\n status: 'packageVerified',\n id: requestId,\n refundData: {\n refundedShippingValue: shippingToRefund,\n items: itemsToRefund,\n },\n cleanUp: onViewVerifyItems,\n })\n }\n\n const refundableShipping =\n refundableAmountTotals.find(({ id }) => id === 'shipping')?.value ?? 0\n\n const totalRefundItems = items.reduce((total, item) => {\n const { orderItemIndex, sellingPrice, tax } = item\n const returningItem = refundItemsInput.get(orderItemIndex)\n const { quantity = 0, restockFee = 0 } = returningItem ?? {}\n const itemTotal = (sellingPrice + tax) * quantity - restockFee\n\n return total + itemTotal\n }, 0)\n\n return (\n <>\n <section>\n <h2>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.title\" />\n </h2>\n <VerifyItemsTable\n items={items}\n refundItemsInput={refundItemsInput}\n onItemChange={handleItemChanges}\n />\n <VerifyTotalsTable\n refundableShipping={refundableShipping}\n shippingToRefund={shippingToRefund}\n totalRefundItems={totalRefundItems}\n onRefundShippingChange={handleShippingChanges}\n />\n </section>\n <FloatingActionBar\n save={{\n label: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.action.confirm\" />\n ),\n isLoading: submitting,\n onClick: () => setIsModalOpen(true),\n }}\n cancel={{\n label: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.action.cancel\" />\n ),\n onClick: onViewVerifyItems,\n }}\n />\n <ModalDialog\n centered\n confirmation={{\n onClick: onSave,\n label: totalRefundItems ? (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.modal.button-verify\" />\n ) : (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.modal.button-deny\" />\n ),\n }}\n cancelation={{\n onClick: () => setIsModalOpen(false),\n label: 'Cancel',\n }}\n isOpen={isModalOpen}\n onClose={() => setIsModalOpen(false)}\n >\n <div>\n <p className=\"f3 f3-ns fw6\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.modal.title\" />\n </p>\n <div>\n <Table\n fullWidth\n schema={verifyItemsModalSchema(refundItemsInput, cultureInfoData)}\n items={items}\n />\n </div>\n\n {totalRefundItems ? (\n <>\n <div className=\"flex mt5 justify-end\">\n <p className=\"f6 mr5 gray\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.shipping-to-refund\" />\n :\n </p>\n <p className=\"f6 \">\n <FormattedNumber\n value={Number(shippingToRefund) / 100}\n currency={cultureInfoData.currencyCode}\n style=\"currency\"\n />\n </p>\n </div>\n <div className=\"flex justify-end\">\n <p className=\"f6 mr5 gray\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.total-refund-items\" />\n :\n </p>\n <p className=\"f6 \">\n <FormattedNumber\n value={Number(totalRefundItems) / 100}\n currency={cultureInfoData.currencyCode}\n style=\"currency\"\n />\n </p>\n </div>\n <div className=\"flex justify-end\">\n <p className=\"f6 mr5 gray b\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.total-refund\" />\n :\n </p>\n <p className=\"f6\">\n <FormattedNumber\n value={\n (Number(shippingToRefund) + Number(totalRefundItems)) /\n 100\n }\n currency={cultureInfoData.currencyCode}\n style=\"currency\"\n />\n </p>\n </div>\n </>\n ) : (\n <div className=\"flex items-center justify-end mt7\">\n <Tooltip\n label={\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.modal.tooltip\" />\n }\n >\n <span className=\"yellow pointer mr3 flex\">\n <IconInfo />\n </span>\n </Tooltip>\n <span className=\"i-s\">\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.modal.deny-message\" />\n </span>\n </div>\n )}\n </div>\n </ModalDialog>\n </>\n )\n}\n\n```"
}
] |
code_return-app_33078130
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/VerifyItemsTable.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage } from 'react-intl'\nimport { Table } from 'vtex.styleguide'\nimport type { ReturnRequestItem } from 'vtex.return-app'\n\nimport { verifyItemsTableSchema } from './verifyItemsTableSchema'\nimport type { RefundItemMap, UpdateItemsChange } from './VerifyItemsPage'\nimport { useReturnDetails } from '../../../../common/hooks/useReturnDetails'\n\ninterface Props {\n items: ReturnRequestItem[]\n refundItemsInput: RefundItemMap\n onItemChange: UpdateItemsChange\n}\n\nexport const VerifyItemsTable = ({\n items,\n refundItemsInput,\n onItemChange,\n}: Props) => {\n const { data } = useReturnDetails()\n\n if (!data) return null\n\n const { cultureInfoData } = data.returnRequestDetails\n\n return (\n <div>\n <h3>\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.title.items\" />\n </h3>\n <Table\n fullWidth\n fixFirstColumn\n schema={verifyItemsTableSchema(\n refundItemsInput,\n onItemChange,\n cultureInfoData\n )}\n items={items}\n />\n </div>\n )\n}\n\n```"
}
] |
code_return-app_e5ded4cd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/verifyTotalsTableSchema.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { ChangeEvent } from 'react'\nimport React from 'react'\nimport { FormattedMessage, FormattedNumber } from 'react-intl'\nimport { InputCurrency } from 'vtex.styleguide'\nimport type { CultureInfoData } from 'vtex.return-app'\n\nimport { AlignItemRight } from '../AlignItemRight'\n\nexport const verifyTotalsTableSchema = (\n handleShippingChanges: (shippingToRefundInput: number) => void,\n cultureInfoData: CultureInfoData\n) => ({\n properties: {\n refundableShipping: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.refundable-shipping\" />\n ),\n headerRight: true,\n cellRenderer: function RefundableShippingHeader({\n cellData,\n }: {\n cellData: number\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n shippingToRefund: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.shipping-to-refund\" />\n ),\n headerRight: true,\n cellRenderer: function ShippingToRefundHeader({\n cellData,\n rowData,\n }: {\n cellData: number\n rowData: { refundableShipping: number }\n }) {\n const handleChange = (event: ChangeEvent<HTMLInputElement>) => {\n const { refundableShipping } = rowData\n const { value } = event.target\n const shippingToRefundInput = Number(value)\n\n const shippingToRefundParsed = Number.isNaN(shippingToRefundInput)\n ? 0\n : shippingToRefundInput * 100\n\n const shippingToRefundChecked =\n shippingToRefundParsed > refundableShipping\n ? refundableShipping\n : shippingToRefundParsed\n\n handleShippingChanges(shippingToRefundChecked)\n }\n\n return (\n <AlignItemRight>\n <InputCurrency\n value={cellData / 100}\n currencyCode={cultureInfoData.currencyCode}\n locale={cultureInfoData.locale}\n onChange={handleChange}\n />\n </AlignItemRight>\n )\n },\n },\n totalRefundItems: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.total-refund-items\" />\n ),\n headerRight: true,\n cellRenderer: function TotalRefundItemsHeader({\n cellData,\n }: {\n cellData: number\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n totalRefund: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.total-refund\" />\n ),\n headerRight: true,\n cellRenderer: function TotalRefundHeader({\n cellData,\n }: {\n cellData: number\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n },\n})\n\n```"
}
] |
code_return-app_b596e185
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/admin/ReturnDetails/components/VerifyItems/verifyItemsModalSchema.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { FormattedMessage, FormattedNumber } from 'react-intl'\nimport type { ReturnRequestItem, CultureInfoData } from 'vtex.return-app'\n\nimport type { RefundItemMap } from './VerifyItemsPage'\nimport { AlignItemRight } from '../AlignItemRight'\nimport { ProductActionStatus } from './ProductActionStatus'\n\nexport const verifyItemsModalSchema = (\n refundItemMap: RefundItemMap,\n cultureInfoData: CultureInfoData\n) => ({\n properties: {\n name: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.product\" />\n ),\n minWidth: 320,\n },\n sellingPrice: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.price\" />\n ),\n width: 90,\n headerRight: true,\n cellRenderer: function SellingPriceHeader({\n cellData,\n }: {\n rowData: ReturnRequestItem\n cellData: ReturnRequestItem['sellingPrice']\n }) {\n return (\n <AlignItemRight>\n <FormattedNumber\n value={cellData / 100}\n style=\"currency\"\n currency={cultureInfoData.currencyCode}\n />\n </AlignItemRight>\n )\n },\n },\n quantity: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.quantity\" />\n ),\n width: 80,\n cellRenderer: function QuantityHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n // cellData: ReturnRequestItem['quantity']\n }) {\n const { orderItemIndex } = rowData\n const selectedQuantity =\n refundItemMap.get(orderItemIndex)?.quantity ?? 0\n\n return (\n <span className=\"w-100 flex justify-center\">{selectedQuantity}</span>\n )\n },\n },\n action: {\n title: (\n <FormattedMessage id=\"admin/return-app.return-request-details.verify-items.table.header.action\" />\n ),\n cellRenderer: function VerifyActionHeader({\n rowData,\n }: {\n rowData: ReturnRequestItem\n }) {\n const { quantity, orderItemIndex } = rowData\n\n const selectedQuantity =\n refundItemMap.get(orderItemIndex)?.quantity ?? 0\n\n return (\n <ProductActionStatus\n quantity={quantity}\n selectedQuantity={selectedQuantity}\n />\n )\n },\n },\n },\n})\n\n```"
}
] |
code_return-app_eed1fbec
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/common/constants/returnsRequest.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport type { IntlFormatters } from 'react-intl'\n\nimport { defaultReturnReasonsMessages } from '../../store/utils/defaultReturnReasonsMessages'\n\nexport function getReasonOptions(\n formatMessage: IntlFormatters['formatMessage']\n) {\n const reasonAccidentalOrder = formatMessage(\n defaultReturnReasonsMessages.reasonAccidentalOrder\n )\n\n const reasonBetterPrice = formatMessage(\n defaultReturnReasonsMessages.reasonBetterPrice\n )\n\n const reasonPerformance = formatMessage(\n defaultReturnReasonsMessages.reasonPerformance\n )\n\n const reasonItemDamaged = formatMessage(\n defaultReturnReasonsMessages.reasonItemDamaged\n )\n\n const reasonIncompatible = formatMessage(\n defaultReturnReasonsMessages.reasonIncompatible\n )\n\n const reasonMissedDelivery = formatMessage(\n defaultReturnReasonsMessages.reasonMissedDelivery\n )\n\n const reasonMissingParts = formatMessage(\n defaultReturnReasonsMessages.reasonMissingParts\n )\n\n const reasonBoxDamaged = formatMessage(\n defaultReturnReasonsMessages.reasonBoxDamaged\n )\n\n const reasonDifferentProduct = formatMessage(\n defaultReturnReasonsMessages.reasonDifferentProduct\n )\n\n const reasonDefective = formatMessage(\n defaultReturnReasonsMessages.reasonDefective\n )\n\n const reasonArrivedInAddition = formatMessage(\n defaultReturnReasonsMessages.reasonArrivedInAddition\n )\n\n const reasonNoLongerNeeded = formatMessage(\n defaultReturnReasonsMessages.reasonNoLongerNeeded\n )\n\n const reasonUnauthorizedPurchase = formatMessage(\n defaultReturnReasonsMessages.reasonUnauthorizedPurchase\n )\n\n const reasonDifferentFromWebsite = formatMessage(\n defaultReturnReasonsMessages.reasonDifferentFromWebsite\n )\n\n return [\n {\n value: reasonAccidentalOrder,\n label: reasonAccidentalOrder,\n },\n {\n value: reasonBetterPrice,\n label: reasonBetterPrice,\n },\n {\n value: reasonPerformance,\n label: reasonPerformance,\n },\n {\n value: reasonIncompatible,\n label: reasonIncompatible,\n },\n {\n value: reasonItemDamaged,\n label: reasonItemDamaged,\n },\n {\n value: reasonMissedDelivery,\n label: reasonMissedDelivery,\n },\n {\n value: reasonMissingParts,\n label: reasonMissingParts,\n },\n {\n value: reasonBoxDamaged,\n label: reasonBoxDamaged,\n },\n {\n value: reasonDifferentProduct,\n label: reasonDifferentProduct,\n },\n {\n value: reasonDefective,\n label: reasonDefective,\n },\n {\n value: reasonArrivedInAddition,\n label: reasonArrivedInAddition,\n },\n {\n value: reasonNoLongerNeeded,\n label: reasonNoLongerNeeded,\n },\n {\n value: reasonUnauthorizedPurchase,\n label: reasonUnauthorizedPurchase,\n },\n {\n value: reasonDifferentFromWebsite,\n label: reasonDifferentFromWebsite,\n },\n ]\n}\n\n```"
}
] |
code_return-app_8109011f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/common/provider/ReturnDetailsProvider.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FC } from 'react'\nimport React, { createContext } from 'react'\nimport type { ApolloError } from 'apollo-client'\nimport { useQuery } from 'react-apollo'\nimport type {\n ReturnRequestResponse,\n QueryReturnRequestArgs,\n} from 'vtex.return-app'\n\nimport GET_REQUEST_DETAILS from '../graphql/getRequestDetails.gql'\n\ninterface ReturnDetailsSetupInterface {\n data?: { returnRequestDetails: ReturnRequestResponse }\n loading: boolean\n error?: ApolloError\n _handleUpdateQuery: (returnRequestDetails: ReturnRequestResponse) => void\n}\n\nexport interface CustomRouteProps {\n requestId: string\n}\n\nexport const ReturnDetailsContext = createContext<ReturnDetailsSetupInterface>(\n {} as ReturnDetailsSetupInterface\n)\n\nexport const ReturnDetailsProvider: FC<CustomRouteProps> = ({\n requestId,\n children,\n}) => {\n const { data, loading, error, updateQuery } = useQuery<\n { returnRequestDetails: ReturnRequestResponse },\n QueryReturnRequestArgs\n >(GET_REQUEST_DETAILS, {\n variables: {\n requestId,\n },\n skip: !requestId,\n })\n\n const _handleUpdateQuery = (returnRequestDetails: ReturnRequestResponse) => {\n updateQuery(() => ({\n returnRequestDetails,\n }))\n }\n\n return (\n <ReturnDetailsContext.Provider\n value={{\n data,\n loading,\n error,\n _handleUpdateQuery,\n }}\n >\n {children}\n </ReturnDetailsContext.Provider>\n )\n}\n\n```"
}
] |
code_return-app_33c7a5d9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/common/utils/defaultReturnConditionsMessages.ts from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { defineMessages } from 'react-intl'\n\nexport const defaultReturnConditionsMessages = defineMessages({\n newWithBox: {\n id: 'store/return-app.return-order-details.conditions.new-with-box',\n },\n newWithoutBox: {\n id: 'store/return-app.return-order-details.conditions.new-without-box',\n },\n usedWithBox: {\n id: 'store/return-app.return-order-details.conditions.used-with-box',\n },\n usedWithoutBox: {\n id: 'store/return-app.return-order-details.conditions.used-without-box',\n },\n selectCondition: {\n id: 'store/return-app.return-order-details.dropdown-conditions.placeholder.select-condition',\n },\n})\n\n```"
}
] |
code_return-app_174e0bf5
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of return-app/react/common/components/RenderStatus.tsx from the return-app VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport type { Status } from 'vtex.return-app'\nimport { FormattedMessage } from 'react-intl'\nimport {\n IconClock,\n IconFailure,\n IconVisibilityOn,\n IconCheck,\n IconSuccess,\n IconExternalLinkMini,\n} from 'vtex.styleguide'\n\nconst status = {\n new: 'new',\n processing: 'processing',\n picked: 'pickedUpFromClient',\n pendingVerification: 'pendingVerification',\n verified: 'packageVerified',\n denied: 'denied',\n refunded: 'amountRefunded',\n cancelled: 'cancelled',\n} as const\n\n/**\n * Renders the status with an icon and color\n */\nexport function renderStatus(requestStatus: Status) {\n switch (requestStatus) {\n case status.verified:\n return (\n <div className=\"green flex items-center\">\n <span className=\"mr2 flex\">\n <IconSuccess size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.package-verified\" />\n </div>\n )\n\n case status.denied:\n return (\n <div className=\"red flex items-center\">\n <span className=\"mr2 flex\">\n <IconFailure size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.denied\" />\n </div>\n )\n\n case status.cancelled:\n return (\n <div className=\"red flex items-center\">\n <span className=\"mr2 flex\">\n <IconFailure size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.cancelled\" />\n </div>\n )\n\n case status.pendingVerification:\n return (\n <div className=\"yellow flex items-center\">\n <span className=\"mr2 flex\">\n <IconClock size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.pending-verification\" />\n </div>\n )\n\n case status.processing:\n return (\n <div className=\"yellow flex items-center\">\n <span className=\"mr2 flex\">\n <IconClock size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.processing\" />\n </div>\n )\n\n case status.refunded:\n return (\n <div className=\"green flex items-center\">\n <span className=\"mr2 flex\">\n <IconCheck size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.refunded\" />\n </div>\n )\n\n case status.picked:\n return (\n <div className=\"flex items-center\">\n <span className=\"mr2 flex\">\n <IconExternalLinkMini size={11} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.pickedup-from-client\" />\n </div>\n )\n\n default:\n return (\n <div className=\"green flex items-center\">\n <span className=\"mr2 flex\">\n <IconVisibilityOn size={14} />\n </span>\n <FormattedMessage id=\"store/return-app.return-request-list.table.status.new\" />\n </div>\n )\n }\n}\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.