Skip to content
Merged

Dev #37

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion amplify/data/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ const schema = a
onboardingCompleted: a.boolean().required(),
onboardingData: a.json(),
})
.secondaryIndexes(index => [index('storeId')])
.secondaryIndexes(index => [index('userId')])
.authorization(allow => [allow.authenticated().to(['read', 'update', 'delete', 'create'])]),

Product: a
Expand Down Expand Up @@ -142,6 +142,7 @@ const schema = a
collection: a.belongsTo('Collection', 'collectionId'),
owner: a.string().required(),
})
.secondaryIndexes(index => [index('storeId'), index('collectionId')])
.authorization(allow => [
allow.ownerDefinedIn('owner').to(['update', 'delete', 'read', 'create']),
allow.guest().to(['read']),
Expand Down
17 changes: 10 additions & 7 deletions app/(setup-layout)/my-store/hooks/useUserStores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { use } from 'react'
import { generateClient } from 'aws-amplify/data'
import type { Schema } from '@/amplify/data/resource'

const client = generateClient<Schema>()
const client = generateClient<Schema>({
authMode: 'userPool',
})

const STORE_LIMITS = {
Imperial: 5,
Expand Down Expand Up @@ -47,13 +49,14 @@ export function getUserStores(userId: string | null, userPlan?: string) {
async function fetchUserStores(userId: string, userPlan?: string) {
try {
// Obtener todas las tiendas del usuario (para verificar límites)
const { data: allUserStores } = await client.models.UserStore.list({
authMode: 'userPool',
filter: {
userId: { eq: userId },
const { data: allUserStores } = await client.models.UserStore.listUserStoreByUserId(
{
userId: userId,
},
selectionSet: ['storeId', 'storeName', 'storeType', 'onboardingCompleted'],
})
{
selectionSet: ['storeId', 'storeName', 'storeType', 'onboardingCompleted'],
}
)

const completedStores = allUserStores || []

Expand Down
8 changes: 7 additions & 1 deletion app/store/components/product-management/InventoryPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Icons } from '@/app/store/icons/index'
import { getStoreId } from '@/utils/store-utils'
import { useParams, usePathname } from 'next/navigation'
import { routes } from '@/utils/routes'

export function InventoryPage() {
const pathname = usePathname()
const params = useParams()
const storeId = getStoreId(params, pathname)
return (
<div className="bg-gray-100 p-3 w-full md:w-5xl mx-auto mt-8">
<h1 className="text-xl md:text-xl font-medium text-gray-800 mb-6">Inventario</h1>
Expand All @@ -24,7 +30,7 @@ export function InventoryPage() {
</p>

{/* Botón */}
<Link href="/productos">
<Link href={routes.store.products.main(storeId)}>
<Button className="bg-gray-800 hover:bg-gray-700 text-white">Ir a productos</Button>
</Link>
</Card>
Expand Down
3 changes: 1 addition & 2 deletions app/store/components/product-management/ProductList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,7 @@ export function ProductList({
<div className="rounded-md border">
{loading && (
<div className="py-8 text-center">
<Loader color="white" />
<p className="mt-2 text-sm text-muted-foreground">Cargando productos...</p>
<Loader color="black" size="large" centered text="Cargando nuevos productos..." />
</div>
)}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ export function ProductPagination({
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ export const useCollectionForm = ({
)

// Redirigir a la lista de colecciones
router.push(routes.store.collections(storeId))
router.push(routes.store.products.collections(storeId))
// No desactivamos isSubmitting para mantener el botón deshabilitado hasta la redirección
} catch (error) {
console.error('Error al guardar la colección:', error)
Expand Down
75 changes: 30 additions & 45 deletions app/store/hooks/useCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { generateClient } from 'aws-amplify/data'
import type { Schema } from '@/amplify/data/resource'
import { useQuery, useMutation, useQueryClient, UseQueryResult } from '@tanstack/react-query'

const client = generateClient<Schema>()
const client = generateClient<Schema>({
authMode: 'userPool',
})

// Clave base para las consultas de colecciones
const COLLECTIONS_KEY = 'collections'
Expand Down Expand Up @@ -65,17 +67,14 @@ export const useCollections = () => {
queryKey: [COLLECTIONS_KEY, id],
queryFn: async () => {
// Obtener la colección
const collection = await performOperation(() =>
client.models.Collection.get({ id }, { authMode: 'userPool' })
)
const collection = await performOperation(() => client.models.Collection.get({ id }))

// Si la colección existe, obtener sus productos
if (collection) {
// Obtener productos de la colección
const productsData = await performOperation(() =>
client.models.Product.list({
filter: { collectionId: { eq: id } },
authMode: 'userPool',
client.models.Product.listProductByCollectionId({
collectionId: id,
})
)

Expand All @@ -102,20 +101,23 @@ export const useCollections = () => {
return useQuery({
queryKey: [COLLECTIONS_KEY, 'list', storeId],
queryFn: () => {
const filter = storeId ? { storeId: { eq: storeId } } : undefined
if (!storeId) {
throw new Error('Store ID is required to list collections by store.')
}

return performOperation(() =>
client.models.Collection.list({
filter,
authMode: 'userPool',
client.models.Collection.listCollectionByStoreId({
storeId: storeId,
})
)
},
staleTime: 5 * 60 * 1000, // 5 minutos en caché
enabled: !!storeId,
})
}

/**
* Obtiene los productos de una colección específica
* Obtiene los productos de una colección específica usando el GSI en collectionId
* @param collectionId - ID de la colección
* @returns Resultado de la consulta con los productos de la colección
*/
Expand All @@ -124,9 +126,8 @@ export const useCollections = () => {
queryKey: [COLLECTIONS_KEY, collectionId, 'products'],
queryFn: () => {
return performOperation(() =>
client.models.Product.list({
filter: { collectionId: { eq: collectionId } },
authMode: 'userPool',
client.models.Product.listProductByCollectionId({
collectionId: collectionId,
})
)
},
Expand All @@ -141,11 +142,7 @@ export const useCollections = () => {
const useCreateCollection = () => {
return useMutation({
mutationFn: (collectionInput: CollectionInput) =>
performOperation(() =>
client.models.Collection.create(collectionInput, {
authMode: 'userPool',
})
),
performOperation(() => client.models.Collection.create(collectionInput)),
onSuccess: () => {
// Invalidar consultas para actualizar la lista
queryClient.invalidateQueries({ queryKey: [COLLECTIONS_KEY, 'list'] })
Expand All @@ -160,15 +157,10 @@ export const useCollections = () => {
return useMutation({
mutationFn: ({ id, data }: { id: string; data: Partial<CollectionInput> }) =>
performOperation(() =>
client.models.Collection.update(
{
id,
...data,
},
{
authMode: 'userPool',
}
)
client.models.Collection.update({
id,
...data,
})
),
onSuccess: data => {
// Actualizar la colección en caché
Expand All @@ -183,8 +175,7 @@ export const useCollections = () => {
*/
const useDeleteCollection = () => {
return useMutation({
mutationFn: (id: string) =>
performOperation(() => client.models.Collection.delete({ id }, { authMode: 'userPool' })),
mutationFn: (id: string) => performOperation(() => client.models.Collection.delete({ id })),
onSuccess: (_, id) => {
// Eliminar la colección de la caché
queryClient.removeQueries({ queryKey: [COLLECTIONS_KEY, id] })
Expand All @@ -202,13 +193,10 @@ export const useCollections = () => {
const addProductToCollection = async (collectionId: string, productId: string) => {
// Actualizar el producto para asignarle la colección
return performOperation(() =>
client.models.Product.update(
{
id: productId,
collectionId: collectionId,
},
{ authMode: 'userPool' }
)
client.models.Product.update({
id: productId,
collectionId: collectionId,
})
)
}

Expand All @@ -220,13 +208,10 @@ export const useCollections = () => {
const removeProductFromCollection = async (productId: string) => {
// Actualizar el producto para eliminar la referencia a la colección
return performOperation(() =>
client.models.Product.update(
{
id: productId,
collectionId: null, // Eliminar la referencia a la colección
},
{ authMode: 'userPool' }
)
client.models.Product.update({
id: productId,
collectionId: null, // Eliminar la referencia a la colección
})
)
}

Expand Down
47 changes: 23 additions & 24 deletions app/store/hooks/useProducts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import { generateClient } from 'aws-amplify/api'
import { getCurrentUser } from 'aws-amplify/auth'
import type { Schema } from '@/amplify/data/resource'

const client = generateClient<Schema>()
const client = generateClient<Schema>({
authMode: 'userPool',
})

/**
* Interfaz para representar un producto
Expand Down Expand Up @@ -126,7 +128,7 @@ export function useProducts(
const queryClient = useQueryClient()

// Valores por defecto para paginación
const limit = options?.limit || 60
const limit = options?.limit || 10
const sortDirection = options?.sortDirection || 'DESC'
const sortField = options?.sortField || 'creationDate'
const enabled = options?.enabled !== false && !!storeId
Expand All @@ -135,12 +137,15 @@ export function useProducts(
const fetchProductsPage = async ({ pageParam = null }: { pageParam: string | null }) => {
if (!storeId) throw new Error('Store ID is required')

const { data, nextToken } = await client.models.Product.list({
filter: { storeId: { eq: storeId } },
authMode: 'userPool',
limit,
nextToken: pageParam,
})
const { data, nextToken } = await client.models.Product.listProductByStoreId(
{
storeId: storeId,
},
{
limit,
nextToken: pageParam,
}
)

// Ordenamos manualmente los resultados
const sortedData = [...(data || [])].sort((a, b) => {
Expand Down Expand Up @@ -187,16 +192,13 @@ export function useProducts(
mutationFn: async (productData: ProductCreateInput) => {
const { username } = await getCurrentUser()

const { data } = await client.models.Product.create(
{
...productData,
storeId: storeId || '',
owner: username,
status: productData.status || 'DRAFT',
quantity: productData.quantity || 0,
},
{ authMode: 'userPool' }
)
const { data } = await client.models.Product.create({
...productData,
storeId: storeId || '',
owner: username,
status: productData.status || 'DRAFT',
quantity: productData.quantity || 0,
})

return data as IProduct
},
Expand Down Expand Up @@ -229,7 +231,7 @@ export function useProducts(
// Mutación para actualizar un producto
const updateProductMutation = useMutation({
mutationFn: async (productData: ProductUpdateInput) => {
const { data } = await client.models.Product.update(productData, { authMode: 'userPool' })
const { data } = await client.models.Product.update(productData)
return data as IProduct
},
onSuccess: updatedProduct => {
Expand Down Expand Up @@ -259,7 +261,7 @@ export function useProducts(
// Mutación para eliminar un producto
const deleteProductMutation = useMutation({
mutationFn: async (id: string) => {
await client.models.Product.delete({ id }, { authMode: 'userPool' })
await client.models.Product.delete({ id })
return id
},
onSuccess: deletedId => {
Expand Down Expand Up @@ -287,9 +289,7 @@ export function useProducts(
// Mutación para eliminar múltiples productos
const deleteMultipleProductsMutation = useMutation({
mutationFn: async (ids: string[]) => {
await Promise.all(
ids.map(id => client.models.Product.delete({ id }, { authMode: 'userPool' }))
)
await Promise.all(ids.map(id => client.models.Product.delete({ id })))
return ids
},
onSuccess: deletedIds => {
Expand Down Expand Up @@ -352,7 +352,6 @@ export function useProducts(
// Primero obtenemos todos los productos de la tienda actual
const { data: storeProducts } = await client.models.Product.list({
filter: { storeId: { eq: storeId } },
authMode: 'userPool',
})

// Buscamos el producto en los productos de la tienda
Expand Down
Loading