id
stringlengths 12
53
| messages
listlengths 3
3
|
|---|---|
code_wish-list-v2_1021f41a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/unitPrice.css from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.unitPriceContainer {\n width: 100%;\n min-width: 100%;\n display: flex;\n align-items: center;\n}\n\n.skuNameContainer {\n text-wrap: wrap;\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.descriptionContainer {}\n\n.wishlistProductTexts,\n.wishlistProductTexts a {\n font-weight: 400;\n color: #000000;\n text-decoration: none;\n}\n\n```"
}
] |
code_wish-list-v2_5d6524dd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/WishlistShare.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useQuery } from 'react-apollo'\nimport { useRuntime } from 'vtex.render-runtime'\nimport { Spinner } from 'vtex.styleguide'\n\nimport GET_WISHLIST_BY_ID from '../graphql/queries/getWishlistById.gql'\nimport { WishlistMD } from '../interfaces'\nimport AppSettings from '../queries/AppSettings.graphql'\nimport styles from '../styles.css'\nimport TableShare from './TableShare'\n\nexport default function WishlistShare() {\n const { query } = useRuntime()\n const { id } = query\n\n const { data, loading } = useQuery(GET_WISHLIST_BY_ID, {\n variables: { id },\n ssr: false,\n fetchPolicy: 'network-only',\n })\n\n const { data: wishlistColumns } = useQuery(AppSettings, {\n variables: {\n // eslint-disable-next-line no-undef\n version: process.env.VTEX_APP_VERSION,\n },\n ssr: false,\n })\n\n if (loading) {\n return (\n <div\n style={{\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n height: '60vh',\n }}\n >\n <Spinner color=\"black\" size={20} />\n </div>\n )\n }\n\n const wishlistMD: WishlistMD = data?.getWishlist || {\n products: [],\n email: '',\n }\n\n const { defaultTitleText } = JSON.parse(\n wishlistColumns.publicSettingsForApp.message\n )\n\n return (\n <div className={`${styles.wishlistShare}`}>\n <h2 className=\"flex justify-center mt6\">\n {`${wishlistMD.email}'s ${defaultTitleText ?? 'Favorites List'}`}\n </h2>\n {wishlistMD.products && (\n <TableShare\n wishlistMD={wishlistMD}\n columns={wishlistColumns}\n queryId={id}\n />\n )}\n </div>\n )\n}\n\n```"
}
] |
code_wish-list-v2_81a8f070
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/ProductPriceTotal.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React from 'react'\nimport { Spinner } from 'vtex.styleguide'\n\nimport useQueryGetProductPrice from '../hooks/actions/useQueryGetProductPrice'\nimport styles from './productPriceTotal.css'\n\nconst ProductPriceTotal = ({ productQuantity = 0, currency = '$', itemId }) => {\n const { price, error: productError, loading } = useQueryGetProductPrice(\n 'sku',\n itemId,\n productQuantity\n )\n\n const handlePrice = () =>\n price ? `${currency} ${parseFloat(price).toFixed(2)}` : null\n\n const Wrapper = ({ children }) => {\n return <div className={`${styles.productPriceContainer}`}>{children}</div>\n }\n\n return productError ? (\n <Wrapper>\n <span>Error</span>\n </Wrapper>\n ) : loading ? (\n <Wrapper>\n <Spinner size={20} />\n </Wrapper>\n ) : (\n <Wrapper>{handlePrice()}</Wrapper>\n )\n}\n\nexport default ProductPriceTotal\n\n```"
}
] |
code_wish-list-v2_de8e1122
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/query.getMdHaveWishlist.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getMdHaveWishlist ($acronym: String, $fields: [String], $pageSize: Int) {\n documents(acronym: $acronym, fields: $fields, pageSize: $pageSize)\n @context(provider: \"vtex.store-graphql\") {\n id\n fields {\n key\n value\n }\n }\n}\n```"
}
] |
code_wish-list-v2_e8f1e2d7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/test.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery TEST($ac: String, $fields: [String], $id: String, $account: String) {\n document(acronym: $ac, fields: $fields, id: $id, account: $account)\n @context(provider: \"vtex.store-graphql\") {\n fields {\n value\n key\n }\n }\n}\n\n```"
}
] |
code_wish-list-v2_5be5bbe2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useAddToCart.ts from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { useContext } from 'react'\nimport { ToastContext } from 'vtex.styleguide'\nimport { useOrderItems } from 'vtex.order-items/OrderItems'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\n\nimport { extractProductData } from '../components/helpers'\nimport handleDataLayerEvent from '../utils/handleDataLayerEvent'\nimport { WishlistMD } from '../interfaces'\n\nconst useAddToCart = () => {\n const { addItems } = useOrderItems()\n const { showToast } = useContext<any>(ToastContext)\n const { orderForm } = useOrderForm()\n\n // hook used to add several products from the wishlist table to the cart\n const addProductsToCart = (\n props: { name: string; itemId: number; quantity?: number },\n wishlist: WishlistMD\n ) => {\n const productsByOrders = orderForm.items\n const findProductQuantity = productsByOrders?.find(\n (item: { id: string }) => Number(item.id) === props.itemId\n )\n\n const quantityAlreadyAdd = findProductQuantity?.quantity\n ? findProductQuantity?.quantity\n : 0\n\n const dataExtract = extractProductData({\n items: wishlist?.products?.map((product) => {\n return {\n ...product,\n quantity: Number(product.quantityProduct),\n name: product.nameProduct,\n }\n }),\n })\n\n const productInfo = dataExtract.find(\n (item: { id: string }) => props.itemId === Number(item.id)\n )\n\n const quantityToAdd = props.quantity ?? Number(productInfo.quantity)\n const items = [\n {\n id: productInfo.id,\n seller: 1,\n quantity: quantityToAdd + Number(quantityAlreadyAdd ?? 0),\n name: productInfo.name,\n },\n ]\n\n if (items.length === 0) return\n\n addItems(items)\n .then(() => {\n handleDataLayerEvent('addToCart', [productInfo])\n showToast('Item added to the cart')\n })\n .catch((error) => {\n console.error(error)\n })\n }\n\n return addProductsToCart\n}\n\nexport default useAddToCart\n\n```"
}
] |
code_wish-list-v2_08a01313
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useBundleMinQuantity.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nconst useBundleMinQuantity = (productContextValue: {\n properties: any[]\n}): number => {\n const unitMultiplier = productContextValue?.properties?.find(\n (property) => property.name === 'UnitMultiplier'\n )?.values?.[0]\n\n return Number(unitMultiplier) || 1\n}\n\nexport default useBundleMinQuantity\n\n```"
}
] |
code_wish-list-v2_ffeed7a2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useAddSharedListPage.ts from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport React, { useEffect, useState } from 'react'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport { useRuntime } from 'vtex.render-runtime'\n\nimport useCreateListAccount from './useCreateListAccount'\nimport { useUserEmail } from './useUserEmail'\nimport useStoreGlobal from '../globalStore/globalStore'\nimport useMutationCreateWishlist from './actions/useMutationCreateWishlist'\nimport useQueryWishlists from './actions/useQueryWishlists'\nimport { WishlistProduct } from '../interfaces'\n\ninterface UseAddSharedListPageProps {\n queryId: string\n products: WishlistProduct[]\n updatedProducts: any\n}\n\nexport default function useAddSharedListPage({\n queryId,\n products,\n}: UseAddSharedListPageProps) {\n // ORDER FORM\n const { orderForm } = useOrderForm()\n\n // RUNTIME\n const { navigate } = useRuntime()\n\n // PATH VALIDATION\n const pathname = encodeURIComponent(\n `${window.location.pathname}?id=${queryId}`\n )\n\n const loginUrl = `/login?returnUrl=${pathname}`\n\n // STATES\n const [isLoading, setIsLoading] = useState(true)\n const [isListNameInputVisible, setIsListNameInputVisible] = useState<boolean>(\n false\n )\n\n isLoading\n\n const { updatedProducts } = useStoreGlobal.getState()\n\n const { createWishlist } = useMutationCreateWishlist(() => {})\n const { data: wishlistsByEmail, refetch } = useQueryWishlists()\n\n // CREATE WISH LIST\n const {\n fieldValidationTable,\n nameListAccountTable,\n setFieldValidationTable,\n setNameListAccountTable,\n setIsModalAccountTable,\n handleNameListTable,\n } = useCreateListAccount()\n\n const setWishlists = useStoreGlobal((state) => state.setWishlists)\n\n // USER EMAIL\n const userEmail = useUserEmail()\n const fetchData = async () => {\n setIsLoading(true)\n refetch()\n const data = wishlistsByEmail\n\n setWishlists(data || [])\n setIsLoading(false)\n }\n\n // EFFECTS\n useEffect(() => {\n fetchData()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [userEmail])\n\n // DATA\n const isUserLoggedOut = orderForm.loggedIn === false\n\n // METHODS\n const navigateToLoginPage = () => {\n navigate({\n to: loginUrl,\n })\n }\n\n const handleInputListNameVisualization = () => {\n setIsListNameInputVisible((state) => !state)\n }\n\n const createNewList = async (event: React.FormEvent) => {\n event.preventDefault()\n\n if (nameListAccountTable.trim() === '') {\n setFieldValidationTable('The field cannot be empty')\n } else {\n const listProducts: any[] = []\n\n if (\n Object.keys(updatedProducts).length > 0 &&\n updatedProducts.filter((item) => item.ID).length\n ) {\n Object.values(updatedProducts).forEach((prod: any) => {\n const newProduct: any = {\n ID: prod.ID,\n Image: prod.Image,\n bundle: prod.bundle,\n unitValue: prod.unitValue,\n linkProduct: prod.linkProduct,\n nameProduct: prod.nameProduct,\n quantityProduct: prod.quantityProduct,\n skuCodeReference: prod.skuCodeReference,\n department: prod.department,\n }\n\n listProducts.push(newProduct)\n })\n } else {\n products.forEach((prod: any) => {\n const newProduct = {\n ID: prod.id || prod.ID,\n Image: prod.image || prod.Image,\n bundle: prod.bundle,\n unitValue: prod.unitValue,\n linkProduct: prod.linkProduct,\n nameProduct: prod.name || prod.nameProduct,\n quantityProduct: prod.qty || prod.quantityProduct,\n skuCodeReference: prod.skuReferenceCode || prod.skuCodeReference,\n department: prod.department,\n }\n\n listProducts.push(newProduct)\n })\n }\n\n await createWishlist({\n variables: {\n wishlist: {\n wishlistType: nameListAccountTable,\n isPublic: false,\n products: listProducts,\n },\n },\n })\n setNameListAccountTable('')\n setFieldValidationTable('')\n setNameListAccountTable(false)\n setIsModalAccountTable(false)\n setIsListNameInputVisible(false)\n navigate({ to: '/account#/my-wishlists' })\n }\n }\n\n // RETURN\n return {\n isUserLoggedOut,\n navigateToLoginPage,\n isListNameInputVisible,\n handleInputListNameVisualization,\n fieldValidationTable,\n handleNameListTable,\n createNewList,\n }\n}\n\n```"
}
] |
code_wish-list-v2_f0954e3e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useGetWishlists.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useEffect, useState, useContext } from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { ToastContext } from 'vtex.styleguide'\n\nimport useBundleMinQuantity from './useBundleMinQuantity'\nimport useQueryWishlists from './actions/useQueryWishlists'\nimport useMutationCreateWishlist from './actions/useMutationCreateWishlist'\n\nconst useGetWishlist = () => {\n const [listWishlist, setListWishlist] = useState<any>([])\n const [productBundle, setProductBundle] = useState<any>(null)\n const [nameListWishlist, setNameListWishlist] = useState('')\n const [errorName, setErrorName] = useState('')\n const [isLoading, setisLoading] = useState(false)\n const [isButton, setIsButton] = useState(true)\n const [isMessage, setIsMessage] = useState(false)\n const [isShowForm2, setIsShowForm2] = useState(false)\n const [clickCreate, setClickCreate] = useState(false)\n const [isShowSelect, setIsShowSelect] = useState(false)\n const [isShowForm, setIsShowForm] = useState(false)\n\n const { product, selectedQuantity, selectedItem } = useProduct()\n const { showToast } = useContext<any>(ToastContext)\n const bundle = useBundleMinQuantity(product)\n\n const { data, refetch } = useQueryWishlists()\n const { createWishlist } = useMutationCreateWishlist(async (d) => {\n const datarefect = await refetch()\n\n const find = datarefect?.data?.getWishlistsByEmail?.find(\n (item: { wishlistType: string }) => item.wishlistType === nameListWishlist\n )\n\n if (!find) {\n const currentWhislist = datarefect?.data?.getWishlistsByEmail\n\n currentWhislist.push({\n id: d.createWishlist.DocumentId,\n wishlistType: nameListWishlist,\n })\n setListWishlist(currentWhislist)\n }\n\n setNameListWishlist('')\n setisLoading(false)\n })\n\n useEffect(() => {\n setProductBundle(bundle)\n }, [bundle])\n\n const nameProduct = product?.productName\n const linkProduct = product?.link\n const idProduct = Number(selectedItem?.itemId)\n const urlImageProduct = product?.items?.find((item: any) => item)?.images?.[0]\n ?.imageUrl\n\n const quantityProduct = selectedQuantity\n const price = Number(product?.priceRange?.sellingPrice?.highPrice)\n const skuCodeReference = product?.items?.[0]?.referenceId?.[0]?.Value\n const departmentArray = product?.categoryTree\n const department = departmentArray?.[0]?.name\n\n useEffect(() => {\n if (data?.getWishlistsByEmail) {\n setListWishlist(data.getWishlistsByEmail)\n }\n }, [data])\n\n const postCreateList = async () => {\n const productObj: any = {\n ID: idProduct,\n Image: urlImageProduct,\n unitValue: price,\n nameProduct,\n linkProduct,\n quantityProduct,\n skuCodeReference,\n department,\n }\n\n setisLoading(true)\n if (productBundle !== 1) {\n productObj.quantityProduct = selectedQuantity * productBundle\n productObj.bundle = productBundle\n }\n\n try {\n await createWishlist({\n variables: {\n wishlist: {\n wishlistType: nameListWishlist,\n products: [productObj],\n isPublic: false,\n },\n },\n refetchQueries: ['getWishlists'],\n })\n\n setisLoading(false)\n showToast('You created a new Favourite List and your product was added')\n } catch (error) {\n setisLoading(false)\n showToast(error)\n }\n }\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const valueNameList = e.target.value\n\n setNameListWishlist(valueNameList)\n }\n\n const addList = () => {\n setIsShowForm2(true)\n setClickCreate(true)\n }\n\n const sendData1 = (e: React.FormEvent) => {\n e.preventDefault()\n\n if (nameListWishlist.trim() === '') {\n setErrorName('The field cannot be empty')\n } else {\n postCreateList()\n\n setIsShowForm2(false)\n setClickCreate(false)\n\n setErrorName('')\n }\n }\n\n const createLengthZero = () => {\n setIsShowForm(true)\n setIsButton(false)\n }\n\n const sendData2 = (e: React.FormEvent) => {\n e.preventDefault()\n\n if (nameListWishlist.trim() === '') {\n setErrorName('The field cannot be empty')\n } else {\n postCreateList()\n\n setIsShowForm(false)\n setIsButton(false)\n setIsMessage(true)\n\n setErrorName('')\n }\n }\n\n useEffect(() => {\n if (isMessage === true) {\n setTimeout(() => {\n setIsMessage(false)\n }, 10000)\n }\n }, [isMessage])\n\n return {\n listWishlist,\n isButton,\n isMessage,\n isShowForm,\n isShowForm2,\n clickCreate,\n isShowSelect,\n nameListWishlist,\n errorName,\n isLoading,\n setIsShowSelect,\n setIsShowForm,\n handleChange,\n addList,\n sendData1,\n createLengthZero,\n sendData2,\n }\n}\n\nexport default useGetWishlist\n\n```"
}
] |
code_wish-list-v2_f5a2c47d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useBulkAction.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useContext } from 'react'\nimport { ToastContext } from 'vtex.styleguide'\nimport { useOrderItems } from 'vtex.order-items/OrderItems'\n\nimport handleDataLayerEvent from '../utils/handleDataLayerEvent'\nimport {\n extractProductData,\n formatProductForWishlist,\n} from '../components/helpers'\n\n// wishlist button in my-account, used to add the product from the table row to the cart\nconst useBulkAction = ({\n wishlist,\n selectedWishlist,\n setUpdatedSelectedRows,\n updateWishlist,\n}) => {\n const { addItems } = useOrderItems()\n const { showToast } = useContext(ToastContext)\n\n const handleBulkAction = async (selectedRows, actionId) => {\n if (actionId === 'addToCart') {\n const dataExtract = extractProductData({ items: wishlist.products })\n const itemsToAdd = selectedRows.map((row) => {\n const productDetails = dataExtract.find(\n (item) => row.name === item.name\n )\n\n return {\n id: Number(productDetails.id),\n seller: 1,\n quantity: productDetails.quantity,\n name: productDetails.name,\n }\n })\n\n if (itemsToAdd.length > 0) {\n addItems(itemsToAdd)\n .then(() => {\n handleDataLayerEvent('addToCart', selectedRows)\n showToast('Items added to the cart')\n })\n .catch((error) => {\n console.error(error)\n })\n }\n }\n\n if (actionId !== 'deleteRowsWishlist') {\n return\n }\n\n const dataExtract = extractProductData({ items: wishlist.products })\n const itemsToDelete = selectedRows.map((row) => {\n const selectedProduct = dataExtract.find((item) => {\n return row.name === item.name\n })\n\n return selectedProduct.id\n })\n\n let updatedList = dataExtract.filter(\n (item) => !itemsToDelete.includes(item.id)\n )\n\n updatedList = formatProductForWishlist(updatedList)\n setUpdatedSelectedRows((prevSelectedRows) =>\n prevSelectedRows.filter((row) => !selectedRows.includes(row))\n )\n updateWishlist({\n variables: {\n wishlist: {\n id: selectedWishlist,\n products: updatedList,\n },\n },\n })\n }\n\n return handleBulkAction\n}\n\nexport default useBulkAction\n\n```"
}
] |
code_wish-list-v2_bd24b499
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useGetIntelligentSearch.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport axios from 'axios'\nimport { useState } from 'react'\n\nconst useGetIntelligentSearch = () => {\n const [searchProduct, setSearchProduct] = useState([])\n const [valueSearchSku, setValueSearchSku] = useState('')\n const [isShowProductSearch, setIsShowProductSearch] = useState(false)\n\n const changeValueSku = (event) => {\n const valueNameSku = event.target.value\n\n setValueSearchSku(valueNameSku)\n }\n\n const getSearchProduct = async () => {\n try {\n const axiosConfig = {\n method: 'get',\n url: `/api/io/_v/api/intelligent-search/product_search/?query=${valueSearchSku}`,\n headers: {\n Accept: 'application/json',\n },\n }\n\n const response = await axios(axiosConfig)\n const arrayDate = response.data.products\n\n setSearchProduct(arrayDate)\n } catch (error) {\n console.error(error)\n }\n\n setValueSearchSku('')\n setIsShowProductSearch(true)\n }\n\n return {\n searchProduct,\n valueSearchSku,\n isShowProductSearch,\n changeValueSku,\n getSearchProduct,\n }\n}\n\nexport default useGetIntelligentSearch\n\n```"
}
] |
code_wish-list-v2_2216bfa6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useUserEmail.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\n\nexport const useUserEmail = () => {\n const { orderForm } = useOrderForm()\n const { email } = orderForm.clientProfileData || { email: '' }\n\n return email\n}\n\n```"
}
] |
code_wish-list-v2_f4ac21ad
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useSelectWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport axios from 'axios'\nimport { useState, useEffect, useRef, useContext } from 'react'\nimport useProduct from 'vtex.product-context/useProduct'\nimport { ToastContext } from 'vtex.styleguide'\n\nimport useWishList from './useWishlists'\nimport useGetWishlist from './useGetWishlists'\nimport useBundleMinQuantity from './useBundleMinQuantity'\nimport useMutationUpdateWishlist from './actions/useMutationUpdateWishlist'\n\nconst useSelectWishlist = () => {\n const {\n emailInfo,\n nameProduct,\n linkProduct,\n urlImageProduct,\n quantityProduct,\n price,\n idProduct,\n skuCodeReference,\n department,\n } = useWishList()\n\n const { listWishlist } = useGetWishlist()\n\n const [textSelect, setTextSelect] = useState('')\n const [valueSelect, setValueSelect] = useState('')\n const [errorSelect, setErrorSelect] = useState('')\n const [selectSize, setSelectSize] = useState(1)\n const selectRef = useRef<HTMLSelectElement | null>(null)\n\n const [closeSelect, setCloseSelect] = useState(true)\n const [productBundle, setProductBundle] = useState<number>(1)\n\n const { product, selectedQuantity } = useProduct()\n const { showToast } = useContext<any>(ToastContext)\n const bundle = useBundleMinQuantity(product)\n const { updateWishlist } = useMutationUpdateWishlist(() => {})\n\n useEffect(() => {\n setProductBundle(bundle)\n }, [bundle])\n\n const captureValue = (e: React.ChangeEvent<HTMLSelectElement>) => {\n const valueText = e.target.value\n const selectedOptionText = e.target.options[e.target.selectedIndex].text\n\n setValueSelect(valueText)\n setTextSelect(selectedOptionText)\n\n if (selectRef.current instanceof HTMLSelectElement) {\n selectRef.current.blur()\n }\n }\n\n const handleSelectFocus = () => {\n setSelectSize(3)\n }\n\n const handleSelectBlur = () => {\n setSelectSize(1)\n }\n\n const addToList = () => {\n if (textSelect.trim().length === 0) {\n setErrorSelect('Select a list to save your product')\n\n return\n }\n\n const existingWishlist = listWishlist.find(\n (typeWish: { wishlistType: string; id: string }) =>\n typeWish.wishlistType === textSelect && typeWish.id === valueSelect\n )\n\n const newProduct: any = {\n ID: idProduct,\n Image: urlImageProduct,\n unitValue: price,\n linkProduct,\n nameProduct,\n quantityProduct,\n skuCodeReference,\n department,\n }\n\n if (productBundle !== 1) {\n newProduct.quantityProduct = selectedQuantity * productBundle\n newProduct.bundle = productBundle\n }\n\n if (existingWishlist) {\n const productExists = existingWishlist.products.some(\n (item: { ID: string | number }) => item.ID === newProduct.ID\n )\n\n if (!productExists) {\n existingWishlist.products.push(newProduct)\n\n delete existingWishlist.email\n updateWishlist({\n variables: {\n wishlist: {\n ...existingWishlist,\n },\n },\n refetchQueries: ['getWishlists'],\n })\n .then(() => {\n showToast('Successfully added to the Favouites List')\n })\n .catch((error) => {\n console.error('PUT request failed:', error)\n })\n } else {\n showToast('You have already added this product to the list')\n }\n }\n\n setCloseSelect(false)\n setErrorSelect('')\n }\n\n const addProductToFavouriteList = (selectedProduct, selectedWishList) => {\n const existingWishlist = listWishlist.find(\n (typeWish: { email: string; id: string | number }) =>\n typeWish.email === emailInfo && typeWish.id === selectedWishList\n )\n\n if (selectedProduct.bundle > 1)\n selectedProduct.quantityProduct *= selectedProduct.bundle\n if (existingWishlist) {\n const productExists = existingWishlist.products.some(\n (item: { ID: any }) => item.ID === selectedProduct.ID\n )\n\n if (!productExists) {\n existingWishlist.products.push(selectedProduct)\n\n const urlPut =\n '/api/dataentities/whitebird_my_wishlists_wishlist/documents?_schema=0.0.2-mywishlists'\n\n axios\n .put(urlPut, existingWishlist)\n .then(() => {\n showToast('Successfully added to the Favorites List')\n })\n .catch((error) => {\n console.error('PUT request failed:', error)\n })\n } else {\n showToast('You have already added this product to the list')\n }\n }\n }\n\n return {\n errorSelect,\n selectSize,\n selectRef,\n valueSelect,\n textSelect,\n closeSelect,\n captureValue,\n handleSelectFocus,\n handleSelectBlur,\n addToList,\n setCloseSelect,\n addProductToFavouriteList,\n }\n}\n\nexport default useSelectWishlist\n\n```"
}
] |
code_wish-list-v2_38ae8f1e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useWishlists.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useRuntime } from 'vtex.render-runtime'\nimport { useOrderForm } from 'vtex.order-manager/OrderForm'\nimport useProduct from 'vtex.product-context/useProduct'\n\nconst useWishList = () => {\n const { navigate } = useRuntime()\n const { orderForm } = useOrderForm()\n const { product, selectedQuantity, selectedItem } = useProduct()\n\n const emailInfo = orderForm?.clientProfileData?.email\n const isLoggedIn =\n orderForm?.loggedIn ||\n (orderForm?.userType === 'CALL_CENTER_OPERATOR' && emailInfo != null)\n\n const nameProduct = product?.productName\n const linkProduct = product?.link\n const idProduct = Number(selectedItem?.itemId)\n const urlImageProduct = product?.items?.[0]?.images?.[0]?.imageUrl\n const quantityProduct = selectedQuantity\n const price = Number(product?.priceRange?.sellingPrice?.highPrice)\n const skuCodeReference = product?.items?.[0]?.referenceId?.[0]?.Value\n const departmentArray = product?.categoryTree\n const department = departmentArray?.[0]?.name\n\n return {\n navigate,\n emailInfo,\n isLoggedIn,\n nameProduct,\n linkProduct,\n idProduct,\n urlImageProduct,\n quantityProduct,\n price,\n skuCodeReference,\n department,\n }\n}\n\nexport default useWishList\n\n```"
}
] |
code_wish-list-v2_332be7db
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/useCreateListAccount.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport { useState } from 'react'\n\nconst useCreateListAccount = () => {\n const [isModalAccountTable, setIsModalAccountTable] = useState(false)\n const [nameListAccountTable, setNameListAccountTable] = useState('')\n const [fieldValidationTable, setFieldValidationTable] = useState('')\n\n const [isModalAccount, setIsModalAccount] = useState(false)\n const [nameListAccount, setNameListAccount] = useState('')\n const [fieldValidation, setFieldValidation] = useState('')\n\n const buttonModalTable = () => {\n setIsModalAccountTable(true)\n }\n\n const buttonCloseModalTable = () => {\n setIsModalAccountTable(false)\n }\n\n const handleNameListTable = (event) => {\n const valueNameList = event.target.value\n\n setNameListAccountTable(valueNameList)\n }\n\n const buttonModal = () => {\n setIsModalAccount(true)\n }\n\n const buttonCloseModal = () => {\n setIsModalAccount(false)\n }\n\n const handleNameList = (event) => {\n const valueNameList = event.target.value\n\n setNameListAccount(valueNameList)\n }\n\n return {\n nameListAccountTable,\n isModalAccountTable,\n fieldValidationTable,\n isModalAccount,\n nameListAccount,\n fieldValidation,\n setNameListAccount,\n setFieldValidation,\n setIsModalAccount,\n buttonModal,\n buttonCloseModal,\n handleNameList,\n setFieldValidationTable,\n setNameListAccountTable,\n setIsModalAccountTable,\n buttonModalTable,\n buttonCloseModalTable,\n handleNameListTable,\n }\n}\n\nexport default useCreateListAccount\n\n```"
}
] |
code_wish-list-v2_66f20e8d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/globalStore/globalStore.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nimport create from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\nconst logMiddleware = (config) => (set, get, api) =>\n config(\n (args) => {\n set(args)\n },\n get,\n api\n )\n\nconst useStoreGlobal = create(\n devtools(\n logMiddleware((set) => ({\n selectedWishlist: null,\n isUpdatingQty: false,\n wishlists: [],\n wishlist: [],\n setSelectedWishlist: (wishlist) => {\n set({ selectedWishlist: wishlist })\n },\n setIsUpdatingQty: (updating) => set({ isUpdatingQty: updating }),\n setWishlist: (wishlistData) => set({ wishlist: wishlistData }),\n setWishlists: (wishlistsData) => {\n set({ wishlists: wishlistsData })\n },\n updatedProducts: [],\n setUpdatedProducts: (products) => set({ updatedProducts: products }),\n })),\n 'Nombre-DevTools'\n )\n)\n\nexport default useStoreGlobal\n\n```"
}
] |
code_wish-list-v2_c15fa608
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/interfaces/index.ts from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport interface SelectWishList {\n isShowForm: boolean\n setIsShowForm: React.Dispatch<React.SetStateAction<boolean>>\n nameListWishlist: string\n handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void\n isButton: boolean\n isMessage: boolean\n isShowForm2: boolean\n handleAddList: () => void\n listTypeWishlist?: any\n emailInfo?: any\n handleSendData1: (e: React.FormEvent) => void\n handleSendData2: (e: React.FormEvent) => void\n showFormClick?: boolean\n clickCreate: boolean\n handleCloseModal?: () => void\n handleCreateLengthZero: () => void\n selectRef: any\n handleCaptureValue: (e: React.ChangeEvent<HTMLSelectElement>) => void\n selectSize: number\n handleSelectFocus: () => void\n handleSelectBlur: () => void\n handleAddToList: () => void\n closeSlect: boolean\n errorName: string\n errorSelect: string\n isLoading: boolean\n}\n\nexport interface PropsModal {\n children: any\n blockClass: string\n}\n\nexport interface AdminSetup {\n storeLogoUrl: string\n hasSchema: boolean\n schemaVersion: string\n}\n\nexport interface AdminSettings {\n defaultTitleText: string\n imageName: string\n image: boolean\n imageRowWidth: number\n skuNameTitle: string\n skuName: boolean\n skuNameRowWidthAccount: number\n skuNameRowWidthShare: number\n departmentTitle: string\n department: boolean\n departmentRowWidth: number\n skuReferenceCodeTitle: string\n skuReferenceCode: boolean\n skuReferenceCodeRowWidth: number\n quantityTitle: string\n quantity: boolean\n quantityRowWidth: number\n unitValueTitle: string\n unitValue: boolean\n unitValueRowWidth: number\n totalValueTitle: string\n totalValue: boolean\n totalValueRowWidth: number\n notes: boolean\n addTitle: string\n add: boolean\n addRowWidth: number\n removeTitle: string\n remove: boolean\n adminSetup: AdminSetup\n}\n\nexport interface PublicSettingsForApp {\n message: string\n}\n\nexport interface WishlistMD {\n email: string\n wishlistType: string\n products: WishlistProduct[]\n isPublic: boolean\n fieldsConfig: any[]\n}\n\nexport interface WishlistProduct {\n id: number\n image: string\n bundle: string | null\n department: string\n linkProduct: string\n nameProduct: string\n notes: string | null\n quantityProduct: number\n skuCodeReference: string\n}\n\nexport interface ExtractedWishlistProductItem {\n id: number\n itemId: number\n image: string\n department: string\n skuReferenceCode: string\n name: string\n quantity: number\n linkProduct: string\n bundle: null | string\n notes: null | string\n}\n\ndeclare global {\n interface Window {\n dataLayer: any[]\n }\n}\n\n```"
}
] |
code_wish-list-v2_d61ba334
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/WishlistPrivacyOptions/index.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React, { useState } from 'react'\n\nimport copyToClipboard from '../../utils/copyToClipboard'\nimport styles from '../../styles.css'\n\nexport default function WishlistPrivacyOptions({\n selectedWishlist,\n wishlists,\n buttonLabel,\n}) {\n const [textCopied, setTextCopied] = useState(false)\n\n const linkToCopy =\n typeof window !== 'undefined'\n ? `${window.location.host}/wishlist-share?id=${\n selectedWishlist || wishlists[0].id\n }`\n : ''\n\n return (\n <div className={`${styles.containerLinkShare} flex items-center`}>\n <button\n className={styles.wishlistCreateNew}\n onClick={() => copyToClipboard(linkToCopy, setTextCopied)}\n id=\"link_wishlist\"\n >\n {buttonLabel}\n </button>\n {textCopied && (\n <p className={styles.popupCopy}>Link copied to clipboard!</p>\n )}\n </div>\n )\n}\n\n```"
}
] |
code_wish-list-v2_7290aa61
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/buttonWishlist/ButtonWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { Button, ToastConsumer, ToastProvider } from 'vtex.styleguide'\n\nimport useGetWishlist from '../../hooks/useGetWishlists'\nimport useSelectWishlist from '../../hooks/useSelectWishlist'\nimport useWishList from '../../hooks/useWishlists'\nimport ModalWishList from '../modal'\nimport SelectWishlist from '../selectWishlists/selectWishlist'\n\nconst CSS_HANDLES = ['container', 'containerLoggedIn'] as const\n\nconst ButtonWishlist = () => {\n const { handles } = useCssHandles(CSS_HANDLES)\n const pathname = encodeURIComponent(window.location.pathname)\n const loginUrl = `/login?returnUrl=${pathname}`\n\n const {\n listWishlist,\n sendData1,\n sendData2,\n handleChange,\n addList,\n createLengthZero,\n isShowSelect,\n nameListWishlist,\n setIsShowSelect,\n isShowForm,\n setIsShowForm,\n isButton,\n isMessage,\n isShowForm2,\n clickCreate,\n errorName,\n isLoading,\n } = useGetWishlist()\n\n const { navigate, isLoggedIn, emailInfo } = useWishList()\n\n const {\n addToList,\n setCloseSelect,\n closeSelect,\n selectRef,\n selectSize,\n captureValue,\n handleSelectFocus,\n handleSelectBlur,\n errorSelect,\n } = useSelectWishlist()\n\n const handleFavoritesList = () => {\n setIsShowSelect(true)\n setCloseSelect(true)\n }\n\n return (\n <div className={`${handles.container}`}>\n {!isLoggedIn ? (\n <ToastProvider positioning=\"window\">\n <ToastConsumer>\n {({ showToast }) => (\n <div className=\"flex\">\n <div className=\"mr5\">\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={() =>\n showToast({\n message:\n 'You need to log in before adding it to the list',\n action: {\n label: 'LOG IN',\n onClick: () =>\n navigate({\n to: loginUrl,\n }),\n },\n })\n }\n >\n Add to Favorites List\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </ToastProvider>\n ) : (\n <div className={`${handles.containerLoggedIn}`}>\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={handleFavoritesList}\n >\n Add to Favorites List\n </Button>\n <div className={`${handles.containerLoggedIn} relative`}>\n <ModalWishList blockClass=\"vtex-select-or-create-wishlist\">\n {isShowSelect && (\n <SelectWishlist\n isButton={isButton}\n isMessage={isMessage}\n isShowForm={isShowForm}\n listTypeWishlist={listWishlist}\n setIsShowForm={setIsShowForm}\n nameListWishlist={nameListWishlist}\n handleChange={handleChange}\n isShowForm2={isShowForm2}\n emailInfo={emailInfo}\n handleAddList={addList}\n handleSendData1={sendData1}\n handleSendData2={sendData2}\n clickCreate={clickCreate}\n handleCloseModal={() => setIsShowSelect(false)}\n handleCreateLengthZero={createLengthZero}\n selectRef={selectRef}\n selectSize={selectSize}\n handleCaptureValue={captureValue}\n handleSelectFocus={handleSelectFocus}\n handleSelectBlur={handleSelectBlur}\n errorSelect={errorSelect}\n handleAddToList={addToList}\n closeSlect={closeSelect}\n errorName={errorName}\n isLoading={isLoading}\n />\n )}\n </ModalWishList>\n </div>\n </div>\n )}\n </div>\n )\n}\n\nexport default ButtonWishlist\n\n```"
}
] |
code_wish-list-v2_e19e079c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/ProductQuantity/index.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useRef, useState } from 'react'\nimport { useMutation } from 'react-apollo'\nimport { NumericStepper } from 'vtex.styleguide'\n\nimport { useProducts } from '../../context/ProductsContext'\nimport { useRow } from '../../context/RowContext'\nimport UPDATE_WISHLIST from '../../graphql/mutations/updateWishlist.gql'\n\nexport const ProductStepper = ({ wishlist: initialWishlist }) => {\n const { updateQuantity, row } = useRow()\n\n const [QTY, setQTY] = useState(row?.quantity ?? 0)\n const { updateQuantityBySkuReferenceCode } = useProducts()\n const wishlistRef = useRef(initialWishlist)\n const timeoutRef = useRef<number | null>(null)\n\n const [updateWishlist] = useMutation(UPDATE_WISHLIST)\n\n useEffect(() => {\n wishlistRef.current = initialWishlist\n }, [initialWishlist])\n\n const modifyProductQTY = (newValue: string, eventType: string) => {\n const quantity = Number(newValue)\n const roundedQuantity =\n eventType === 'change' && row.bundle\n ? Math.max(quantity - (quantity % row.bundle), row.bundle)\n : Math.max(row.bundle, quantity)\n\n const finalValue = roundedQuantity + (quantity - roundedQuantity)\n\n const updatedProducts = wishlistRef.current?.products?.map(\n (product: { skuCodeReference: string }) =>\n product.skuCodeReference === row.skuReferenceCode\n ? { ...product, quantityProduct: finalValue }\n : product\n )\n\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n\n updateQuantity(finalValue)\n updateQuantityBySkuReferenceCode(row.skuReferenceCode, finalValue)\n setQTY(finalValue)\n timeoutRef.current = window.setTimeout(() => {\n updateWishlist({\n variables: {\n wishlist: {\n id: wishlistRef.current.id,\n products: updatedProducts,\n isPublic: true,\n wishlistType: wishlistRef.current.wishlistType,\n },\n },\n }).catch((error: unknown) => {\n console.error('Error updating products:', error)\n })\n }, 700)\n }\n\n useEffect(() => {\n return () => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n }\n }, [])\n\n return (\n <NumericStepper\n value={QTY}\n size=\"small\"\n onChange={(e: { value: string; type: string }) => {\n modifyProductQTY(e.value, e.type)\n }}\n />\n )\n}\n\n```"
}
] |
code_wish-list-v2_707ee573
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/SearchSKU/AutocompleteBlock.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport type { FunctionComponent } from 'react'\nimport React, { useState } from 'react'\nimport type { WrappedComponentProps } from 'react-intl'\nimport { injectIntl } from 'react-intl'\nimport { Button, Tag, IconClear } from 'vtex.styleguide'\nimport PropTypes from 'prop-types'\nimport { useApolloClient } from 'react-apollo'\nimport { Item, Product } from 'vtex.product-context/react/ProductTypes'\n\nimport QuickOrderAutocomplete from './QuickOrderAutocomplete'\nimport productQuery from '../../queries/product.gql'\nimport handles from '../../styles.css'\n\ninterface SelectedProps {\n label: string\n seller?: string\n slug: string\n thumb?: string\n value: string\n data?: { product: Product }\n product?: Product\n}\n\nconst AutocompleteBlock: FunctionComponent<any & WrappedComponentProps> = ({\n text,\n description,\n componentOnly,\n onAddToWishlist,\n}) => {\n const client = useApolloClient()\n const [state, setState] = useState<{\n selectedItem: SelectedProps | null\n quantitySelected: number\n unitMultiplier: number\n }>({\n selectedItem: null,\n quantitySelected: 1,\n unitMultiplier: 1,\n })\n\n const clear = () => {\n setState({\n ...state,\n selectedItem: null,\n quantitySelected: 1,\n unitMultiplier: 1,\n })\n }\n\n const { selectedItem } = state\n\n const onSelect = async (product: any) => {\n if (!!product && product.length) {\n const query = {\n query: productQuery,\n variables: { slug: product[0].slug },\n }\n\n const response = await client.query(query)\n\n const { data } = response\n const selectedSku =\n data.product.items.length === 1 ? data.product.items[0].itemId : null\n\n const seller = selectedSku\n ? data.product.items[0].sellers.find(\n (item: { sellerDefault: boolean }) => {\n return item.sellerDefault === true\n }\n ).sellerId\n : null\n\n let multiplier = 1\n\n if (data.product.items.length === 1) {\n multiplier = data.product.items[0].unitMultiplier\n }\n\n setState({\n ...state,\n selectedItem:\n !!product && product.length\n ? { ...product[0], value: selectedSku, seller, data }\n : null,\n unitMultiplier: multiplier,\n quantitySelected: multiplier,\n })\n }\n\n return true\n }\n\n const selectSku = (value: string) => {\n const seller = selectedItem?.data?.product?.items\n .find((item: { itemId: string }) => {\n return item?.itemId === value\n })\n ?.sellers?.find((s: { sellerDefault: boolean }) => {\n return s.sellerDefault === true\n })?.sellerId\n\n const newSelected = {\n label: selectedItem?.label ?? '',\n slug: selectedItem?.slug ?? '',\n ...selectedItem,\n seller,\n value,\n }\n\n const matchedItem = selectedItem?.data?.product.items.find(\n (item: { itemId: string }) => item.itemId === value\n )\n\n setState({\n ...state,\n selectedItem: newSelected,\n unitMultiplier: matchedItem?.unitMultiplier ?? 1,\n quantitySelected: matchedItem?.unitMultiplier ?? 1,\n })\n }\n\n const thumb = (url: string) => {\n return url.replace('25-25', `50-50`)\n }\n\n const onAddToFavoritesList = async () => {\n const result = await onAddToWishlist(selectedItem)\n\n if (result) {\n clear()\n }\n }\n\n return (\n <div className={`${handles.addSkuContainer}`}>\n {!componentOnly && (\n <div className={`${handles.textContainer} w-third-l w-100-ns fl-l`}>\n <h2\n className={`${handles.textContainerTitle} t-heading-3 mb3 ml5 ml3-ns mt4`}\n >\n {text}\n </h2>\n <div\n className={`${handles.textContainerDescription} t-body lh-copy c-muted-1 mb7 ml3 false`}\n >\n {description}\n </div>\n </div>\n )}\n <div\n className={`${handles.componentContainer} ${!componentOnly ? '' : ''}`}\n >\n <div className=\"w-100\">\n <div\n className={`bg-base t-body c-on-base pa7 br3 b--muted-4 ${handles.componentContainerHelper}`}\n >\n <div className={handles.quickOrderAutocomplete}>\n {!selectedItem && <QuickOrderAutocomplete onSelect={onSelect} />}\n </div>\n {!!selectedItem && (\n <div\n className={`flex flex-row ${handles.quickOrderAutocompleteItemsWrapper}`}\n >\n <div\n className={`w-two-thirds-l w-100-ns fl-l flex ${handles.quickOrderAutocomplete}`}\n >\n <div\n className={`flex flex-row ${handles.quickOrderAutocompleteItems}`}\n >\n <div\n className={`flex flex-column w-15 fl ${handles.productThumb}`}\n >\n <img\n src={thumb(selectedItem?.thumb ?? '')}\n width=\"50\"\n height=\"50\"\n alt=\"\"\n />\n </div>\n <div\n className={`flex flex-row w-85 fl ${handles.productLabel}`}\n >\n <span className={`${handles.productTitle}`}>\n {selectedItem.label}\n </span>\n <div\n className={`flex flex-column fl h-50 ${handles.addToFavouritebutton}`}\n >\n <Button\n variation=\"primary\"\n size=\"small\"\n onClick={onAddToFavoritesList}\n >\n Add to Favourite List\n </Button>\n </div>\n </div>\n </div>\n {(selectedItem?.data?.product?.items ?? [])?.length > 1 && (\n <div className={`${handles.productSku} flex flex-row`}>\n {selectedItem.data?.product.items.map((item: Item) => {\n return (\n <span\n key={item.itemId}\n className={`${handles.skuSelection} ${item.itemId === selectedItem.value && handles.skuSelected} mr4\n `}\n >\n <Tag\n size=\"small\"\n bgColor={\n item.itemId === selectedItem.value\n ? '#8bc34a'\n : '#979899'\n }\n onClick={() => {\n selectSku(item.itemId)\n }}\n >\n {item.name}\n </Tag>\n </span>\n )\n })}\n </div>\n )}\n </div>\n <div\n className={`w-third-l w-100-ns fr-l flex-row-l ${handles.buttonClearWrapper}`}\n >\n <div\n className={`flex flex-column w-100 fl ${handles.buttonClear}`}\n >\n <Button\n variation=\"tertiary\"\n size=\"medium\"\n onClick={() => {\n clear()\n }}\n >\n <IconClear\n onClick={() => {\n clear()\n }}\n />\n </Button>\n </div>\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n </div>\n )\n}\n\nAutocompleteBlock.propTypes = {\n componentOnly: PropTypes.bool,\n text: PropTypes.string,\n description: PropTypes.string,\n onAddToWishlist: PropTypes.func,\n}\n\nexport default injectIntl(AutocompleteBlock)\n\n```"
}
] |
code_wish-list-v2_42bf27aa
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/SearchSKU/index.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport PropTypes from 'prop-types'\n\nimport styles from '../../styles.css'\n\ninterface Item {\n productId: string\n items: Array<{\n images: Array<{\n imageUrl: string\n imageText: string\n }>\n referenceId: Array<{ Value: string }>\n }>\n}\n\nconst SearchSKU = ({\n valueSearchSku,\n changeValueSku,\n getSearchProduct,\n isShowProductSearch,\n searchProduct,\n}) => {\n return (\n <div className={styles.wishlistSearchSKUContainer}>\n <label htmlFor=\"searchInputWishlist\">Search SKU</label>\n <input\n id=\"searchInputWishlist\"\n type=\"text\"\n value={valueSearchSku}\n onChange={changeValueSku}\n />\n <button onClick={getSearchProduct}>Buscar</button>\n\n {isShowProductSearch && (\n <div>\n {searchProduct.map((item: Item) => (\n <div\n key={item.productId}\n id={item.productId}\n style={{ display: 'flex', flexDirection: 'row' }}\n >\n <img\n src={item.items[0].images[0].imageUrl}\n alt={item.items[0].images[0].imageText}\n width={50}\n height={50}\n />\n <p>{item.items[0].referenceId[0].Value}</p>\n </div>\n ))}\n </div>\n )}\n </div>\n )\n}\n\nSearchSKU.propTypes = {\n valueSearchSku: PropTypes.string,\n isShowProductSearch: PropTypes.bool,\n searchProduct: PropTypes.array,\n changeValueSku: PropTypes.func,\n getSearchProduct: PropTypes.func,\n}\n\nexport default SearchSKU\n\n```"
}
] |
code_wish-list-v2_14d31bcc
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/SearchSKU/QuickOrderAutocomplete.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { FunctionComponent } from 'react'\nimport React, { useState, useRef } from 'react'\nimport { AutocompleteInput } from 'vtex.styleguide'\nimport PropTypes from 'prop-types'\nimport type { WrappedComponentProps } from 'react-intl'\nimport { injectIntl, IntlShape } from 'react-intl'\nimport { useApolloClient } from 'react-apollo'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { SearchIcon } from '../Icons'\nimport autocomplete from '../../queries/autocomplete.gql'\nimport styles from './searchSKU.css'\n\nconst getImageSrc = (img: string) => {\n const td = img.split('/')\n const ids = td[td.indexOf('ids') + 1]\n\n return img.replace(ids, `${ids}-50-50`)\n}\n\ninterface Item {\n items: any\n}\n\nconst CustomOption = (props: any) => {\n const { roundedBottom, searchTerm, value, selected, onClick } = props\n const [highlightOption, setHighlightOption] = useState(false)\n const CSS_HANDLES = [\n 'customOptionButton',\n 'imageThumbContainer',\n 'imageThumb',\n 'searchTextPreviewWrapper',\n ] as const\n\n const { handles } = useCssHandles(CSS_HANDLES)\n const renderOptionHighlightedText = () => {\n const highlightableText = typeof value === 'string' ? value : value.label\n const index: number = highlightableText\n .toLowerCase()\n .indexOf(searchTerm.toLowerCase())\n\n if (index === -1) {\n return highlightableText\n }\n\n const prefix = highlightableText.substring(0, index)\n const match = highlightableText.substr(index, searchTerm.length)\n const suffix = highlightableText.substring(\n index + parseInt(match.length, 10)\n )\n\n return (\n <span className=\"truncate\">\n <span className=\"fw7\">{prefix}</span>\n {match}\n <span className=\"fw7\">{suffix}</span>\n </span>\n )\n }\n\n const buttonClasses = `\n ${handles.customOptionButton}\n ${roundedBottom ? 'br2 br--bottom' : ''}\n ${highlightOption || selected ? 'bg-muted-5' : 'bg-base'}\n bn w-100 tl pointer pa4 f6\n `\n\n const thumb = value.thumb ? value.thumb : ''\n\n return (\n <button\n className={buttonClasses}\n onFocus={() => setHighlightOption(true)}\n onMouseEnter={() => setHighlightOption(true)}\n onMouseLeave={() => setHighlightOption(false)}\n onClick={onClick}\n >\n <div className=\"flex items-center\">\n {thumb && (\n <span\n className={`${handles.imageThumbContainer} mr3 c-muted-2 flex pt1`}\n >\n <img className={`${handles.imageThumb}`} src={thumb} alt=\"\" />\n </span>\n )}\n <div className={`${handles.searchTextPreviewWrapper}`}>\n <span className=\"pr2\">{renderOptionHighlightedText()}</span>\n {typeof value !== 'string' && (\n <div className=\"t-mini c-muted-1\">{value.caption}</div>\n )}\n </div>\n </div>\n </button>\n )\n}\n\ninterface QuickOrderAutocompleteInt {\n onSelect: any\n}\nconst QuickOrderAutocomplete: FunctionComponent<\n WrappedComponentProps & QuickOrderAutocompleteInt\n> = ({\n onSelect,\n intl,\n}: {\n onSelect: (...args: any) => void\n intl: IntlShape\n}) => {\n const client = useApolloClient()\n const [optionsResult, setOptions] = useState([])\n const [term, setTerm] = useState('')\n const [loading, setLoading] = useState(false)\n const [lastSearched, setLastSearched] = useState([])\n const timeoutRef: any = useRef(null)\n\n const handleSearch = async ({ value }: { value: string }) => {\n if (value.length > 1) {\n const { data } = await client.query({\n query: autocomplete,\n variables: { inputValue: value },\n })\n\n setOptions(\n !!data &&\n !!data.productSuggestions &&\n !!data.productSuggestions.products\n ? data.productSuggestions.products\n : []\n )\n }\n }\n\n const renderOptionRender = (props: any) => <CustomOption {...props} />\n\n const options = {\n onSelect: (...args: any) => {\n onSelect(args)\n },\n loading,\n value: !term.length\n ? []\n : optionsResult\n .filter((item: Item) => {\n return !!item.items[0].images[0].imageUrl\n })\n .map((item: any) => {\n return {\n value: item.items[0].itemId,\n label: item.productName,\n slug: item.linkText,\n thumb: getImageSrc(item.items[0].images[0].imageUrl),\n }\n }),\n lastSearched: {\n value: lastSearched,\n label: 'Last searched products',\n onChange: (option: never) =>\n option && setLastSearched([...new Set([...lastSearched, option])]),\n },\n // --- This is what makes the custom option work!\n renderOption: renderOptionRender,\n }\n\n const input = {\n onChange: (nterm: string) => {\n if (nterm) {\n setLoading(true)\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n }\n\n timeoutRef.current = setTimeout(() => {\n setLoading(false)\n setTerm(nterm)\n handleSearch({ value: nterm })\n timeoutRef.current = null\n }, 1000)\n } else {\n setTerm(nterm)\n }\n },\n onClear: () => setTerm(''),\n placeholder: intl.formatMessage({\n id: 'store/favorite-list.search-product-by-sku',\n }),\n value: term,\n }\n\n return (\n <div className={`${styles.autocompleteInputWrapper}`}>\n <AutocompleteInput input={input} options={options} />\n <SearchIcon />\n </div>\n )\n}\n\nQuickOrderAutocomplete.propTypes = {\n onSelect: PropTypes.func,\n}\nexport default injectIntl(QuickOrderAutocomplete)\n\n```"
}
] |
code_wish-list-v2_24386d1a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/SearchSKU/searchSKU.css from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.autocompleteInputWrapper {\n display: flex;\n align-items: center;\n border-radius: 5px;\n border: 2px solid #E3E4E6;\n height: 38px;\n}\n\n.autocompleteInputWrapper label div {\n border-radius: 0 !important;\n border-top: none;\n border-bottom: none;\n border-left: none;\n height: auto;\n}\n\n.autocompleteInputWrapper label div:focus {\n outline: none;\n}\n\n.autocompleteInputWrapper :global(.vtex-styleguide-9-x-noAppearance) {\n border: none;\n border-radius: 0;\n}\n\n.autocompleteInputWrapper :global(.vtex-styleguide-9-x-noAppearance):focus {\n outline: none;\n}\n\n.autocompleteInputWrapper svg{\n padding: 0 0.5rem;\n}\n\n.imageThumb {\n width: 2.5rem;\n height: 2.5rem;\n min-width: 2.5rem;\n object-fit: none;\n}\n\n.searchTextPreviewWrapper {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n```"
}
] |
code_wish-list-v2_ad749c6d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/WishlistName/WishlistName.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React, { useState, useEffect } from 'react'\nimport { useMutation } from 'react-apollo'\nimport { IconEdit } from 'vtex.styleguide'\n\nimport styles from '../../styles.css'\nimport UPDATE_WISHLIST from '../../graphql/mutations/updateWishlist.gql'\n\nfunction EditableWishlistTitle({ initialTitle, wishlist, fetchData }) {\n const [isEditing, setIsEditing] = useState(false)\n const [title, setTitle] = useState(initialTitle || 'Default name')\n const [updateWishlist] = useMutation(UPDATE_WISHLIST, {\n variables: {\n wishlist: {\n id: wishlist.id,\n wishlistType: title,\n products: wishlist.products,\n isPublic: true,\n },\n },\n onCompleted: () => {\n fetchData()\n },\n })\n\n useEffect(() => {\n setTitle(initialTitle)\n }, [initialTitle])\n\n const handleEditClick = () => setIsEditing(true)\n\n const handleSaveClick = () => {\n setIsEditing(false)\n updateWishlist()\n }\n\n return (\n <div>\n {isEditing ? (\n <div>\n <input\n type=\"text\"\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n className={styles.titleWishlistName}\n />\n <button\n className={styles.buttonWishlistName}\n onClick={handleSaveClick}\n >\n Save\n </button>\n </div>\n ) : (\n <div\n className={styles.wishlistNameContainer}\n aria-hidden=\"true\"\n >\n <h1\n className={styles.wishlistName}\n onClick={handleEditClick}\n >\n {title} {title && <IconEdit />}\n </h1>\n </div>\n )}\n </div>\n )\n}\n\nexport default EditableWishlistTitle\n\n```"
}
] |
code_wish-list-v2_e0ba5e56
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/TableShare/index.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport PropTypes from 'prop-types'\nimport React, { useContext, useState } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { useRuntime } from 'vtex.render-runtime'\nimport {\n Button,\n Table,\n ToastConsumer,\n ToastContext,\n ToastProvider,\n} from 'vtex.styleguide'\n\nimport { ProductsProvider } from '../../context/ProductsContext'\nimport { RowProvider, useRow } from '../../context/RowContext'\nimport useAddSharedListPage from '../../hooks/useAddSharedListPage'\nimport useAddToCart from '../../hooks/useAddToCart'\nimport {\n AdminSettings,\n PublicSettingsForApp,\n WishlistMD,\n} from '../../interfaces'\nimport styles from '../../styles.css'\nimport { getProductPath } from '../../utils/jsonSchema'\nimport ModalCreateList from '../ModalCreateList'\nimport ProductPriceTotal from '../ProductPriceTotal'\nimport SkuName from '../SkuName'\nimport UnitPrice from '../UnitPrice'\nimport { ProductStepper } from './ProductStepper'\n\nconst CSS_HANDLES = [\n 'importList__generalContainer',\n 'importList__buttonContainer',\n 'importList__modalContainer',\n]\n\ninterface ITableWishListColumns {\n publicSettingsForApp: PublicSettingsForApp\n}\n\ninterface WrapperTableWishListProps {\n schema: any\n items: any[]\n}\n\nconst WrapperTableWishList: React.FC<WrapperTableWishListProps> = React.memo(\n ({ schema, items }) => {\n return (\n <Table\n fullWidth\n dynamicRowHeight\n updateTableKey={`vtex-table=${Math.floor(Math.random() * 1000)}`}\n schema={schema}\n density=\"medium\"\n items={items}\n emptyStateLabel=\"Nothing to show\"\n />\n )\n },\n (prevProps, nextProps) => {\n return prevProps.items.length === nextProps.items.length\n }\n)\n\nWrapperTableWishList.displayName = 'WrapperTableWishList'\n\nconst WrapperProductStepper = ({ handleQuantityChange, setIsUpdatingQty }) => {\n const { row: rowData } = useRow()\n\n return (\n <ProductStepper\n initialQty={rowData.qty || rowData.quantityProduct}\n productName={rowData.name || rowData.nameProduct}\n bundle={rowData.bundle}\n setIsUpdatingQty={(value) => setIsUpdatingQty(value)}\n rowData={rowData}\n productId={rowData.ID}\n handleQuantityChange={handleQuantityChange}\n />\n )\n}\n\nexport default function TableWishList({\n wishlistMD,\n queryId,\n columns,\n}: {\n wishlistMD: WishlistMD\n queryId: string\n columns: ITableWishListColumns\n}) {\n const { showToast } = useContext(ToastContext)\n const { handles } = useCssHandles(CSS_HANDLES)\n const [localProducts, setLocalProducts] = useState([\n ...wishlistMD?.products.map((product: any) => ({\n ...product,\n unitValue: product.unitValue ?? 0,\n totalValue: product.quantityProduct * (product.unitValue ?? 0),\n })),\n ])\n\n const [, setIsUpdatingQty] = useState(false)\n const runtime = useRuntime()\n const { culture } = runtime\n const currency = culture.customCurrencySymbol\n const addProductsToCart = useAddToCart()\n const handleQuantityChange = (productId, newQuantity) => {\n // Lógica para actualizar la cantidad de Products en la lista...\n const updatedProducts = localProducts.map((product) => {\n if (product.ID === productId) {\n const newTotalValue = newQuantity * (product.unitValue ?? 0)\n\n return {\n ...product,\n unitValue: product.unitValue ?? 0,\n qty: newQuantity,\n totalValue: newTotalValue,\n }\n }\n\n return product\n })\n\n // Actualiza el estado local\n setLocalProducts(updatedProducts)\n }\n\n const priceCellRenderer = ({ rowData }) => {\n return (\n <ProductPriceTotal\n itemId={rowData?.ID}\n productQuantity={rowData?.quantityProduct}\n currency={currency}\n />\n )\n }\n\n const unitValueCellRenderer = ({ rowData }) => {\n return (\n <UnitPrice\n itemId={rowData?.ID}\n skuReference={rowData?.skuCodeReference}\n currency={currency}\n />\n )\n }\n\n const imageCellRenderer = ({ cellData, rowData, updateCellMeasurements }) => {\n const productUrl = getProductPath(rowData)\n\n return (\n <a\n href={productUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={styles.wishlistShareTableCell}\n >\n <img\n src={cellData || rowData.Image}\n alt=\"\"\n className={styles.wishlistProductImage}\n onLoad={() => updateCellMeasurements()}\n />\n </a>\n )\n }\n\n const skuReferenceCodeCellRenderer = ({ cellData, rowData }) => {\n const linkUrl = rowData.linkProduct\n const parts = linkUrl.split('.br/')\n const productUrl = `/${parts[parts.length - 1]}`\n\n return (\n <a\n href={productUrl}\n className={styles.wishlistProductTexts}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {cellData || rowData.skuCodeReference}\n </a>\n )\n }\n\n const qtyCellRenderer = ({ rowData }) => (\n <RowProvider row={rowData}>\n <div className={styles.wishlistShareTableCell}>\n <WrapperProductStepper\n handleQuantityChange={handleQuantityChange}\n setIsUpdatingQty={setIsUpdatingQty}\n />\n </div>\n </RowProvider>\n )\n\n const addCellRenderer = ({ rowData }) => (\n <div className={styles.wishlistShareTableCell}>\n <button\n className={styles.wishlistAddItem}\n onClick={() =>\n addProductsToCart(\n {\n name: rowData.name,\n itemId: rowData.ID,\n quantity:\n localProducts?.find((product) => product.ID === rowData.ID)\n ?.qty ?? rowData.quantity,\n },\n wishlistMD\n )\n }\n >\n Add\n </button>\n </div>\n )\n\n // ADD SHARED LIST PAGE\n const {\n isUserLoggedOut,\n navigateToLoginPage,\n isListNameInputVisible,\n handleInputListNameVisualization,\n fieldValidationTable,\n handleNameListTable,\n createNewList,\n } = useAddSharedListPage({\n queryId,\n products: wishlistMD.products,\n updatedProducts: null,\n })\n\n const skuNameCellRenderer = ({ rowData }) => {\n const productUrl = getProductPath(rowData)\n\n return <SkuName itemId={rowData.ID} productUrl={productUrl} />\n }\n\n const schema: any = {\n properties: {\n // Definición del esquema de la tabla...\n image: {\n title: 'Image',\n // width: 100,\n cellRenderer: imageCellRenderer,\n },\n nameProduct: {\n title: 'Name',\n // width: 300,\n active: true,\n cellRenderer: skuNameCellRenderer,\n },\n department: {\n title: 'Department',\n // width: 190,\n },\n skuReferenceCode: {\n title: 'Part #',\n // width: 130,\n cellRenderer: skuReferenceCodeCellRenderer,\n },\n quantity: {\n title: 'Qty',\n // width: 130,\n cellRenderer: qtyCellRenderer,\n },\n unitValue: {\n title: 'Unit Value',\n // width: 145,\n cellRenderer: unitValueCellRenderer,\n },\n totalValue: {\n title: 'Total Value',\n // width: 120,\n cellRenderer: priceCellRenderer,\n },\n add: {\n title: 'Add',\n // width: 100,\n cellRenderer: addCellRenderer,\n },\n },\n }\n\n const wishlistColumnsSettings: AdminSettings = JSON.parse(\n columns.publicSettingsForApp.message\n )\n\n if (wishlistColumnsSettings) {\n schema.properties.image.title = wishlistColumnsSettings.imageName\n schema.properties.image.width = wishlistColumnsSettings.imageRowWidth\n schema.properties.nameProduct.title = wishlistColumnsSettings.skuNameTitle\n schema.properties.nameProduct.width =\n wishlistColumnsSettings.skuNameRowWidthShare\n schema.properties.department.title = wishlistColumnsSettings.departmentTitle\n schema.properties.department.width =\n wishlistColumnsSettings.departmentRowWidth\n schema.properties.skuReferenceCode.title =\n wishlistColumnsSettings.skuReferenceCodeTitle\n schema.properties.skuReferenceCode.width =\n wishlistColumnsSettings.skuReferenceCodeRowWidth\n schema.properties.quantity.title = wishlistColumnsSettings.quantityTitle\n schema.properties.quantity.width = wishlistColumnsSettings.quantityRowWidth\n schema.properties.unitValue.title = wishlistColumnsSettings.unitValueTitle\n schema.properties.unitValue.width =\n wishlistColumnsSettings.unitValueRowWidth\n schema.properties.totalValue.title = wishlistColumnsSettings.totalValueTitle\n schema.properties.totalValue.width =\n wishlistColumnsSettings.totalValueRowWidth\n schema.properties.add.title = wishlistColumnsSettings.addTitle\n schema.properties.add.width = wishlistColumnsSettings.addRowWidth\n }\n\n for (const [key, value] of Object.entries(wishlistColumnsSettings)) {\n if (!value) {\n delete schema.properties[key]\n }\n }\n\n return (\n <div className={handles.importList__generalContainer}>\n {/* NEW */}\n {isUserLoggedOut ? (\n <ToastProvider positioning=\"window\">\n <ToastConsumer>\n {() => (\n <div className=\"flex\">\n <div>\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={() =>\n showToast({\n message:\n 'You need to be logged in to import this wishlist',\n action: {\n label: 'LOG IN',\n onClick: navigateToLoginPage,\n },\n })\n }\n >\n Import Favourite List\n </Button>\n </div>\n </div>\n )}\n </ToastConsumer>\n </ToastProvider>\n ) : (\n <div className=\"flex\">\n <div className={handles.importList__buttonContainer}>\n <Button\n size=\"small\"\n variation=\"secondary\"\n onClick={handleInputListNameVisualization}\n >\n Import Favourite List\n </Button>\n <div className={`${handles.importList__modalContainer} relative`}>\n {isListNameInputVisible && (\n <ModalCreateList\n handleButtonCloseModal={handleInputListNameVisualization}\n handleNameList={handleNameListTable}\n fieldValidation={fieldValidationTable}\n handleSubmitData={createNewList}\n blockClass=\"vtex-create-wishlist-favorite-list\"\n />\n )}\n </div>\n </div>\n </div>\n )}\n <ProductsProvider items={localProducts}>\n <WrapperTableWishList items={localProducts} schema={schema} />\n </ProductsProvider>\n </div>\n )\n}\n\nTableWishList.propTypes = {\n products: PropTypes.any.isRequired,\n queryId: PropTypes.string.isRequired,\n name: PropTypes.string,\n}\n\n```"
}
] |
code_wish-list-v2_706364de
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/TableShare/ProductStepper.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport React, { useState, useEffect, useRef } from 'react'\nimport { NumericStepper } from 'vtex.styleguide'\n\nexport const ProductStepper = ({\n initialQty,\n handleQuantityChange,\n bundle,\n setIsUpdatingQty,\n productId,\n}) => {\n // Hooks y funciones de utilidad...\n const [QTY, setQTY] = useState(initialQty)\n const qtyRef = useRef(initialQty)\n\n useEffect(() => {\n qtyRef.current = QTY\n }, [QTY])\n\n useEffect(() => {\n setQTY(initialQty)\n }, [initialQty])\n\n const modifyProductQTY = (newValue, eventType) => {\n // Lógica para modificar la cantidad del producto...\n setIsUpdatingQty(true)\n\n let finalValue = 0 + newValue\n \n const quantity = finalValue\n const minimumQuantity = bundle || 1\n const maximumQuantity = qtyRef.current\n \n if (eventType === 'click') {\n if (quantity < minimumQuantity) {\n finalValue = minimumQuantity\n } else if (quantity === maximumQuantity) {\n finalValue = quantity - minimumQuantity + 1\n } \n } else if (eventType === 'change') {\n const roundedQty = Math.ceil(quantity / minimumQuantity) * minimumQuantity\n\n finalValue = Math.max(\n minimumQuantity,\n Math.min(roundedQty, maximumQuantity)\n )\n }\n \n setQTY(finalValue)\n handleQuantityChange(productId, finalValue)\n }\n\n return (\n <NumericStepper\n value={QTY}\n size=\"small\"\n onChange={(e) => {\n const newValue = e.value\n setQTY(newValue)\n modifyProductQTY(newValue, e.type)\n }}\n />\n )\n}\n\n```"
}
] |
code_wish-list-v2_baf913d7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/selectWishlists/selectWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nimport { SelectWishList } from '../../interfaces'\n\nconst CSS_HANDLES = [\n 'containerSelect',\n 'containerErrorAdd',\n 'containerError',\n 'containerButtonCloseBox',\n 'containerSelectDiv',\n 'containerSelectFlex',\n 'containerMessageAddCreate',\n 'containerShowForm',\n 'containerButtonCreateList2',\n 'containerSelectTitle',\n 'containerButtonClose',\n 'containerButtonCreateList',\n 'containerInput',\n 'containerTitleCreateList',\n 'containerSelectDropdown',\n 'containerButtonAddList',\n 'containerButtonCreate',\n] as const\n\nconst SelectWishlist = (props: SelectWishList) => {\n const { handles } = useCssHandles(CSS_HANDLES)\n\n return (\n <>\n {props.closeSlect && (\n <div className={`${handles.containerSelect}`}>\n <div className={`${handles.containerButtonCloseBox}`}>\n <button\n onClick={props.handleCloseModal}\n className={`${handles.containerButtonClose}`}\n >\n X\n </button>\n </div>\n {props.listTypeWishlist?.length > 0 && (\n <div className={`${handles.containerSelectFlex}`}>\n {!props.clickCreate && (\n <>\n <select\n id=\"selectList\"\n style={{ marginBottom: '15px' }}\n ref={props.selectRef}\n className={`${handles.containerSelectDropdown}`}\n onFocus={props.handleSelectFocus}\n onBlur={props.handleSelectBlur}\n onChange={props.handleCaptureValue}\n size={props.selectSize}\n >\n <option value=\"\" disabled selected>\n Select List\n </option>\n {props.listTypeWishlist?.map(\n (newDates: { id: string; wishlistType: string }) => (\n <option\n value={newDates.id}\n key={newDates.id}\n id={newDates.id}\n >\n {newDates.wishlistType}\n </option>\n )\n )}\n </select>\n\n {props.isLoading ? (\n <>\n <button\n disabled={props.isLoading}\n className={`${handles.containerButtonCreate}`}\n onClick={props.handleAddList}\n >\n {props.isLoading ? 'loading..' : 'Create new list'}\n </button>\n </>\n ) : (\n <>\n <button\n className={`${handles.containerButtonAddList}`}\n onClick={props.handleAddToList}\n >\n Add to list\n </button>\n\n {props.errorSelect && (\n <p className={`${handles.containerError}`}>\n {props.errorSelect}\n </p>\n )}\n <button\n disabled={props.isLoading}\n className={`${handles.containerButtonCreate}`}\n onClick={props.handleAddList}\n >\n {props.isLoading ? 'loading..' : 'Create new list'}\n </button>\n </>\n )}\n </>\n )}\n\n {props.isShowForm2 && (\n <div className={`${handles.containerShowForm}`}>\n <p className={`${handles.containerTitleCreateList}`}>\n Create a name for the list\n </p>\n <input\n type=\"text\"\n placeholder=\"List name\"\n name=\"nameList\"\n value={props.nameListWishlist}\n onChange={props.handleChange}\n className={`${handles.containerInput}`}\n />\n {props.errorName && (\n <p className={`${handles.containerErrorAdd}`}>\n {props.errorName}\n </p>\n )}\n <button\n disabled={props.isLoading}\n onClick={props.handleSendData1}\n className={`${handles.containerButtonCreateList}`}\n >\n {props.isLoading ? 'loading..' : 'Create list'}\n </button>\n </div>\n )}\n </div>\n )}\n {props.listTypeWishlist?.length === 0 && (\n <div className={`${handles.containerSelectFlex}`}>\n {props.isButton && (\n <button\n className={`${handles.containerButtonCreate}`}\n onClick={props.handleCreateLengthZero}\n >\n Create new list\n </button>\n )}\n {props.isShowForm && (\n <div className={`${handles.containerSelectFlex}`}>\n <p className={`${handles.containerTitleCreateList}`}>\n Create a name for the list\n </p>\n <input\n className={`${handles.containerInput}`}\n type=\"text\"\n placeholder=\"List name\"\n name=\"nameList\"\n value={props.nameListWishlist}\n onChange={props.handleChange}\n />\n {props.errorName && (\n <p className={`${handles.containerErrorAdd}`}>\n {props.errorName}\n </p>\n )}\n <button\n className={`${handles.containerButtonCreateList2}`}\n onClick={props.handleSendData2}\n >\n Create List\n </button>\n </div>\n )}\n {props.isMessage && (\n <div className={`${handles.containerMessageAddCreate}`}>\n You created a new Favourite List and your product was added\n successfully.\n </div>\n )}\n </div>\n )}\n </div>\n )}\n </>\n )\n}\n\nexport default SelectWishlist\n\n```"
}
] |
code_wish-list-v2_6b3a29c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/modal/index.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\n\nimport { PropsModal } from '../../interfaces/index'\nimport handles from './modalstyle.css'\n\nconst ModalWishList = (props: PropsModal) => {\n return (\n <div\n className={`${props.blockClass} ${handles.modalWishListWrapper} relative`}\n >\n {props.children}\n </div>\n )\n}\n\nexport default ModalWishList\n\n```"
}
] |
code_wish-list-v2_541b02d8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/modal/modalstyle.css from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.modalWishListWrapper {\n background: white;\n border: 1px solid var(--lines-dark);;\n z-index: 1;\n}\n\n:global(.vtex-create-wishlist-main) {\n margin-top: .5rem;\n position: absolute;\n}\n\n:global(.vtex-create-wishlist-desktop) {\n position: absolute;\n top: 2.8rem;\n}\n\n:global(.vtex-create-wishlist-mobile) {\n position: absolute;\n top: 3rem;\n right: 1rem;\n width: 13rem;\n}\n```"
}
] |
code_wish-list-v2_fd94caa1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/extractProductData.ts from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ExtractedWishlistProductItem } from '../../interfaces'\n\nconst extractProductData = ({ items }): ExtractedWishlistProductItem[] => {\n return items?.map(\n ({\n ID,\n Image,\n department,\n skuCodeReference,\n nameProduct,\n quantityProduct,\n linkProduct,\n bundle,\n notes,\n }) => {\n const pr = {\n id: ID,\n itemId: ID,\n image: Image,\n department,\n skuReferenceCode: skuCodeReference,\n name: nameProduct,\n quantity: quantityProduct,\n linkProduct,\n bundle: bundle || null,\n notes,\n }\n\n return pr\n }\n )\n}\n\nexport default extractProductData\n\n```"
}
] |
code_wish-list-v2_c377792b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/deleteItemsWishlist.ts from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport formatProductForWishlist from './formatProductForWishlist'\nimport extractProductData from './extractProductData'\n\nconst deleteItemFromWishlist = async ({\n row,\n wishlist,\n selectedWishlist,\n updateWishlist,\n}) => {\n const selectedRow = row.rowData\n\n const wishlistProducts = extractProductData({ items: wishlist.products })\n const wishlistItem = wishlistProducts.find(\n (item: { name: string }) => item.name === selectedRow.name\n )\n\n if (!wishlistItem) return\n\n const updatedWishlistProducts = wishlistProducts.filter(\n (item: { id: number }) => item.id !== wishlistItem.id\n )\n\n const formattedWishlistProducts = formatProductForWishlist(\n updatedWishlistProducts\n )\n\n await updateWishlist({\n variables: {\n wishlist: {\n id: selectedWishlist,\n products: formattedWishlistProducts,\n },\n },\n })\n}\n\nexport default deleteItemFromWishlist\n\n```"
}
] |
code_wish-list-v2_6766cca6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/getEmailID.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst getEmailID = (wishlists) => {\n const info = wishlists.map((item) => ({\n label: item.wishlistType,\n value: item.id,\n }))\n\n return info\n}\n\nexport default getEmailID\n\n```"
}
] |
code_wish-list-v2_b62b6af9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/formatProductForWishlist.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst formatProductForWishlist = (list) =>\n list.map((item) => ({\n ID: item.id,\n bundle: item.bundle,\n Image: item.image,\n unitValue: item.unitValue,\n linkProduct: item.linkProduct,\n nameProduct: item.name,\n quantityProduct: item.qty,\n skuCodeReference: item.skuReferenceCode,\n department: item.department,\n }))\n\nexport default formatProductForWishlist\n\n```"
}
] |
code_wish-list-v2_bc7042e9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/index.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport { default as extractProductData } from './extractProductData'\nexport { default as formatProductForWishlist } from './formatProductForWishlist'\nexport { default as AddProductsToCart } from './addProductsToCart'\nexport { default as deleteItemsWishlist } from './deleteItemsWishlist'\nexport { default as handleQuantityChange } from './handleQuantityChange'\nexport { default as getEmailID } from './getEmailID'\n\n```"
}
] |
code_wish-list-v2_52d72b40
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/addProductsToCart.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useContext } from 'react'\nimport { ToastContext } from 'vtex.styleguide'\nimport { useOrderItems } from 'vtex.order-items/OrderItems'\nimport { usePixel } from 'vtex.pixel-manager'\n\nimport extractProductData from './extractProductData'\n\n// function not used in the project\nconst AddProductToCart = ({ name }, wishlist) => {\n const { addItems } = useOrderItems()\n const { showToast } = useContext<any>(ToastContext)\n const { push } = usePixel()\n\n const data = extractProductData({ items: wishlist.products })\n const product = data.find((item) => name === item.name)\n\n if (!product) return\n\n const item = {\n id: product.id,\n seller: 1,\n quantity: product.quantity,\n name: product.name,\n }\n\n addItems([item])\n .then(async () => {\n push({ event: 'addToCart', id: 'addToCart' })\n showToast('Item added to the cart')\n })\n .catch((error) => console.error(error))\n}\n\nexport default AddProductToCart\n\n```"
}
] |
code_wish-list-v2_8519fdaf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/handleQuantityChange.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nconst handleQuantityChange = (setPaginatedData, newData) => {\n const newPaginatedData = newData.map((item) => {\n return {\n id: item.ID,\n image: item.Image,\n department: item.department,\n skuReferenceCode: item.skuCodeReference,\n name: item.nameProduct,\n qty: item.quantityProduct,\n unitValue: item.unitValue,\n totalValue: item.unitValue * item.quantityProduct,\n linkProduct: item.linkProduct,\n bundle: item.bundle,\n }\n })\n\n setPaginatedData(newPaginatedData)\n}\n\nexport default handleQuantityChange\n\n```"
}
] |
code_wish-list-v2_32f1b3e3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/ModalCreateList/index.jsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```jsx\nimport PropTypes from 'prop-types'\nimport React from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\nimport { Button, Input } from 'vtex.styleguide'\n\nimport ModalWishList from '../modal'\n\nimport './modalCreateList.css'\n\nconst CSS_HANDLES = [\n 'containerSelectFlexAccount',\n 'containerButtonCloseBox',\n 'buttonCloseModal',\n 'containerButtonClose',\n 'containerTitleCreateList',\n 'containerInput',\n 'containerButtonCreateList2',\n 'containerErrorAdd',\n]\n\nconst ModalCreateList = (props) => {\n const { handles } = useCssHandles(CSS_HANDLES)\n\n const handleSubmitForm = (e) => {\n e.preventDefault()\n props.handleSubmitData()\n }\n\n return (\n <ModalWishList blockClass={props.blockClass}>\n <form onSubmit={handleSubmitForm}>\n <div className={`${handles.containerSelectFlexAccount}`}>\n <div className={`${handles.containerButtonCloseBox}`}>\n <button\n // eslint-disable-next-line react/jsx-handler-names\n onClick={props.buttonCloseModal}\n className={`${handles.buttonCloseModal}`}\n type=\"button\"\n >\n X\n </button>\n </div>\n <p className={`${handles.containerTitleCreateList}`}>\n Create a name for the list\n </p>\n <Input\n className={`${handles.containerInput}`}\n type=\"text\"\n placeholder=\"List name\"\n name=\"nameList\"\n onChange={props.handleNameList}\n />\n {props.fieldValidation && (\n <p className={`${handles.containerErrorAdd}`}>\n {props.fieldValidation}\n </p>\n )}\n <Button\n onClick={props.handleSubmitData}\n type=\"submit\"\n className={`${handles.containerButtonCreateList2}`}\n variation=\"primary\"\n isLoading={props.isButtonLoading}\n >\n Create List\n </Button>\n </div>\n </form>\n </ModalWishList>\n )\n}\n\nModalCreateList.propTypes = {\n buttonCloseModal: PropTypes.func,\n handleNameList: PropTypes.func,\n fieldValidation: PropTypes.string,\n handleSubmitData: PropTypes.func,\n blockClass: PropTypes.string,\n isButtonLoading: PropTypes.bool,\n}\n\nexport default ModalCreateList\n\n```"
}
] |
code_wish-list-v2_d542ecb9
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/ModalCreateList/modalCreateList.css from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.containerSelectFlexAccount {\n display: flex;\n flex-direction: column;\n row-gap: 1rem;\n padding: 1rem;\n}\n\n.containerSelectFlexAccount :global(.vtex-styleguide-9-x-input),\n.containerSelectFlexAccount :global(.vtex-button) {\n font-size: 12px;\n}\n\n.containerTitleCreateList {\n margin: 0;\n}\n\n.containerButtonCloseBox .buttonCloseModal {\n position: absolute;\n right: 0;\n top: 0;\n border: none;\n height: 2rem;\n width: 2rem;\n font-size: 1rem;\n background: unset;\n cursor: pointer;\n}\n\n.containerButtonCloseBox .buttonCloseModal:hover {\n scale: 1.2;\n}\n```"
}
] |
code_wish-list-v2_108ce8f3
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/tableConfig/index.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { Checkbox } from 'vtex.styleguide'\n\nexport const handleNextClick = ({\n currentPage,\n setCurrentPage,\n totalItems,\n itemsPerPage,\n}) => {\n if (currentPage < Math.ceil(totalItems / itemsPerPage)) {\n setCurrentPage(Number(currentPage) + 1)\n }\n}\n\nexport const handlePrevClick = (\n currentPage: number,\n setCurrentPage: React.Dispatch<React.SetStateAction<number>>\n) => {\n if (currentPage > 1) {\n setCurrentPage(currentPage - 1)\n }\n}\n\n// Create list post\nexport const handleSubmitDataTable = async ({\n event,\n createWishlist,\n setFieldValidationTable,\n nameListAccountTable,\n setNameListAccountTable,\n setIsModalAccountTable,\n}) => {\n event.preventDefault()\n\n if (nameListAccountTable.trim() === '') {\n setFieldValidationTable('The field cannot be empty')\n } else {\n await createWishlist({\n variables: {\n wishlist: {\n wishlistType: nameListAccountTable,\n isPublic: false,\n products: [],\n },\n },\n })\n setNameListAccountTable('')\n setFieldValidationTable('')\n setNameListAccountTable(false)\n setIsModalAccountTable(false)\n }\n}\n\n// Filter Table\nexport const SelectorObject = (props: any, filterState: any) => {\n const [, setNewValueObject] = useState({})\n\n const initialValue = {\n Ascending: false,\n Descending: false,\n ...(props.value || {}),\n }\n\n const toggleValueByKey = (key) => {\n const copyInitialObject = {\n ...(props.value || initialValue),\n }\n\n const newValue = {\n ...copyInitialObject,\n [key]: copyInitialObject ? !copyInitialObject[key] : false,\n }\n\n setNewValueObject(newValue)\n\n return newValue\n }\n\n return (\n <div>\n {Object.keys(initialValue).map((opt, index) => {\n return (\n <div className=\"mb3\" key={`class-statement-object-${opt}-${index}`}>\n <Checkbox\n checked={props.value ? props?.value?.[opt] : filterState?.[opt]}\n label={opt}\n name=\"default-checkbox-group\"\n onChange={() => {\n const newValue = toggleValueByKey(`${opt}`)\n const newValueKeys = Object.keys(newValue)\n const isEmptyFilter = !newValueKeys.some(\n (key) => !newValue[key]\n )\n\n props.onChange(isEmptyFilter ? null : newValue)\n }}\n value={opt}\n />\n </div>\n )\n })}\n </div>\n )\n}\n\nexport const handleFiltersChange = ({\n statements,\n initialState,\n setInitialState,\n paginatedData,\n setPaginatedData,\n setDisplayedProducts,\n onChangeStatements,\n setfilterState,\n filterState,\n}) => {\n const newData = paginatedData ? [...paginatedData] : []\n\n if (onChangeStatements?.object) {\n const { subject, object } = onChangeStatements\n\n setfilterState({ ...filterState, [subject]: onChangeStatements })\n\n switch (subject) {\n case 'department':\n newData.sort((a, b) => {\n return object.Ascending\n ? a.department.localeCompare(b.department)\n : b.department.localeCompare(a.department)\n })\n break\n\n case 'name':\n newData.sort((a, b) => {\n return object.Ascending\n ? a.name.localeCompare(b.name)\n : b.name.localeCompare(a.name)\n })\n break\n\n default:\n // Manejar caso no reconocido\n break\n }\n }\n\n setPaginatedData(newData)\n setDisplayedProducts(newData)\n\n if (statements.length <= 0) {\n return\n }\n\n const newDataLength = newData.length\n const { tableLength } = initialState\n const newSlicedData = newData.slice(0, tableLength)\n\n setInitialState((prevState) => ({\n ...prevState,\n filterStatements: statements,\n slicedData: newSlicedData,\n itemsLength: newDataLength,\n currentItemTo: Math.min(tableLength, newDataLength),\n }))\n}\n\n```"
}
] |
code_wish-list-v2_f8d39d96
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/components/helpers/tableSearch/index.js from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```javascript\nexport const handleInputSearchChange = ({\n e,\n allProducts,\n setSearchValue,\n setDisplayedProducts,\n}) => {\n const { value } = e.target\n\n setSearchValue(value)\n\n if (!value) {\n setDisplayedProducts(allProducts)\n } else {\n const filteredProducts = allProducts.filter((product) => {\n const valueLower = value.toLowerCase()\n const nameMatches = product.name.toLowerCase().includes(valueLower)\n const departmentMatches = product.department\n .toLowerCase()\n .includes(valueLower)\n\n const skuMatches = product.skuReferenceCode\n .toLowerCase()\n .includes(valueLower)\n\n return nameMatches || departmentMatches || skuMatches\n })\n\n setDisplayedProducts(filteredProducts)\n }\n}\n\nexport const handleInputSearchClear = (setDisplayedProducts, allProducts) =>\n setDisplayedProducts(allProducts)\n\nexport const handleInputSearchSubmit = ({\n e,\n allProducts,\n searchValue,\n setDisplayedProducts,\n}) => {\n e.preventDefault()\n\n if (!searchValue) {\n setDisplayedProducts(allProducts)\n } else {\n const filteredProducts = allProducts.filter((product) => {\n const searchValueLower = searchValue.toLowerCase()\n const nameMatches = product.name.toLowerCase().includes(searchValueLower)\n const departmentMatches = product.department\n .toLowerCase()\n .includes(searchValueLower)\n\n const skuMatches = product.skuReferenceCode\n .toLowerCase()\n .includes(searchValueLower)\n\n return nameMatches || departmentMatches || skuMatches\n })\n\n setDisplayedProducts(filteredProducts)\n }\n}\n\n```"
}
] |
code_wish-list-v2_c29266d0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/mutations/updateWishlist.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateWishlist($wishlist: WishlistInput!) {\n updateWishlist(wishlist: $wishlist) {\n id\n success\n }\n}\n\n```"
}
] |
code_wish-list-v2_7805b938
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/mutations/deleteWishlist.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation deleteWishlist($id: ID!){\n deleteWishlist(id: $id){\n id\n success\n }\n}\n\n```"
}
] |
code_wish-list-v2_32b9467c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/mutations/createWishlist.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation createWishlist($wishlist: WishlistInput!) {\n createWishlist(wishlist: $wishlist) {\n Id\n Href\n DocumentId\n }\n}\n\n```"
}
] |
code_wish-list-v2_ca73102a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/queries/getWishlistById.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getWishlist($id: ID!) {\n getWishlist(id: $id) {\n id\n email\n wishlistType\n isPublic\n fieldsConfig {\n description\n department\n }\n products {\n ID\n Image\n linkProduct\n nameProduct\n quantityProduct\n skuCodeReference\n department\n bundle\n notes\n }\n }\n}\n\n```"
}
] |
code_wish-list-v2_3c4c0cb8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/queries/getWishlists.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getWishlists($page: Int, $pageSize: Int) {\n getWishlistsByEmail(page: $page, pageSize: $pageSize) {\n id\n email\n wishlistType\n isPublic\n fieldsConfig {\n department\n description\n }\n products {\n ID\n Image\n linkProduct\n nameProduct\n quantityProduct\n skuCodeReference\n department\n bundle\n notes\n }\n }\n}\n\n```"
}
] |
code_wish-list-v2_2eaa9db0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/queries/getPriceBySkuId.gql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getPriceBySkuId(\n $skuId: Int\n $skuReference: String\n $productQuantity: Int\n) {\n getPriceBySkuId(\n skuId: $skuId\n skuReference: $skuReference\n productQuantity: $productQuantity\n ) {\n itemId\n listPrice\n costPrice\n markup\n basePrice\n }\n}\n\n```"
}
] |
code_wish-list-v2_10813317
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/graphql/queries/productPrice.graphql from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery ProductPrice($identifier: ProductUniqueIdentifier) {\n product(identifier: $identifier) @context(provider: \"vtex.search-graphql\") {\n productName\n description\n items {\n itemId\n name\n referenceId {\n Key\n Value\n }\n sellers {\n commertialOffer {\n Price\n }\n }\n }\n }\n}\n\n```"
}
] |
code_wish-list-v2_8c307996
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useQueryWishlistById.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useQuery } from 'react-apollo'\n\nimport GET_WISHLIST from '../../graphql/queries/getWishlistById.gql'\n\nconst useQueryWishlistById = (id: string, callback: (data: any) => void) => {\n const { refetch } = useQuery(GET_WISHLIST, {\n skip: !id,\n variables: { id },\n onCompleted: async (data) => {\n await callback(data)\n },\n fetchPolicy: 'network-only',\n })\n\n return {\n refetch,\n }\n}\n\nexport default useQueryWishlistById\n\n```"
}
] |
code_wish-list-v2_13b0d623
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useQueryGetProductPrice.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useQuery } from 'react-apollo'\n\nimport PRODUCT_QUERY from '../../graphql/queries/productPrice.graphql'\n\nconst useQueryWishlists = (field: string, itemId: number, quantity: number) => {\n const { data, error, loading } = useQuery(PRODUCT_QUERY, {\n variables: {\n identifier: { field, value: itemId },\n },\n notifyOnNetworkStatusChange: true,\n })\n\n const unitPrice = (data?.product.items ?? [])\n .find((item) => item.itemId === itemId?.toString())\n ?.sellers?.find((seller) => seller)?.commertialOffer?.Price\n\n const price = unitPrice ? unitPrice * quantity : 0\n\n return {\n price,\n loading,\n error,\n }\n}\n\nexport default useQueryWishlists\n\n```"
}
] |
code_wish-list-v2_776cd4c2
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useQueryWishlists.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useQuery } from 'react-apollo'\nimport { useEffect } from 'react'\n\nimport GET_WISHLISTS from '../../graphql/queries/getWishlists.gql'\n\nconst useQueryWishlists = () => {\n const { data, loading, error, refetch } = useQuery(GET_WISHLISTS, {\n fetchPolicy: 'network-only',\n })\n\n useEffect(() => {\n let retryCount = 0\n const maxRetries = 3\n const retryTimeout = 1000\n\n const handleRetry = async () => {\n if (error && retryCount < maxRetries) {\n retryCount += 1\n await new Promise((resolve) => setTimeout(resolve, retryTimeout))\n refetch()\n }\n }\n\n handleRetry()\n }, [error, refetch])\n\n return {\n data,\n loading,\n error,\n refetch,\n }\n}\n\nexport default useQueryWishlists\n\n```"
}
] |
code_wish-list-v2_daec9336
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useQueryProductByIdentifier.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useQuery } from 'react-apollo'\n\nimport PRODUCT_QUERY from '../../graphql/queries/productPrice.graphql'\n\nconst useQueryProductByIdentifier = (field: string, itemId: number) => {\n const { data, error, loading } = useQuery(PRODUCT_QUERY, {\n variables: {\n identifier: { field, value: itemId },\n },\n notifyOnNetworkStatusChange: true,\n })\n\n const getProperty = (name: string) => {\n const selectedSku = data?.product?.items?.find(\n (item) => item.itemId === itemId?.toString()\n )\n\n if (name === 'productName') return data?.product?.productName\n if (name === 'productDescription') return data?.product?.description\n if (name === 'productNameWithSkuName')\n return `${data?.product?.productName} - ${selectedSku?.name ?? ''}`\n\n return ''\n }\n\n return {\n data,\n getProperty,\n loading,\n error,\n }\n}\n\nexport default useQueryProductByIdentifier\n\n```"
}
] |
code_wish-list-v2_cfb9d678
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useMutationUpdateWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useMutation } from 'react-apollo'\n\nimport UPDATE_WISHLIST from '../../graphql/mutations/updateWishlist.gql'\n\nconst useMutationUpdateWishlist = (callback) => {\n const [updateWishlist] = useMutation(UPDATE_WISHLIST, {\n onCompleted: async () => {\n await callback()\n },\n })\n\n return {\n updateWishlist,\n }\n}\n\nexport default useMutationUpdateWishlist\n\n```"
}
] |
code_wish-list-v2_d5d95f1b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useMutationCreateWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useMutation } from 'react-apollo'\n\nimport CREATE_WISHLIST from '../../graphql/mutations/createWishlist.gql'\n\nconst useMutationCreateWishlist = (callback: (data: any) => void) => {\n const [createWishlist] = useMutation(CREATE_WISHLIST, {\n onCompleted: callback,\n })\n\n return {\n createWishlist,\n }\n}\n\nexport default useMutationCreateWishlist\n\n```"
}
] |
code_wish-list-v2_113b50be
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of wish-list-v2/react/hooks/actions/useMutationDeleteWishlist.tsx from the wish-list-v2 VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { useMutation } from 'react-apollo'\n\nimport DELETE_WISHLIST from '../../graphql/mutations/deleteWishlist.gql'\n\nconst useMutationDeleteWishlist = (\n wishlistId: string,\n callback: () => void\n) => {\n const [deleteWishlist, { loading, error }] = useMutation(DELETE_WISHLIST, {\n variables: {\n id: wishlistId,\n },\n onCompleted: callback,\n })\n\n return { deleteWishlist, loading, error }\n}\n\nexport default useMutationDeleteWishlist\n\n```"
}
] |
code_organizations_f9d3f55d
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/hu.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"Saját szervezet\",\n \"store/my-organization.add-user.title\": \"Új felhasználó hozzáadása\",\n \"store/my-organization.edit-user.title\": \"Felhasználó szerkesztése\",\n \"store/my-organization.add-user\": \"Felhasználó hozzáadása\",\n \"store/my-organization.email\": \"E-mail-cím\",\n \"store/my-organization.budget-amount\": \"Költségvetés összege\",\n \"store/my-organization.role-id\": \"Szerep\",\n \"store/my-organization.errors.role-id.empty\": \"A szerep üres\",\n \"store/my-organization.errors.email.empty\": \"Az e-mail-cím üres\",\n \"store/my-organization.errors.email.exists\": \"A felhasználó már létezik\",\n \"store/my-organization.errors.email.invalid\": \"Az e-mail-cím érvénytelen\",\n \"store/my-organization.success\": \"A felhasználó hozzáadása sikeres\",\n \"store/my-organization.errors.organization.text\": \"Szervezet\",\n \"store/my-organization.button.cancel\": \"Mégse\",\n \"store/my-organization.button.save\": \"Mentés\",\n \"store/my-organization.label.email\": \"E-mail\",\n \"store/my-organization.button.ok\": \"Rendben\",\n \"store/my-organization.input.placeholder.organizationName\": \"A szervezet neve\",\n \"store/my-organization.input.label.organizationName\": \"Név\",\n \"store/my-organization.input.placeholder.telephone\": \"A szervezet telefonszáma\",\n \"store/my-organization.input.label.telephone\": \"Telefonszám\",\n \"store/my-organization.input.placeholder.address\": \"A szervezet címe\",\n \"store/my-organization.input.label.address\": \"Cím\",\n \"store/my-organization.input.placeholder.email\": \"A szervezet e-mail-címe\",\n \"store/my-organization.input.label.email\": \"E-mail\",\n \"store/my-organization.my-organization.create-new-organization\": \"Szervezet létrehozása\",\n \"store/my-organization.my-organization.organization\": \"Szervezeti adatok\",\n \"store/my-organization.my-organization.organization.name\": \"Név\",\n \"store/my-organization.my-organization.organization.telephone\": \"Telefonszám\",\n \"store/my-organization.my-organization.organization.address\": \"Cím\",\n \"store/my-organization.my-organization.organization.email\": \"E-mail\",\n \"store/my-organization.my-organization.role\": \"Felhasználói szerep\",\n \"store/my-organization.my-organization.leave\": \"Kilépés\",\n \"store/my-organization.my-organization.delete\": \"Törlése\",\n \"store/my-organization.my-organization.users-in-organization\": \"A szervezet felhasználói\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Nem lehet kilépni a szervezetből\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"Nem tud kilépni a szervezetből: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"Mielőtt kilép a szervezetből, át kell adnia a „Vezető” szerepet\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"Mielőtt kilép a szervezetből, át kell adnia a „Szervezeti adminisztrátor” szerepet\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"Nem lehet törölni a szervezetet\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"Egynél több hozzárendelt felhasználóval rendelkezik a szervezet: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"A szervezet törlése előtt törölje az összes felhasználót\",\n \"store/my-organization.my-organization.user.already.assigned\": \"Nem lehet hozzáadni ezt a felhasználót\",\n \"store/my-organization.my-organization.button.leave\": \"Kilépés\",\n \"store/my-organization.my-organization.leave.message\": \"El szeretné hagyni a következő szervezetet: \",\n \"store/my-organization.my-organization.button.delete\": \"Törlése\",\n \"store/my-organization.my-organization.delete.message\": \"Törölni szeretné hagyni a következő szervezetet: \",\n \"store/my-organization.my-user.table-title.email\": \"E-mail\",\n \"store/my-organization.my-user.table-title.status\": \"Állapot\",\n \"store/my-organization.my-user.table-title.role\": \"Szerep\",\n \"store/my-organization.my-user.table-title.invite\": \"Meghívás\",\n \"store/my-organization.my-user.table-title.edit\": \"Szerkesztés\",\n \"store/my-organization.my-user.table-title.delete\": \"Törlése\",\n \"store/my-organization.my-user.table.button.add-new\": \"Új hozzáadása\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Törlése\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Szeretné törölni a következő felhasználót: \",\n \"store/my-organization.toast.organization.create.error\": \"Nem lehet létrehozni a szervezetet a következő ok miatt:\",\n \"store/my-organization.toast.organization.leave.error\": \"Nem lehet elhagyni a szervezetet a következő ok miatt:\",\n \"store/my-organization.toast.organization.delete.error\": \"Nem lehet törölni a szervezetet a következő ok miatt:\",\n \"store/my-organization.toast.user.create.error\": \"Nem lehet létrehozni a felhasználót a következő ok miatt:\",\n \"store/my-organization.toast.user.edit.error\": \"Nem lehet létrehozni a felhasználót a következő ok miatt:\",\n \"store/my-organization.toast.user.delete.error\": \"Nem lehet törölni a felhasználót a következő ok miatt:\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Ismételt meghívó elküldve\",\n \"store/my-organization.toast.user.reinvitation.error\": \"Ismételt meghívó sikertelen, \",\n \"store/my-organization.my-organization.reload-message\": \"A módosításokat sikeresen alkalmazták, eltarthat egy ideig, amíg azok életbe lépnek\",\n \"store/my-organization.my-organization.organization.title\": \"Saját szervezet\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"VISSZA\",\n \"store/my-organization.my-organization.status.approved\": \"Jóváhagyva\",\n \"store/my-organization.my-organization.status.not-approved\": \"Nincs jóváhagyva\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Szervezeti adminisztrátor\",\n \"store/my-organization.my-organization.showMore\": \"Több megjelenítése\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"Még nincs hozzárendelve egyetlen szervezethez sem.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Kérjen jogosultságot egy szervezet létrehozásához, ha Ön adminisztrátor.\"\n}\n\n```"
}
] |
code_organizations_bd59f4bd
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/fi.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"Oma organisaatio\",\n \"store/my-organization.add-user.title\": \"Lisää uusi käyttäjä\",\n \"store/my-organization.edit-user.title\": \"Muokkaa käyttäjää\",\n \"store/my-organization.add-user\": \"Lisää käyttäjä\",\n \"store/my-organization.email\": \"Sähköpostiosoite\",\n \"store/my-organization.budget-amount\": \"Budjetin summa\",\n \"store/my-organization.role-id\": \"Rooli\",\n \"store/my-organization.errors.role-id.empty\": \"Rooli on tyhjä\",\n \"store/my-organization.errors.email.empty\": \"Sähköpostiosoite on tyhjä\",\n \"store/my-organization.errors.email.exists\": \"Käyttäjä on jo olemassa\",\n \"store/my-organization.errors.email.invalid\": \"Sähköpostiosoite on virheellinen\",\n \"store/my-organization.success\": \"Käyttäjän lisääminen onnistui\",\n \"store/my-organization.errors.organization.text\": \"Organisaatio\",\n \"store/my-organization.button.cancel\": \"Peruuta\",\n \"store/my-organization.button.save\": \"Tallenna\",\n \"store/my-organization.label.email\": \"Sähköpostiosoite\",\n \"store/my-organization.button.ok\": \"Ok\",\n \"store/my-organization.input.placeholder.organizationName\": \"Organisaation nimi\",\n \"store/my-organization.input.label.organizationName\": \"Nimi\",\n \"store/my-organization.input.placeholder.telephone\": \"Organisaation puhelinnumero\",\n \"store/my-organization.input.label.telephone\": \"Puhelinnumero\",\n \"store/my-organization.input.placeholder.address\": \"Organisaation osoite\",\n \"store/my-organization.input.label.address\": \"Osoite\",\n \"store/my-organization.input.placeholder.email\": \"Organisaation sähköpostiosoite\",\n \"store/my-organization.input.label.email\": \"Sähköpostiosoite\",\n \"store/my-organization.my-organization.create-new-organization\": \"Luo organisaatio\",\n \"store/my-organization.my-organization.organization\": \"Organisaation tiedot\",\n \"store/my-organization.my-organization.organization.name\": \"Nimi\",\n \"store/my-organization.my-organization.organization.telephone\": \"Puhelinnumero\",\n \"store/my-organization.my-organization.organization.address\": \"Osoite\",\n \"store/my-organization.my-organization.organization.email\": \"Sähköpostiosoite\",\n \"store/my-organization.my-organization.role\": \"Käyttäjärooli\",\n \"store/my-organization.my-organization.leave\": \"Poistu\",\n \"store/my-organization.my-organization.delete\": \"Poista\",\n \"store/my-organization.my-organization.users-in-organization\": \"Organisaation käyttäjät\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Ei voida poistua organisaatiosta\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"Et voi poistua organisaatiosta: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"Sinun tulee siirtää johtajan rooli ennen organisaatiosta poistumista\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"Sinun tulee siirtää organisaation järjestelmänvalvojan rooli ennen organisaatiosta poistumista\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"Organisaatiota ei voida poistaa\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"Organisaatiossa on useampi kuin yksi määritetty käyttäjä: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"Poista kaikki käyttäjät ennen organisaation poistamista\",\n \"store/my-organization.my-organization.user.already.assigned\": \"Tätä käyttäjää ei voida lisätä\",\n \"store/my-organization.my-organization.button.leave\": \"Poistu\",\n \"store/my-organization.my-organization.leave.message\": \"Haluatko poistua organisaatiosta: \",\n \"store/my-organization.my-organization.button.delete\": \"Poista\",\n \"store/my-organization.my-organization.delete.message\": \"Haluatko poistaa organisaation: \",\n \"store/my-organization.my-user.table-title.email\": \"Sähköpostiosoite\",\n \"store/my-organization.my-user.table-title.status\": \"Tila\",\n \"store/my-organization.my-user.table-title.role\": \"Rooli\",\n \"store/my-organization.my-user.table-title.invite\": \"Kutsu\",\n \"store/my-organization.my-user.table-title.edit\": \"Muokkaa\",\n \"store/my-organization.my-user.table-title.delete\": \"Poista\",\n \"store/my-organization.my-user.table.button.add-new\": \"Lisää uusi\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Poista\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Haluatko poistaa käyttäjän: \",\n \"store/my-organization.toast.organization.create.error\": \"Organisaatiota ei voida luoda, koska\",\n \"store/my-organization.toast.organization.leave.error\": \"Organisaatiosta ei voida poistua, koska\",\n \"store/my-organization.toast.organization.delete.error\": \"Organisaatiota ei voida poistaa, koska\",\n \"store/my-organization.toast.user.create.error\": \"Käyttäjää ei voida luoda, koska\",\n \"store/my-organization.toast.user.edit.error\": \"Käyttäjää ei voida luoda, koska\",\n \"store/my-organization.toast.user.delete.error\": \"Poistoa ei voida luoda, koska\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Kutsu lähetetty uudelleen\",\n \"store/my-organization.toast.user.reinvitation.error\": \"Kutsun lähettäminen uudelleen epäonnistui, \",\n \"store/my-organization.my-organization.reload-message\": \"Tekemäsi muutokset on otettu käyttöön, niiden voimaan tulossa voi kestää hetki\",\n \"store/my-organization.my-organization.organization.title\": \"Oma organisaatio\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"PALAA\",\n \"store/my-organization.my-organization.status.approved\": \"Hyväksytty\",\n \"store/my-organization.my-organization.status.not-approved\": \"Ei hyväksytty\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Organisaation järjestelmänvalvoja\",\n \"store/my-organization.my-organization.showMore\": \"Näytä lisää\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"Sinua ei ole vielä määrätty mihinkään organisaatioon.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Pyydä oikeus luoda organisaatio, jos olet järjestelmänvalvoja.\"\n}\n\n```"
}
] |
code_organizations_0d8522c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/pt.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"Minha Organização\",\n \"store/my-organization.add-user.title\": \"Adicionar usuário\",\n \"store/my-organization.edit-user.title\": \"Editar usuário\",\n \"store/my-organization.add-user\": \"Adicionar usuário\",\n \"store/my-organization.email\": \"Endereço de e-mail\",\n \"store/my-organization.budget-amount\": \"Orçamento total\",\n \"store/my-organization.role-id\": \"Função\",\n \"store/my-organization.errors.role-id.empty\": \"A função está vazia\",\n \"store/my-organization.errors.email.empty\": \"O e-mail está vazio\",\n \"store/my-organization.errors.email.exists\": \"O usuário já existe\",\n \"store/my-organization.errors.email.invalid\": \"O e-mail é inválido\",\n \"store/my-organization.success\": \"Usuário adicionado com sucesso\",\n \"store/my-organization.errors.organization.text\": \"Organização\",\n \"store/my-organization.button.cancel\": \"Cancelar\",\n \"store/my-organization.button.save\": \"Salvar\",\n \"store/my-organization.label.email\": \"E-mail\",\n \"store/my-organization.button.ok\": \"Confirmar\",\n \"store/my-organization.input.placeholder.organizationName\": \"Nome da organização\",\n \"store/my-organization.input.label.organizationName\": \"Nome\",\n \"store/my-organization.input.placeholder.telephone\": \"Número de telefone da organização\",\n \"store/my-organization.input.label.telephone\": \"Telefone\",\n \"store/my-organization.input.placeholder.address\": \"Endereço da organização\",\n \"store/my-organization.input.label.address\": \"Endereço\",\n \"store/my-organization.input.placeholder.email\": \"Endereço de e-mail da organização\",\n \"store/my-organization.input.label.email\": \"E-mail\",\n \"store/my-organization.my-organization.create-new-organization\": \"Criar nova organização\",\n \"store/my-organization.my-organization.organization\": \"Info Organização\",\n \"store/my-organization.my-organization.organization.name\": \"Nome\",\n \"store/my-organization.my-organization.organization.telephone\": \"Telefone\",\n \"store/my-organization.my-organization.organization.address\": \"Endereço\",\n \"store/my-organization.my-organization.organization.email\": \"E-mail\",\n \"store/my-organization.my-organization.role\": \"Função\",\n \"store/my-organization.my-organization.leave\": \"Sair\",\n \"store/my-organization.my-organization.delete\": \"Apagar\",\n \"store/my-organization.my-organization.users-in-organization\": \"Usuários na organização\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Não foi possível deixar a organização\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"Você não consegue sair da organização: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"Você deve transferir a função \\\"Gerente\\\" antes de sair da organização\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"Você deve transferir o papel de \\\"organização admin\\\" antes de sair da organização\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"Não foi possível excluir a organização\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"Você tem mais de um usuário atribuído na organização: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"Exclua todos os usuários antes de excluir esta organização\",\n \"store/my-organization.my-organization.user.already.assigned\": \"Esse usuário já pertence a outra organização\",\n \"store/my-organization.my-organization.button.leave\": \"Sair\",\n \"store/my-organization.my-organization.leave.message\": \"Deseja sair da organização: \",\n \"store/my-organization.my-organization.button.delete\": \"Apagar\",\n \"store/my-organization.my-organization.delete.message\": \"Deseja excluir a organização: \",\n \"store/my-organization.my-user.table-title.email\": \"E-mail\",\n \"store/my-organization.my-user.table-title.status\": \"Status\",\n \"store/my-organization.my-user.table-title.role\": \"Função\",\n \"store/my-organization.my-user.table-title.invite\": \"Convite\",\n \"store/my-organization.my-user.table-title.edit\": \"Editar\",\n \"store/my-organization.my-user.table-title.delete\": \"Apagar\",\n \"store/my-organization.my-user.table.button.add-new\": \"Adicionar novo\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Apagar\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Deseja excluir o usuário:\",\n \"store/my-organization.toast.organization.create.error\": \"Não foi possível criar organização porque\",\n \"store/my-organization.toast.organization.leave.error\": \"Não foi possível sair da organização porque\",\n \"store/my-organization.toast.organization.delete.error\": \"Não foi possível remover organização porque\",\n \"store/my-organization.toast.user.create.error\": \"Não foi possível criar usuário porque\",\n \"store/my-organization.toast.user.edit.error\": \"Não foi possível editar usuário porque\",\n \"store/my-organization.toast.user.delete.error\": \"Não foi possível remover usuário porque\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Convite enviado\",\n \"store/my-organization.toast.user.reinvitation.error\": \"O convite falhou, \",\n \"store/my-organization.my-organization.reload-message\": \"Suas alterações foram aplicadas com sucesso, pode demorar um momento até que sejam refletidas\",\n \"store/my-organization.my-organization.organization.title\": \"Minha Organização\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"Retornar\",\n \"store/my-organization.my-organization.status.approved\": \"Aprovado\",\n \"store/my-organization.my-organization.status.not-approved\": \"Não Aprovado\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Organização Admin\",\n \"store/my-organization.my-organization.showMore\": \"Ver mais\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"Você ainda não foi atribuído a nenhuma organização.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Solicite permissão para criar uma organização se você for um administrador.\"\n}\n\n```"
}
] |
code_organizations_d6b63fee
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/en.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"My Organization\",\n \"store/my-organization.add-user.title\": \"Add new user\",\n \"store/my-organization.edit-user.title\": \"Edit user\",\n \"store/my-organization.add-user\": \"Add User\",\n \"store/my-organization.email\": \"Email Address\",\n \"store/my-organization.budget-amount\": \"Budget Amount\",\n \"store/my-organization.role-id\": \"Role\",\n \"store/my-organization.errors.role-id.empty\": \"Role is empty\",\n \"store/my-organization.errors.email.empty\": \"Email is empty\",\n \"store/my-organization.errors.email.exists\": \"User already exists\",\n \"store/my-organization.errors.email.invalid\": \"Email is invalid\",\n \"store/my-organization.success\": \"User added successfully\",\n \"store/my-organization.errors.organization.text\": \"Organization\",\n \"store/my-organization.button.cancel\": \"Cancel\",\n \"store/my-organization.button.save\": \"Save\",\n \"store/my-organization.label.email\": \"Email\",\n \"store/my-organization.button.ok\": \"Ok\",\n \"store/my-organization.input.placeholder.organizationName\": \"Name of the organization\",\n \"store/my-organization.input.label.organizationName\": \"Name\",\n \"store/my-organization.input.placeholder.telephone\": \"Telephone number of the organization\",\n \"store/my-organization.input.label.telephone\": \"Telephone\",\n \"store/my-organization.input.placeholder.address\": \"Address of the organization\",\n \"store/my-organization.input.label.address\": \"Address\",\n \"store/my-organization.input.placeholder.email\": \"Email address of the organization\",\n \"store/my-organization.input.label.email\": \"Email\",\n \"store/my-organization.my-organization.create-new-organization\": \"Create organization\",\n \"store/my-organization.my-organization.organization\": \"Organization info\",\n \"store/my-organization.my-organization.organization.name\": \"Name\",\n \"store/my-organization.my-organization.organization.telephone\": \"Telephone\",\n \"store/my-organization.my-organization.organization.address\": \"Address\",\n \"store/my-organization.my-organization.organization.email\": \"Email\",\n \"store/my-organization.my-organization.role\": \"User role\",\n \"store/my-organization.my-organization.leave\": \"Leave\",\n \"store/my-organization.my-organization.delete\": \"Delete\",\n \"store/my-organization.my-organization.users-in-organization\": \"Users in organization\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Unable to leave organization\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"You are unable to leave organization: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"You should transfer \\\"Manager\\\" role before leaving the organization\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"You should transfer \\\"organization admin\\\" role before leaving the organization\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"Unable to delete organization\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"You have more than one assigned users in organization: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"Please delete all the users before deleting this organization\",\n \"store/my-organization.my-organization.user.already.assigned\": \"This user cannot be added\",\n \"store/my-organization.my-organization.button.leave\": \"Leave\",\n \"store/my-organization.my-organization.leave.message\": \"Do you want to leave organization: \",\n \"store/my-organization.my-organization.button.delete\": \"Delete\",\n \"store/my-organization.my-organization.delete.message\": \"Do you want to delete organization: \",\n \"store/my-organization.my-user.table-title.email\": \"Email\",\n \"store/my-organization.my-user.table-title.status\": \"Status\",\n \"store/my-organization.my-user.table-title.role\": \"Role\",\n \"store/my-organization.my-user.table-title.invite\": \"Invite\",\n \"store/my-organization.my-user.table-title.edit\": \"Edit\",\n \"store/my-organization.my-user.table-title.delete\": \"Delete\",\n \"store/my-organization.my-user.table.button.add-new\": \"Add New\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Delete\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Do you want to delete user: \",\n \"store/my-organization.toast.organization.create.error\": \"Can't create organization because\",\n \"store/my-organization.toast.organization.leave.error\": \"Can't leave organization because\",\n \"store/my-organization.toast.organization.delete.error\": \"Can't delete organization because\",\n \"store/my-organization.toast.user.create.error\": \"Can't create user because\",\n \"store/my-organization.toast.user.edit.error\": \"Can't create user because\",\n \"store/my-organization.toast.user.delete.error\": \"Can't create delete because\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Re invitation sent\",\n \"store/my-organization.toast.user.reinvitation.error\": \"Re invitation failed, \",\n \"store/my-organization.my-organization.reload-message\": \"Your changes have been applied successfully, it may take a while to reflect them\",\n \"store/my-organization.my-organization.organization.title\": \"My Organization\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"RETURN\",\n \"store/my-organization.my-organization.status.approved\": \"Approved\",\n \"store/my-organization.my-organization.status.not-approved\": \"Not Approved\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Organization Admin\",\n \"store/my-organization.my-organization.showMore\": \"Show More\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"You are not yet assigned to any organization.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Please request permission to create an organization if you are an administrator.\"\n}\n\n```"
}
] |
code_organizations_7cd4eb43
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/context.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"My Organization\",\n \"store/my-organization.add-user.title\": \"Add new user\",\n \"store/my-organization.edit-user.title\": \"Edit user\",\n \"store/my-organization.add-user\": \"Add User\",\n \"store/my-organization.email\": \"Email Address\",\n \"store/my-organization.budget-amount\": \"Budget Amount\",\n \"store/my-organization.role-id\": \"Role\",\n \"store/my-organization.errors.role-id.empty\": \"Role is empty\",\n \"store/my-organization.errors.email.empty\": \"Email is empty\",\n \"store/my-organization.errors.email.exists\": \"User already exists\",\n \"store/my-organization.errors.email.invalid\": \"Email is invalid\",\n \"store/my-organization.success\": \"User added successfully\",\n \"store/my-organization.errors.organization.text\": \"My Organization\",\n \"store/my-organization.button.cancel\": \"Cancel\",\n \"store/my-organization.button.save\": \"Save\",\n \"store/my-organization.label.email\": \"Email\",\n \"store/my-organization.button.ok\": \"Ok\",\n \"store/my-organization.input.placeholder.organizationName\": \"Name of the organization\",\n \"store/my-organization.input.label.organizationName\": \"Name\",\n \"store/my-organization.input.placeholder.telephone\": \"Telephone number of the organization\",\n \"store/my-organization.input.label.telephone\": \"Telephone\",\n \"store/my-organization.input.placeholder.address\": \"Address of the organization\",\n \"store/my-organization.input.label.address\": \"Address\",\n \"store/my-organization.input.placeholder.email\": \"Email address of the organization\",\n \"store/my-organization.input.label.email\": \"Email\",\n \"store/my-organization.my-organization.create-new-organization\": \"Create new organization\",\n \"store/my-organization.my-organization.organization\": \"Organization info\",\n \"store/my-organization.my-organization.organization.name\": \"Name\",\n \"store/my-organization.my-organization.organization.telephone\": \"Telephone\",\n \"store/my-organization.my-organization.organization.address\": \"Address\",\n \"store/my-organization.my-organization.organization.email\": \"Email\",\n \"store/my-organization.my-organization.role\": \"User role\",\n \"store/my-organization.my-organization.leave\": \"Leave\",\n \"store/my-organization.my-organization.delete\": \"Delete\",\n \"store/my-organization.my-organization.users-in-organization\": \"Users in organization\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Unable to leave organization\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"You are unable to leave organization: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"You should transfer \\\"Manager\\\" role before leaving the organization\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"You should transfer \\\"organization admin\\\" role before leaving the organization\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"Unable to delete organization\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"You have more than one assigned users in organization: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"Please delete all the users before deleting this organization\",\n \"store/my-organization.my-organization.user.already.assigned\": \"This user cannot be added\",\n \"store/my-organization.my-organization.button.leave\": \"Leave\",\n \"store/my-organization.my-organization.leave.message\": \"Do you want to leave organization: \",\n \"store/my-organization.my-organization.button.delete\": \"Delete\",\n \"store/my-organization.my-organization.delete.message\": \"Do you want to delete organization: \",\n \"store/my-organization.my-user.table-title.email\": \"Email\",\n \"store/my-organization.my-user.table-title.status\": \"Status\",\n \"store/my-organization.my-user.table-title.role\": \"Role\",\n \"store/my-organization.my-user.table-title.invite\": \"Invite\",\n \"store/my-organization.my-user.table-title.edit\": \"Edit\",\n \"store/my-organization.my-user.table-title.delete\": \"Delete\",\n \"store/my-organization.my-user.table.button.add-new\": \"Add New\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Delete\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Do you want to delete user: \",\n \"store/my-organization.toast.organization.create.error\": \"Can't create organization because\",\n \"store/my-organization.toast.organization.leave.error\": \"Can't leave organization because\",\n \"store/my-organization.toast.organization.delete.error\": \"Can't delete organization because\",\n \"store/my-organization.toast.user.create.error\": \"Can't create user because\",\n \"store/my-organization.toast.user.edit.error\": \"Can't create user because\",\n \"store/my-organization.toast.user.delete.error\": \"Can't create delete because\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Re invitation sent\",\n \"store/my-organization.toast.user.reinvitation.error\": \"Re invitation failed, \",\n \"store/my-organization.my-organization.reload-message\": \"Your changes have been applied successfully, it may take a while to reflect them\",\n \"store/my-organization.my-organization.organization.title\": \"My Organization\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"RETURN\",\n \"store/my-organization.my-organization.status.approved\": \"Approved\",\n \"store/my-organization.my-organization.status.not-approved\": \"Not Approved\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Organization Admin\",\n \"store/my-organization.my-organization.showMore\": \"Show More\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"You are not yet assigned to any organization.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Please request permission to create an organization if you are an administrator.\"\n}\n```"
}
] |
code_organizations_768c32b1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/es.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"Mi Organización\",\n \"store/my-organization.add-user.title\": \"Añadir nuevo usuario\",\n \"store/my-organization.edit-user.title\": \"Editar usuario\",\n \"store/my-organization.add-user\": \"Agregar usuario\",\n \"store/my-organization.email\": \"Dirección de correo electrónico\",\n \"store/my-organization.budget-amount\": \"Cantidad de presupuesto\",\n \"store/my-organization.role-id\": \"Papel\",\n \"store/my-organization.errors.role-id.empty\": \"El rol está vacío.\",\n \"store/my-organization.errors.email.empty\": \"El correo esta vacio\",\n \"store/my-organization.errors.email.exists\": \"User already exists\",\n \"store/my-organization.errors.email.invalid\": \"El correo electrónico es invalido\",\n \"store/my-organization.success\": \"Usuario agregado exitosamente\",\n \"store/my-organization.errors.organization.text\": \"Organización\",\n \"store/my-organization.button.cancel\": \"Cancelar\",\n \"store/my-organization.button.save\": \"Guardar\",\n \"store/my-organization.label.email\": \"Correo Electrónico\",\n \"store/my-organization.button.ok\": \"Bien\",\n \"store/my-organization.input.placeholder.organizationName\": \"Nombre de la organización\",\n \"store/my-organization.input.label.organizationName\": \"Nombre\",\n \"store/my-organization.input.placeholder.telephone\": \"Número de teléfono de la organización.\",\n \"store/my-organization.input.label.telephone\": \"Teléfono\",\n \"store/my-organization.input.placeholder.address\": \"Dirección de la organización.\",\n \"store/my-organization.input.label.address\": \"Habla a\",\n \"store/my-organization.input.placeholder.email\": \"Dirección de correo electrónico de la organización.\",\n \"store/my-organization.input.label.email\": \"Correo Electrónico\",\n \"store/my-organization.my-organization.create-new-organization\": \"Crear nueva organización\",\n \"store/my-organization.my-organization.organization\": \"Organización info\",\n \"store/my-organization.my-organization.organization.name\": \"Nombre\",\n \"store/my-organization.my-organization.organization.telephone\": \"Teléfono\",\n \"store/my-organization.my-organization.organization.address\": \"Dirección\",\n \"store/my-organization.my-organization.organization.email\": \"Correo Electrónico\",\n \"store/my-organization.my-organization.role\": \"Papel de Usuario\",\n \"store/my-organization.my-organization.leave\": \"Salir\",\n \"store/my-organization.my-organization.delete\": \"Eliminar\",\n \"store/my-organization.my-organization.users-in-organization\": \"Usuarios en la organización\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"Incapaz de abandonar la organización\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"No puede abandonar la organización:\",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"Debe transferir el rol \\\"Administrador\\\" antes de abandonar la organización\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"Debe transferir el papel de \\\"organización admin\\\" antes de dejar la organización\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"No se puede eliminar la organización\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"Tiene más de un usuario asignado en la organización: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"Elimine todos los usuarios antes de eliminar esta organización.\",\n \"store/my-organization.my-organization.user.already.assigned\": \"Este usuario ya pertenece a alguna otra compañía\",\n \"store/my-organization.my-organization.button.leave\": \"Salir\",\n \"store/my-organization.my-organization.leave.message\": \"Quieres dejar la organización \",\n \"store/my-organization.my-organization.button.delete\": \"Eliminar\",\n \"store/my-organization.my-organization.delete.message\": \"Desea eliminar la organización \",\n \"store/my-organization.my-user.table-title.email\": \"Correo Electrónico\",\n \"store/my-organization.my-user.table-title.status\": \"Situación\",\n \"store/my-organization.my-user.table-title.role\": \"Papel\",\n \"store/my-organization.my-user.table-title.invite\": \"Invitación\",\n \"store/my-organization.my-user.table-title.edit\": \"Editar\",\n \"store/my-organization.my-user.table-title.delete\": \"Eliminar\",\n \"store/my-organization.my-user.table.button.add-new\": \"Añadir nuevo\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"Eliminar\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"Quieres eliminar usuario: \",\n \"store/my-organization.toast.organization.create.error\": \"No se puede crear la organización porque\",\n \"store/my-organization.toast.organization.leave.error\": \"No puedo dejar la organización porque\",\n \"store/my-organization.toast.organization.delete.error\": \"No se puede borrar la organización porque\",\n \"store/my-organization.toast.user.create.error\": \"No se puede crear el usuario porque\",\n \"store/my-organization.toast.user.edit.error\": \"No se puede crear un usuario porque\",\n \"store/my-organization.toast.user.delete.error\": \"No se puede crear borrar porque\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"Re invitación enviada\",\n \"store/my-organization.toast.user.reinvitation.error\": \"Re invitación fallida, \",\n \"store/my-organization.my-organization.reload-message\": \"Sus cambios se han aplicado con éxito, puede tardar un tiempo en reflejarlos\",\n \"store/my-organization.my-organization.organization.title\": \"Mi Organización\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"Volver\",\n \"store/my-organization.my-organization.status.approved\": \"Aprobado\",\n \"store/my-organization.my-organization.status.not-approved\": \"No aprobado\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"Organización Admin\",\n \"store/my-organization.my-organization.showMore\": \"Mostrar más\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"Aún no está asignado a ninguna organización.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"Solicite permiso para crear una organización si es administrador.\"\n}\n```"
}
] |
code_organizations_329f6ad6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/messages/ar.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"store/my-organization.link\": \"منظمتي\",\n \"store/my-organization.add-user.title\": \"إضافة مستخدم جديد\",\n \"store/my-organization.edit-user.title\": \"تعديل مستخدم\",\n \"store/my-organization.add-user\": \"أضف مستخدمًا\",\n \"store/my-organization.email\": \"عنوان البريد الإلكتروني\",\n \"store/my-organization.budget-amount\": \"مبلغ الميزانية\",\n \"store/my-organization.role-id\": \"الدور\",\n \"store/my-organization.errors.role-id.empty\": \"الدور فارغ\",\n \"store/my-organization.errors.email.empty\": \"البريد الإلكتروني فارغ\",\n \"store/my-organization.errors.email.exists\": \"مستخدم موجود فعلًا\",\n \"store/my-organization.errors.email.invalid\": \"عنوان بريد إلكتروني غير صالح\",\n \"store/my-organization.success\": \"تمت إضافة المستخدم بنجاح\",\n \"store/my-organization.errors.organization.text\": \"المنظمة\",\n \"store/my-organization.button.cancel\": \"إلغاء\",\n \"store/my-organization.button.save\": \"حفظ\",\n \"store/my-organization.label.email\": \"البريد الإلكتروني\",\n \"store/my-organization.button.ok\": \"موافق\",\n \"store/my-organization.input.placeholder.organizationName\": \"اسم المنظمة\",\n \"store/my-organization.input.label.organizationName\": \"الإسم\",\n \"store/my-organization.input.placeholder.telephone\": \"رقم هاتف المنظمة\",\n \"store/my-organization.input.label.telephone\": \"الهاتف\",\n \"store/my-organization.input.placeholder.address\": \"عنوان المنظمة\",\n \"store/my-organization.input.label.address\": \"العنوان\",\n \"store/my-organization.input.placeholder.email\": \"عنوان البريد الإلكتروني للمنظمة\",\n \"store/my-organization.input.label.email\": \"البريد الإلكتروني\",\n \"store/my-organization.my-organization.create-new-organization\": \"إنشاء منظمة\",\n \"store/my-organization.my-organization.organization\": \"معلومات المنظمة\",\n \"store/my-organization.my-organization.organization.name\": \"الإسم\",\n \"store/my-organization.my-organization.organization.telephone\": \"الهاتف\",\n \"store/my-organization.my-organization.organization.address\": \"العنوان\",\n \"store/my-organization.my-organization.organization.email\": \"البريد الإلكتروني\",\n \"store/my-organization.my-organization.role\": \"دور المستخدم\",\n \"store/my-organization.my-organization.leave\": \"مغادرة\",\n \"store/my-organization.my-organization.delete\": \"حذف\",\n \"store/my-organization.my-organization.users-in-organization\": \"مستخدمون في المنظمة\",\n \"store/my-organization.my-organization.unable-to-leave-title\": \"غير قادر على مغادرة المنظمة\",\n \"store/my-organization.my-organization.unable-to-leave-message1\": \"لا يمكنك مغادرة المنظمة: \",\n \"store/my-organization.my-organization.unable-to-leave-message2\": \"يجب عليك نقل دور \\\"المدير\\\" قبل مغادرة المنظمة\",\n \"store/my-organization.my-organization.unable-to-leave-manager-message2\": \"يجب عليك نقل دور \\\"مسؤول المؤسسة\\\" قبل مغادرة المنظمة\",\n \"store/my-organization.my-organization.unable-to-delete-title\": \"غير قادر على حذف المنظمة\",\n \"store/my-organization.my-organization.unable-to-delete-message1\": \"لديك أكثر من مستخدم معين في المنظمة: \",\n \"store/my-organization.my-organization.unable-to-delete-message2\": \"يرجى حذف جميع المستخدمين قبل حذف هذه المنظمة\",\n \"store/my-organization.my-organization.user.already.assigned\": \"لا يمكن إضافة هذا المستخدم\",\n \"store/my-organization.my-organization.button.leave\": \"مغادرة\",\n \"store/my-organization.my-organization.leave.message\": \"أتريد مغادرة المنظمة: \",\n \"store/my-organization.my-organization.button.delete\": \"حذف\",\n \"store/my-organization.my-organization.delete.message\": \"أتريد حذف المنظمة: \",\n \"store/my-organization.my-user.table-title.email\": \"البريد الإلكتروني\",\n \"store/my-organization.my-user.table-title.status\": \"الحالات\",\n \"store/my-organization.my-user.table-title.role\": \"الدور\",\n \"store/my-organization.my-user.table-title.invite\": \"دعوة\",\n \"store/my-organization.my-user.table-title.edit\": \"تعديل\",\n \"store/my-organization.my-user.table-title.delete\": \"حذف\",\n \"store/my-organization.my-user.table.button.add-new\": \"إضافة جديد(ة)\",\n \"store/my-organization.my-user.delete-confirmation-action\": \"حذف\",\n \"store/my-organization.my-user.delete-confirmation-message\": \"أتريد حذف المستخدم: \",\n \"store/my-organization.toast.organization.create.error\": \"لا يمكن إنشاء منظمة لأن\",\n \"store/my-organization.toast.organization.leave.error\": \"لا يمكن مغادرة منظمة لأن\",\n \"store/my-organization.toast.organization.delete.error\": \"لا يمكن حذف منظمة لأن\",\n \"store/my-organization.toast.user.create.error\": \"لا يمكن إنشاء مستخدم لأن\",\n \"store/my-organization.toast.user.edit.error\": \"لا يمكن إنشاء مستخدم لأن\",\n \"store/my-organization.toast.user.delete.error\": \"لا يمكن إنشاء الحذف لأن\",\n \"store/my-organization.toast.user.reinvitation.sent\": \"تمت إعادة إرسال الدعوة\",\n \"store/my-organization.toast.user.reinvitation.error\": \"فشل إعادة إرسال الدعوة، \",\n \"store/my-organization.my-organization.reload-message\": \"تم تطبيق التغييرات الخاصة بك بنجاح، قد يستغرق الأمر بعض الوقت لإظهارها\",\n \"store/my-organization.my-organization.organization.title\": \"منظماتي\",\n \"store/my-organization.my-organization.organization.returnBtn.text\": \"رجوع\",\n \"store/my-organization.my-organization.status.approved\": \"معتمد(ة)\",\n \"store/my-organization.my-organization.status.not-approved\": \"غير معتمد\",\n \"store/my-organization.my-organization.status.isOrgAdmin\": \"مشرف المنظمة\",\n \"store/my-organization.my-organization.showMore\": \"عرض المزيد\",\n \"store/my-organization.my-organization.not-yet-assigned-1\": \"لم يتم تعيينك بعد إلى أي منظمة.\",\n \"store/my-organization.my-organization.not-yet-assigned-2\": \"يرجى طلب الإذن لإنشاء منظمة إذا كنت مسؤولاً.\"\n}\n\n```"
}
] |
code_organizations_4a1cc453
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/docs/README.md from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```markdown\n# Organizations\n\nThis application allows you to create organization and manage users under that organization with diffrent roles. \n\n## Usage\n\nInstall this app in your workspace\n\n```js\nvtex install vtex.organizations@1.x\n```\n\n> ### Link application to development workspace\n> - clone the application to your working environment and checkout to the correct branch (i.e: `dev-master`)\n> - link this app to your workspace (`vtex link --verbose`)\n\n## Prerequisites\n\nIn order to run this application following master data schemas and indices should be created. \nUse `MASTER DATA API - V2` in vtex api documentation to create those schemas (https://developers.vtex.com/reference#master-data-api-v2-overview)\n\nThese schemas are shared among several applications `vtex.admin-organizations`, `vtex.auth-challenge` and `vtex.organizations`, therefore if you have already created these schemas and indices you can ignore this step\n\n### Master data schemas\n\n<details><summary>BusinessPermission</summary>\n\n``` \n\nData Entity Name: BusinessPermission\nSchema Name: business-permission-schema-v1\n\n{\n\t\"properties\": {\n\t\t\"name\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"label\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t},\n\t\"v-default-fields\": [\n\t\t\"name\",\n\t\t\"label\",\n\t\t\"id\"\n\t],\n\t\"required\": [\n\t\t\"name\"\n\t],\n\t\"v-indexed\": [\n\t\t\"name\"\n\t],\n\t\"v-security\": {\n\t\t\"allowGetAll\": true,\n\t\t\"publicRead\": [\n\t\t\t\"name\",\n\t\t\t\"label\",\n\t\t\t\"id\"\n\t\t],\n\t\t\"publicWrite\": [\n\t\t\t\"name\",\n\t\t\t\"label\"\n\t\t],\n\t\t\"publicFilter\": [\n\t\t\t\"name\",\n\t\t\t\"id\"\n\t\t]\n\t}\n}\n\n```\n</details>\n\n<details><summary>BusinessRole</summary>\n\n``` \n\nData Entity Name: BusinessRole\nSchema Name: business-role-schema-v1\n\n{\n\t\"properties\": {\n\t\t\"name\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"label\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"permissions\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t},\n\t\"definitions\": {\n\t\t\"permission\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t},\n\t\"v-default-fields\": [\n\t\t\"name\",\n\t\t\"label\",\n\t\t\"id\",\n\t\t\"permissions\"\n\t],\n\t\"required\": [\n\t\t\"name\"\n\t],\n\t\"v-indexed\": [\n\t\t\"name\"\n\t],\n\t\"v-security\": {\n\t\t\"allowGetAll\": true,\n\t\t\"publicRead\": [\n\t\t\t\"name\",\n\t\t\t\"label\",\n\t\t\t\"permissions\",\n\t\t\t\"id\"\n\t\t],\n\t\t\"publicWrite\": [\n\t\t\t\"name\",\n\t\t\t\"label\",\n\t\t\t\"permissions\"\n\t\t],\n\t\t\"publicFilter\": [\n\t\t\t\"name\",\n\t\t\t\"id\"\n\t\t]\n\t}\n}\n\n```\n</details>\n\n<details><summary>BusinessOrganization</summary>\n\n``` \n\nData Entity Name: BusinessOrganization\nSchema Name: business-organization-schema-v1\n\n{\n\t\"properties\": {\n\t\t\"name\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"telephone\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"address\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"email\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t},\n\t\"v-default-fields\": [\n\t\t\"name\",\n\t\t\"telephone\",\n\t\t\"id\",\n\t\t\"address\",\n\t\t\"email\"\n\t],\n\t\"required\": [\n\t\t\"name\",\n\t\t\"telephone\"\n\t],\n\t\"v-indexed\": [\n\t\t\"name\",\n\t\t\"telephone\",\n\t\t\"email\"\n\t],\n\t\"v-security\": {\n\t\t\"allowGetAll\": true,\n\t\t\"publicRead\": [\n\t\t\t\"name\",\n\t\t\t\"telephone\",\n\t\t\t\"id\",\n\t\t\t\"address\",\n\t\t\t\"email\"\n\t\t],\n\t\t\"publicWrite\": [\n\t\t\t\"name\",\n\t\t\t\"telephone\",\n\t\t\t\"address\",\n\t\t\t\"email\"\n\t\t],\n\t\t\"publicFilter\": [\n\t\t\t\"name\",\n\t\t\t\"telephone\",\n\t\t\t\"id\",\n\t\t\t\"email\"\n\t\t]\n\t}\n}\n\n```\n</details>\n\n<details><summary>UserOrganization</summary>\n\n``` \n\nData Entity Name: UserOrganization\nSchema Name: user-organization-schema-v1\n\n{\n\t\"properties\": {\n\t\t\"email\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"businessOrganizationId\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"link\": \"http://api.vtex.com/{{accountName}}/dataentities/BusinessOrganization/schemas/business-organization-schema-v1\"\n\t\t},\n\t\t\"roleId\": {\n\t\t\t\"type\": \"string\",\n\t\t\t\"link\": \"http://api.vtex.com/{{accountName}}/dataentities/BusinessRole/schemas/business-role-schema-v1\"\n\t\t},\n\t\t\"status\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t},\n\t\"v-default-fields\": [\n\t\t\"email\",\n\t\t\"id\",\n\t\t\"businessOrganizationId\",\n\t\t\"roleId\",\n\t\t\"status\"\n\t],\n\t\"required\": [\n\t\t\"email\",\n\t\t\"businessOrganizationId\",\n\t\t\"roleId\",\n\t\t\"status\"\n\t],\n\t\"v-indexed\": [\n\t\t\"email\",\n\t\t\"businessOrganizationId\",\n\t\t\"roleId\",\n\t\t\"status\"\n\t],\n\t\"v-security\": {\n\t\t\"allowGetAll\": true,\n\t\t\"publicRead\": [\n\t\t\t\"email\",\n\t\t\t\"id\",\n\t\t\t\"businessOrganizationId\",\n\t\t\t\"businessOrganizationId_linked\",\n\t\t\t\"roleId\",\n\t\t\t\"roleId_linked\",\n\t\t\t\"status\"\n\t\t],\n\t\t\"publicWrite\": [\n\t\t\t\"id\",\n\t\t\t\"email\",\n\t\t\t\"businessOrganizationId\",\n\t\t\t\"roleId\",\n\t\t\t\"status\"\n\t\t],\n\t\t\"publicFilter\": [\n\t\t\t\"email\",\n\t\t\t\"id\",\n\t\t\t\"businessOrganizationId\",\n\t\t\t\"roleId\",\n\t\t\t\"status\"\n\t\t]\n\t},\n\t\"v-triggers\": [\n\t\t{\n\t\t\t\"name\": \"organization-assignment-accept-email\",\n\t\t\t\"active\": true,\n\t\t\t\"condition\": \"status=APPROVED\",\n\t\t\t\"action\": {\n\t\t\t\t\"type\": \"email\",\n\t\t\t\t\"provider\": \"default\",\n\t\t\t\t\"subject\": \"Organization Assignment Acceptance\",\n\t\t\t\t\"to\": [\n\t\t\t\t\t\"{!email}\"\n\t\t\t\t],\n\t\t\t\t\"replyTo\": \"noreply@company.com\",\n\t\t\t\t\"body\": \"You have been assigned to {!businessOrganizationId_linked.name}.\"\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t\"name\": \"organization-assignment-decline-email\",\n\t\t\t\"active\": true,\n\t\t\t\"condition\": \"status=DECLINED\",\n\t\t\t\"action\": {\n\t\t\t\t\"type\": \"email\",\n\t\t\t\t\"provider\": \"default\",\n\t\t\t\t\"subject\": \"Organization Assignment Decline\",\n\t\t\t\t\"to\": [\n\t\t\t\t\t\"{!email}\"\n\t\t\t\t],\n\t\t\t\t\"replyTo\": \"noreply@company.com\",\n\t\t\t\t\"body\": \"You have left the organization {!businessOrganizationId_linked.name}.\"\n\t\t\t}\n\t\t}\n\t]\n}\n\n```\n</details>\n\n### Changes to existing **CL** table\nWe need to add two fields to existing **CL** master data table. \n```\nisOrgAdmin: Boolean \norganizationId: VarChar 100\n```\nAfter creating the fields change settings of that fields with edit field feature.\nYou can update the field settings as shown in the image below. \n\n<a href=\"https://drive.google.com/uc?export=view&id=1IzMTKBpB4A9snERILSQJ-DQd1Zp758wE\">View Image</a>\n\n>**_NOTE:_** **isOrgAdmin** field should check following checkboxes \n> **Make readable without credential**, \n> **Is searchable**, \n> **Is filterable**, \n\n> **organizationId** field should check following checkboxes \n> **Is nullable**, \n> **Make readable without credential**, \n> **Allow editing without credential**, \n> **Allow filter without credential**, \n> **Is searchable**, \n> **Is filterable**, \n\nDont forget to `save` and `reindex` `CL` table once you add all the fields. \n\n### [Deprecated] removed master data collections and schemas\n>Data Entity Name: **Persona**, Schema Name: **persona-schema-v1**\n\n>Data Entity Name: **OrgAssignment**, Schema Name: **organization-assignment-schema-v1**\n\n## Important\n\n> **_NOTE:_** create `Manager` role with required permissions using `vtex.admin-organizations` application (https://github.com/vtex/admin-organizations)\n\n\n```"
}
] |
code_organizations_9af5a06e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/my-organization.css from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```css\n.reloadMessage >div>div>div>div:nth-child(2){\n width: 100%;\n}\n\n.collapsibleWrapper > div > div:first-child{\n margin-right: 8px;\n}\n\n.listItemBlock{\n height: 160px;\n}\n\n.detailSummaryColumn{\n width: 32%;\n height: 180px;\n}\n```"
}
] |
code_organizations_696df727
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/MyOrganizationLink.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport { FC } from 'react'\nimport { injectIntl } from 'react-intl'\n\ninterface RenderProps {\n name: string\n path: string\n}\n\ninterface Props {\n render: (paths: RenderProps[]) => any\n intl: any\n}\n\nconst MyOrganizationLink: FC<Props> = ({ render, intl }: Props) => {\n return render([\n {\n name: intl.formatMessage({ id: 'store/my-organization.link' }),\n path: '/myorganization',\n },\n ])\n}\n\nexport default injectIntl(MyOrganizationLink)\n\n```"
}
] |
code_organizations_56b58744
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/MyOrganizationPage.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Route } from 'react-router-dom'\nimport { ToastProvider } from 'vtex.styleguide'\nimport MyOrganization from './components/MyOrganization'\n\nconst MyOrganizationPage = () => {\n return (\n <ToastProvider positioning=\"window\">\n <Route\n path=\"/myorganization\"\n exact\n component={() => <MyOrganization />}\n />\n </ToastProvider>\n )\n}\n\nexport default MyOrganizationPage\n\n```"
}
] |
code_organizations_e087b44b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/BlockContent.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC } from 'react'\nimport { useCssHandles } from 'vtex.css-handles'\n\nconst CSS_HANDLES = ['challengeContentWrapper'] as const\n\nconst BlockContent: FC<ChallengeProps> = ({ children }: ChallengeProps) => {\n const handles = useCssHandles(CSS_HANDLES)\n return (\n <div className={`mw9 center ${handles.challengeContentWrapper}`}>\n {children}\n </div>\n )\n}\n\nexport default BlockContent\n\n```"
}
] |
code_organizations_5cad812f
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/package.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"scripts\": {\n \"lint\": \"tsc --noEmit && eslint --quiet --fix --ext ts,tsx .\",\n \"test\": \"vtex-test-tools test\"\n },\n \"dependencies\": {\n \"apollo-client\": \"^2.6.3\",\n \"classnames\": \"^2.2.6\",\n \"graphql\": \"^14.5.8\",\n \"graphql-tag\": \"^2.10.3\",\n \"ramda\": \"^0.26.1\",\n \"react\": \"^16.8.6\",\n \"react-apollo\": \"^3.1.3\",\n \"react-dom\": \"^16.8.6\",\n \"react-intl\": \"3.9.1\",\n \"react-router-dom\": \"^4.3.1\"\n },\n \"devDependencies\": {\n \"@types/classnames\": \"^2.2.9\",\n \"@types/graphql\": \"^14.5.0\",\n \"@types/jest\": \"^24.0.21\",\n \"@types/node\": \"^12.12.3\",\n \"@types/ramda\": \"^0.26.33\",\n \"@types/react\": \"^16.8.22\",\n \"@types/react-intl\": \"^2.3.18\",\n \"@types/react-router-dom\": \"^4.3.1\",\n \"@vtex/test-tools\": \"^0.3.2\",\n \"@vtex/tsconfig\": \"^0.2.0\",\n \"eslint\": \"5.x\",\n \"eslint-config-vtex-react\": \"^5.0.1\",\n \"prettier\": \"^1.18.2\",\n \"prop-types\": \"^15.7.2\",\n \"typescript\": \"3.9.7\"\n },\n \"version\": \"1.9.0\"\n}\n\n```"
}
] |
code_organizations_9d9ad497
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/store/interfaces.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"my-account-link.my-organizations-link\": {\n \"component\": \"MyOrganizationLink\"\n },\n \"my-account-link.my-organizations-page\": {\n \"component\": \"MyOrganizationPage\"\n }\n}\n\n```"
}
] |
code_organizations_13ee9d97
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/store/plugins.json from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```json\n{\n \"my-account-menu > my-account-link\": \"my-account-link.my-organizations-link\",\n \"my-account-pages > my-account-page\": \"my-account-link.my-organizations-page\"\n}\n\n```"
}
] |
code_organizations_8f0d82c7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/vtex.my-account-commons.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.my-account-commons' {\n import React from 'react'\n\n interface ComponentProps {\n titleId: string\n namespace: string\n }\n\n export const ContentWrapper: React.SFC<ComponentProps>\n}\n\n```"
}
] |
code_organizations_3ff4356a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/globals.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { ReactNode } from 'react'\nimport { ApolloError } from 'apollo-client'\n\ndeclare global {\n interface ChallengeProps {\n children: ReactNode[]\n }\n\n interface MDField {\n key: string\n value: string\n }\n\n interface MDSearchResult {\n loading: boolean\n error?: ApolloError\n data: MDSearchData\n }\n\n interface MDSearchData {\n documents: MDSearchDocumentResult[]\n }\n\n interface MDSearchDocumentResult {\n id: string\n fields: MDField[]\n }\n\n interface StorefrontFunctionComponent<P = {}> extends FunctionComponent<P> {\n schema?: object\n getSchema?(props?: P): object\n }\n\n interface Role {\n value: string\n label: string\n name: string\n }\n\n interface BusinessOrganization {\n name: string\n telephone: string\n id: string\n address?: string\n email?: string\n }\n\n interface OrganizationAssignment {\n id: string\n email?: string\n budgetAmount?: string\n roleId?: string\n status?: string\n roleId_linked?: Role\n businessOrganizationId_linked?: BusinessOrganization\n }\n}\n\n```"
}
] |
code_organizations_485cf486
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/vtex.render-runtime.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\n/* Typings for `render-runtime` */\ndeclare module 'vtex.render-runtime' {\n import { Component, ComponentType, ReactElement, ReactType } from 'react'\n\n export interface NavigationOptions {\n page: string\n params?: any\n }\n\n export interface RenderContextProps {\n runtime: {\n navigate: (options: NavigationOptions) => void\n }\n }\n\n interface ExtensionPointProps {\n id: string\n [key: string]: any\n }\n\n 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: any\n export const TreePathContextConsumer: any\n export const useTreePath: any\n export const useRuntime: any\n export const canUseDOM: boolean\n export const withRuntimeContext: <TOriginalProps extends {}>(\n Component: ComponentType<TOriginalProps & RenderContextProps>\n ) => ComponentType<TOriginalProps>\n\n export const withSession: <TOriginalProps extends {}>(\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 profile: {\n isAuthenticated: KeyValue\n }\n }\n }\n\n interface SessionUnauthorized {\n type: 'Unauthorized'\n message: string\n }\n\n export interface RenderSession {\n sessionPromise: Promise<SessionPromise>\n }\n\n export interface SessionPromise {\n response: Session | SessionUnauthorized\n }\n}\n\n```"
}
] |
code_organizations_69fac31c
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/css.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.css' {\n const css: any\n export default css\n}\n\n```"
}
] |
code_organizations_5a9ac7b1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/graphql.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module '*.graphql' {\n import { DocumentNode } from 'graphql'\n\n const value: DocumentNode\n export default value\n}\n\n```"
}
] |
code_organizations_e8ab5f5b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/typings/vtex.styleguide.d.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\ndeclare module 'vtex.styleguide' {\n import { ComponentType } from 'react'\n export const Button: ComponentType<InputProps>\n export const Dropdown: ComponentType<InputProps>\n export const Input: ComponentType<InputProps>\n export const Table: ComponentType<InputProps>\n export const EmptyState: ComponentType<InputProps>\n export const PageHeader: ComponentType<InputProps>\n export const Layout: ComponentType<InputProps>\n export const PageBlock: ComponentType<InputProps>\n export const Divider: ComponentType<InputProps>\n export const ButtonWithIcon: ComponentType<InputProps>\n export const IconCheck: ComponentType<InputProps>\n export const Modal: ComponentType<InputProps>\n export const ModalDialog: ComponentType<InputProps>\n export const Alert: ComponentType<InputProps>\n export const ToastProvider: ComponentType<InputProps>\n export const ToastConsumer: ComponentType<InputProps>\n export const Spinner: ComponentType<InputProps>\n export const Tag: ComponentType<InputProps>\n export const Collapsible: ComponentType<InputProps>\n export const Checkbox: ComponentType<InputProps>\n\n interface InputProps {\n [key: string]: any\n }\n}\n\n```"
}
] |
code_organizations_20548e0b
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/utils/const.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const CLIENT_ACRONYM = 'CL'\nexport const CLIENT_FIELDS = [\n 'id',\n 'email',\n 'budgetAmount',\n 'approved',\n 'isOrgAdmin',\n 'organizationId',\n]\nexport const PROFILE_FIELDS = 'isOrgAdmin,organizationId'\n\nexport const BUSINESS_ROLE = 'BusinessRole'\nexport const BUSINESS_ROLE_FIELDS = ['id', 'name', 'label']\nexport const BUSINESS_ROLE_SCHEMA = 'business-role-schema-v1'\n\nexport const ORG_ASSIGNMENT = 'UserOrganization'\nexport const ORG_ASSIGNMENT_FIELDS = [\n 'id',\n 'email',\n 'budgetAmount',\n 'businessOrganizationId',\n 'businessOrganizationId_linked',\n 'status',\n 'roleId',\n 'roleId_linked',\n]\nexport const ORG_ASSIGNMENT_SCHEMA = 'user-organization-schema-v1'\n\nexport const BUSINESS_ORGANIZATION = 'BusinessOrganization'\nexport const BUSINESS_ORGANIZATION_FIELDS = [\n 'id',\n 'name',\n 'telephone',\n 'address',\n 'email',\n]\nexport const BUSINESS_ORGANIZATION_SCHEMA = 'business-organization-schema-v1'\n\nexport const ORG_ASSIGNMENT_STATUS_APPROVED = 'APPROVED'\n\n```"
}
] |
code_organizations_c1318bed
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/utils/documentSerializer.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { endsWith } from 'ramda'\n\nexport const documentSerializer = (documents: any) => {\n if (!documents) {\n return []\n }\n\n const fieldReducer = (fieldsAccumulator: any, field: any) => {\n if (!endsWith('_linked', field.key)) {\n fieldsAccumulator[field.key] = field.value\n }\n if (endsWith('_linked', field.key)) {\n fieldsAccumulator[field.key] = JSON.parse(field.value)\n }\n return fieldsAccumulator\n }\n\n const documentReducer = (documentAccumulator: any, document: any) => {\n if (!document || !document.fields) {\n return documentAccumulator\n }\n documentAccumulator.push(document.fields.reduce(fieldReducer, {}))\n return documentAccumulator\n }\n\n return documents.reduce(documentReducer, [])\n}\n\n```"
}
] |
code_organizations_7acd6642
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/utils/textUtil.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nexport const addressSplitter = (address: string) => {\n if (address === undefined || address.trim() === '') {\n return []\n }\n\n return address.split(',')\n}\n\n```"
}
] |
code_organizations_d9921bc8
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/utils/graphqlErrorHandler.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { pathOr } from 'ramda'\n\nexport const getErrorMessage = (e: any) => {\n const message = pathOr(\n '',\n [\n 'graphQLErrors',\n 0,\n 'extensions',\n 'exception',\n 'response',\n 'data',\n 'Message',\n ],\n e\n )\n return message\n}\n\nexport const handleGlobalError = () => {\n return (e: Error) => {\n var message: string = pathOr(\n '',\n [\n 'graphQLErrors',\n 0,\n 'extensions',\n 'exception',\n 'response',\n 'data',\n 'Message',\n ],\n e\n )\n\n if (message == '') {\n message = pathOr(\n '',\n [\n 'graphQLErrors',\n 0,\n 'extensions',\n 'exception',\n 'response',\n 'data',\n 'errors',\n 0,\n 'errors',\n 0,\n 'Message',\n ],\n e\n )\n }\n\n return Promise.reject(message)\n }\n}\n\n```"
}
] |
code_organizations_023bb67e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/utils/cacheUtils.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport GET_DOCUMENT from '../graphql/documents.graphql'\nimport profileQuery from '../graphql/getProfile.graphql'\nimport { pathOr, find, propEq, reject } from 'ramda'\nimport {\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n PROFILE_FIELDS,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_FIELDS,\n ORG_ASSIGNMENT_SCHEMA,\n} from './const'\n\nconst compareEmailFields = (a: any, b: any) => {\n const emailA = a.fields.find(({ key }: { key: string }) => key === 'email')\n const emailB = b.fields.find(({ key }: { key: string }) => key === 'email')\n return emailA.value.localeCompare(emailB.value)\n}\n\nconst userListArgs = (orgId: string) => {\n return {\n query: GET_DOCUMENT,\n variables: {\n acronym: ORG_ASSIGNMENT,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `businessOrganizationId=${orgId}`,\n schema: ORG_ASSIGNMENT_SCHEMA,\n page: 1,\n pageSize: 100,\n sort: 'email ASC',\n },\n }\n}\n\nconst getProfile = () => {\n return {\n query: profileQuery,\n variables: { customFields: PROFILE_FIELDS },\n }\n}\n\nconst clientListArgs = (email: string) => {\n return {\n query: GET_DOCUMENT,\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${email}`,\n },\n }\n}\n\nexport const updateCacheClient = (\n cache: any,\n data: any,\n email: string,\n budgetAmount: string,\n organizationId: string,\n isOrgAdmin: string\n) => {\n try {\n const response: any = cache.readQuery(clientListArgs(email))\n const id = pathOr(\n pathOr('', ['updateMyDocument', 'cacheId'], data),\n ['createMyDocument', 'cacheId'],\n data\n )\n let fields = pathOr([], ['myDocuments', 0, 'fields'], response)\n\n fields = reject(propEq('key', 'organizationId'), fields) as any\n fields = reject(propEq('key', 'isOrgAdmin'), fields) as any\n fields = reject(propEq('key', 'email'), fields) as any\n fields = reject(propEq('key', 'budgetAmount'), fields) as any\n fields = reject(propEq('key', 'approved'), fields) as any\n\n const newFields = [\n ...fields,\n ...[\n { key: 'organizationId', value: organizationId, __typename: 'Field' },\n { key: 'isOrgAdmin', value: isOrgAdmin, __typename: 'Field' },\n { key: 'email', value: email, __typename: 'Field' },\n { key: 'budgetAmount', value: budgetAmount, __typename: 'Field' },\n { key: 'approved', value: 'true', __typename: 'Field' },\n ],\n ]\n\n response.myDocuments = [\n { id: id, fields: newFields, __typename: 'Document' },\n ]\n const writeData = {\n ...clientListArgs(email),\n data: { myDocuments: response.myDocuments },\n }\n cache.writeQuery(writeData)\n } catch (e) {\n // continue regardless of error\n }\n}\n\nexport const updateCacheAddUser = (\n cache: any,\n data: any,\n roles: Role[],\n organizationId: string,\n email: string,\n budgetAmount: string,\n roleId: string\n) => {\n try {\n const response: any = cache.readQuery(userListArgs(organizationId))\n\n const org = pathOr(\n '',\n ['value'],\n find(\n propEq('key', 'businessOrganizationId_linked'),\n pathOr([], ['myDocuments', 0, 'fields'], response)\n )\n )\n const selectedRole = find(propEq('value', roleId), roles)\n const id = pathOr(\n pathOr('', ['updateMyDocument', 'cacheId'], data),\n ['createMyDocument', 'cacheId'],\n data\n )\n const assignmentFields = [\n { key: 'id', value: id, __typename: 'Field' },\n {\n key: 'businessOrganizationId',\n value: organizationId,\n __typename: 'Field',\n },\n {\n key: 'email',\n value: email,\n __typename: 'Field',\n },\n {\n key: 'budgetAmount',\n value: budgetAmount,\n __typename: 'Field',\n },\n {\n key: 'roleId',\n value: roleId,\n __typename: 'Field',\n },\n { key: 'businessOrganizationId_linked', value: org, __typename: 'Field' },\n {\n key: 'roleId_linked',\n value: selectedRole\n ? JSON.stringify({\n name: selectedRole.name,\n label: selectedRole.label,\n id: selectedRole.value,\n })\n : '',\n __typename: 'Field',\n },\n ]\n\n const newData = [\n ...response.myDocuments,\n { id: id, fields: assignmentFields, __typename: 'Document' },\n ].sort(compareEmailFields)\n const writeData = {\n ...userListArgs(organizationId),\n data: { myDocuments: newData },\n }\n cache.writeQuery(writeData)\n } catch (e) {\n // continue regardless of error\n }\n}\n\nexport const updateCacheEditUser = (\n cache: any,\n data: any,\n roles: Role[],\n organizationId: string,\n roleId: string\n) => {\n try {\n const response: any = cache.readQuery(userListArgs(organizationId))\n const selectedRole = find(propEq('value', roleId), roles)\n const id = pathOr(\n pathOr('', ['createMyDocument', 'cacheId'], data),\n ['updateMyDocument', 'cacheId'],\n data\n )\n\n const fields = pathOr(\n [],\n ['fields'],\n find(propEq('id', id), pathOr([], ['myDocuments'], response))\n )\n const fieldsExceptRoleAndRoleIdLinked = reject(\n propEq('key', 'roleId'),\n reject(propEq('key', 'roleId_linked'), fields)\n )\n\n fieldsExceptRoleAndRoleIdLinked.push({\n key: 'roleId_linked',\n value: selectedRole\n ? JSON.stringify({\n name: selectedRole.name,\n label: selectedRole.label,\n id: selectedRole.value,\n })\n : '',\n __typename: 'Field',\n })\n fieldsExceptRoleAndRoleIdLinked.push({\n key: 'roleId',\n value: roleId,\n __typename: 'Field',\n })\n\n const newData = pathOr([], ['myDocuments'], response).map((x: any) => {\n if (x.id === id) {\n x.fields = fieldsExceptRoleAndRoleIdLinked\n }\n return x\n })\n const writeData = {\n ...userListArgs(organizationId),\n data: { myDocuments: newData },\n }\n cache.writeQuery(writeData)\n } catch (e) {\n // continue regardless of error\n }\n}\n\nexport const updateCacheDeleteUser = (\n cache: any,\n data: any,\n organizationId: string\n) => {\n try {\n const id = pathOr('', ['deleteMyDocument', 'cacheId'], data)\n const response: any = cache.readQuery(userListArgs(organizationId))\n\n const newData = reject(propEq('id', id), response.myDocuments)\n\n const writeData = {\n ...userListArgs(organizationId),\n data: { myDocuments: newData },\n }\n\n cache.writeQuery(writeData)\n } catch (e) {\n // continue regardless of error\n }\n}\n\nexport const updateCacheProfile = (cache: any, organizationId: string) => {\n try {\n const response: any = cache.readQuery(getProfile())\n\n const customFieldsExceptOrgId = reject(\n propEq('key', 'organizationId'),\n response.profile.customFields\n )\n\n const customFields = [\n ...customFieldsExceptOrgId,\n {\n key: 'organizationId',\n value: organizationId,\n __typename: 'ProfileCustomField',\n },\n ]\n\n response.profile.customFields = customFields\n\n const writeData = {\n ...getProfile(),\n data: { profile: response.profile },\n }\n\n cache.writeQuery(writeData)\n } catch (e) {\n // continue regardless of error\n }\n}\n\n```"
}
] |
code_organizations_5c49509e
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/AddOrganization.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useReducer } from 'react'\nimport { pathOr, isEmpty, filter, propEq, reject, find, last } from 'ramda'\nimport { PageBlock, Input, Button } from 'vtex.styleguide'\nimport { useMutation, useQuery } from 'react-apollo'\nimport { injectIntl } from 'react-intl'\n\nimport CREATE_DOCUMENT from '../graphql/createDocument.graphql'\nimport GET_DOCUMENT from '../graphql/documents.graphql'\nimport UPDATE_DOCUMENT from '../graphql/updateDocument.graphql'\n\nimport {\n BUSINESS_ROLE,\n BUSINESS_ROLE_FIELDS,\n BUSINESS_ROLE_SCHEMA,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_SCHEMA,\n BUSINESS_ORGANIZATION,\n BUSINESS_ORGANIZATION_SCHEMA,\n CLIENT_ACRONYM,\n ORG_ASSIGNMENT_STATUS_APPROVED,\n} from '../utils/const'\nimport { handleGlobalError } from '../utils/graphqlErrorHandler'\nimport { updateCacheProfile } from '../utils/cacheUtils'\n\ninterface Props {\n userEmail: string\n clientId: string\n updateOrgInfo: () => void\n showToast: (message: any) => void\n intl: any\n}\n\ninterface ErrorMessage {\n name: string\n isError: boolean\n message: string\n}\n\ninterface ErrorState {\n errorMessages: ErrorMessage[]\n}\n\ntype Action<K, V = void> = V extends void ? { type: K } : { type: K } & V\n\ntype Actions =\n | Action<'NAME_ERROR', { args: { name: string } }>\n | Action<'TELEPHONE_ERROR', { args: { telephone: string } }>\n | Action<'EMAIL_ERROR', { args: { email: string } }>\n\nconst AddOrganization = ({\n userEmail,\n clientId,\n intl,\n updateOrgInfo,\n showToast,\n}: Props) => {\n const initialState = {\n errorMessages: [] as ErrorMessage[],\n }\n\n const reducer = (state: ErrorState, action: Actions): ErrorState => {\n switch (action.type) {\n case 'NAME_ERROR': {\n const isErrorN = isEmpty(action.args.name)\n const messageN = isErrorN ? 'Name is required' : ''\n const _errorN: ErrorMessage = {\n ...pathOr(\n [],\n [0],\n filter(propEq('name', 'NAME_ERROR'), state.errorMessages)\n ),\n ...{ name: 'NAME_ERROR', isError: isErrorN, message: messageN },\n }\n return {\n ...state,\n ...{\n errorMessages: [\n ...reject(propEq('name', 'NAME_ERROR'), state.errorMessages),\n ...[_errorN],\n ],\n },\n }\n }\n case 'TELEPHONE_ERROR': {\n const isErrorT = isEmpty(action.args.telephone)\n const messageT = isErrorT ? 'Telephone is required' : ''\n const _errorT: ErrorMessage = {\n ...pathOr(\n [],\n [0],\n filter(propEq('name', 'TELEPHONE_ERROR'), state.errorMessages)\n ),\n ...{ name: 'TELEPHONE_ERROR', isError: isErrorT, message: messageT },\n }\n return {\n ...state,\n ...{\n errorMessages: [\n ...reject(propEq('name', 'TELEPHONE_ERROR'), state.errorMessages),\n ...[_errorT],\n ],\n },\n }\n }\n case 'EMAIL_ERROR': {\n let isErrorE = false\n let messageE = ''\n if (\n !isEmpty(action.args.email) &&\n !/^\\w+([.-]?\\w+)*@\\w+([.-]?\\w+)*(\\.\\w{2,3})+$/.test(action.args.email)\n ) {\n isErrorE = true\n }\n\n messageE = isErrorE ? 'Email is incorrect' : ''\n const _errorE: ErrorMessage = {\n ...pathOr(\n [],\n [0],\n filter(propEq('name', 'EMAIL_ERROR'), state.errorMessages)\n ),\n ...{ name: 'EMAIL_ERROR', isError: isErrorE, message: messageE },\n }\n return {\n ...state,\n ...{\n errorMessages: [\n ...reject(propEq('name', 'EMAIL_ERROR'), state.errorMessages),\n ...[_errorE],\n ],\n },\n }\n }\n default:\n return state\n }\n }\n\n const [state, dispatch] = useReducer(reducer, initialState)\n\n const [name, setName] = useState('')\n const [telephone, setTelephone] = useState('')\n const [address, setAddress] = useState('')\n const [email, setEmail] = useState('')\n\n const [createDocument] = useMutation(CREATE_DOCUMENT)\n const [updateDocument] = useMutation(UPDATE_DOCUMENT)\n\n const getOrganizationFields = () => {\n return [\n { key: 'name', value: name },\n { key: 'telephone', value: telephone },\n { key: 'address', value: address },\n { key: 'email', value: email },\n ]\n }\n\n const getOrganizationAssignmentFields = (\n organizationId: string,\n roleId: string\n ) => {\n return [\n { key: 'email', value: userEmail },\n { key: 'businessOrganizationId', value: organizationId },\n { key: 'roleId', value: roleId },\n { key: 'status', value: ORG_ASSIGNMENT_STATUS_APPROVED },\n ]\n }\n\n const createOrganization = async (roleId: string) => {\n let orgId = ''\n createDocument({\n variables: {\n acronym: BUSINESS_ORGANIZATION,\n document: { fields: getOrganizationFields() },\n schema: BUSINESS_ORGANIZATION_SCHEMA,\n },\n })\n .then((organizationResponse: any) => {\n orgId = pathOr(\n '',\n ['data', 'createMyDocument', 'cacheId'],\n organizationResponse\n )\n\n return createDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n document: {\n fields: getOrganizationAssignmentFields(orgId, roleId),\n },\n schema: ORG_ASSIGNMENT_SCHEMA,\n },\n })\n })\n .then(() => {\n return updateDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: [\n { key: 'id', value: clientId },\n { key: 'organizationId', value: orgId },\n ],\n },\n },\n update: (cache: any) => updateCacheProfile(cache, orgId),\n })\n })\n\n .catch(handleGlobalError())\n .then(() => {\n setName('')\n setTelephone('')\n setAddress('')\n setEmail('')\n updateOrgInfo()\n })\n .catch((message: string) => {\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.organization.create.error',\n })} \"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n })\n }\n\n const { data: roleData } = useQuery(GET_DOCUMENT, {\n variables: {\n acronym: BUSINESS_ROLE,\n fields: BUSINESS_ROLE_FIELDS,\n where: '(name=*manager*)',\n schema: BUSINESS_ROLE_SCHEMA,\n },\n })\n\n const roleFields = roleData\n ? pathOr([], ['fields'], last(roleData.myDocuments))\n : []\n\n const roleId =\n roleFields && roleFields.length > 0\n ? pathOr('', ['value'], find(propEq('key', 'id'), roleFields))\n : ''\n\n return (\n <PageBlock>\n <div className=\"mb5\">\n <Input\n placeholder={intl.formatMessage({\n id: 'store/my-organization.input.placeholder.organizationName',\n })}\n label={intl.formatMessage({\n id: 'store/my-organization.input.label.organizationName',\n })}\n value={name}\n error={pathOr(\n false,\n [0, 'isError'],\n filter(propEq('name', 'NAME_ERROR'), state.errorMessages)\n )}\n errorMessage={pathOr(\n '',\n [0, 'message'],\n filter(propEq('name', 'NAME_ERROR'), state.errorMessages)\n )}\n onChange={(e: any) => {\n setName(e.target.value)\n dispatch({ type: 'NAME_ERROR', args: { name: e.target.value } })\n }}\n />\n </div>\n <div className=\"mb5\">\n <Input\n placeholder={intl.formatMessage({\n id: 'store/my-organization.input.placeholder.telephone',\n })}\n label={intl.formatMessage({\n id: 'store/my-organization.input.label.telephone',\n })}\n value={telephone}\n error={pathOr(\n false,\n [0, 'isError'],\n filter(propEq('name', 'TELEPHONE_ERROR'), state.errorMessages)\n )}\n errorMessage={pathOr(\n '',\n [0, 'message'],\n filter(propEq('name', 'TELEPHONE_ERROR'), state.errorMessages)\n )}\n onChange={(e: any) => {\n setTelephone(e.target.value)\n dispatch({\n type: 'TELEPHONE_ERROR',\n args: { telephone: e.target.value },\n })\n }}\n />\n </div>\n <div className=\"mb5\">\n <Input\n placeholder={intl.formatMessage({\n id: 'store/my-organization.input.placeholder.address',\n })}\n label={intl.formatMessage({\n id: 'store/my-organization.input.label.address',\n })}\n value={address}\n onChange={(e: any) => setAddress(e.target.value)}\n />\n </div>\n <div className=\"mb5\">\n <Input\n placeholder={intl.formatMessage({\n id: 'store/my-organization.input.placeholder.email',\n })}\n label={intl.formatMessage({\n id: 'store/my-organization.input.label.email',\n })}\n value={email}\n error={pathOr(\n false,\n [0, 'isError'],\n filter(propEq('name', 'EMAIL_ERROR'), state.errorMessages)\n )}\n errorMessage={pathOr(\n '',\n [0, 'message'],\n filter(propEq('name', 'EMAIL_ERROR'), state.errorMessages)\n )}\n onChange={(e: any) => {\n setEmail(e.target.value)\n dispatch({ type: 'EMAIL_ERROR', args: { email: e.target.value } })\n }}\n />\n </div>\n\n <div className=\"mb5\">\n <Button\n variation=\"primary\"\n disabled={\n name === '' ||\n telephone === '' ||\n (email !== '' &&\n pathOr(\n true,\n [0, 'isError'],\n filter(propEq('name', 'EMAIL_ERROR'), state.errorMessages)\n ))\n }\n onClick={() => createOrganization(roleId)}>\n {intl.formatMessage({ id: 'store/my-organization.button.save' })}\n </Button>\n </div>\n </PageBlock>\n )\n}\n\nexport default injectIntl(AddOrganization)\n\n```"
}
] |
code_organizations_cfc9ffe0
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/UserListItem.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { pathOr } from 'ramda'\nimport { useQuery } from 'react-apollo'\nimport DOCUMENTS from '../graphql/documents.graphql'\nimport { CLIENT_ACRONYM, CLIENT_FIELDS } from '../utils/const'\nimport { Collapsible, Tag, Button } from 'vtex.styleguide'\nimport { documentSerializer } from '../utils/documentSerializer'\n\nimport { injectIntl } from 'react-intl'\n\nimport styles from '../my-organization.css'\n\ninterface Props {\n isCurrentUserAdmin: boolean\n isDefaultAssignment: boolean\n orgAssignment: OrganizationAssignment\n intl: any\n edit: (assignmentId: string) => void\n deleteAssignment: (assignmentId: string) => void\n}\n\nconst UserListItem = ({\n isCurrentUserAdmin,\n isDefaultAssignment,\n orgAssignment,\n edit,\n deleteAssignment,\n intl,\n}: Props) => {\n const { data, loading } = useQuery(DOCUMENTS, {\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${orgAssignment.email}`,\n },\n })\n\n const client = pathOr(\n {},\n [0],\n documentSerializer(pathOr([], ['myDocuments'], data))\n ) as any\n\n const isAdminUserListItem: boolean = ((pathOr(\n 'false',\n ['isOrgAdmin'],\n client\n ) as string) === 'true') as boolean\n\n const isApprovedUser: boolean = ((pathOr(\n 'false',\n ['approved'],\n client\n ) as string) === 'true') as boolean\n\n const [isOpen, setIsOpen] = useState(false)\n\n const userContent = () => {\n return (\n <div\n key={`item-sub-key-${orgAssignment.id}`}\n className=\"flex center ph3-ns pa2\">\n <div className=\"flex-row w-100 cf ph2-ns\">\n <div className=\"fl w-60 pa2\">\n <div className=\"pt2 f6\">\n <span>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table-title.email',\n })}\n </span>\n </div>\n <div className=\"pt3 b\">\n <span>{orgAssignment.email}</span>\n </div>\n </div>\n <div className=\"fl w-20 pa2\">\n <div className=\"pt2 f6\">\n <span>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table-title.role',\n })}\n </span>\n </div>\n <div className=\"pt3 b\">\n <span>\n {pathOr('', ['roleId_linked', 'label'], orgAssignment)}\n </span>\n </div>\n </div>\n <div className=\"fl w-20 pa2\">\n <div className=\"pt2 f6\">\n <span>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table-title.status',\n })}\n </span>\n </div>\n <div className=\"pt3\">\n <span>\n {isApprovedUser ? (\n <Tag type=\"success\" variation=\"low\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.status.approved',\n })}\n </Tag>\n ) : (\n <Tag type=\"warning\" variation=\"low\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.status.not-approved',\n })}\n </Tag>\n )}\n </span>\n </div>\n </div>\n </div>\n </div>\n )\n }\n\n const toggleOpen = () => {\n setIsOpen(!isOpen)\n }\n\n return loading ? (\n <div key=\"loading-\" />\n ) : (\n <div\n id={`item-${orgAssignment.id}`}\n key={`item-key-${orgAssignment.id}`}\n className={`${styles.collapsibleWrapper} bg-muted-5 ma3 ba b--black-10`}>\n <Collapsible\n header={userContent()}\n onClick={toggleOpen}\n isOpen={isOpen}\n align=\"right\"\n caretColor=\"muted\">\n <div className=\"center bg-white bt b--black-10 pt3\">\n <div className=\"flex cf ph2-ns\">\n <div className=\"flex-column fl w-70 pa5 f6\">\n <span>\n {isAdminUserListItem && (\n <Tag type=\"success\" variation=\"low\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.status.isOrgAdmin',\n })}\n </Tag>\n )}\n </span>\n </div>\n <div className=\"flex-column fl w-30\">\n {!isDefaultAssignment &&\n (isCurrentUserAdmin || !isAdminUserListItem) ? (\n <div className=\"pt5 pb5 pr3\">\n <div className=\"pa2 w-100\">\n <Button\n variation=\"tertiary\"\n size=\"small\"\n onClick={() => edit(orgAssignment.id)}\n block>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table-title.edit',\n })}\n </Button>\n </div>\n <div className=\"pa2 w-100\">\n <Button\n variation=\"danger-tertiary\"\n size=\"small\"\n onClick={() => deleteAssignment(orgAssignment.id)}\n block>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table-title.delete',\n })}\n </Button>\n </div>\n </div>\n ) : (\n <div />\n )}\n </div>\n </div>\n </div>\n </Collapsible>\n </div>\n )\n}\n\nexport default injectIntl(UserListItem)\n\n```"
}
] |
code_organizations_e4de22c6
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/MyOrganization.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useEffect, useState, useRef, useCallback } from 'react'\nimport { useQuery, useApolloClient } from 'react-apollo'\nimport { Alert, ToastConsumer, Button, Spinner, Tag } from 'vtex.styleguide'\nimport { injectIntl } from 'react-intl'\nimport { pathOr, find, propEq, equals } from 'ramda'\n\nimport { ContentWrapper } from 'vtex.my-account-commons'\n\nimport MyUsers from './MyUsers'\nimport AddOrganization from './AddOrganization'\nimport DefaultAssignmentInfo from './DefaultAssignmentInfo'\n\nimport DOCUMENTS from '../graphql/documents.graphql'\nimport profileQuery from '../graphql/getProfile.graphql'\n\nimport { documentSerializer } from '../utils/documentSerializer'\nimport {\n PROFILE_FIELDS,\n BUSINESS_ROLE,\n BUSINESS_ROLE_FIELDS,\n BUSINESS_ROLE_SCHEMA,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_FIELDS,\n ORG_ASSIGNMENT_SCHEMA,\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n ORG_ASSIGNMENT_STATUS_APPROVED,\n} from '../utils/const'\nimport styles from '../my-organization.css'\n\ninterface Props {\n intl: any\n}\n\nconst MyOrganization = ({ intl }: Props) => {\n // my organization state\n const [clientId, setClientId] = useState('')\n const [organizationId, setOrganizationId] = useState('')\n const [email, setEmail] = useState('')\n const [isOrgAdmin, setIsOrgAdmin] = useState(false)\n const [defaultOrgAssignment, setDefaultOrgAssignment] = useState(\n ({} as any) as OrganizationAssignment\n )\n const [userRole, setUserRole] = useState(({} as any) as Role)\n const [loading, setLoading] = useState(false)\n const [reloadStart, setReloadStart] = useState(false)\n const [showOrganizationReload, setShowOrganizationReload] = useState(false)\n\n // apollo client\n const client = useApolloClient()\n\n // restrict re render multiple times\n const afterEmailSet = useRef(false)\n const afterFirstLoad = useRef(false)\n\n // get initial profile info\n const { data: profileData, loading: profileLoading } = useQuery(\n profileQuery,\n { variables: { customFields: PROFILE_FIELDS } }\n )\n\n // Load data\n const load = useCallback(() => {\n let organizationIdData = ''\n let orgAssignmentsData = ([] as any) as OrganizationAssignment[]\n let defaultAssignmentData = ({} as any) as OrganizationAssignment\n let userRoleData = ({} as any) as Role\n\n setReloadStart(true)\n\n // Get client info\n return client\n .query({\n query: DOCUMENTS,\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${email}`,\n },\n fetchPolicy: 'no-cache',\n })\n .then(({ data }: any) => {\n const clients = documentSerializer(data ? data.myDocuments : [])\n\n organizationIdData = pathOr('', [0, 'organizationId'], clients)\n\n // get current user organization assignments\n return client\n .query({\n query: DOCUMENTS,\n variables: {\n acronym: ORG_ASSIGNMENT,\n schema: ORG_ASSIGNMENT_SCHEMA,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `email=${email}`,\n },\n fetchPolicy: 'no-cache',\n })\n .catch(() => {\n return Promise.resolve({ myDocuments: [] })\n })\n })\n\n .then(({ data }: any) => {\n if (data) {\n const assignments = documentSerializer(data ? data.myDocuments : [])\n\n const defaultAssignment: OrganizationAssignment = find(\n propEq('businessOrganizationId', organizationIdData)\n )(assignments)\n\n defaultAssignmentData = defaultAssignment\n ? defaultAssignment\n : (({} as any) as OrganizationAssignment)\n }\n\n // get current organization's users assignments\n return client\n .query({\n query: DOCUMENTS,\n variables: {\n acronym: ORG_ASSIGNMENT,\n schema: ORG_ASSIGNMENT_SCHEMA,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `(businessOrganizationId=${organizationIdData} AND status=${ORG_ASSIGNMENT_STATUS_APPROVED})`,\n },\n fetchPolicy: 'no-cache',\n })\n .catch(() => {\n return Promise.resolve({ myDocuments: [] })\n })\n })\n .then(({ data }: any) => {\n if (data) {\n orgAssignmentsData = documentSerializer(data ? data.myDocuments : [])\n }\n\n // get roles in the system\n return client.query({\n query: DOCUMENTS,\n variables: {\n acronym: BUSINESS_ROLE,\n schema: BUSINESS_ROLE_SCHEMA,\n fields: BUSINESS_ROLE_FIELDS,\n },\n fetchPolicy: 'no-cache',\n })\n })\n .then(({ data }: any) => {\n if (data) {\n const rolesList = documentSerializer(data ? data.myDocuments : [])\n const roleId = pathOr('', ['roleId'], defaultAssignmentData)\n userRoleData =\n roleId !== '' ? find(propEq('id', roleId))(rolesList) : {}\n\n setReloadStart(false)\n }\n return Promise.resolve({\n organizationIdData,\n orgAssignmentsData,\n defaultAssignmentData,\n userRoleData,\n })\n })\n }, [client, email])\n\n // update state variables\n const updateState = (data: any) => {\n setOrganizationId(data.organizationIdData)\n setDefaultOrgAssignment(data.defaultAssignmentData)\n setUserRole(data.userRoleData)\n }\n\n // after email changed\n useEffect(() => {\n const abortController = new AbortController()\n if (afterEmailSet.current && !afterFirstLoad.current) {\n afterFirstLoad.current = true\n\n setLoading(true)\n load().then((data: any) => {\n updateState(data)\n setLoading(false)\n })\n }\n return () => {\n setLoading(false)\n abortController.abort()\n }\n }, [email, load])\n\n // after profile data loaded\n useEffect(() => {\n const abortController = new AbortController()\n\n const idData = pathOr('', ['profile', 'id'], profileData)\n const emailData = pathOr('', ['profile', 'email'], profileData)\n const isOrgAdminData = pathOr(\n 'false',\n ['value'],\n find(propEq('key', 'isOrgAdmin'))(\n pathOr([], ['profile', 'customFields'], profileData)\n )\n ) as any\n const organizationIdData = pathOr(\n '',\n ['value'],\n find(propEq('key', 'organizationId'))(\n pathOr([], ['profile', 'customFields'], profileData)\n )\n ) as any\n\n if (emailData !== '') {\n setClientId(idData)\n setEmail(emailData)\n setIsOrgAdmin(isOrgAdminData === 'true' || isOrgAdminData === true)\n setOrganizationId(organizationIdData)\n }\n\n if (emailData !== '' && !afterFirstLoad.current) {\n afterEmailSet.current = true\n }\n\n return () => {\n abortController.abort()\n }\n }, [profileData])\n\n // Continue reload - [Leave, Delete] default organization\n const infoUpdatedDefaultAssignment = () => {\n setShowOrganizationReload(true)\n load().then((data: any) => {\n if (\n data &&\n equals(\n data.organizationIdData,\n '' && equals(data.defaultAssignmentData, {})\n )\n ) {\n updateState(data)\n setShowOrganizationReload(false)\n } else {\n infoUpdatedDefaultAssignment()\n }\n })\n }\n\n // Continue reload - [Create] organization\n const infoUpdatedCreateOrganization = () => {\n setShowOrganizationReload(true)\n load().then((data: any) => {\n const isValidDefaultAssignment =\n find(propEq('email', email))(\n pathOr([], ['orgAssignmentsData'], data)\n ) !== undefined\n if (\n data &&\n !equals(data.organizationIdData, '') &&\n !equals(data.defaultAssignmentData, {}) &&\n isValidDefaultAssignment\n ) {\n updateState(data)\n setShowOrganizationReload(false)\n } else {\n infoUpdatedCreateOrganization()\n }\n })\n }\n\n const closeReloadMessage = () => {\n setShowOrganizationReload(false)\n }\n\n const getHeaderContent = () => {\n return isOrgAdmin ? (\n <span className=\"mr4\">\n <Tag type=\"success\" variation=\"low\">\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.status.isOrgAdmin',\n })}\n </Tag>\n </span>\n ) : (\n <span />\n )\n }\n\n const headerConfig = () => {\n return {\n namespace: 'vtex-account__my_organization',\n titleId: 'store/my-organization.my-organization.organization.title',\n headerContent: getHeaderContent(),\n }\n }\n\n return (\n <ContentWrapper {...headerConfig()}>\n {() => (\n <ToastConsumer>\n {({ showToast }: any) =>\n loading || profileLoading ? (\n <Spinner />\n ) : (\n <div className=\"pl5 pl7-ns near-black\">\n {showOrganizationReload && (\n <div className={`${styles.reloadMessage} mb5`}>\n <Alert type=\"warning\" onClose={closeReloadMessage}>\n <div className=\"flex-row w-100\">\n {' '}\n <div className=\"fl flex-grow-1 justify-start w-90\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.reload-message',\n })}\n </div>\n <div className=\"fl flex-grow-1 justify-end w-10\">\n <Button\n variation=\"secondary\"\n size=\"small\"\n isLoading={reloadStart}>\n Reload\n </Button>\n </div>\n </div>\n </Alert>\n </div>\n )}\n {(organizationId == '' || organizationId === 'null') &&\n (isOrgAdmin ? (\n <div className=\"mb5 mt5\">\n <h2 className=\"\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.create-new-organization',\n })}\n </h2>\n\n <AddOrganization\n userEmail={email}\n clientId={clientId}\n updateOrgInfo={infoUpdatedCreateOrganization}\n showToast={showToast}\n />\n </div>\n ) : (\n <div className=\"flex flex-column items-center\">\n <span className=\"c-on-base\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.not-yet-assigned-1',\n })}\n </span>\n <span className=\"c-on-base\">\n {intl.formatMessage({\n id:\n 'store/my-organization.my-organization.not-yet-assigned-2',\n })}\n </span>\n </div>\n ))}\n {defaultOrgAssignment && defaultOrgAssignment.id && (\n <div className=\"ba b--light-gray\">\n <DefaultAssignmentInfo\n clientId={clientId}\n defaultAssignment={defaultOrgAssignment}\n userRole={userRole}\n infoUpdated={infoUpdatedDefaultAssignment}\n showToast={showToast}\n isOrgAdmin={isOrgAdmin}\n />\n\n {((userRole &&\n userRole.name &&\n userRole.name === 'manager') ||\n isOrgAdmin) && (\n <MyUsers\n isCurrentUserAdmin={isOrgAdmin}\n organizationId={organizationId}\n email={email}\n showToast={showToast}\n />\n )}\n </div>\n )}\n </div>\n )\n }\n </ToastConsumer>\n )}\n </ContentWrapper>\n )\n}\n\nexport default React.memo(injectIntl(MyOrganization))\n\n```"
}
] |
code_organizations_6d3f9d43
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/MyUsers.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { useQuery, useMutation, useApolloClient } from 'react-apollo'\nimport { Button } from 'vtex.styleguide'\nimport { pathOr, find, propEq } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport { Input } from 'vtex.styleguide'\n\nimport { documentSerializer } from '../utils/documentSerializer'\n\nimport AddUser from './modals/AddUser'\nimport UserConfirmationModal from './modals/UserConfirmationModal'\nimport UserEditModal from './modals/UserEditModal'\n\nimport documentQuery from '../graphql/documents.graphql'\nimport DELETE_DOCUMENT from '../graphql/deleteDocument.graphql'\nimport UPDATE_DOCUMENT from '../graphql/updateDocument.graphql'\nimport UserListItem from './UserListItem'\n\nimport { updateCacheDeleteUser } from '../utils/cacheUtils'\nimport {\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n BUSINESS_ROLE,\n BUSINESS_ROLE_FIELDS,\n BUSINESS_ROLE_SCHEMA,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_FIELDS,\n ORG_ASSIGNMENT_SCHEMA,\n} from '../utils/const'\nimport { getErrorMessage } from '../utils/graphqlErrorHandler'\n\ninterface Props {\n isCurrentUserAdmin: boolean\n email: string\n organizationId: string\n showToast: (message: any) => void\n intl: any\n}\n\nconst MyUsers = ({\n isCurrentUserAdmin,\n organizationId,\n email,\n showToast,\n intl,\n}: Props) => {\n const PAGE_SIZE_STEPPER = 100\n const [searchUser, setSearchUser] = useState('')\n const [updateDocument] = useMutation(UPDATE_DOCUMENT)\n const [deleteDocument] = useMutation(DELETE_DOCUMENT, {\n update: (cache: any, { data }: any) =>\n updateCacheDeleteUser(cache, data, organizationId),\n })\n\n const [isAddNewUserOpen, setIsAddNewUserOpen] = useState(false)\n\n const [isDeleteConfirmationOpen, setIsDeleteConfirmationOpen] = useState(\n false\n )\n\n const [deleteConfirmationLoading, setDeleteConfirmationLoading] = useState(\n false\n )\n\n const [sharedOrgAssignment, setSharedOrgAssignment] = useState(\n ({} as any) as OrganizationAssignment\n )\n\n const client = useApolloClient()\n\n const [isUserEditOpen, setIsUserEditOpen] = useState(false)\n\n const { data: roleData } = useQuery(documentQuery, {\n variables: {\n acronym: BUSINESS_ROLE,\n fields: BUSINESS_ROLE_FIELDS,\n schema: BUSINESS_ROLE_SCHEMA,\n },\n })\n const { data: orgAssignments } = useQuery(documentQuery, {\n skip: organizationId == '',\n variables: {\n acronym: ORG_ASSIGNMENT,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `businessOrganizationId=${organizationId}`,\n schema: ORG_ASSIGNMENT_SCHEMA,\n page: 1,\n pageSize: PAGE_SIZE_STEPPER,\n sort: 'email ASC',\n },\n })\n\n const { data: defaultAssignmentData } = useQuery(documentQuery, {\n skip: organizationId == '',\n variables: {\n acronym: ORG_ASSIGNMENT,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `businessOrganizationId=${organizationId} AND email=${email}`,\n schema: ORG_ASSIGNMENT_SCHEMA,\n },\n })\n\n const rolesList: any[] = documentSerializer(\n pathOr([], ['myDocuments'], roleData)\n )\n const roles: Role[] = rolesList.map((role: any) => ({\n label: role.label,\n value: role.id,\n name: role.name,\n }))\n\n const assignments: OrganizationAssignment[] = documentSerializer(\n pathOr([], ['myDocuments'], orgAssignments)\n )\n\n const defaultAssignment: OrganizationAssignment[] = documentSerializer(\n pathOr([], ['myDocuments'], defaultAssignmentData)\n )\n\n const defaultUserAssignment = find(\n propEq('email', email),\n defaultAssignment\n ) as OrganizationAssignment\n\n const deleteOrgAssignment = (assignment: OrganizationAssignment) => {\n return deleteDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n documentId: assignment.id,\n },\n })\n }\n\n // ** Delete Org Assignment\n // ** Remove `organizationId` from CL\n // ** Remove `isOrgAdmin` from CL\n const deleteAssignmentWithUser = (assignment: OrganizationAssignment) => {\n return deleteOrgAssignment(assignment)\n .then(() => {\n return client.query({\n query: documentQuery,\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${assignment.email}`,\n },\n })\n })\n .then(({ data }: any) => {\n const clid = pathOr('', ['myDocuments', 0, 'id'], data)\n return updateDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: [\n { key: 'id', value: clid },\n { key: 'organizationId', value: '' },\n { key: 'isOrgAdmin', value: 'false' },\n { key: 'approved', value: 'false' },\n ],\n },\n },\n })\n })\n }\n\n // Delete user - [Delete Btn clicked]\n const deleteUserAssignment = (assignmentId: string) => {\n const assignment = find(propEq('id', assignmentId), assignments)\n setSharedOrgAssignment(assignment as OrganizationAssignment)\n setIsDeleteConfirmationOpen(true)\n }\n\n // Confirm delete - [Confirm delete btn clicked]\n // ** delete org assignment with user if request is approved\n const confirmDelete = () => {\n setDeleteConfirmationLoading(true)\n deleteAssignmentWithUser(sharedOrgAssignment)\n .then(() => {\n setDeleteConfirmationLoading(false)\n setIsDeleteConfirmationOpen(false)\n setSharedOrgAssignment(({} as any) as OrganizationAssignment)\n })\n .catch((e: Error) => {\n const message = getErrorMessage(e)\n setDeleteConfirmationLoading(false)\n setIsDeleteConfirmationOpen(false)\n setSharedOrgAssignment(({} as any) as OrganizationAssignment)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.user.delete.error',\n })} ${message}`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n })\n }\n\n // Close delete confirmation\n const closeDelete = () => {\n setIsDeleteConfirmationOpen(false)\n setSharedOrgAssignment(({} as any) as OrganizationAssignment)\n }\n\n // Edit organization assignment - [Edit Btn clicked]\n const editUser = (assignmentId: string) => {\n const assignment = find(propEq('id', assignmentId), assignments)\n setSharedOrgAssignment(assignment as OrganizationAssignment)\n setIsUserEditOpen(true)\n }\n\n // Close edit organization assignment\n const closeUserEditModal = () => {\n setSharedOrgAssignment(({} as any) as OrganizationAssignment)\n setIsUserEditOpen(false)\n }\n\n // Create organization assignment - [New organization Btn clicked]\n const addNewUser = () => {\n setIsAddNewUserOpen(true)\n }\n\n // close modals org assignment create\n const closeModalAddNewUser = () => {\n setIsAddNewUserOpen(false)\n }\n\n const handleChangeSearch = (event: any) => {\n setSearchUser(event.target.value)\n }\n\n // eslint-disable-next-line prettier/prettier\n const assignmentsFilter = assignments.filter(item => item.email?.toLowerCase().includes(searchUser))\n\n return defaultUserAssignment ? (\n <div className=\"flex flex-column pa5\">\n <div className=\"flex-row\">\n <div className=\"fl pr2\">\n <h3>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.users-in-organization',\n })}\n </h3>\n </div>\n <div className=\"fl pl3 mt5\">\n <Button\n variation=\"secondary\"\n size=\"small\"\n onClick={() => addNewUser()}>\n {intl.formatMessage({\n id: 'store/my-organization.my-user.table.button.add-new',\n })}\n </Button>\n </div>\n </div>\n <div className=\"flex flex-column\">\n <div>\n <Input\n placeholder=\"Search\"\n value={searchUser}\n onChange={handleChangeSearch}\n />\n </div>\n <div>\n <div className=\"mb5\">\n {assignmentsFilter.map(\n (assignment: OrganizationAssignment, index: number) => {\n return (\n <div key={`list-item-${index}`}>\n <UserListItem\n isCurrentUserAdmin={isCurrentUserAdmin}\n isDefaultAssignment={\n defaultUserAssignment.id == assignment.id\n }\n orgAssignment={assignment}\n edit={editUser}\n deleteAssignment={deleteUserAssignment}\n />\n </div>\n )\n }\n )}\n </div>\n </div>\n <UserConfirmationModal\n isOpen={isDeleteConfirmationOpen}\n isLoading={deleteConfirmationLoading}\n onConfirm={confirmDelete}\n onClose={closeDelete}\n assignment={sharedOrgAssignment}\n confirmAction={intl.formatMessage({\n id: 'store/my-organization.my-user.delete-confirmation-action',\n })}\n message={intl.formatMessage({\n id: 'store/my-organization.my-user.delete-confirmation-message',\n })}\n />\n <UserEditModal\n isOpen={isUserEditOpen}\n onClose={closeUserEditModal}\n onSave={closeUserEditModal}\n orgAssignment={sharedOrgAssignment}\n roles={roles}\n showToast={showToast}\n isCurrentUserAdmin={isCurrentUserAdmin}\n />\n <AddUser\n roles={roles}\n organizationId={organizationId}\n isOpen={isAddNewUserOpen}\n onClose={closeModalAddNewUser}\n onSuccess={closeModalAddNewUser}\n showToast={showToast}\n isCurrentUserAdmin={isCurrentUserAdmin}\n existingUsers={assignments.map((assignment: OrganizationAssignment) =>\n pathOr('', ['personaId_linked', 'email'], assignment)\n )}\n />\n </div>\n </div>\n ) : (\n <div />\n )\n}\n\nexport default injectIntl(MyUsers)\n\n```"
}
] |
code_organizations_2ec3a2be
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/DefaultAssignmentInfo.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState } from 'react'\nimport { injectIntl } from 'react-intl'\nimport { reject, filter, propEq, pathOr } from 'ramda'\nimport { Button } from 'vtex.styleguide'\nimport { useApolloClient, useMutation } from 'react-apollo'\n\nimport WarningModal from './modals/WarningModal'\nimport ConfirmationModal from './modals/ConfirmationModal'\n\nimport DOCUMENTS from '../graphql/documents.graphql'\nimport UPDATE_DOCUMENT from '../graphql/updateDocument.graphql'\nimport DELETE_DOCUMENT from '../graphql/deleteDocument.graphql'\n\nimport { getErrorMessage } from '../utils/graphqlErrorHandler'\nimport { documentSerializer } from '../utils/documentSerializer'\nimport {\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_FIELDS,\n ORG_ASSIGNMENT_SCHEMA,\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n BUSINESS_ORGANIZATION,\n} from '../utils/const'\n\nimport { updateCacheProfile } from '../utils/cacheUtils'\n\ninterface Props {\n clientId: string\n defaultAssignment: OrganizationAssignment\n userRole: any\n infoUpdated: () => void\n showToast: (message: any) => void\n intl: any\n isOrgAdmin: boolean\n}\n\nconst DefaultAssignmentInfo = ({\n clientId,\n defaultAssignment,\n userRole,\n infoUpdated,\n showToast,\n intl,\n isOrgAdmin,\n}: Props) => {\n const [isLeaveWarningOpen, setIsLeaveWarningOpen] = useState(false)\n const [\n isDeleteAssignmentWarningOpen,\n setIsDeleteAssignmentWarningOpen,\n ] = useState(false)\n\n const [\n isDeleteOrgConfirmationOpen,\n setIsDeleteOrgConfirmationOpen,\n ] = useState(false)\n\n const [\n deleteOrgConfirmationLoading,\n setDeleteOrgConfirmationLoading,\n ] = useState(false)\n\n const [isLeaveOrgConfirmationOpen, setIsLeaveOrgConfirmationOpen] = useState(\n false\n )\n\n const [\n leaveOrgConfirmationLoading,\n setLeaveOrgConfirmationLoading,\n ] = useState(false)\n\n const [isLeaveBtnLoading, setIsLeaveBtnLoading] = useState(false)\n const [isDeleteBtnLoading, setIsDeleteBtnLoading] = useState(false)\n\n const client = useApolloClient()\n const [updateDocument] = useMutation(UPDATE_DOCUMENT)\n const [deleteDocument] = useMutation(DELETE_DOCUMENT)\n\n // Cancel leave\n const closeLeaveOrganization = () => {\n setIsLeaveOrgConfirmationOpen(false)\n }\n\n // Cancel leave warning\n const closeLeaveOrganizationMessageModal = () => {\n setIsLeaveWarningOpen(false)\n }\n\n // Check conditions before leave - [Leave btn clicked]\n const leaveOrganization = () => {\n const orgId = pathOr('', ['businessOrganizationId'], defaultAssignment)\n const email = pathOr('', ['email'], defaultAssignment)\n setIsLeaveBtnLoading(true)\n\n // get all approved organization assignments\n client\n .query({\n query: DOCUMENTS,\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `(organizationId=${orgId})`,\n },\n fetchPolicy: 'no-cache',\n })\n .then(({ data }: any) => {\n if (data) {\n const clients = documentSerializer(data ? data.myDocuments : [])\n\n // orgAdmins belongs to this organization\n const orgAdmins = filter(propEq('isOrgAdmin', 'true'), clients)\n\n // orgAdmins except current user\n const orgAdminsExcept = reject(propEq('email', email), orgAdmins)\n\n // Ok to leave if\n // ** organization admins except current user\n if (orgAdminsExcept.length > 0) {\n // show leave confirmation\n setIsLeaveOrgConfirmationOpen(true)\n setIsLeaveBtnLoading(false)\n } else {\n // show warning\n setIsLeaveWarningOpen(true)\n setIsLeaveBtnLoading(false)\n }\n }\n })\n .catch((e: any) => {\n setIsLeaveBtnLoading(false)\n const message = getErrorMessage(e)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.organization.leave.error',\n })}\"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n return Promise.resolve({ myDocuments: [] })\n })\n }\n\n // Confirm leave - [Leave organization]\n const confirmLeaveOrganization = () => {\n setLeaveOrgConfirmationLoading(true)\n const assignmentId = pathOr('', ['id'], defaultAssignment)\n\n // update organization assignment status to declined\n deleteDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n documentId: assignmentId,\n },\n })\n .then(() => {\n // remove client organizationId\n return updateDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: [\n { key: 'id', value: clientId },\n { key: 'organizationId', value: '' },\n { key: 'approved', value: isOrgAdmin ? 'true' : 'false' },\n // { key: 'isOrgAdmin', value: 'false' },\n ],\n },\n },\n update: (cache: any) => updateCacheProfile(cache, ''),\n })\n })\n .then(() => {\n setLeaveOrgConfirmationLoading(false)\n setIsLeaveOrgConfirmationOpen(false)\n\n infoUpdated()\n })\n .catch((e: any) => {\n const message = getErrorMessage(e)\n setLeaveOrgConfirmationLoading(false)\n setIsLeaveOrgConfirmationOpen(false)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.organization.leave.error',\n })}\"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n })\n }\n\n // close delete warning\n const closeDeleteAssignmentWarningModal = () => {\n setIsDeleteAssignmentWarningOpen(false)\n }\n\n // delete confirmation open\n const deleteOrganization = () => {\n setIsDeleteOrgConfirmationOpen(true)\n }\n\n // close delete confirmation\n const closeDeleteOrganization = () => {\n setIsDeleteOrgConfirmationOpen(false)\n }\n\n // Check conditions before delete - [Delete btn clicked]\n const deleteCurrentOrganization = () => {\n const orgId = pathOr('', ['businessOrganizationId'], defaultAssignment)\n const email = pathOr('', ['email'], defaultAssignment)\n setIsDeleteBtnLoading(true)\n\n // get all approved organization assignments\n client\n .query({\n query: DOCUMENTS,\n variables: {\n acronym: ORG_ASSIGNMENT,\n schema: ORG_ASSIGNMENT_SCHEMA,\n fields: ORG_ASSIGNMENT_FIELDS,\n where: `(businessOrganizationId=${orgId})`,\n },\n fetchPolicy: 'no-cache',\n })\n .then(({ data }: any) => {\n if (data) {\n const assignmentsData = documentSerializer(\n data ? data.myDocuments : []\n )\n\n // assignments except current user\n const assignmentsExceptMe = reject(\n propEq('email', email),\n assignmentsData\n )\n\n // Delete organization if\n // ** No other user exists\n if (assignmentsExceptMe && assignmentsExceptMe.length > 0) {\n setIsDeleteAssignmentWarningOpen(true)\n setIsDeleteBtnLoading(false)\n } else {\n setIsDeleteBtnLoading(false)\n deleteOrganization()\n }\n }\n })\n .catch((e: any) => {\n setIsDeleteBtnLoading(false)\n const message = getErrorMessage(e)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.organization.leave.error',\n })}\"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n return Promise.resolve({ myDocuments: [] })\n })\n }\n\n // Confirm delete - [Delete organization]\n const confirmDeleteOrganization = () => {\n setDeleteOrgConfirmationLoading(true)\n const assignmentId = pathOr('', ['id'], defaultAssignment)\n\n // delete current organization assignment\n return deleteDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n documentId: assignmentId,\n },\n })\n .then(() => {\n const orgId: string = pathOr(\n '',\n ['businessOrganizationId'],\n defaultAssignment\n )\n\n // delete organization\n return deleteDocument({\n variables: {\n acronym: BUSINESS_ORGANIZATION,\n documentId: orgId,\n },\n })\n })\n .then(() => {\n // remove client organization id\n return updateDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: [\n { key: 'id', value: clientId },\n { key: 'organizationId', value: '' },\n { key: 'approved', value: isOrgAdmin ? 'true' : 'false' },\n // { key: 'isOrgAdmin', value: 'false' },\n ],\n },\n },\n update: (cache: any) => updateCacheProfile(cache, ''),\n })\n })\n .then(() => {\n setDeleteOrgConfirmationLoading(false)\n setIsDeleteOrgConfirmationOpen(false)\n infoUpdated()\n })\n .catch((e: any) => {\n const message = getErrorMessage(e)\n setDeleteOrgConfirmationLoading(false)\n setIsDeleteOrgConfirmationOpen(false)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.organization.delete.error',\n })} \"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n })\n }\n\n return (\n <div className=\"pa5\">\n <div>\n <h3>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.organization',\n })}\n </h3>\n </div>\n <div className=\"flex flex-row\">\n <div className=\"fl mt3 w-40\">\n <div className=\"w-100 pt2 pb2\">\n <span>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.organization.name',\n })}\n :{' '}\n </span>\n <span className=\"b\">\n {pathOr(\n '',\n ['businessOrganizationId_linked', 'name'],\n defaultAssignment\n )}\n </span>\n </div>\n <div className=\"w-100 pt2 pb2\">\n <span>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.role',\n })}{' '}\n </span>\n :{' '}\n <span className=\"b\">\n {' '}\n {userRole && userRole.label ? userRole.label : ''}\n </span>\n </div>\n <div className=\"w-100 pt2 pb2\"></div>\n </div>\n <div className=\"fl w-20 flex flex-column\">\n <span className=\"pa2\">\n <Button\n variation=\"danger-tertiary\"\n size=\"small\"\n isLoading={isLeaveBtnLoading}\n onClick={() => leaveOrganization()}\n block>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.leave',\n })}\n </Button>\n </span>\n {isOrgAdmin && (\n <span className=\"pa2\">\n <Button\n variation=\"danger-tertiary\"\n isLoading={isDeleteBtnLoading}\n size=\"small\"\n onClick={() => deleteCurrentOrganization()}\n block>\n {intl.formatMessage({\n id: 'store/my-organization.my-organization.delete',\n })}\n </Button>\n </span>\n )}\n </div>\n <WarningModal\n onOk={closeLeaveOrganizationMessageModal}\n onClose={closeLeaveOrganizationMessageModal}\n isOpen={isLeaveWarningOpen}\n assignment={defaultAssignment}\n title={intl.formatMessage({\n id: 'store/my-organization.my-organization.unable-to-leave-title',\n })}\n messageLine1={intl.formatMessage({\n id:\n 'store/my-organization.my-organization.unable-to-leave-message1',\n })}\n messageLine2={\n isOrgAdmin\n ? intl.formatMessage({\n id:\n 'store/my-organization.my-organization.unable-to-leave-manager-message2',\n })\n : intl.formatMessage({\n id:\n 'store/my-organization.my-organization.unable-to-leave-message2',\n })\n }\n />\n\n <WarningModal\n onOk={closeDeleteAssignmentWarningModal}\n onClose={closeDeleteAssignmentWarningModal}\n isOpen={isDeleteAssignmentWarningOpen}\n assignment={defaultAssignment}\n title={intl.formatMessage({\n id: 'store/my-organization.my-organization.unable-to-delete-title',\n })}\n messageLine1={intl.formatMessage({\n id:\n 'store/my-organization.my-organization.unable-to-delete-message1',\n })}\n messageLine2={intl.formatMessage({\n id:\n 'store/my-organization.my-organization.unable-to-delete-message2',\n })}\n />\n\n <ConfirmationModal\n isOpen={isLeaveOrgConfirmationOpen}\n isLoading={leaveOrgConfirmationLoading}\n onConfirm={confirmLeaveOrganization}\n onClose={closeLeaveOrganization}\n assignment={defaultAssignment}\n confirmAction={intl.formatMessage({\n id: 'store/my-organization.my-organization.button.leave',\n })}\n message={intl.formatMessage({\n id: 'store/my-organization.my-organization.leave.message',\n })}\n />\n\n <ConfirmationModal\n isOpen={isDeleteOrgConfirmationOpen}\n isLoading={deleteOrgConfirmationLoading}\n onConfirm={confirmDeleteOrganization}\n onClose={closeDeleteOrganization}\n assignment={defaultAssignment}\n confirmAction={intl.formatMessage({\n id: 'store/my-organization.my-organization.button.delete',\n })}\n message={intl.formatMessage({\n id: 'store/my-organization.my-organization.delete.message',\n })}\n />\n </div>\n </div>\n )\n}\n\nexport default injectIntl(DefaultAssignmentInfo)\n\n```"
}
] |
code_organizations_6b49a498
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/CurrencyInput.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { FC, useCallback, useMemo } from 'react'\nimport { Input } from 'vtex.styleguide'\n\ninterface Props extends React.ComponentPropsWithoutRef<typeof Input> {\n separator?: string;\n valueAsString?: boolean;\n}\n\nconst getDigitsFromValue = (value = '') => value.replace(/(-(?!\\d))|[^0-9|-]/g, '') || ''\n\nconst padDigits = (digits: string) => {\n const desiredLength = 3\n const actualLength = digits.length\n\n if (actualLength >= desiredLength) {\n return digits\n\n }\n\n const amountToAdd = desiredLength - actualLength\n const padding = '0'.repeat(amountToAdd)\n\n return padding + digits\n}\n\nconst removeLeadingZeros = (number: string) =>\n number.replace(/^0+([0-9]+)/, '$1')\n\nconst addDecimalToNumber = (number: string, separator: string) => {\n const centsStartingPosition = number.length - 2\n const dollars = removeLeadingZeros(number.substring(0, centsStartingPosition))\n const cents = number.substring(centsStartingPosition)\n\n return dollars + separator + cents\n}\n\nconst toCurrency = (separator: string, value?: string) => {\n const digits = getDigitsFromValue(value)\n const digitsWithPadding = padDigits(digits)\n\n return addDecimalToNumber(digitsWithPadding, separator)\n}\n\nconst CurrencyInput: FC<Props> = ({\n onChange,\n separator = ',',\n value,\n valueAsString,\n ...props\n}) => {\n const handleChange = useCallback(\n (event) => {\n const { value: stringValue } = event.target\n const cents = typeof stringValue === 'string' ? parseInt(stringValue.replace(',', ''), 10) : undefined\n event.persist()\n\n // eslint-disable-next-line prettier/prettier\n onChange?.(({\n target: {\n value: valueAsString ? toCurrency(separator, stringValue) : cents,\n },\n } as unknown) as React.ChangeEvent<HTMLInputElement>)\n },\n [onChange, valueAsString, separator]\n )\n\n const innerValue = useMemo(() => {\n const stringValue = typeof value === 'number' ? value.toString() : value\n\n if (stringValue) {\n return toCurrency(separator, stringValue as string)\n }\n return\n }, [value, separator])\n\n return (\n <Input\n inputMode=\"numeric\"\n pattern=\"[0-9,]*\"\n {...props}\n value={innerValue}\n onChange={handleChange}\n />\n )\n}\n\nexport default CurrencyInput\n\n```"
}
] |
code_organizations_47562faf
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/__tests__/index.test.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\ndescribe('Product description scenario', () => {\n it('should work', () => {\n expect(1).toBe(1)\n })\n})\n\n```"
}
] |
code_organizations_2e4f8940
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/getProfile.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Profile($customFields: String) {\n profile (customFields: $customFields){\n id\n email\n customFields {\n key\n value\n }\n }\n}\n\n```"
}
] |
code_organizations_97f96e72
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/deleteDocument.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation deleteDocument($acronym: String!, $documentId: String!) {\n deleteMyDocument(acronym: $acronym, documentId: $documentId) {\n id\n cacheId\n }\n}\n\n```"
}
] |
code_organizations_56f809e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/documents.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery getDocuments(\n $acronym: String\n $fields: [String]\n $schema: String\n $where: String\n $page: Int\n $pageSize: Int,\n $sort: String\n) {\n myDocuments(\n acronym: $acronym\n fields: $fields\n schema: $schema\n where: $where\n page: $page\n pageSize: $pageSize,\n sort: $sort\n ) {\n id\n fields {\n key\n value\n }\n }\n}\n\n```"
}
] |
code_organizations_06a1cf20
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/createDocument.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation createDocument(\n $acronym: String!\n $document: DocumentInput\n $schema: String\n) {\n createMyDocument(acronym: $acronym, document: $document, schema: $schema) {\n id\n cacheId\n }\n}\n\n```"
}
] |
code_organizations_32e4c793
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/updateDocument.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nmutation updateDocument(\n $acronym: String!\n $document: DocumentInput\n $schema: String\n) {\n updateMyDocument(acronym: $acronym, document: $document, schema: $schema) {\n id\n cacheId\n }\n}\n\n```"
}
] |
code_organizations_e2e0b7e1
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/graphql/getSession.graphql from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```graphql\nquery Session {\n getSession {\n id\n adminUserId\n profile {\n id\n }\n }\n}\n\n```"
}
] |
code_organizations_63f18727
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/modules/session.ts from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```typescript\nimport { SessionPromise } from 'vtex.render-runtime'\n\nexport function getSession() {\n return window &&\n (window as any).__RENDER_8_SESSION__ &&\n (window as any).__RENDER_8_SESSION__.sessionPromise\n ? ((window as any).__RENDER_8_SESSION__.sessionPromise as Promise<\n SessionPromise\n >)\n : null\n}\n\n```"
}
] |
code_organizations_84bf3bc7
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/modals/UserConfirmationModal.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ModalDialog } from 'vtex.styleguide'\nimport { pathOr } from 'ramda'\nimport { injectIntl } from 'react-intl'\n\ninterface Props {\n isOpen: boolean\n isLoading: boolean\n onConfirm: Function\n onClose: Function\n assignment: OrganizationAssignment\n confirmAction: string\n message: string\n intl: any\n}\n\nconst UserConfirmationModal = ({\n isOpen,\n isLoading,\n onConfirm,\n onClose,\n assignment,\n confirmAction,\n message,\n intl,\n}: Props) => {\n return (\n <ModalDialog\n centered\n loading={isLoading}\n confirmation={{\n onClick: () => onConfirm(assignment),\n label: confirmAction,\n isDangerous: true,\n }}\n cancelation={{\n onClick: () => onClose(),\n label: intl.formatMessage({\n id: 'store/my-organization.button.cancel',\n }),\n }}\n isOpen={isOpen}\n onClose={() => onClose()}>\n <h1>{confirmAction}</h1>\n <div className=\"flex flex-column mb5 mt5\">\n <div>\n <span>{message}</span>\n <span className=\"b\">{pathOr('', ['email'], assignment)}</span>\n </div>\n </div>\n </ModalDialog>\n )\n}\n\nexport default injectIntl(UserConfirmationModal)\n\n```"
}
] |
code_organizations_e1a52afb
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/modals/WarningModal.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { Modal, Button } from 'vtex.styleguide'\nimport { pathOr } from 'ramda'\nimport { injectIntl } from 'react-intl'\n\ninterface Props {\n isOpen: boolean\n onOk: Function\n onClose: Function\n assignment: OrganizationAssignment\n title: string\n messageLine1?: string\n messageLine2?: string\n intl: any\n}\n\nconst WarningModal = ({\n isOpen,\n onOk,\n onClose,\n assignment,\n title,\n messageLine1,\n messageLine2,\n intl,\n}: Props) => {\n return (\n <Modal\n isOpen={isOpen}\n title={title}\n responsiveFullScreen\n centered\n bottomBar={\n <div className=\"nowrap\">\n <span className=\"mr4\">\n <Button variation=\"tertiary\" onClick={() => onOk()}>\n {intl.formatMessage({ id: 'store/my-organization.button.ok' })}\n </Button>\n </span>\n </div>\n }\n onClose={() => onClose()}>\n <div className=\"flex flex-column mb5 mt5\">\n <div>\n <span>{messageLine1}</span>\n <span className=\"b\">\n {pathOr('', ['businessOrganizationId_linked', 'name'], assignment)}\n </span>\n </div>\n <div className=\"mt2\">\n <span className=\"red\">{messageLine2}</span>\n </div>\n </div>\n </Modal>\n )\n}\n\nexport default injectIntl(WarningModal)\n\n```"
}
] |
code_organizations_ebf57bed
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/modals/ConfirmationModal.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React from 'react'\nimport { ModalDialog } from 'vtex.styleguide'\nimport { pathOr } from 'ramda'\nimport { injectIntl } from 'react-intl'\n\ninterface Props {\n isOpen: boolean\n isLoading: boolean\n onConfirm: Function\n onClose: Function\n assignment: OrganizationAssignment\n confirmAction: string\n message: string\n intl: any\n}\n\nconst ConfirmationModal = ({\n isOpen,\n isLoading,\n onConfirm,\n onClose,\n assignment,\n confirmAction,\n message,\n intl,\n}: Props) => {\n return (\n <ModalDialog\n centered\n loading={isLoading}\n confirmation={{\n onClick: () => onConfirm(assignment),\n label: confirmAction,\n isDangerous: true,\n }}\n cancelation={{\n onClick: () => onClose(),\n label: 'Cancel',\n }}\n isOpen={isOpen}\n onClose={() => onClose()}>\n <h1>\n {confirmAction}{' '}\n {intl.formatMessage({\n id: 'store/my-organization.errors.organization.text',\n })}\n </h1>\n <div className=\"flex flex-column mb5 mt5\">\n <div>\n <span>{message}</span>\n <span className=\"b\">\n {pathOr('', ['businessOrganizationId_linked', 'name'], assignment)}\n </span>\n </div>\n </div>\n </ModalDialog>\n )\n}\n\nexport default injectIntl(ConfirmationModal)\n\n```"
}
] |
code_organizations_0967651a
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/modals/UserEditModal.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { useState, useEffect } from 'react'\nimport { Modal, Button, Dropdown, Checkbox, Spinner } from 'vtex.styleguide'\nimport { useMutation, useQuery } from 'react-apollo'\nimport { pathOr } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport CurrencyInput from '../../components/CurrencyInput'\n\nimport { updateCacheEditUser, updateCacheClient } from '../../utils/cacheUtils'\nimport UPDATE_DOCUMENT from '../../graphql/updateDocument.graphql'\nimport GET_DOCUMENT from '../../graphql/documents.graphql'\n\nimport { documentSerializer } from '../../utils/documentSerializer'\n\nimport {\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_SCHEMA,\n} from '../../utils/const'\nimport { getErrorMessage } from '../../utils/graphqlErrorHandler'\n\ninterface Props {\n isOpen: boolean\n onClose: Function\n onSave: Function\n orgAssignment: OrganizationAssignment\n roles: Role[]\n showToast: (message: any) => void\n isCurrentUserAdmin: boolean\n intl: any\n}\n\nconst UserEditModal = ({\n isOpen,\n onClose,\n onSave,\n orgAssignment,\n roles,\n showToast,\n isCurrentUserAdmin,\n intl,\n}: Props) => {\n const [clientId, setClientId] = useState('')\n const [email, setEmail] = useState('')\n const [budgetAmount, setBudgetAmount] = useState('')\n const [roleId, setRoleId] = useState('')\n const [assignmentId, setAssignmentId] = useState('')\n const [organizationId, setOrganizationId] = useState('')\n const [isOrgAdmin, setIsOrgAdmin] = useState(false)\n\n const [updateUserDocument] = useMutation(UPDATE_DOCUMENT, {\n update: (cache: any, { data }: any) =>\n updateCacheEditUser(cache, data, roles, organizationId, roleId),\n })\n\n const [updateClientDocument] = useMutation(UPDATE_DOCUMENT)\n\n const { data: clientData, loading } = useQuery(GET_DOCUMENT, {\n skip: email === '',\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${email}`,\n },\n })\n\n useEffect(() => {\n const abortController = new AbortController()\n\n setEmail(pathOr('', ['email'], orgAssignment))\n setBudgetAmount(pathOr('', ['budgetAmount'], orgAssignment))\n setAssignmentId(pathOr('', ['id'], orgAssignment))\n setRoleId(pathOr('', ['roleId_linked', 'id'], orgAssignment))\n setOrganizationId(pathOr('', ['businessOrganizationId'], orgAssignment))\n\n return () => {\n abortController.abort()\n }\n }, [orgAssignment])\n\n useEffect(() => {\n const abortController = new AbortController()\n\n const clients = documentSerializer(clientData ? clientData.myDocuments : [])\n setClientId(pathOr('', [0, 'id'], clients))\n setIsOrgAdmin((pathOr('', [0, 'isOrgAdmin'], clients) as string) === 'true')\n\n return () => {\n abortController.abort()\n }\n }, [clientData])\n\n // update client if isOrgAdmin changed\n const updateClient = () => {\n const clients = documentSerializer(clientData ? clientData.myDocuments : [])\n if (\n (pathOr('', [0, 'isOrgAdmin'], clients) as string) !==\n isOrgAdmin.toString()\n ) {\n return updateClientDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: [\n { key: 'id', value: clientId },\n { key: 'isOrgAdmin', value: isOrgAdmin.toString() },\n ],\n },\n },\n update: (cache: any, { data }: any) =>\n updateCacheClient(\n cache,\n data,\n email,\n budgetAmount,\n organizationId,\n isOrgAdmin.toString()\n ),\n })\n } else {\n return Promise.resolve() as any\n }\n }\n\n const onSaveEdit = () => {\n updateClient()\n .then(() => {\n return updateUserDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n document: {\n fields: [\n { key: 'id', value: assignmentId },\n { key: 'budgetAmount', value: budgetAmount },\n { key: 'roleId', value: roleId },\n ],\n },\n schema: ORG_ASSIGNMENT_SCHEMA,\n },\n })\n })\n .then(() => {\n onSave()\n })\n .then(() => {\n window.location.reload()\n })\n .catch((e: Error) => {\n const message = getErrorMessage(e)\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.user.edit.error',\n })} \"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n })\n }\n\n return (\n <Modal\n isOpen={isOpen}\n title={intl.formatMessage({\n id: 'store/my-organization.edit-user.title',\n })}\n responsiveFullScreen\n centered\n bottomBar={\n <div className=\"nowrap\">\n <span className=\"mr4\">\n <Button variation=\"tertiary\" onClick={() => onClose()}>\n {intl.formatMessage({\n id: 'store/my-organization.button.cancel',\n })}\n </Button>\n </span>\n <span>\n <Button\n variation=\"secondary\"\n disabled={roleId === ''}\n onClick={() => onSaveEdit()}>\n {intl.formatMessage({ id: 'store/my-organization.button.save' })}\n </Button>\n </span>\n </div>\n }\n onClose={() => onClose()}>\n {loading ? (\n <Spinner />\n ) : (\n <div>\n <div className=\"mb5 mt5\">\n {intl.formatMessage({ id: 'store/my-organization.label.email' })} :{' '}\n {email}\n </div>\n <div className=\"mb5\">\n <CurrencyInput\n type=\"text\"\n label={intl.formatMessage({\n id: 'store/my-organization.budget-amount',\n })}\n onChange={(e: { target: { value: string } }) => {\n setBudgetAmount(e.target.value)\n }}\n defaultValue={budgetAmount}\n value={budgetAmount}\n />\n </div>\n <div className=\"mb5\">\n <Dropdown\n label={'Role'}\n options={roles}\n onChange={(e: { target: { value: string } }) => {\n setRoleId(e.target.value)\n }}\n value={roleId}\n errorMessage={roleId === '' ? 'Role is required' : ''}\n />\n </div>\n {isCurrentUserAdmin && (\n <div className=\"mb5\">\n <Checkbox\n checked={isOrgAdmin}\n name=\"disabled-checkbox-group\"\n label=\"Organization Admin\"\n onChange={(e: { target: { checked: boolean } }) => {\n setIsOrgAdmin(e.target.checked)\n }}\n id=\"option-0\"\n />\n </div>\n )}\n </div>\n )}\n </Modal>\n )\n}\n\nexport default injectIntl(UserEditModal)\n\n```"
}
] |
code_organizations_ff31df15
|
[
{
"role": "system",
"content": "You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms."
},
{
"role": "user",
"content": "Show me the implementation of organizations/react/components/modals/AddUser.tsx from the organizations VTEX app."
},
{
"role": "assistant",
"content": "Here's the implementation:\n\n```tsx\nimport React, { SyntheticEvent, useReducer } from 'react'\nimport { isEmpty, path, contains, pathOr } from 'ramda'\nimport { injectIntl } from 'react-intl'\nimport { Modal, Button, Dropdown, Input, Checkbox } from 'vtex.styleguide'\nimport CurrencyInput from '../../components/CurrencyInput'\nimport { useMutation, useApolloClient } from 'react-apollo'\n\nimport CREATE_DOCUMENT from '../../graphql/createDocument.graphql'\nimport UPDATE_DOCUMENT from '../../graphql/updateDocument.graphql'\nimport GET_DOCUMENT from '../../graphql/documents.graphql'\n\nimport { documentSerializer } from '../../utils/documentSerializer'\nimport { updateCacheAddUser, updateCacheClient } from '../../utils/cacheUtils'\nimport { getErrorMessage } from '../../utils/graphqlErrorHandler'\nimport {\n CLIENT_ACRONYM,\n CLIENT_FIELDS,\n ORG_ASSIGNMENT,\n ORG_ASSIGNMENT_SCHEMA,\n ORG_ASSIGNMENT_STATUS_APPROVED,\n} from '../../utils/const'\n\ninterface Props {\n isOpen: boolean\n onClose: Function\n onSuccess: Function\n existingUsers: string[]\n roles: Role[]\n organizationId: string\n showToast: (message: any) => void\n isCurrentUserAdmin: boolean\n intl: any\n}\n\ninterface State {\n email: string\n roleId: string\n budgetAmount: string\n personaId: string\n isOrgAdmin: boolean\n formErrors: Errors\n touched: {\n email: boolean\n roleId: boolean\n }\n messages: {\n type: string\n value: string\n }[]\n}\n\ninterface Errors {\n email: string[]\n roleId: string[]\n}\n\ntype Action<K, V = void> = V extends void ? { type: K } : { type: K } & V\n\ntype Actions =\n | Action<'CHANGE_ROLE', { args: { roleId: string } }>\n | Action<'CHANGE_EMAIL', { args: { email: string } }>\n | Action<'CHANGE_BUDGET_AMOUNT', { args: { budgetAmount: string } }>\n | Action<'CHANGE_PERSONA_ID', { args: { personaId: string } }>\n | Action<'CHANGE_IS_ORG_ADMIN', { args: { isOrgAdmin: boolean } }>\n | Action<\n 'RESPONSE',\n {\n args: {\n type: string\n message: string\n }\n }\n >\n | Action<'INPUT_TOUCHED', { args: { input: string } }>\n\nconst AddUser = ({\n isOpen,\n onClose,\n onSuccess,\n intl,\n roles,\n organizationId,\n existingUsers,\n showToast,\n isCurrentUserAdmin,\n}: Props) => {\n const client = useApolloClient()\n const [createDocument, { loading: loadingAdd }] = useMutation(CREATE_DOCUMENT)\n const [updateDocument, { loading: loadingUpdate }] = useMutation(\n UPDATE_DOCUMENT\n )\n\n const reducer = (state: State, action: Actions): State => {\n let errors: string[] = []\n switch (action.type) {\n case 'CHANGE_ROLE':\n if (isEmpty(action.args.roleId)) {\n errors = [\n intl.formatMessage({\n id: 'store/my-organization.errors.role-id.empty',\n }),\n ]\n }\n return {\n ...state,\n roleId: action.args.roleId,\n formErrors: { roleId: errors, email: state.formErrors.email },\n }\n case 'CHANGE_EMAIL': {\n if (isEmpty(action.args.email)) {\n errors = [\n intl.formatMessage({\n id: 'store/my-organization.errors.email.empty',\n }),\n ]\n } else if (\n !/^\\w+([.-]?\\w+)*@\\w+([.-]?\\w+)*(\\.\\w{2,3})+$/.test(action.args.email)\n ) {\n errors = [\n intl.formatMessage({\n id: 'store/my-organization.errors.email.invalid',\n }),\n ]\n } else if (contains(action.args.email, existingUsers)) {\n errors = [\n intl.formatMessage({\n id: 'store/my-organization.errors.email.exists',\n }),\n ]\n }\n\n return {\n ...state,\n email: action.args.email,\n formErrors: { roleId: state.formErrors.roleId, email: errors },\n }\n }\n case 'CHANGE_BUDGET_AMOUNT': {\n return {\n ...state,\n budgetAmount: action.args.budgetAmount,\n }\n }\n case 'CHANGE_IS_ORG_ADMIN':\n return {\n ...state,\n ...{ isOrgAdmin: action.args.isOrgAdmin },\n }\n case 'RESPONSE': {\n return {\n ...state,\n messages: [\n {\n type: action.args.type,\n value: action.args.message,\n },\n ],\n }\n }\n case 'INPUT_TOUCHED': {\n if (action.args.input == 'email') {\n return {\n ...state,\n touched: {\n email: true,\n roleId: state.touched.roleId,\n },\n }\n } else if (action.args.input == 'roleId') {\n return {\n ...state,\n touched: {\n roleId: true,\n email: state.touched.email,\n },\n }\n }\n return state\n }\n case 'CHANGE_PERSONA_ID':\n return {\n ...state,\n personaId: action.args.personaId,\n }\n default:\n throw new Error(`Unhandled action type on my-users`)\n }\n }\n const initialState = {\n roleId: '',\n email: '',\n budgetAmount: '',\n isOrgAdmin: false,\n personaId: '',\n formErrors: {\n email: [],\n roleId: [],\n },\n messages: [],\n touched: {\n email: false,\n roleId: false,\n },\n }\n const [state, dispatch] = useReducer(reducer, initialState)\n\n const handleGraphqlError = () => {\n return (e: Error) => {\n const message = getErrorMessage(e)\n dispatch({\n type: 'RESPONSE',\n args: {\n type: 'ERROR',\n message: message,\n },\n })\n return Promise.reject(message)\n }\n }\n\n const getClientFields = (clientId?: string) => {\n const fields = [\n { key: 'email', value: state.email },\n { key: 'budgetAmount', value: state.budgetAmount },\n { key: 'organizationId', value: organizationId },\n { key: 'isOrgAdmin', value: state.isOrgAdmin.toString() },\n { key: 'approved', value: 'true' },\n ]\n if (clientId) {\n fields.push({ key: 'id', value: clientId })\n }\n return fields\n }\n\n const getAssignmentFields = () => {\n const fields = [\n {\n key: 'businessOrganizationId',\n value: organizationId,\n },\n {\n key: 'email',\n value: state.email,\n },\n {\n key: 'budgetAmount',\n value: state.budgetAmount,\n },\n {\n key: 'roleId',\n value: state.roleId,\n },\n {\n key: 'status',\n value: ORG_ASSIGNMENT_STATUS_APPROVED,\n },\n ]\n\n return fields\n }\n\n const handleSubmit = (e: SyntheticEvent) => {\n e.preventDefault()\n\n if (state.email && state.roleId) {\n client\n .query({\n query: GET_DOCUMENT,\n variables: {\n acronym: CLIENT_ACRONYM,\n fields: CLIENT_FIELDS,\n where: `email=${state.email}`,\n },\n fetchPolicy: 'no-cache',\n })\n .then(({ data }: any) => {\n const clients = documentSerializer(data ? data.myDocuments : [])\n\n const clientIdData = pathOr('', [0, 'id'], clients)\n const organizationIdData = pathOr('', [0, 'organizationId'], clients)\n\n if (clients.length == 0) {\n return createDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: getClientFields(),\n },\n },\n update: (cache: any, { data }: any) =>\n updateCacheClient(\n cache,\n data,\n state.email,\n state.budgetAmount,\n organizationId,\n state.isOrgAdmin.toString()\n ),\n })\n } else if (\n organizationIdData == undefined ||\n organizationIdData === '' ||\n organizationIdData === 'null'\n ) {\n return updateDocument({\n variables: {\n acronym: CLIENT_ACRONYM,\n document: {\n fields: getClientFields(clientIdData),\n },\n },\n update: (cache: any, { data }: any) =>\n updateCacheClient(\n cache,\n data,\n state.email,\n state.budgetAmount,\n organizationId,\n state.isOrgAdmin.toString()\n ),\n })\n } else {\n showToast({\n message: intl.formatMessage({\n id:\n 'store/my-organization.my-organization.user.already.assigned',\n }),\n duration: 5000,\n horizontalPosition: 'right',\n })\n return Promise.reject()\n }\n })\n .then(() => {\n return createDocument({\n variables: {\n acronym: ORG_ASSIGNMENT,\n document: {\n fields: getAssignmentFields(),\n },\n schema: ORG_ASSIGNMENT_SCHEMA,\n },\n update: (cache: any, { data }: any) => {\n updateCacheAddUser(\n cache,\n data,\n roles,\n organizationId,\n state.email,\n state.budgetAmount,\n state.roleId\n )\n },\n })\n })\n .catch(handleGraphqlError())\n .then(() => {\n dispatch({\n type: 'RESPONSE',\n args: {\n type: 'SUCCESS',\n message: intl.formatMessage({\n id: 'store/my-organization.success',\n }),\n },\n })\n dispatch({\n type: 'CHANGE_EMAIL',\n args: { email: '' },\n })\n dispatch({\n type: 'CHANGE_BUDGET_AMOUNT',\n args: { budgetAmount: '' },\n })\n dispatch({\n type: 'CHANGE_ROLE',\n args: { roleId: '' },\n })\n dispatch({\n type: 'CHANGE_PERSONA_ID',\n args: { personaId: '' },\n })\n dispatch({\n type: 'CHANGE_IS_ORG_ADMIN',\n args: { isOrgAdmin: false },\n })\n\n onSuccess()\n })\n .catch((message: string) => {\n if (message) {\n showToast({\n message: `${intl.formatMessage({\n id: 'store/my-organization.toast.user.create.error',\n })} \"${message}\"`,\n duration: 5000,\n horizontalPosition: 'right',\n })\n }\n })\n }\n }\n\n return (\n <Modal\n title={intl.formatMessage({ id: 'store/my-organization.add-user.title' })}\n isOpen={isOpen}\n onClose={() => onClose()}>\n <form onSubmit={(e: SyntheticEvent) => handleSubmit(e)}>\n <div className=\"mt3 flex\">\n <Input\n type=\"text\"\n label={intl.formatMessage({ id: 'store/my-organization.email' })}\n onChange={(e: { target: { value: string } }) => {\n dispatch({\n type: 'CHANGE_EMAIL',\n args: { email: e.target.value },\n })\n dispatch({ type: 'INPUT_TOUCHED', args: { input: 'email' } })\n }}\n value={state.email}\n errorMessage={path(['formErrors', 'email', 0], state)}\n />\n </div>\n <div className=\"mt3 flex\">\n <CurrencyInput\n type=\"text\"\n label={intl.formatMessage({\n id: 'store/my-organization.budget-amount',\n })}\n onChange={(e: { target: { value: string } }) => {\n dispatch({\n type: 'CHANGE_BUDGET_AMOUNT',\n args: { budgetAmount: e.target.value },\n })\n dispatch({\n type: 'INPUT_TOUCHED',\n args: { input: 'budgetAmount' },\n })\n }}\n value={state.budgetAmount}\n errorMessage={path(['formErrors', 'budgetAmount', 0], state)}\n />\n </div>\n <div className=\"mt5\">\n <Dropdown\n label={intl.formatMessage({ id: 'store/my-organization.role-id' })}\n options={roles}\n onChange={(e: { target: { value: string } }) => {\n dispatch({\n type: 'CHANGE_ROLE',\n args: { roleId: e.target.value },\n })\n dispatch({ type: 'INPUT_TOUCHED', args: { input: 'roleId' } })\n }}\n value={state.roleId}\n errorMessage={path(['formErrors', 'roleId', 0], state)}\n />\n </div>\n {isCurrentUserAdmin && (\n <div className=\"mt5\">\n <Checkbox\n checked={state.isOrgAdmin}\n name=\"disabled-checkbox-group\"\n label=\"Organization Admin\"\n onChange={(e: { target: { checked: boolean } }) => {\n dispatch({\n type: 'CHANGE_IS_ORG_ADMIN',\n args: { isOrgAdmin: e.target.checked },\n })\n }}\n id=\"option-0\"\n />\n </div>\n )}\n\n <div className=\"mt5\">\n <Button\n variation=\"primary\"\n type=\"submit\"\n isLoading={loadingAdd || loadingUpdate}\n disabled={\n !state.touched.email ||\n !state.touched.roleId ||\n (state.touched.email && !isEmpty(state.formErrors.email)) ||\n (state.touched.roleId && !isEmpty(state.formErrors.roleId))\n }>\n {intl.formatMessage({ id: 'store/my-organization.add-user' })}\n </Button>\n </div>\n </form>\n </Modal>\n )\n}\n\nexport default injectIntl(AddUser)\n\n```"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.