PullNJBNSCHystrixService.java 19.8 KB
Newer Older
akbar fauzi's avatar
akbar fauzi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
package com.eksad.masterdata.service;

import com.eksad.ddms.common.dto.DealerDTO;
import com.eksad.ddms.common.dto.RequestGetPPNDTO;
import com.eksad.ddms.common.dto.ResponsePPNDTO;
import com.eksad.ddms.common.h2.dto.apigateway.response.PullNotaJBSCResponseDTO;
import com.eksad.ddms.common.h2.dto.apigateway.response.ResponsePullNJBNSCGetListDTO;
import com.eksad.ddms.common.h2.dto.orafin.workorder.WorkOrderPartOrafinDTO;
import com.eksad.ddms.common.h2.dto.orafin.workorder.WorkOrderServiceOrafinDTO;
import com.eksad.ddms.common.h3.dto.salesorder.ResponseSalesOrderGetDTO;
import com.eksad.ddms.common.h3.dto.salesorder.SalesOrderDTO;
import com.eksad.ddms.common.h3.type.salesorder.SalesOrderStatus;
import com.eksad.ddms.common.type.WoState;
import com.eksad.ddms.common.uri.DealerURI;
import com.eksad.ddms.common.util.DateUtil;
import com.eksad.ddms.common.util.StringUtil;
import com.eksad.ddms.common.util.uri.SalesOrderURI;
import com.eksad.masterdata.common.CustomRestTemplate;
import com.eksad.masterdata.common.RequestUtil;
import com.eksad.masterdata.common.dto.PullNotaJBSCRequestDTO;
import com.eksad.masterdata.domain.APIPullNjbNscDetail;
import com.eksad.masterdata.domain.APIPullNjbNscHeader;
import com.eksad.masterdata.domain.workorder.WorkOrder;
import com.eksad.masterdata.repository.APIPullNjbNscRepository;
import com.eksad.masterdata.repository.WorkOrderRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

@Service
@Transactional
public class PullNJBNSCHystrixService {

    @Autowired
    private APIPullNjbNscRepository pullNjbNscRepository;

    @Autowired
    private WorkOrderRepository woRepository;

60 61
    @Value("${ddms.h2.service}")
    private String DDMS_H2_SERVICE;
akbar fauzi's avatar
akbar fauzi committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    @Value("${dam.masterdata.h1}")
    private String DAM_MASTERDATA_H1;

    @Value("${dam.ppn.query.url}")
    private String PPN_QUERY_URL;

    RestTemplate restTemplate = new RestTemplate();

    Double totalJasa = 0d;
    Double totalPart = 0d;

