Direcciones actualizables

This commit is contained in:
Mireya Serrano 2026-05-24 14:11:23 +02:00
parent a7c8242936
commit f4cf440ff0
3 changed files with 86 additions and 23 deletions

View File

@ -161,13 +161,13 @@ public class DolibarrClient {
public DolibarrAddressDto createThirdpartyAddress(Integer socid, DolibarrAddressDto dto) { public DolibarrAddressDto createThirdpartyAddress(Integer socid, DolibarrAddressDto dto) {
log.debug("Creating Dolibarr thirdparty address socid={}", socid); log.debug("Creating Dolibarr thirdparty address socid={}", socid);
Integer newId = restClient.post() Integer newId = restClient.post()
.uri("/thirdparties/{socid}/addresses", socid) .uri("/socaddress")
.body(dto) .body(dto)
.retrieve() .retrieve()
.body(Integer.class); .body(Integer.class);
return restClient.get() return restClient.get()
.uri("/thirdparties/{socid}/addresses/{id}", socid, newId) .uri("/socaddress/{id}", newId)
.retrieve() .retrieve()
.body(DolibarrAddressDto.class); .body(DolibarrAddressDto.class);
} }
@ -175,7 +175,9 @@ public class DolibarrClient {
public List<DolibarrAddressDto> getThirdpartyAddresses(Integer socid) { public List<DolibarrAddressDto> getThirdpartyAddresses(Integer socid) {
try{ try{
List<DolibarrAddressDto> addresses = restClient.get() List<DolibarrAddressDto> addresses = restClient.get()
.uri("/thirdparties/{socid}/addresses", socid) .uri(u -> u.path("/socaddress")
.queryParam("sqlfilters", "(s.fk_soc:=:'" + socid + "')")
.build())
.retrieve() .retrieve()
.body(new ParameterizedTypeReference<List<DolibarrAddressDto>>() {}); .body(new ParameterizedTypeReference<List<DolibarrAddressDto>>() {});
return addresses != null ? addresses : List.of(); return addresses != null ? addresses : List.of();
@ -188,6 +190,30 @@ public class DolibarrClient {
} }
} }
/** * Updates an existing address in Dolibarr. */
public DolibarrAddressDto updateThirdpartyAddress(Integer addressId, DolibarrAddressDto dto) {
log.debug("Updating Dolibarr address id={}", addressId);
restClient.put()
.uri("/socaddress/{id}", addressId)
.body(dto)
.retrieve()
.toBodilessEntity();
return restClient.get()
.uri("/socaddress/{id}", addressId)
.retrieve()
.body(DolibarrAddressDto.class);
}
/** * Deletes an address from Dolibarr. */
public void deleteThirdpartyAddress(Integer addressId) {
log.debug("Deleting Dolibarr address id={}", addressId);
restClient.delete()
.uri("/socaddress/{id}", addressId)
.retrieve()
.toBodilessEntity();
}
// ── Orders ──────────────────────────────────────────────────────────── // ── Orders ────────────────────────────────────────────────────────────
/** /**

View File

@ -8,12 +8,12 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
public record DolibarrAddressDto( public record DolibarrAddressDto(
Integer id, Integer id,
@JsonProperty("socid") Integer socid, @JsonProperty("fk_soc") Integer fkSoc,
String label, String label,
String address, String address,
String zip, String zip,
String city, String city,
@JsonProperty("id_country") Integer idCountry, @JsonProperty("fk_country") Integer fkCountry,
String phone, String phone,
@JsonProperty("default_address") Integer defaultAddress @JsonProperty("default_address") Integer defaultAddress
) {} ) {}

View File

@ -25,6 +25,8 @@ import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/** /**
* Pulls new PrestaShop orders and imports them into Dolibarr as sales orders and invoices. * Pulls new PrestaShop orders and imports them into Dolibarr as sales orders and invoices.
@ -199,46 +201,81 @@ public class OrderSyncService {
private void syncCustomerAddresses(Integer psCustomerId, Integer dolibarrThirdpartyId) { private void syncCustomerAddresses(Integer psCustomerId, Integer dolibarrThirdpartyId) {
try { try {
// 1. Obtener direcciones de PrestaShop
List<PrestashopAddressDto> psAddresses = prestashopClient.getCustomerAddresses(psCustomerId); List<PrestashopAddressDto> psAddresses = prestashopClient.getCustomerAddresses(psCustomerId);
if (psAddresses.isEmpty()) {
return;
}
// Get the default address ID to skip it (avoid duplication) // 2. Obtener direcciones existentes en Dolibarr
List<DolibarrAddressDto> dolibarrAddresses = dolibarrClient.getThirdpartyAddresses(dolibarrThirdpartyId);
PrestashopCustomerDto psCustomer = prestashopClient.getCustomer(psCustomerId); PrestashopCustomerDto psCustomer = prestashopClient.getCustomer(psCustomerId);
String defaultAddressId = psCustomer != null ? psCustomer.idDefaultAddress() : null; String defaultAddressId = psCustomer != null ? psCustomer.idDefaultAddress() : null;
// 3. Procesar cada dirección de PrestaShop
for (PrestashopAddressDto psAddr : psAddresses) { for (PrestashopAddressDto psAddr : psAddresses) {
// Skip the default address (already synced to thirdparty main fields) // Ignorar la dirección por defecto (ya está en thirdparty.address/city/zip)
if (psAddr.id() != null && psAddr.id().toString().equals(defaultAddressId)) { if (psAddr.id() != null && psAddr.id().toString().equals(defaultAddressId)) {
continue; continue;
} }
// Check if address already exists in Dolibarr String formattedAddress = formatAddress(psAddr.address1(), psAddr.address2());
List<DolibarrAddressDto> existingAddresses = dolibarrClient.getThirdpartyAddresses(dolibarrThirdpartyId); String formattedCity = psAddr.city();
boolean alreadyExists = existingAddresses.stream()
.anyMatch(a -> a.address() != null && a.address().equals(formatAddress(psAddr.address1(), psAddr.address2()))
&& a.city() != null && a.city().equals(psAddr.city()));
if (!alreadyExists) { // Buscar si existe una dirección con los mismos datos en Dolibarr
// Create new address in Dolibarr DolibarrAddressDto existingAddr = dolibarrAddresses.stream()
.filter(a -> a.address() != null && a.address().equals(formattedAddress)
&& a.city() != null && a.city().equals(formattedCity))
.findFirst()
.orElse(null);
if (existingAddr != null) {
// ACTUALIZAR: La dirección existe pero podría tener cambios en zip, phone, etc.
DolibarrAddressDto updatedAddr = new DolibarrAddressDto(
existingAddr.id(),
dolibarrThirdpartyId,
formatPersonName(psAddr.firstname(), psAddr.lastname()),
formattedAddress,
psAddr.postcode(),
formattedCity,
null,
psAddr.phone(),
0
);
dolibarrClient.updateThirdpartyAddress(existingAddr.id(), updatedAddr);
log.debug("Updated PS address {} in Dolibarr", psAddr.id());
} else {
// CREAR: Dirección nueva en PrestaShop
DolibarrAddressDto newAddr = new DolibarrAddressDto( DolibarrAddressDto newAddr = new DolibarrAddressDto(
null, null,
dolibarrThirdpartyId, dolibarrThirdpartyId,
formatPersonName(psAddr.firstname(), psAddr.lastname()), formatPersonName(psAddr.firstname(), psAddr.lastname()),
formatAddress(psAddr.address1(), psAddr.address2()), formattedAddress,
psAddr.postcode(), psAddr.postcode(),
psAddr.city(), formattedCity,
null, // id_country null,
psAddr.phone(), psAddr.phone(),
0 // not default 0
); );
dolibarrClient.createThirdpartyAddress(dolibarrThirdpartyId, newAddr); dolibarrClient.createThirdpartyAddress(dolibarrThirdpartyId, newAddr);
log.debug("Synced PS address {} to Dolibarr thirdparty {}", psAddr.id(), dolibarrThirdpartyId); log.debug("Created PS address {} in Dolibarr", psAddr.id());
} }
} }
// 4. ELIMINAR direcciones que ya no existen en PrestaShop
Set<String> psAddressStrings = psAddresses.stream()
.filter(a -> !(a.id() != null && a.id().toString().equals(defaultAddressId)))
.map(a -> formatAddress(a.address1(), a.address2()) + "|" + a.city())
.collect(Collectors.toSet());
for (DolibarrAddressDto dolibarrAddr : dolibarrAddresses) {
String dolibarrAddressStr = dolibarrAddr.address() + "|" + dolibarrAddr.city();
if (!psAddressStrings.contains(dolibarrAddressStr)) {
dolibarrClient.deleteThirdpartyAddress(dolibarrAddr.id());
log.debug("Deleted orphaned address {} from Dolibarr", dolibarrAddr.id());
}
}
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to sync additional addresses for PS customer {}: {}", psCustomerId, e.getMessage()); log.warn("Failed to sync addresses for PS customer {}: {}", psCustomerId, e.getMessage());
} }
} }