mirror of
https://git.imnavajas.es/jjimenez/erp-imprimelibros.git
synced 2026-01-12 16:38:48 +00:00
trabajando en obtener las direcciones para guardar
This commit is contained in:
5
pom.xml
5
pom.xml
@ -193,6 +193,11 @@
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<!-- IMPORTANTE: incluir dependencias con scope=system en el fat-jar -->
|
||||
<configuration>
|
||||
<!-- Esto hace que meta las dependencias con scope=system en BOOT-INF/lib -->
|
||||
<includeSystemScope>true</includeSystemScope>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!-- (Migraciones) Plugin Maven para generar/ejecutar changelogs -->
|
||||
|
||||
@ -14,11 +14,13 @@ import java.util.Objects;
|
||||
|
||||
import com.imprimelibros.erp.presupuesto.classes.PresupuestoFormatter;
|
||||
import com.imprimelibros.erp.presupuesto.dto.Presupuesto;
|
||||
import com.imprimelibros.erp.presupuesto.service.PresupuestoService;
|
||||
import com.imprimelibros.erp.cart.dto.CartDireccionRepository;
|
||||
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.direcciones.Direccion;
|
||||
import com.imprimelibros.erp.direcciones.DireccionService;
|
||||
import com.imprimelibros.erp.externalApi.skApiClient;
|
||||
import com.imprimelibros.erp.pedido.PedidoService;
|
||||
@ -36,12 +38,13 @@ public class CartService {
|
||||
private final DireccionService direccionService;
|
||||
private final skApiClient skApiClient;
|
||||
private final PedidoService pedidoService;
|
||||
private final PresupuestoService presupuestoService;
|
||||
|
||||
public CartService(CartRepository cartRepo, CartItemRepository itemRepo,
|
||||
CartDireccionRepository cartDireccionRepo, MessageSource messageSource,
|
||||
PresupuestoFormatter presupuestoFormatter, PresupuestoRepository presupuestoRepo,
|
||||
Utils utils, DireccionService direccionService, skApiClient skApiClient,
|
||||
PedidoService pedidoService) {
|
||||
PedidoService pedidoService, PresupuestoService presupuestoService) {
|
||||
this.cartRepo = cartRepo;
|
||||
this.itemRepo = itemRepo;
|
||||
this.cartDireccionRepo = cartDireccionRepo;
|
||||
@ -51,6 +54,7 @@ public class CartService {
|
||||
this.direccionService = direccionService;
|
||||
this.skApiClient = skApiClient;
|
||||
this.pedidoService = pedidoService;
|
||||
this.presupuestoService = presupuestoService;
|
||||
}
|
||||
|
||||
|
||||
@ -411,6 +415,72 @@ public class CartService {
|
||||
cartDireccionRepo.deleteByDireccionIdAndCartStatus(direccionId, Cart.Status.ACTIVE);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Long crearPedido(Long cartId) {
|
||||
|
||||
Cart cart = this.getCartById(cartId);
|
||||
List<CartItem> items = cart.getItems();
|
||||
|
||||
List<Map<String, Object>> presupuestoRequests = new ArrayList<>();
|
||||
|
||||
for (CartItem item : items) {
|
||||
Presupuesto p = item.getPresupuesto();
|
||||
|
||||
Map<String, Object> data_to_send = presupuestoService.toSkApiRequest(p, true);
|
||||
|
||||
Map<String, Object> result = skApiClient.savePresupuesto(data_to_send);
|
||||
|
||||
if (result.containsKey("error")) {
|
||||
System.out.println("Error al guardar presupuesto en SK: " + 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;
|
||||
|
||||
presupuestoRequests.add(dataMap);
|
||||
}
|
||||
|
||||
// Aquí ya tienes todos los presupuestos SK en presupuestoRequests
|
||||
// TODO: crear el pedido de verdad y devolver su ID
|
||||
// Long pedidoId = pedidoService.crearPedidoDesdePresupuestos(cart,
|
||||
// presupuestoRequests);
|
||||
// return pedidoId;
|
||||
|
||||
return 1L;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getDireccionesPresupuesto(Cart cart, Presupuesto presupuesto) {
|
||||
|
||||
List<CartDireccion> direcciones = cart.getDirecciones().stream()
|
||||
.filter(d -> d.getPresupuesto() != null && d.getPresupuesto().getId().equals(presupuesto.getId()))
|
||||
.toList();
|
||||
if(cart.getOnlyOneShipment()){
|
||||
direcciones = direcciones.stream().limit(1).toList();
|
||||
Direccion dir = direcciones.size() > 0 ? direcciones.get(0).getDireccion() : null;
|
||||
if(dir != null){
|
||||
asdaslkdjasldjaslkdjaslkdjaslkdjaslkjljaslkd
|
||||
}
|
||||
}
|
||||
List<Map<String, Object>> resultado = new ArrayList<>();
|
||||
for (CartDireccion cd : direcciones) {
|
||||
Map<String, Object> dirMap = new HashMap<>();
|
||||
dirMap.put("direccion", cd.getDireccion());
|
||||
dirMap.put("isPalets", cd.getIsPalets());
|
||||
dirMap.put("unidades", cd.getUnidades());
|
||||
resultado.add(dirMap);
|
||||
}
|
||||
return resultado;
|
||||
}
|
||||
|
||||
/***************************************
|
||||
* MÉTODOS PRIVADOS
|
||||
***************************************/
|
||||
@ -454,4 +524,6 @@ public class CartService {
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -128,6 +128,75 @@ public class skApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
public Map<String, Object> savePresupuesto(Map<String, Object> requestBody) {
|
||||
return performWithRetryMap(() -> {
|
||||
String url = this.skApiUrl + "api/guardar";
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
Object dataObj = responseBody.get("data");
|
||||
if (dataObj instanceof Map<?, ?> dataRaw) {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) dataRaw;
|
||||
|
||||
Boolean success = (Boolean) data.get("success");
|
||||
|
||||
// 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.
|
||||
if (success != null && !success) {
|
||||
Map<String, String> presupuestoData = mapper.convertValue(
|
||||
data.get("data"),
|
||||
new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
|
||||
if (presupuestoData != null && !presupuestoData.isEmpty()) {
|
||||
data.put("id", Long.valueOf(presupuestoData.get("id")));
|
||||
data.put("iskn", presupuestoData.get("iskn"));
|
||||
}
|
||||
} else {
|
||||
// Tu lógica actual: si success es true u otra cosa → error 2
|
||||
return Map.of("error", 2);
|
||||
}
|
||||
|
||||
// Devolvemos sólo la parte interesante: el data ya enriquecido
|
||||
return Map.of("data", data);
|
||||
}
|
||||
|
||||
// Si data no es un Map, devolvemos error genérico
|
||||
return Map.of("error", 1);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return Map.of("error", 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public Integer getMaxSolapas(Map<String, Object> requestBody, Locale locale) {
|
||||
try {
|
||||
String jsonResponse = performWithRetry(() -> {
|
||||
@ -238,7 +307,6 @@ public class skApiClient {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(authService.getToken());
|
||||
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
uri,
|
||||
HttpMethod.GET,
|
||||
@ -255,10 +323,10 @@ public class skApiClient {
|
||||
return Map.of("error", messageSource.getMessage("direcciones.error.noShippingCost", null, locale));
|
||||
} else {
|
||||
Double total = Optional.ofNullable(responseBody.get("data"))
|
||||
.filter(Number.class::isInstance)
|
||||
.map(Number.class::cast)
|
||||
.map(Number::doubleValue)
|
||||
.orElse(0.0);
|
||||
.filter(Number.class::isInstance)
|
||||
.map(Number.class::cast)
|
||||
.map(Number::doubleValue)
|
||||
.orElse(0.0);
|
||||
|
||||
return Map.of("data", total);
|
||||
}
|
||||
|
||||
@ -36,7 +36,7 @@ public class PaymentService {
|
||||
this.payRepo = payRepo;
|
||||
this.txRepo = txRepo;
|
||||
this.refundRepo = refundRepo;
|
||||
this.redsysService = redsysService;
|
||||
this.redsysService = redsysService;
|
||||
this.webhookEventRepo = webhookEventRepo;
|
||||
this.cartService = cartService;
|
||||
}
|
||||
@ -456,6 +456,8 @@ public class PaymentService {
|
||||
if (cart != null) {
|
||||
// Bloqueamos el carrito
|
||||
this.cartService.lockCartById(cart.getId());
|
||||
// Creamos el pedido
|
||||
this.cartService.crearPedido(cart.getId());
|
||||
// order ID es generado dentro de createOrderFromCart donde se marcan los
|
||||
// presupuestos como no editables
|
||||
// Long orderId =
|
||||
|
||||
@ -2,25 +2,41 @@ package com.imprimelibros.erp.pedido;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.imprimelibros.erp.externalApi.skApiClient;
|
||||
import com.imprimelibros.erp.presupuesto.service.PresupuestoService;
|
||||
|
||||
|
||||
@Service
|
||||
public class PedidoService {
|
||||
|
||||
protected final skApiClient skApiClient;
|
||||
protected final PresupuestoService presupuestoService;
|
||||
|
||||
public PedidoService(skApiClient skApiClient, PresupuestoService presupuestoService) {
|
||||
this.skApiClient = skApiClient;
|
||||
this.presupuestoService = presupuestoService;
|
||||
}
|
||||
|
||||
public int getDescuentoFidelizacion() {
|
||||
// descuento entre el 1% y el 6% para clientes fidelidad (mas de 1500€ en el ultimo año)
|
||||
// descuento entre el 1% y el 6% para clientes fidelidad (mas de 1500€ en el
|
||||
// ultimo año)
|
||||
double totalGastado = 1600.0; // Ejemplo, deberías obtenerlo del historial del cliente
|
||||
if(totalGastado < 1200) {
|
||||
if (totalGastado < 1200) {
|
||||
return 0;
|
||||
} else if(totalGastado >= 1200 && totalGastado < 1999) {
|
||||
} else if (totalGastado >= 1200 && totalGastado < 1999) {
|
||||
return 1;
|
||||
} else if(totalGastado >= 2000 && totalGastado < 2999) {
|
||||
} else if (totalGastado >= 2000 && totalGastado < 2999) {
|
||||
return 2;
|
||||
} else if(totalGastado >= 3000 && totalGastado < 3999) {
|
||||
} else if (totalGastado >= 3000 && totalGastado < 3999) {
|
||||
return 3;
|
||||
} else if(totalGastado >= 4000 && totalGastado < 4999) {
|
||||
} else if (totalGastado >= 4000 && totalGastado < 4999) {
|
||||
return 4;
|
||||
} else if(totalGastado >= 5000) {
|
||||
} else if (totalGastado >= 5000) {
|
||||
return 5;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -290,6 +290,10 @@ public class PresupuestoService {
|
||||
}
|
||||
|
||||
public Map<String, Object> toSkApiRequest(Presupuesto presupuesto) {
|
||||
return toSkApiRequest(presupuesto, false);
|
||||
}
|
||||
|
||||
public Map<String, Object> toSkApiRequest(Presupuesto presupuesto, Boolean toSave) {
|
||||
final int SK_CLIENTE_ID = 1284;
|
||||
final int SK_PAGINAS_CUADERNILLO = 32;
|
||||
|
||||
@ -343,9 +347,41 @@ public class PresupuestoService {
|
||||
faja.put("alto", presupuesto.getAltoFaja());
|
||||
body.put("faja", faja);
|
||||
}
|
||||
// body.put("servicios", servicios);
|
||||
|
||||
if( toSave ){
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("input_data", body);
|
||||
data.put("ferroDigital", 1);
|
||||
data.put("ferro", 0);
|
||||
data.put("marcapaginas", 0);
|
||||
data.put("retractilado5", 0);
|
||||
if(presupuesto.getServiciosJson() != null && presupuesto.getServiciosJson().indexOf("ejemplar-prueba")>0){
|
||||
data.put("prototipo", 1);
|
||||
}
|
||||
else{
|
||||
data.put("prototipo", 0);
|
||||
}
|
||||
if(presupuesto.getServiciosJson() != null && presupuesto.getServiciosJson().indexOf("retractilado")>0){
|
||||
data.put("retractilado", 1);
|
||||
}
|
||||
else{
|
||||
data.put("retractilado", 0);
|
||||
}
|
||||
data.put("ivaReducido", presupuesto.getIvaReducido() ? 1 : 0);
|
||||
data.put("confirmar", 1);
|
||||
Map<String, Object> datosCabecera = new HashMap<>();
|
||||
datosCabecera.put("titulo", presupuesto.getTitulo());
|
||||
datosCabecera.put("autor", presupuesto.getAutor());
|
||||
datosCabecera.put("isbn", presupuesto.getIsbn());
|
||||
datosCabecera.put("coleccion", "");
|
||||
datosCabecera.put("referenciaCliente", presupuesto.getId());
|
||||
data.put("datosCabecera", datosCabecera);
|
||||
return data;
|
||||
|
||||
}
|
||||
return body;
|
||||
|
||||
|
||||
}
|
||||
|
||||
public Integer getTipoImpresionId(Presupuesto presupuesto) {
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
package com.imprimelibros.erp.presupuesto;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.imprimelibros.erp.cart.CartService;
|
||||
|
||||
@SpringBootTest
|
||||
public class savePresupuestosTest {
|
||||
|
||||
@Autowired
|
||||
private CartService cartService;
|
||||
|
||||
@Test
|
||||
void testGuardarPresupuesto() {
|
||||
Long resultado = cartService.crearPedido(8L);
|
||||
|
||||
System.out.println("📦 Presupuesto guardado:");
|
||||
System.out.println(resultado);
|
||||
|
||||
// Aquí irían las aserciones para verificar que el presupuesto se guardó correctamente
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user