haciendo pruebas en SK

This commit is contained in:
2025-11-09 14:46:41 +01:00
parent 7254c8f11b
commit 032e44b9c5
6 changed files with 229 additions and 61 deletions

View File

@ -1,6 +1,8 @@
package com.imprimelibros.erp.cart; package com.imprimelibros.erp.cart;
import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import com.imprimelibros.erp.cart.dto.DireccionCardDTO; import com.imprimelibros.erp.cart.dto.DireccionCardDTO;
@ -98,4 +100,53 @@ public class CartDireccion {
); );
} }
public Map<String, Object> toSkMap(Integer numeroUnidades, Double pesoKg, Boolean palets, Boolean ejemplarPrueba) {
Map<String, Object> direccion = new HashMap<>();
direccion.put("cantidad", numeroUnidades);
direccion.put("peso", pesoKg);
direccion.put("att", this.getDireccion().getAtt());
direccion.put("email", this.getDireccion().getUser().getUserName());
direccion.put("direccion", this.getDireccion().getDireccion());
direccion.put("pais_code3", this.getDireccion().getPaisCode3());
direccion.put("cp", this.getDireccion().getCp());
direccion.put("municipio", this.getDireccion().getCiudad());
direccion.put("provincia", this.getDireccion().getProvincia());
direccion.put("telefono", this.getDireccion().getTelefono());
direccion.put("entregaPieCalle", palets ? 1 : 0);
direccion.put("is_ferro_prototipo", ejemplarPrueba ? 1 : 0);
direccion.put("num_ferro_prototipo", ejemplarPrueba ? 1 : 0);
Map<String, Object> map = new HashMap<>();
map.put("direccion", direccion);
map.put("unidades", numeroUnidades);
map.put("entregaPalets", palets ? 1 : 0);
return map;
}
public Map<String, Object> toSkMapDepositoLegal() {
Map<String, Object> direccion = new HashMap<>();
direccion.put("cantidad", 4);
direccion.put("peso", 0);
direccion.put("att", "Unidades para Depósito Legal (sin envío)");
direccion.put("email", "");
direccion.put("direccion", "");
direccion.put("pais_code3", "esp");
direccion.put("cp", "");
direccion.put("municipio", "");
direccion.put("provincia", "");
direccion.put("telefono", "");
direccion.put("entregaPieCalle", 0);
direccion.put("is_ferro_prototipo", 0);
direccion.put("num_ferro_prototipo", 0);
Map<String, Object> map = new HashMap<>();
map.put("direccion", direccion);
map.put("unidades", 4);
map.put("entregaPalets", 0);
return map;
}
} }

View File

