mirror of
https://git.imnavajas.es/jjimenez/erp-imprimelibros.git
synced 2026-01-13 08:58:48 +00:00
haciendo pagos pendientes
This commit is contained in:
@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@ -20,15 +21,17 @@ import com.imprimelibros.erp.cart.dto.DireccionCardDTO;
|
||||
import com.imprimelibros.erp.cart.dto.DireccionShipment;
|
||||
import com.imprimelibros.erp.cart.dto.UpdateCartRequest;
|
||||
import com.imprimelibros.erp.common.Utils;
|
||||
import com.imprimelibros.erp.common.email.EmailService;
|
||||
import com.imprimelibros.erp.direcciones.DireccionService;
|
||||
import com.imprimelibros.erp.externalApi.skApiClient;
|
||||
import com.imprimelibros.erp.pedidos.Pedido;
|
||||
import com.imprimelibros.erp.pedidos.PedidoService;
|
||||
import com.imprimelibros.erp.pedidos.PedidoRepository;
|
||||
import com.imprimelibros.erp.presupuesto.PresupuestoRepository;
|
||||
|
||||
@Service
|
||||
public class CartService {
|
||||
|
||||
private final EmailService emailService;
|
||||
|
||||
private final CartRepository cartRepo;
|
||||
private final CartDireccionRepository cartDireccionRepo;
|
||||
private final CartItemRepository itemRepo;
|
||||
@ -36,14 +39,13 @@ public class CartService {
|
||||
private final PresupuestoRepository presupuestoRepo;
|
||||
private final DireccionService direccionService;
|
||||
private final skApiClient skApiClient;
|
||||
private final PedidoService pedidoService;
|
||||
private final PresupuestoService presupuestoService;
|
||||
private final PedidoRepository pedidoRepository;
|
||||
|
||||
public CartService(CartRepository cartRepo, CartItemRepository itemRepo,
|
||||
CartDireccionRepository cartDireccionRepo, MessageSource messageSource,
|
||||
PresupuestoFormatter presupuestoFormatter, PresupuestoRepository presupuestoRepo,
|
||||
DireccionService direccionService, skApiClient skApiClient,
|
||||
PedidoService pedidoService, PresupuestoService presupuestoService) {
|
||||
PresupuestoFormatter presupuestoFormatter, PresupuestoRepository presupuestoRepo, PedidoRepository pedidoRepository,
|
||||
DireccionService direccionService, skApiClient skApiClient,PresupuestoService presupuestoService, EmailService emailService) {
|
||||
this.cartRepo = cartRepo;
|
||||
this.itemRepo = itemRepo;
|
||||
this.cartDireccionRepo = cartDireccionRepo;
|
||||
@ -51,8 +53,9 @@ public class CartService {
|
||||
this.presupuestoRepo = presupuestoRepo;
|
||||
this.direccionService = direccionService;
|
||||
this.skApiClient = skApiClient;
|
||||
this.pedidoService = pedidoService;
|
||||
this.presupuestoService = presupuestoService;
|
||||
this.emailService = emailService;
|
||||
this.pedidoRepository = pedidoRepository;
|
||||
}
|
||||
|
||||
public Cart findById(Long cartId) {
|
||||
@ -264,7 +267,7 @@ public class CartService {
|
||||
}
|
||||
|
||||
double totalBeforeDiscount = base + iva4 + iva21 + shipment;
|
||||
int fidelizacion = pedidoService.getDescuentoFidelizacion(cart.getUserId());
|
||||
int fidelizacion = this.getDescuentoFidelizacion(cart.getUserId());
|
||||
double descuento = totalBeforeDiscount * fidelizacion / 100.0;
|
||||
double total = totalBeforeDiscount - descuento;
|
||||
|
||||
@ -291,6 +294,27 @@ public class CartService {
|
||||
return summary;
|
||||
}
|
||||
|
||||
public int getDescuentoFidelizacion(Long userId) {
|
||||
// descuento entre el 1% y el 6% para clientes fidelidad (mas de 1500€ en el
|
||||
// ultimo año)
|
||||
Instant haceUnAno = Instant.now().minusSeconds(365 * 24 * 60 * 60);
|
||||
double totalGastado = pedidoRepository.sumTotalByCreatedByAndCreatedAtAfter(userId, haceUnAno);
|
||||
if (totalGastado < 1200) {
|
||||
return 0;
|
||||
} else if (totalGastado >= 1200 && totalGastado < 1999) {
|
||||
return 1;
|
||||
} else if (totalGastado >= 2000 && totalGastado < 2999) {
|
||||
return 2;
|
||||
} else if (totalGastado >= 3000 && totalGastado < 3999) {
|
||||
return 3;
|
||||
} else if (totalGastado >= 4000 && totalGastado < 4999) {
|
||||
return 4;
|
||||
} else if (totalGastado >= 5000) {
|
||||
return 5;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public Map<String, Object> getCartSummary(Cart cart, Locale locale) {
|
||||
Map<String, Object> raw = getCartSummaryRaw(cart, locale);
|
||||
|
||||
@ -411,184 +435,6 @@ public class CartService {
|
||||
cartDireccionRepo.deleteByDireccionIdAndCartStatus(direccionId, Cart.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Long crearPedido(Long cartId, Long dirFactId, Locale locale) {
|
||||
|
||||
Cart cart = this.getCartById(cartId);
|
||||
List<CartItem> items = cart.getItems();
|
||||
|
||||
List<Map<String, Object>> presupuestoRequests = new ArrayList<>();
|
||||
Map<String, Object> presupuestoDireccionesRequest = new HashMap<>();
|
||||
List<Long> presupuestoIds = new ArrayList<>();
|
||||
|
||||
for (Integer i = 0; i < items.size(); i++) {
|
||||
CartItem item = items.get(i);
|
||||
Presupuesto pCart = item.getPresupuesto();
|
||||
|
||||
// Asegurarnos de trabajar con la entidad gestionada por JPA
|
||||
Presupuesto p = presupuestoRepo.findById(pCart.getId())
|
||||
.orElseThrow(() -> new IllegalStateException("Presupuesto no encontrado: " + pCart.getId()));
|
||||
|
||||
Map<String, Object> data_to_send = presupuestoService.toSkApiRequest(p, true);
|
||||
data_to_send.put("createPedido", 0);
|
||||
|
||||
// Recuperar el mapa anidado datosCabecera
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> datosCabecera = (Map<String, Object>) data_to_send.get("datosCabecera");
|
||||
if (datosCabecera != null) {
|
||||
Object tituloOriginal = datosCabecera.get("titulo");
|
||||
datosCabecera.put(
|
||||
"titulo",
|
||||
"[" + (i + 1) + "/" + items.size() + "] " + (tituloOriginal != null ? tituloOriginal : ""));
|
||||
}
|
||||
|
||||
Map<String, Object> direcciones_presupuesto = this.getDireccionesPresupuesto(cart, p);
|
||||
data_to_send.put("direcciones", direcciones_presupuesto.get("direcciones"));
|
||||
data_to_send.put("direccionesFP1", direcciones_presupuesto.get("direccionesFP1"));
|
||||
|
||||
presupuestoDireccionesRequest.put(p.getId().toString(), direcciones_presupuesto);
|
||||
|
||||
Map<String, Object> result = skApiClient.savePresupuesto(data_to_send);
|
||||
|
||||
if (result.containsKey("error")) {
|
||||
System.out.println("Error al guardar presupuesto en SK");
|
||||
System.out.println("-------------------------");
|
||||
System.out.println(result.get("error"));
|
||||
// decide si seguir con otros items o abortar:
|
||||
// continue; o bien throw ...
|
||||
continue;
|
||||
}
|
||||
|
||||
Object dataObj = result.get("data");
|
||||
if (!(dataObj instanceof Map<?, ?> dataRaw)) {
|
||||
System.out.println("Formato inesperado de 'data' en savePresupuesto: " + result);
|
||||
continue;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> dataMap = (Map<String, Object>) dataRaw;
|
||||
Long presId = ((Number) dataMap.get("id")).longValue();
|
||||
String skin = ((String) dataMap.get("iskn")).toString();
|
||||
p.setProveedor("Safekat");
|
||||
p.setProveedorRef1(skin);
|
||||
p.setProveedorRef2(presId);
|
||||
p.setEstado(Presupuesto.Estado.aceptado);
|
||||
presupuestoRepo.save(p);
|
||||
|
||||
presupuestoIds.add(p.getId());
|
||||
|
||||
presupuestoRequests.add(dataMap);
|
||||
}
|
||||
|
||||
// Crear el pedido en base a los presupuestos guardados
|
||||
if (presupuestoRequests.isEmpty()) {
|
||||
throw new IllegalStateException("No se pudieron guardar los presupuestos en SK.");
|
||||
} else {
|
||||
ArrayList<Long> presupuestoSkIds = new ArrayList<>();
|
||||
for (Map<String, Object> presData : presupuestoRequests) {
|
||||
Long presId = ((Number) presData.get("id")).longValue();
|
||||
presupuestoSkIds.add(presId);
|
||||
}
|
||||
Map<String, Object> ids = new HashMap<>();
|
||||
ids.put("presupuesto_ids", presupuestoSkIds);
|
||||
Long pedidoId = skApiClient.crearPedido(ids);
|
||||
if (pedidoId == null) {
|
||||
throw new IllegalStateException("No se pudo crear el pedido en SK.");
|
||||
}
|
||||
Pedido pedidoInterno = pedidoService.crearPedido(
|
||||
presupuestoIds,
|
||||
presupuestoDireccionesRequest,
|
||||
dirFactId,
|
||||
this.getCartSummaryRaw(cart, locale),
|
||||
"Safekat",
|
||||
String.valueOf(pedidoId),
|
||||
cart.getUserId());
|
||||
return pedidoInterno.getId();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> getDireccionesPresupuesto(Cart cart, Presupuesto presupuesto) {
|
||||
|
||||
List<Map<String, Object>> direccionesPresupuesto = new ArrayList<>();
|
||||
List<Map<String, Object>> direccionesPrueba = new ArrayList<>();
|
||||
if (cart.getOnlyOneShipment()) {
|
||||
List<CartDireccion> direcciones = cart.getDirecciones().stream().limit(1).toList();
|
||||
if (!direcciones.isEmpty()) {
|
||||
if (presupuesto.getServiciosJson() != null
|
||||
&& presupuesto.getServiciosJson().contains("deposito-legal")) {
|
||||
direccionesPresupuesto.add(direcciones.get(0).toSkMap(
|
||||
presupuesto.getSelectedTirada(),
|
||||
presupuesto.getPeso(),
|
||||
direcciones.get(0).getIsPalets(),
|
||||
false));
|
||||
|
||||
direccionesPresupuesto.add(direcciones.get(0).toSkMapDepositoLegal());
|
||||
}
|
||||
else {
|
||||
direccionesPresupuesto.add(direcciones.get(0).toSkMap(
|
||||
presupuesto.getSelectedTirada(),
|
||||
presupuesto.getPeso(),
|
||||
direcciones.get(0).getIsPalets(),
|
||||
false));
|
||||
}
|
||||
if (presupuesto.getServiciosJson() != null
|
||||
&& presupuesto.getServiciosJson().contains("ejemplar-prueba")) {
|
||||
direccionesPrueba.add(direcciones.get(0).toSkMap(
|
||||
1,
|
||||
presupuesto.getPeso(),
|
||||
false,
|
||||
true));
|
||||
}
|
||||
|
||||
Map<String, Object> direccionesRet = new HashMap<>();
|
||||
direccionesRet.put("direcciones", direccionesPresupuesto);
|
||||
if (!direccionesPrueba.isEmpty())
|
||||
direccionesRet.put("direccionesFP1", direccionesPrueba.get(0));
|
||||
else {
|
||||
direccionesRet.put("direccionesFP1", new ArrayList<>());
|
||||
}
|
||||
return direccionesRet;
|
||||
}
|
||||
} else {
|
||||
List<CartDireccion> direcciones = cart.getDirecciones().stream()
|
||||
.filter(d -> d.getPresupuesto() != null && d.getPresupuesto().getId().equals(presupuesto.getId()))
|
||||
.toList();
|
||||
|
||||
for (CartDireccion cd : direcciones) {
|
||||
|
||||
// direccion de ejemplar de prueba
|
||||
if (cd.getPresupuesto() == null || !cd.getPresupuesto().getId().equals(presupuesto.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (cd.getUnidades() == null || cd.getUnidades() <= 0) {
|
||||
direccionesPrueba.add(cd.toSkMap(
|
||||
1,
|
||||
presupuesto.getPeso(),
|
||||
false,
|
||||
true));
|
||||
} else {
|
||||
direccionesPresupuesto.add(cd.toSkMap(
|
||||
cd.getUnidades(),
|
||||
presupuesto.getPeso(),
|
||||
cd.getIsPalets(),
|
||||
false));
|
||||
}
|
||||
}
|
||||
if (presupuesto.getServiciosJson() != null
|
||||
&& presupuesto.getServiciosJson().contains("deposito-legal")) {
|
||||
CartDireccion cd = new CartDireccion();
|
||||
direccionesPresupuesto.add(cd.toSkMapDepositoLegal());
|
||||
}
|
||||
}
|
||||
Map<String, Object> direccionesRet = new HashMap<>();
|
||||
direccionesRet.put("direcciones", direccionesPresupuesto);
|
||||
if (!direccionesPrueba.isEmpty())
|
||||
direccionesRet.put("direccionesFP1", direccionesPrueba.get(0));
|
||||
else {
|
||||
direccionesRet.put("direccionesFP1", new ArrayList<>());
|
||||
}
|
||||
return direccionesRet;
|
||||
}
|
||||
|
||||
/***************************************
|
||||
* MÉTODOS PRIVADOS
|
||||
|
||||
Reference in New Issue
Block a user