ClientCustomerServiceHttpClient.java 2.24 KB
package com.infoloop.tianting.service.client;

import com.infoloop.tianting.config.BusinessConfig;
import com.infoloop.tianting.constant.CommonConstants;
import com.infoloop.tianting.exception.ClientEndExceptions;
import com.infoloop.tianting.exception.ErrorCodeEnum;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.CurrentClientCustomerDto;
import com.infoloop.tianting.model.dto.ClientCustomerDbDTO.CurrentClientCustomerListDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ClientCustomerServiceHttpClient {

    private final BusinessConfig businessConfig;
    private final RestTemplate restTemplate;

    public List<CurrentClientCustomerDto> getCurrentClientCustomer(String token, boolean isHis) {
        String url = isHis ? businessConfig.getHisCustomerQueryUrl() : businessConfig.getClientCustomerQueryUrl();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(CommonConstants.AUTHORIZATION, token);
        HttpEntity<String> requestEntity = new HttpEntity<>("{}", headers);
        try {
            ResponseEntity<CurrentClientCustomerListDto> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, CurrentClientCustomerListDto.class);
            if (!responseEntity.getStatusCode().is2xxSuccessful() || responseEntity.getBody() == null) {
                log.error("Failed to fetch client customer data. Response: {}", responseEntity);
                throw ClientEndExceptions.BusinessException.build(ErrorCodeEnum.QUERY_CLIENT_CUSTOMER_ERROR);
            }
            return responseEntity.getBody().getRows();
        } catch (Exception e) {
            log.error("Error fetching client customer data", e);
            throw ClientEndExceptions.BusinessException.build(ErrorCodeEnum.QUERY_CLIENT_CUSTOMER_ERROR);
        }
    }
}