@ -57,14 +57,11 @@ public class CartService {
this.presupuestoService = presupuestoService; this.presupuestoService = presupuestoService;
} }
public Cart findById(Long cartId) { public Cart findById(Long cartId) {
return cartRepo.findById(cartId) return cartRepo.findById(cartId)
.orElseThrow(() -> new IllegalArgumentException("Carrito no encontrado")); .orElseThrow(() -> new IllegalArgumentException("Carrito no encontrado"));
} }
/** Devuelve el carrito activo o lo crea si no existe. */ /** Devuelve el carrito activo o lo crea si no existe. */
@Transactional @Transactional
public Cart getOrCreateActiveCart(Long userId) { public Cart getOrCreateActiveCart(Long userId) {
@ -223,8 +220,7 @@ public class CartService {
Map<String, Object> res = getShippingCost(cd, peso, unidades, locale); Map<String, Object> res = getShippingCost(cd, peso, unidades, locale);
if (res.get("success").equals(Boolean.FALSE)) { if (res.get("success").equals(Boolean.FALSE)) {
errorShipementCost = true; errorShipementCost = true;
} } else {
else{
shipment += (Double) res.get("shipment"); shipment += (Double) res.get("shipment");
iva21 += (Double) res.get("iva21"); iva21 += (Double) res.get("iva21");
} }
@ -236,8 +232,7 @@ public class CartService {
Map<String, Object> res = getShippingCost(cd, peso, 1, locale); Map<String, Object> res = getShippingCost(cd, peso, 1, locale);
if (res.get("success").equals(Boolean.FALSE)) { if (res.get("success").equals(Boolean.FALSE)) {
errorShipementCost = true; errorShipementCost = true;
} } else {
else{
shipment += (Double) res.get("shipment"); shipment += (Double) res.get("shipment");
iva21 += (Double) res.get("iva21"); iva21 += (Double) res.get("iva21");
} }
@ -288,8 +283,7 @@ public class CartService {
Map<String, Object> res = getShippingCost(cd_prueba, peso, 1, locale); Map<String, Object> res = getShippingCost(cd_prueba, peso, 1, locale);
if (res.get("success").equals(Boolean.FALSE)) { if (res.get("success").equals(Boolean.FALSE)) {
errorShipementCost = true; errorShipementCost = true;
} } else {
else{
shipment += (Double) res.get("shipment"); shipment += (Double) res.get("shipment");
iva21 += (Double) res.get("iva21"); iva21 += (Double) res.get("iva21");
} }
@ -408,10 +402,7 @@ public class CartService {
// delete cart directions by direccion id in ACTIVE carts // delete cart directions by direccion id in ACTIVE carts
@Transactional @Transactional
public void deleteCartDireccionesByDireccionId(Long direccionId) { public void deleteCartDireccionesByDireccionId(Long direccionId) {
/*List<CartDireccion> cartDirecciones = cartDireccionRepo.findByDireccion_IdAndCart_Status(direccionId, Cart.Status.ACTIVE);
for (CartDireccion cd : cartDirecciones) {
cartDireccionRepo.deleteById(cd.getId());
}*/
cartDireccionRepo.deleteByDireccionIdAndCartStatus(direccionId, Cart.Status.ACTIVE); cartDireccionRepo.deleteByDireccionIdAndCartStatus(direccionId, Cart.Status.ACTIVE);
} }
@ -423,10 +414,27 @@ public class CartService {
List<Map<String, Object>> presupuestoRequests = new ArrayList<>(); List<Map<String, Object>> presupuestoRequests = new ArrayList<>();
for (CartItem item : items) { for (Integer i = 0; i < items.size(); i++) {
CartItem item = items.get(i);
Presupuesto p = item.getPresupuesto(); Presupuesto p = item.getPresupuesto();
Map<String, Object> data_to_send = presupuestoService.toSkApiRequest(p, true); Map<String, Object> data_to_send = presupuestoService.toSkApiRequest(p, true);
data_to_send.put("createPedido", 0);
if (items.size() > 1) {
// 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"));
Map<String, Object> result = skApiClient.savePresupuesto(data_to_send); Map<String, Object> result = skApiClient.savePresupuesto(data_to_send);
@ -449,36 +457,90 @@ public class CartService {
presupuestoRequests.add(dataMap); presupuestoRequests.add(dataMap);
} }
// Aquí ya tienes todos los presupuestos SK en presupuestoRequests // Crear el pedido en base a los presupuestos guardados
// TODO: crear el pedido de verdad y devolver su ID if(presupuestoRequests.isEmpty()) {
// Long pedidoId = pedidoService.crearPedidoDesdePresupuestos(cart, throw new IllegalStateException("No se pudieron guardar los presupuestos en SK.");
// presupuestoRequests); }
// return pedidoId; else{
List<Long> presupuestoIds = new ArrayList<>();
return 1L; for (Map<String, Object> presData : presupuestoRequests) {
Long presId = ((Number) presData.get("id")).longValue();
presupuestoIds.add(presId);
}
Map<String, Object> ids = new HashMap<>();
ids.put("presupuesto_ids", presupuestoIds);
Long pedidoId = skApiClient.crearPedido(ids);
return pedidoId;
}
} }
public List<Map<String, Object>> getDireccionesPresupuesto(Cart cart, Presupuesto presupuesto) { public Map<String, Object> getDireccionesPresupuesto(Cart cart, Presupuesto presupuesto) {
List<Map<String, Object>> direccionesPresupuesto = new ArrayList<>();
List<Map<String, Object>> direccionesPrueba = new ArrayList<>();
List<CartDireccion> direcciones = cart.getDirecciones().stream() List<CartDireccion> direcciones = cart.getDirecciones().stream()
.filter(d -> d.getPresupuesto() != null && d.getPresupuesto().getId().equals(presupuesto.getId())) .filter(d -> d.getPresupuesto() != null && d.getPresupuesto().getId().equals(presupuesto.getId()))
.toList(); .toList();
if(cart.getOnlyOneShipment()){ if (cart.getOnlyOneShipment()) {
direcciones = direcciones.stream().limit(1).toList(); direcciones = direcciones.stream().limit(1).toList();
Direccion dir = direcciones.size() > 0 ? direcciones.get(0).getDireccion() : null; if (!direcciones.isEmpty()) {
if(dir != null){ direccionesPresupuesto.add(direcciones.get(0).toSkMap(
asdaslkdjasldjaslkdjaslkdjaslkdjaslkjljaslkd 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));
}
if (presupuesto.getServiciosJson() != null
&& presupuesto.getServiciosJson().contains("deposito-legal")) {
direccionesPresupuesto.add(direcciones.get(0).toSkMapDepositoLegal());
}
Map<String, Object> direccionesRet = new HashMap<>();
direccionesRet.put("direcciones", direccionesPresupuesto);
direccionesRet.put("direccionesFP1", direccionesPrueba.get(0));
return direccionesRet;
}
} else {
for (CartDireccion cd : cart.getDirecciones()) {
// 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());
} }
} }
List<Map<String, Object>> resultado = new ArrayList<>(); Map<String, Object> direccionesRet = new HashMap<>();
for (CartDireccion cd : direcciones) { direccionesRet.put("direcciones", direccionesPresupuesto);
Map<String, Object> dirMap = new HashMap<>(); if(!direccionesPrueba.isEmpty())
dirMap.put("direccion", cd.getDireccion()); direccionesRet.put("direccionesFP1", direccionesPrueba.get(0));
dirMap.put("isPalets", cd.getIsPalets()); else{
dirMap.put("unidades", cd.getUnidades()); direccionesRet.put("direccionesFP1", new ArrayList<>());
resultado.add(dirMap);
} }
return resultado; return direccionesRet;
} }
/*************************************** /***************************************
@ -524,6 +586,4 @@ public class CartService {
return result; return result;
} }
} }

View File

@ -2,6 +2,8 @@ package com.imprimelibros.erp.direcciones;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLRestriction; import org.hibernate.annotations.SQLRestriction;

View File

@ -164,19 +164,17 @@ public class skApiClient {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) dataRaw; Map<String, Object> data = (Map<String, Object>) dataRaw;
Boolean success = (Boolean) data.get("success"); Boolean success = (Boolean) (responseBody.get("success") != null ? responseBody.get("success")
: false);
Long id = ((Integer) data.get("id")).longValue();
String iskn = (String) data.get("iskn");
// OJO: aquí mantengo tu lógica tal cual (success == null o false => OK) // OJO: aquí mantengo tu lógica tal cual (success == null o false => OK)
// Si tu API realmente usa success=true como éxito, esto habría que invertirlo. // Si tu API realmente usa success=true como éxito, esto habría que invertirlo.
if (success != null && !success) { if (success != null && success) {
Map<String, String> presupuestoData = mapper.convertValue( if (id != null && iskn != null) {
data.get("data"), data.put("id", Long.valueOf(id));
new TypeReference<Map<String, String>>() { data.put("iskn", iskn);
});
if (presupuestoData != null && !presupuestoData.isEmpty()) {
data.put("id", Long.valueOf(presupuestoData.get("id")));
data.put("iskn", presupuestoData.get("iskn"));
} }
} else { } else {
// Tu lógica actual: si success es true u otra cosa → error 2 // Tu lógica actual: si success es true u otra cosa → error 2
@ -197,6 +195,58 @@ public class skApiClient {
}); });
} }
public Long crearPedido(Map<String, Object> requestBody) {
Map<String, Object> result = performWithRetryMap(() -> {
String url = this.skApiUrl + "api/crear-pedido";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(authService.getToken());
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
entity,
String.class);
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> responseBody = mapper.readValue(
response.getBody(),
new TypeReference<Map<String, Object>>() {
});
// Si la API devuelve "error" a nivel raíz
if (responseBody.get("error") != null) {
// Devolvemos un mapa con sólo el error para que el caller decida
return Map.of("error", responseBody.get("error"));
}
Boolean success = (Boolean) (responseBody.get("success") != null ? responseBody.get("success") : false);
Long id = ((Integer) responseBody.get("id")).longValue();
if (success != null && id != null && success) {
return Map.of("data", id);
} else {
// Tu lógica actual: si success es true u otra cosa → error 2
return Map.of("error", 2);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
return Map.of("error", 1);
}
});
if (result.get("error") != null) {
throw new RuntimeException("Error al crear el pedido: " + result.get("error"));
}
return (Long) result.get("data");
}
public Integer getMaxSolapas(Map<String, Object> requestBody, Locale locale) { public Integer getMaxSolapas(Map<String, Object> requestBody, Locale locale) {
try { try {
String jsonResponse = performWithRetry(() -> { String jsonResponse = performWithRetry(() -> {

View File

@ -315,9 +315,16 @@ public class PresupuestoService {
Map<String, Object> body = new HashMap<>(); Map<String, Object> body = new HashMap<>();
body.put("tipo_impresion_id", this.getTipoImpresionId(presupuesto)); body.put("tipo_impresion_id", this.getTipoImpresionId(presupuesto));
body.put("tirada", Arrays.stream(presupuesto.getTiradas()) if (toSave) {
.filter(Objects::nonNull) body.put("tirada", Arrays.stream(presupuesto.getTiradas())
.collect(Collectors.toList())); .filter(Objects::nonNull)
.map(tirada -> tirada + 4)
.collect(Collectors.toList()));
} else {
body.put("tirada", Arrays.stream(presupuesto.getTiradas())
.filter(Objects::nonNull)
.collect(Collectors.toList()));
}
body.put("tamanio", tamanio); body.put("tamanio", tamanio);
body.put("tipo", presupuesto.getTipoEncuadernacion()); body.put("tipo", presupuesto.getTipoEncuadernacion());
body.put("clienteId", SK_CLIENTE_ID); body.put("clienteId", SK_CLIENTE_ID);
@ -348,23 +355,22 @@ public class PresupuestoService {
body.put("faja", faja); body.put("faja", faja);
} }
if( toSave ){ if (toSave) {
Map<String, Object> data = new HashMap<>(); Map<String, Object> data = new HashMap<>();
data.put("input_data", body); data.put("input_data", body);
data.put("ferroDigital", 1); data.put("ferroDigital", 1);
data.put("ferro", 0); data.put("ferro", 0);
data.put("marcapaginas", 0); data.put("marcapaginas", 0);
data.put("retractilado5", 0); data.put("retractilado5", 0);
if(presupuesto.getServiciosJson() != null && presupuesto.getServiciosJson().indexOf("ejemplar-prueba")>0){ if (presupuesto.getServiciosJson() != null
&& presupuesto.getServiciosJson().indexOf("ejemplar-prueba") > 0) {
data.put("prototipo", 1); data.put("prototipo", 1);
} } else {
else{
data.put("prototipo", 0); data.put("prototipo", 0);
} }
if(presupuesto.getServiciosJson() != null && presupuesto.getServiciosJson().indexOf("retractilado")>0){ if (presupuesto.getServiciosJson() != null && presupuesto.getServiciosJson().indexOf("retractilado") > 0) {
data.put("retractilado", 1); data.put("retractilado", 1);
} } else {
else{
data.put("retractilado", 0); data.put("retractilado", 0);
} }
data.put("ivaReducido", presupuesto.getIvaReducido() ? 1 : 0); data.put("ivaReducido", presupuesto.getIvaReducido() ? 1 : 0);
@ -381,7 +387,6 @@ public class PresupuestoService {
} }
return body; return body;
} }
public Integer getTipoImpresionId(Presupuesto presupuesto) { public Integer getTipoImpresionId(Presupuesto presupuesto) {
@ -639,7 +644,7 @@ public class PresupuestoService {
if (presupuestoMaquetacion.getNumColumnas() > 1) { if (presupuestoMaquetacion.getNumColumnas() > 1) {
precio = precio.add(precio.multiply( precio = precio.add(precio.multiply(
BigDecimal.valueOf(presupuestoMaquetacion.getNumColumnas() - 1)) BigDecimal.valueOf(presupuestoMaquetacion.getNumColumnas() - 1))
.multiply(BigDecimal.valueOf(price.apply("columnas"))) ); .multiply(BigDecimal.valueOf(price.apply("columnas"))));
} }
precio = precio precio = precio

View File

@ -14,7 +14,7 @@ public class savePresupuestosTest {
@Test @Test
void testGuardarPresupuesto() { void testGuardarPresupuesto() {
Long resultado = cartService.crearPedido(8L); Long resultado = cartService.crearPedido(9L);
System.out.println("📦 Presupuesto guardado:"); System.out.println("📦 Presupuesto guardado:");
System.out.println(resultado); System.out.println(resultado);