public <T> ResponseEntity<T> scheduleAppointment(Optional<Garage> garageOptional, ScheduleAppointmentRequest appointmentRequest, String userId, String userType) throws Exception {
Gson gson = new Gson();
String offerId = appointmentRequest.getOfferId();
Long smartIQVehicleId;
String kavakCatalogId = "f75c5be516fe";
Integer kilometers = null;
Vehicle vehicleTemp = null;
Optional<Offer> offerOptional = offerService.findFirstByOfferId(offerId);
if (!offerOptional.isPresent()) {
throw new NotFoundException();
}
Offer offer = offerOptional.get();
String carId = offer.getCarId();
if (!garageOptional.isPresent()) {
List<Vehicle> vehicles = vehicleService.findFirstByCarId(carId, userId, userType);
if (vehicles != null && vehicles.size() > 0) {
vehicleTemp = vehicles.get(0);
smartIQVehicleId = vehicleTemp.getSmartIQVehicleId();
kilometers = vehicleTemp.getKilometers();
} else {
throw new NotFoundException();
}
} else {
Garage garage = garageOptional.get();
smartIQVehicleId = garage.getSmartIQVehicleId();
kilometers = garage.getKilometers();
vehicleTemp = garage.getVehicle();
}
SHVehicleCatalog shVehicleCatalog = shCatalogDataService.findBySmartIQVehicleId(smartIQVehicleId);
if (shVehicleCatalog == null) {
throw new WrongCatalogInfoException();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
KavakCustomerDTO kavakCustomerDTO = KavakCustomerDTO.builder()
.email(appointmentRequest.getCustomer().getEmail())
.phone(appointmentRequest.getCustomer().getPhone())
.fullName(appointmentRequest.getCustomer().getFirstName() + " " + appointmentRequest.getCustomer().getLastName())
.build();
KavakVehicleDTO kavakVehicleDTO = KavakVehicleDTO.builder()
.catalogId(kavakCatalogId)
.mileage(kilometers)
.plate(appointmentRequest.getPlateNumber())
.build();
KavakScheduleAppointmentRequestDTO kavakScheduleAppointmentRequestDTO = KavakScheduleAppointmentRequestDTO.builder()
.branchId(Long.valueOf(appointmentRequest.getCentreId()))
.startTime(sdf.format(appointmentRequest.getAppointmentStartTime()))
.endTime(sdf.format(appointmentRequest.getAppointmentEndTime()))
.externalId(carId)
.valuationPrice(offer.getRetailPrice().longValue())
.kavakVehicleDTO(kavakVehicleDTO)
.kavakCustomerDTO(kavakCustomerDTO)
.build();
String apiURL = baseUrl + "/appointments";
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
System.err.println("HTTP Response Code" + response.getStatusCode());
}
});
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("x-consumer-key", kavakToken);
Centre centre = getBranch(appointmentRequest.getCentreId());
Timestamp cal = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("GMT+3")));
VavaAppointment vavaAppointment =
VavaAppointment.builder()
.carId(carId)
.centreId(appointmentRequest.getCentreId())
.centreName(centre.getCentreName())
.centreEmail(centre.getEmail())
.centrePhone(centre.getPhone())
.centreAddress(centre.getAddress() == null ? null : centre.getAddress().getFullAddress())
.phone(appointmentRequest.getCustomer().getPhone())
.email(appointmentRequest.getCustomer().getEmail())
.lastName(appointmentRequest.getCustomer().getLastName())
.firstName(appointmentRequest.getCustomer().getFirstName())
.minPrice(offer.getRetailPrice())
.maxPrice(offer.getRetailPrice())
.startDate(new Timestamp(appointmentRequest.getAppointmentStartTime().getTime()))
.endDate(new Timestamp(appointmentRequest.getAppointmentEndTime().getTime()))
.status(AppointmentStatusEnums.IN_PROGRESS.name())
.createDate(cal)
.updateDate(cal)
.build();
log.info("Kavak appointment schedule request: " + gson.toJson(kavakScheduleAppointmentRequestDTO));
HttpEntity<String> entity = new HttpEntity(kavakScheduleAppointmentRequestDTO, headers);
try {
ResponseEntity<String> result = restTemplate.exchange(apiURL, HttpMethod.POST, entity, String.class);
log.info("Kavak appointment schedule response: " + result.getBody());
if (result.getStatusCodeValue() == 200) {
appointmentService.save(vavaAppointment);
if (garageOptional.isPresent()) {
garageService.updateStatusAndPlateNumber(C2BStatusEnums.IN_SALES_PROCESS.name(), appointmentRequest.getPlateNumber(), carId, userType, userId);
} else {
Garage garage = vehicleTemp.getGarage();
garage.setTitle(Utils.getVehicleTitle(shVehicleCatalog));
garage.setPricingStatus(C2BStatusEnums.PRICED.name());
garage.setStatus(C2BStatusEnums.IN_SALES_PROCESS.name());
garage.setPlateNumber(appointmentRequest.getPlateNumber());
garageService.saveBase(garage);
}
garageLogService.saveGarageLog(carId, C2BStatusEnums.IN_SALES_PROCESS.name(), ApprovementEnums.CREATED.name(), "", userId);
Type collectionType = new TypeToken<KavakApiResponseDto<String>>() {}.getType();
KavakApiResponseDto<String> kavakApiResponseDto = gson.fromJson(result.getBody(),collectionType);
T t = (T) gson.fromJson(kavakApiResponseDto.getData(), KavakApiAppointmentResponseDTO.class);
return new ResponseEntity<>(t, result.getStatusCode());
} else {
Type collectionType = new TypeToken<KavakApiResponseDto<String>>() {}.getType();
KavakApiResponseDto<String> responseDto = gson.fromJson(result.getBody(),collectionType);
if (!ObjectUtils.isEmpty(responseDto.getValidations())) {
throw new DetailedInvalidRequestException(String.join(" ", responseDto.getValidations()));
}
throw new Exception(MessageTypes.INTERNAL_SERVER_ERROR.getMessage());
}
} catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
throw new Exception(MessageTypes.INTERNAL_SERVER_ERROR.getMessage());
}
}
}