estructura inicial de carrito hecha

This commit is contained in:
2025-10-14 15:16:02 +02:00
parent 90376e61c8
commit a33ba3256b
11 changed files with 408 additions and 3 deletions

View File

@ -0,0 +1,89 @@
package com.imprimelibros.erp.cart;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CartService {
private final CartRepository cartRepo;
private final CartItemRepository itemRepo;
public CartService(CartRepository cartRepo, CartItemRepository itemRepo) {
this.cartRepo = cartRepo;
this.itemRepo = itemRepo;
}
/** Devuelve el carrito activo o lo crea si no existe. */
@Transactional
public Cart getOrCreateActiveCart(Long userId) {
return cartRepo.findByUserIdAndStatus(userId, Cart.Status.ACTIVE)
.orElseGet(() -> {
Cart c = new Cart();
c.setUserId(userId);
c.setStatus(Cart.Status.ACTIVE);
return cartRepo.save(c);
});
}
/** Lista items (presupuestos) del carrito activo del usuario. */
@Transactional
public List<CartItem> listItems(Long userId) {
Cart cart = getOrCreateActiveCart(userId);
return itemRepo.findByCartId(cart.getId());
}
/** Añade un presupuesto al carrito. Si ya está, no hace nada (idempotente). */
@Transactional
public void addPresupuesto(Long userId, Long presupuestoId) {
Cart cart = getOrCreateActiveCart(userId);
boolean exists = itemRepo.existsByCartIdAndPresupuestoId(cart.getId(), presupuestoId);
if (!exists) {
CartItem ci = new CartItem();
ci.setCart(cart);
ci.setPresupuestoId(presupuestoId);
itemRepo.save(ci);
}
}
/** Elimina una línea del carrito por ID de item (validando pertenencia). */
@Transactional
public void removeItem(Long userId, Long itemId) {
Cart cart = getOrCreateActiveCart(userId);
CartItem item = itemRepo.findById(itemId).orElseThrow(() -> new IllegalArgumentException("Item no existe"));
if (!item.getCart().getId().equals(cart.getId()))
throw new IllegalStateException("El item no pertenece a tu carrito");
itemRepo.delete(item);
}
/** Elimina una línea del carrito buscando por presupuesto_id. */
@Transactional
public void removeByPresupuesto(Long userId, Long presupuestoId) {
Cart cart = getOrCreateActiveCart(userId);
itemRepo.findByCartIdAndPresupuestoId(cart.getId(), presupuestoId)
.ifPresent(itemRepo::delete);
}
/** Vacía todo el carrito activo. */
@Transactional
public void clear(Long userId) {
Cart cart = getOrCreateActiveCart(userId);
itemRepo.deleteByCartId(cart.getId());
}
/** Marca el carrito como bloqueado (por ejemplo, antes de crear un pedido). */
@Transactional
public void lockCart(Long userId) {
Cart cart = getOrCreateActiveCart(userId);
cart.setStatus(Cart.Status.LOCKED);
cartRepo.save(cart);
}
@Transactional
public long countItems(Long userId) {
Cart cart = getOrCreateActiveCart(userId);
return itemRepo.findByCartId(cart.getId()).size();
}
}