Skip to content
Merged
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
120 changes: 104 additions & 16 deletions amplify/data/models/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,133 @@ import { a } from '@aws-amplify/backend';

export const orderModel = a
.model({
orderNumber: a.string().required(),
orderNumber: a
.string()
.required()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
storeId: a
.string()
.required()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['read']),
allow.publicApiKey().to(['create', 'read']),
]),
customerId: a.string(), // Puede ser userId o sessionId
customerId: a
.string()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]), // Puede ser userId o sessionId
customerType: a.enum(['registered', 'guest']),
items: a.hasMany('OrderItem', 'orderId'),
subtotal: a.float().required(),
shippingCost: a.float().default(0),
taxAmount: a.float().default(0),
totalAmount: a.float().required(),
currency: a.string().default('USD'),
customerEmail: a
.string()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
items: a
.hasMany('OrderItem', 'orderId')
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
subtotal: a
.float()
.required()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
shippingCost: a
.float()
.default(0)
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
taxAmount: a
.float()
.default(0)
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
totalAmount: a
.float()
.required()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
currency: a
.string()
.default('COP')
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
status: a.enum(['pending', 'processing', 'shipped', 'delivered', 'cancelled']),
paymentStatus: a.enum(['pending', 'paid', 'failed', 'refunded']),
paymentMethod: a.string(),
paymentId: a.string(), // ID de la transacción del gateway de pago
shippingAddress: a.json(),
billingAddress: a.json(),
customerInfo: a.json(), // Email, nombre, teléfono
notes: a.string(),
paymentMethod: a
.string()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
paymentId: a
.string()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]), // ID de la transacción del gateway de pago
shippingAddress: a
.json()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
billingAddress: a
.json()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
customerInfo: a
.json()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]), // Email, nombre, teléfono
notes: a
.string()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
storeOwner: a
.string()
.required()
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
store: a.belongsTo('UserStore', 'storeId'),
store: a
.belongsTo('UserStore', 'storeId')
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read']),
allow.publicApiKey().to(['create', 'read']),
]),
})
.secondaryIndexes((index) => [
index('storeId'),
index('customerId'),
index('orderNumber'),
index('status'),
index('storeOwner'),
index('customerEmail'),
])
.authorization((allow) => [
allow.ownerDefinedIn('storeOwner').to(['create', 'read', 'update']),
Expand Down
2 changes: 1 addition & 1 deletion app/api/stores/[storeId]/cart/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import { getCartCookieOptions } from '@/lib/cookies/cookiesOption';
import { getNextCorsHeaders } from '@/lib/utils/next-cors';
import { logger } from '@/renderer-engine/lib/logger';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart-fetcher';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { v4 as uuidv4 } from 'uuid';
Expand Down
2 changes: 1 addition & 1 deletion app/api/stores/[storeId]/checkout/complete/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import { getNextCorsHeaders } from '@/lib/utils/next-cors';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout-fetcher';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout';
import { NextRequest, NextResponse } from 'next/server';

export async function OPTIONS(request: NextRequest) {
Expand Down
4 changes: 2 additions & 2 deletions app/api/stores/[storeId]/checkout/direct/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/

import { getNextCorsHeaders } from '@/lib/utils/next-cors';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart-fetcher';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout-fetcher';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';

Expand Down
4 changes: 2 additions & 2 deletions app/api/stores/[storeId]/checkout/start/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/

import { getNextCorsHeaders } from '@/lib/utils/next-cors';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart-fetcher';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout-fetcher';
import { cartFetcher } from '@/renderer-engine/services/fetchers/cart';
import { checkoutFetcher } from '@/renderer-engine/services/fetchers/checkout';
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';

Expand Down
14 changes: 14 additions & 0 deletions app/store/hooks/data/useProducts/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Exportar el hook principal
export { useProducts } from './useProducts';

// Exportar tipos
export type * from './types';

// Exportar utilidades
export * from './utils';

// Exportar mutaciones
export * from './mutations';

// Exportar queries
export * from './queries';
1 change: 1 addition & 0 deletions app/store/hooks/data/useProducts/mutations/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useProductMutations } from './useProductMutations';
166 changes: 166 additions & 0 deletions app/store/hooks/data/useProducts/mutations/useProductMutations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import type { Schema } from '@/amplify/data/resource';
import { normalizeAttributesField, normalizeTagsField, withLowercaseName } from '@/app/store/hooks/utils/productUtils';
import { useCacheInvalidation } from '@/hooks/cache/useCacheInvalidation';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { generateClient } from 'aws-amplify/api';
import { getCurrentUser } from 'aws-amplify/auth';
import type { IProduct, ProductCreateInput, ProductUpdateInput } from '../types';

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

/**
* Hook para manejar todas las mutaciones de productos
*/
export const useProductMutations = (storeId: string | undefined) => {
const queryClient = useQueryClient();
const { invalidateProductCache } = useCacheInvalidation();

/**
* Mutación para crear un producto
*/
const createProductMutation = useMutation({
mutationFn: async (productData: ProductCreateInput) => {
const { username } = await getCurrentUser();
const dataToSend = withLowercaseName({
...productData,
attributes: normalizeAttributesField(
productData.attributes as string | { name?: string; values?: string[] }[] | undefined
),
tags: normalizeTagsField(productData.tags as string[] | string | undefined),
storeId: storeId || '',
owner: username,
status: productData.status || 'DRAFT',
quantity: productData.quantity || 0,
});

const { data } = await client.models.Product.create(dataToSend);
return data as IProduct;
},
onSuccess: async () => {
// Invalidar React Query cache
queryClient.invalidateQueries({ queryKey: ['products', storeId] });

// Invalidar caché del motor de renderizado
if (storeId) {
await invalidateProductCache(storeId);
}
},
});

/**
* Mutación para actualizar un producto
*/
const updateProductMutation = useMutation({
mutationFn: async (productData: ProductUpdateInput) => {
const dataToSend = withLowercaseName({
...productData,
attributes: normalizeAttributesField(
productData.attributes as string | { name?: string; values?: string[] }[] | undefined
),
tags: normalizeTagsField(productData.tags as string[] | string | undefined),
});

const { data } = await client.models.Product.update(dataToSend);
return data as IProduct;
},
onSuccess: async (updatedProduct) => {
// Invalidar caché del motor de renderizado
if (storeId) {
await invalidateProductCache(storeId, updatedProduct.id);
}
},
});

/**
* Mutación para eliminar un producto
*/
const deleteProductMutation = useMutation({
mutationFn: async (id: string) => {
await client.models.Product.delete({ id });
return id;
},
onSuccess: async (deletedId) => {
// Invalidar caché del motor de renderizado
if (storeId) {
await invalidateProductCache(storeId, deletedId);
}
},
});

/**
* 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 })));
return ids;
},
onSuccess: async (deletedIds) => {
// Invalidar caché del motor de renderizado para cada producto eliminado
if (storeId) {
await Promise.all(deletedIds.map((id) => invalidateProductCache(storeId, id)));
}
},
});

/**
* Mutación para duplicar un producto
*/
const duplicateProductMutation = useMutation({
mutationFn: async (id: string) => {
const { data: originalProduct } = await client.models.Product.get({ id });
if (!originalProduct) {
throw new Error(`Product with ID ${id} not found`);
}

const { username } = await getCurrentUser();

// Crear una copia del producto sin campos que se generan automáticamente
const duplicatedProduct = withLowercaseName({
storeId: originalProduct.storeId,
name: `${originalProduct.name} (Copia)`,
nameLowercase: `${originalProduct.name} (copia)`.toLowerCase(),
description: originalProduct.description,
price: originalProduct.price,
compareAtPrice: originalProduct.compareAtPrice,
costPerItem: originalProduct.costPerItem,
sku: originalProduct.sku ? `${originalProduct.sku}-copy` : undefined,
barcode: originalProduct.barcode,
quantity: 0,
category: originalProduct.category,
images: originalProduct.images,
attributes: originalProduct.attributes,
status: 'active',
slug: originalProduct.slug ? `${originalProduct.slug}-copy` : undefined,
featured: false,
tags: originalProduct.tags,
variants: originalProduct.variants,
collectionId: originalProduct.collectionId,
supplier: originalProduct.supplier,
owner: username,
});

const { data } = await client.models.Product.create(duplicatedProduct);
return data as IProduct;
},
onSuccess: async () => {
// Invalidar React Query cache
queryClient.invalidateQueries({ queryKey: ['products', storeId] });

// Invalidar caché del motor de renderizado
if (storeId) {
await invalidateProductCache(storeId);
}
},
});

return {
createProductMutation,
updateProductMutation,
deleteProductMutation,
deleteMultipleProductsMutation,
duplicateProductMutation,
};
};
1 change: 1 addition & 0 deletions app/store/hooks/data/useProducts/queries/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useProductQueries } from './useProductQueries';
Loading