    public ResponseEntity<Object> postRequestPullNJBNSCv2(PullNotaJBSCRequestDTO dto) {
        try {
            List<PullNotaJBSCResponseDTO> listResponse = new ArrayList<>();

            if (!StringUtil.hasValue(dto.getDealerId())) {
//                return ResponseEntity.ok(new ResponsePullNJBNSCGetListDTO(0, "Mohon isi dealerId.", null));
            }
            if (StringUtil.hasValue(dto.getFromTime())) {
                if (!StringUtil.hasValue(dto.getToTime())) {
                    dto.setToTime(getCurrentDate());
                }
                if (!checkToTimeIs7Days(dto.getFromTime(), dto.getToTime())) {
                    return ResponseEntity.status(HttpStatus.FOUND).body(new ResponsePullNJBNSCGetListDTO(0, "Range waktu melebihi 7 hari.", null));
                }
            } else {
                return ResponseEntity.status(HttpStatus.FOUND).body(new ResponsePullNJBNSCGetListDTO(0, "Mohon isi Range Waktu mulai.", null));
            }
            PullNotaJBSCResponseDTO res;
            if (StringUtil.hasValue(dto.getNoWorkOrder())) {
                if (checkIfTransactionsComplete(dto.getNoWorkOrder())) {
                    return ResponseEntity.status(HttpStatus.FOUND).body(new ResponsePullNJBNSCGetListDTO(0, "Pembayaran Invoice telah dilakukan sebelumnya.", null));
                }
                List<APIPullNjbNscHeader> ora = pullNjbNscRepository.findAllNjbNscHeaderByWoID(dto.getNoWorkOrder());
                List<APIPullNjbNscDetail> oraDetail = pullNjbNscRepository.findAllPullNjbNscDetailByWoID(dto.getNoWorkOrder());
                if (!ora.isEmpty()) {
                    res = populateResponseWoOrafin(ora.get(0), oraDetail);
                    listResponse.add(res);
                }
            } else {
                List<APIPullNjbNscHeader> listOra = new ArrayList<>();
                List<APIPullNjbNscDetail> listOraDetail = new ArrayList<>();
                if (StringUtil.hasValue(dto.getDealerId())) {
                    listOra = pullNjbNscRepository.findAllNjbNscHeaderByRangeDate(dto.getFromTime(), dto.getToTime(), dto.getDealerId());
                    listOraDetail = pullNjbNscRepository.findAllPullNjbNscDetailByRangeDate(dto.getFromTime(), dto.getToTime(), dto.getDealerId());
                } else {
                    listOra = pullNjbNscRepository.findAllNjbNscHeaderByRangeDate(dto.getFromTime(), dto.getToTime(), null);
                    listOraDetail = pullNjbNscRepository.findAllPullNjbNscDetailByRangeDate(dto.getFromTime(), dto.getToTime(), null);
                }
                if (listOra != null && !listOra.isEmpty()) {
                    for (APIPullNjbNscHeader ora : listOra) {
                        res = populateResponseWoOrafin(ora, listOraDetail);
                        listResponse.add(res);
                    }
                }
            }
            if (listResponse.isEmpty()) {
                return ResponseEntity.status(HttpStatus.FOUND).body(new ResponsePullNJBNSCGetListDTO(0, "Terdapat kesalahan, Data Tidak Dapat Ditemukan", null));
            }

            return ResponseEntity.status(HttpStatus.FOUND).body(new ResponsePullNJBNSCGetListDTO(1, null, listResponse));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.ACCEPTED).body(new ResponsePullNJBNSCGetListDTO(0, "Terjadi kesalahan. " + e.getLocalizedMessage(), null));
        }
    }

    public static String getCurrentDate() throws ParseException {
        final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    private Boolean checkToTimeIs7Days(String fromTime, String toTime) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date from = dateFormat.parse(fromTime);
        Date to = dateFormat.parse(toTime);
        LocalDateTime fromLocal = from.toInstant().atZone(ZoneId.of("Asia/Jakarta")).toLocalDateTime();
        LocalDateTime toLocal = to.toInstant().atZone(ZoneId.of("Asia/Jakarta")).toLocalDateTime();
        Duration durasi = Duration.between(fromLocal, toLocal);
        long dayDifference = Math.abs(durasi.toHours());
        if (dayDifference > (7 * 24) + 1) {  // if duration greater than 24*7 + 1 hours
            return false;
        }
        return true;
    }

    public Boolean checkIfTransactionsComplete(String woID) {
        String prefix = woID.substring(0, 2);
        String prefix2 = woID.substring(0, 3);
        if (prefix.equalsIgnoreCase("WO") || prefix2.equalsIgnoreCase("VST") || prefix.equalsIgnoreCase("JR")) {
            WorkOrder wo = woRepository.findOneByWoID(woID);
            if (wo != null) {
                if (wo.getWoLastKnownState().equals(WoState.COMPLETE)) {
                    return true;
                }
            }
        } else if (prefix.equalsIgnoreCase("SO")) {
            SalesOrderDTO so = getSalesOrderByID(woID);
            if (so != null && so.getSalesOrderID() != null) {
                if (so.getSalesOrderLastKnownStatus().equals(SalesOrderStatus.COMPLETE)) {
                    return true;
                }
            }
        }
        return false;
    }

    private PullNotaJBSCResponseDTO populateResponseWoOrafin(APIPullNjbNscHeader data, List<APIPullNjbNscDetail> listDetail) {
        PullNotaJBSCResponseDTO res = new PullNotaJBSCResponseDTO();
        res.setWoid(data.getNoWorkOrder());
        res.setNoNJB(data.getNoNJB() == null ? "" : data.getNoNJB());
        res.setNoNSC(data.getNoNSC() == null ? "" : data.getNoNSC());
        res.setTanggalnjb(data.getTanggalNJB() == null ? "" : DateUtil.dateToString(data.getTanggalNJB(), "dd/MM/yyyy HH:mm:ss"));
        res.setTanggalnsc(data.getTanggalNSC() == null ? "" : DateUtil.dateToString(data.getTanggalNSC(), "dd/MM/yyyy HH:mm:ss"));
        res.setTotalharganjb(data.getTotalHargaJasa() == null ? 0 : data.getTotalHargaJasa().intValue());
        res.setTotalhargansc(data.getTotalHargaSparepart() == null ? 0 : data.getTotalHargaSparepart().intValue());
        res.setHondaidsa(data.getHondaIdSA() == null || data.getHondaIdSA().equalsIgnoreCase("none") ? "" : data.getHondaIdSA().toUpperCase());
        res.setHondaidmekanik(data.getHondaIdMekanik() == null ? "" : data.getHondaIdMekanik().toUpperCase());
        res.setDealerid(data.getDealerId());
        res.setCreatedtime(data.getCreatedTime());
        res.setModifiedtime(data.getModifiedTime());
        populateResponseDetail(res, data, listDetail);
        return res;
    }

    private SalesOrderDTO getSalesOrderByID(String soID) {
        if (StringUtil.hasValue(soID)) {
            ResponseEntity<ResponseSalesOrderGetDTO> resp = restTemplate.exchange(
191
                    DDMS_H2_SERVICE + SalesOrderURI.SALES_ORDER_GET_BY_ID.getUri(),
akbar fauzi's avatar
akbar fauzi committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                    HttpMethod.GET,
                    RequestUtil.getPreFormattedRequestWithUserPassword(),
                    ResponseSalesOrderGetDTO.class, soID);
            if (resp.getBody() != null) {
                return resp.getBody().getData();
            }
        }
        return null;
    }

    public DealerDTO findDealerByID(String dealerID) {
        if (com.eksad.ddms.common.util.StringUtil.hasValue(dealerID)) {
            ResponseEntity<DealerDTO> response = restTemplate.exchange(
                    DAM_MASTERDATA_H1 +
                            DealerURI.DEALER_GET_BY_AHASS_ID.getUri(),
                    HttpMethod.GET,
                    RequestUtil.getPreFormattedRequestWithUserPassword(),
                    DealerDTO.class,
                    dealerID);
            return response.getBody() == null ? new DealerDTO() : response.getBody();
        }
        return new DealerDTO();
    }

    public ResponsePPNDTO getResponsePPN(RequestGetPPNDTO req) {
        ResponsePPNDTO ppnDTO = new ResponsePPNDTO();
        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        header.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
        CustomRestTemplate restTemplate = new CustomRestTemplate();
        ResponseEntity<ResponsePPNDTO> response = restTemplate.restTemplate().exchange(
                PPN_QUERY_URL,
                HttpMethod.POST,
                new HttpEntity<>(req, header),
                ResponsePPNDTO.class);

        return response.getBody();
    }

    private void populateResponseDetail(PullNotaJBSCResponseDTO resp, APIPullNjbNscHeader header, List<APIPullNjbNscDetail> listDetail) {
        try {
            List<WorkOrderServiceOrafinDTO> listNjb = new ArrayList<>();
            List<WorkOrderPartOrafinDTO> listNsc = new ArrayList<>();
            Double totalDP = 0d;        // Set 0 impact fixing Hotline
            totalJasa = 0d;
            totalPart = 0d;
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
            RequestGetPPNDTO req = new RequestGetPPNDTO();
            DealerDTO dealer = findDealerByID(resp.getDealerid());
            req.setDealerId(dealer.getDealerCode());
            req.setQueryDate(dateFormat.format(new Date()));
            ResponsePPNDTO ppnData = getResponsePPN(req);
            ObjectMapper ob = new ObjectMapper();
            System.out.println("Req : " + ob.writeValueAsString(req));
            System.out.println("Response : " + ob.writeValueAsString(ppnData));
            Double divValue = (ppnData.getData().getPpnRate() + 100.0) / 100.0;

            //        partJasaMap = new HashMap<>();
            listDetail.stream().filter(p -> Objects.equals(header.getNoWorkOrder(), p.getWoID())).forEachOrdered((APIPullNjbNscDetail par) -> {
                Double harga = par.getHarga() == null ? 0d : getRoundingHalfDown(par.getHarga());
                Double dpp = harga <= 0d ? 0d : getRoundingHalfDown(harga / 1.1);
                Double discount = par.getDiscount() == null ? 0d : getRoundingHalfDown(par.getDiscount());
                Double qty = par.getQty() == null ? 1 : par.getQty();
                Double totalDiscount = discount <= 0d ? 0d : discount * qty;
                Double total = par.getTotal() == null ? 0d : getRoundingHalfDown(par.getTotal());
                Double ppn = 0d;
                Double uangMuka = par.getUangMuka() == null ? 0d : par.getUangMuka();
                String discountCode = header.getDiscountCode() == null ? "" : header.getDiscountCode();
                String promoIDJasa = "", satuanPromoJasa = "", promoIDPart = "", satuanPromoPart = "";
                if (StringUtil.hasValue(header.getPromoIdJasa())) {
                    String[] promoAttrJasa = header.getPromoIdJasa().split("_");
                    promoIDJasa = promoAttrJasa[0];
                    satuanPromoJasa = promoAttrJasa[1];
                }
                if (StringUtil.hasValue(header.getPromoIdPart())) {
                    String[] promoAttrPart = header.getPromoIdPart().split("_");
                    promoIDPart = promoAttrPart[0];
                    satuanPromoPart = promoAttrPart[1];
                }
                if (par.getTipe().equals("SERVICE")) {
                    WorkOrderServiceOrafinDTO njb = new WorkOrderServiceOrafinDTO();
                    String[] cwsAttr = par.getCwsCode().split("_");
                    String cwsCode = cwsAttr[0];
                    String serviceCategory = cwsAttr[1];
                    if (discount <= 0 && !("ASS".equalsIgnoreCase(serviceCategory.substring(0, 3)) || "CLAIM C2".equalsIgnoreCase(serviceCategory))) {
                        njb.setPromoIdJasa("");
                        njb.setDiscServiceAmount(0);
                        njb.setDiscServicePercentage(0d);
                    } else {
                        njb.setPromoIdJasa(("ASS".equalsIgnoreCase(serviceCategory.substring(0, 3)) || "CLAIM C2".equalsIgnoreCase(serviceCategory)) ? "" : promoIDJasa.isEmpty() ? discountCode : promoIDJasa);
                        njb.setDiscServiceAmount(discount.intValue());
                        njb.setDiscServicePercentage(0d);
                        if ("PERCENTAGE".equals(satuanPromoJasa)) {
                            njb.setDiscServiceAmount(0);
                            njb.setDiscServicePercentage(discount > 0 ? discount / harga > 1 ? 100d : getRoundingHalfDownOnePlace((discount / harga) * 100) : 0d);
                        }
                    }
                    njb.setIdJob(cwsCode == null ? "" : cwsCode.substring(cwsCode.length() - 5, cwsCode.length()));
                    njb.setHargaServis(harga.intValue());
                    njb.setTotalHargaServis(total.intValue());
                    njb.setCreatedTime(par.getCreatedAt());
                    njb.setModifiedTime(par.getModifiedAt());
                    //                njb.setNoWorkOrder(header.getNoWorkOrderOrafin());
                    listNjb.add(njb);
                    totalJasa = totalJasa + njb.getTotalHargaServis();
                    //                if(StringUtil.hasValue(par.getPartID())) partJasaMap.put(par.getPartID(), njb.getIdJob());
                } else if (par.getTipe().equals("PART") || par.getTipe().equals("PART_H3")) {
                    WorkOrderPartOrafinDTO nsc = new WorkOrderPartOrafinDTO();
//                ppn = (harga-discount) <= 0d ? 0d : getRoundingHalfDown((harga-discount)*0.1/1.1);
                    String tipe = par.getCwsCode() == null ? "" : par.getCwsCode();
                    String[] tipeChar = tipe.split("_");
                    String cwsCode = null;
                    if (tipeChar.length >= 2) {
                        cwsCode = tipeChar[1].substring(tipeChar[1].length() - 5, tipeChar[1].length());
                        tipe = tipeChar[0];
                    }
                    if ("CLAIM".equalsIgnoreCase(tipe)) ppn = 0d;
                    if (discount <= 0 && !"CLAIM".equalsIgnoreCase(tipe)) {
                        nsc.setPromoIdParts("");
                        nsc.setDiscPartsPercentage(0d);
                        nsc.setDiscPartsAmount(0);
                    } else {
                        nsc.setPromoIdParts("CLAIM".equalsIgnoreCase(tipe) ? "" : promoIDPart.isEmpty() ? discountCode : promoIDPart);
                        nsc.setDiscPartsPercentage(0d);
                        nsc.setDiscPartsAmount(discount.intValue());
                        if (!promoIDPart.isEmpty() || par.getTipe().equals("PART_H3")) {
                            nsc.setDiscPartsPercentage(discount > 0 ? discount / harga > 1 ? 100d : getRoundingHalfDownOnePlace(discount / harga * 100) : 0d);
                            nsc.setDiscPartsAmount(0);
                            //                        nsc.setPromoIdParts(header.getDiscountCode());
                        }
                    }
                    nsc.setIdJob(cwsCode == null ? "" : cwsCode.toUpperCase());
                    Double hargaParts = Math.ceil(harga / divValue);
                    System.out.println("harga parts " + hargaParts);
                    nsc.setHargaParts(hargaParts.intValue());
                    nsc.setTotalHargaParts(total.intValue());
                    nsc.setUangMuka(uangMuka.intValue());
                    if (header.getNoWorkOrder().startsWith("SO")) {
                        nsc.setTotalHargaParts(total.intValue() - discount.intValue());
                        ppn = getRoundingDown((((total / qty) / ((ppnData.getData().getPpnRate() + 100) / 100)) * ppnData.getData().getPpnRate() / 100)) -
                                (discount > 0 ? getRoundingDown(((discount / ((ppnData.getData().getPpnRate() + 100) / 100)) * ppnData.getData().getPpnRate() / 100)) : 0);
                        nsc.setPpn(ppn.intValue());
                    } else {
                        nsc.setTotalHargaParts(total.intValue());
                        ppn = getRoundingDown((((total / qty) / ((ppnData.getData().getPpnRate() + 100) / 100)) * ppnData.getData().getPpnRate() / 100));
                        nsc.setPpn(ppn.intValue());
                    }

                    nsc.setPartsNumber(par.getPartID());
                    nsc.setKuantitas(qty.intValue());
                    nsc.setCreatedTime(par.getCreatedAt());
                    nsc.setModifiedTime(par.getModifiedAt());
                    //                nsc.setNoWorkOrder(header.getNoWorkOrderOrafin());
                    listNsc.add(nsc);
                    totalPart = totalPart + nsc.getTotalHargaParts();
                }
            });
            resp.setTotalharganjb(totalJasa.intValue());
            resp.setTotalhargansc(totalPart.intValue() - totalDP.intValue());
            resp.setNjb(listNjb);
            resp.setNsc(listNsc);
        } catch (JsonProcessingException ex) {
            Logger.getLogger(PullNJBNSCHystrixService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static Double getRoundingHalfDown(Double num) {
        BigDecimal bd = new BigDecimal(num).setScale(0, RoundingMode.HALF_DOWN);
        return bd.doubleValue();
    }

    private static Double getRoundingHalfDownOnePlace(Double num) {
        BigDecimal bd = new BigDecimal(num).setScale(1, RoundingMode.HALF_DOWN);
        return bd.doubleValue();
    }

    private static Double getRoundingDown(Double num) {
        BigDecimal bd = new BigDecimal(num).setScale(0, RoundingMode.DOWN);
        return bd.doubleValue();
    }
}