Untitled

 avatar
unknown
plain_text
a year ago
12 kB
3
Indexable
package com.muf.integrasi_ppd_java.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.muf.integrasi_ppd_java.config.Consumer;
import com.muf.integrasi_ppd_java.dto.ContractDTO;
import com.muf.integrasi_ppd_java.dto.LogidDTO;
import com.muf.integrasi_ppd_java.dto.ParamOutDTO;
import com.muf.integrasi_ppd_java.helper.HelpersAM;
import com.muf.integrasi_ppd_java.helper.NullValueHelper;
import com.muf.integrasi_ppd_java.model.mufam.ContractMaster;
import com.muf.integrasi_ppd_java.repository.mufam.ContractMasterRepository;
import com.muf.integrasi_ppd_java.repository.procedure.CallingProcedureRepository;
import com.muf.integrasi_ppd_java.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.muf.integrasi_ppd_java.config.Consumer.*;

@RestController
@Slf4j
public class RetryController {
    @Autowired
    private CallingProcedure callingProcedure;
    @Autowired
    private CustomerPersonalEmployeesService customerPersonalEmployeesService;
    @Autowired
    private CustomerPersonalProfessionalService customerPersonalProfessionalService;
    @Autowired
    private CustomerPersonalEnterpriseService customerPersonalEnterpriseService;
    @Autowired
    private CallingProcedureRepository callingProcedureRepository;
    @Autowired
    public Consumer consumer;
    @Autowired
    private ContractMasterRepository contractMasterRepository;
    @Autowired
    private ContractAmortizeService contractAmortizeService;


    //private ExecutorService executor = Executors.newSingleThreadExecutor();
    private static final int CORE_POOL_SIZE = 10; // Jumlah minimal thread dalam pool
    private static final int MAX_POOL_SIZE = 10; // Jumlah maksimal thread dalam pool
    private static final long KEEP_ALIVE_TIME = 60L; // Waktu idle sebelum thread dihapus (dalam detik)

    private ExecutorService executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>()
    );


    @PostMapping("/retry_data_integrasi")
    @Transactional
    public ResponseEntity<Map<String, Object>> retryDataIntegrasi(@RequestBody String jsonData) {
        ResponseEntity<Map<String, Object>> response;
        Map<String, Object> result = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        try {
            Map<String, Object> data = mapper.readValue(jsonData, Map.class);
            Map<String, Object> detail = (Map<String, Object>) data.get("detail");
            Map<String, Object> dataEntryCompletion = (Map<String, Object>) detail.get("data_entry_completion");
            String createdBy = NullValueHelper.resultStrFromJson(dataEntryCompletion, "confirmed_by");
            Date createdDate = NullValueHelper.resultDateFromJson(dataEntryCompletion, "confirmed_date");
            String branchCode = NullValueHelper.resultStrFromJson(data,"branch_code");
            String contractNo = HelpersAM.parsingContractNo(data);

            executor.submit(() -> {
                try {
                    handleRetryIntegration(contractNo, data, createdBy, createdDate, branchCode);
                } catch (Exception e) {
                    log.error("Transaksi gagal di retry integrasi: " + e.getMessage(), e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            });
            result.put("Status", "200");
            result.put("Message", "Data Berhasil Terintegrasi");
            response = new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            log.error("Error in Retry Data Integrasi: " + e.getMessage(), e);
            result.put("Status", "500");
            result.put("Message", "Internal Server Error");
            response = new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response;
    }

    @PostMapping("/retry_data_jurnal_kp")
    @Transactional
    public ResponseEntity<Map<String, Object>> retryDataJurnalKp(@RequestParam String contractNo) {
        ResponseEntity<Map<String, Object>> response;
        Map<String, Object> result = new HashMap<>();
        ContractMaster data = contractMasterRepository.findContractMasterByContractNo(contractNo).orElse(null);
        try {
            executor.submit(() -> {
                try {
                    String statusIntegrasi = consumer.cekStatusIntegrasi(contractNo);
                    String statusJurnalKp = consumer.cekStatusJurnalKp(contractNo);
                    if (statusIntegrasi.equals("1") && statusJurnalKp.equals("3")) {
                        //panggil procedure jurnal kp
                        String validasi = callingProcedureRepository.journalPpd(contractNo);
                        if (validasi == null || validasi.isEmpty()) {
                            consumer.saveToFlaggingTable(contractNo, FLAG_SUCCESS, FLAG_SUCCESS, "BERHASIL PEMBENTUKAN JURNAL KP", data.getCreatedBy(),data.getCreateDate());
                        } else {
                            consumer.saveToFlaggingTable(contractNo, FLAG_SUCCESS, FLAG_FAILURE, validasi, data.getCreatedBy(),data.getCreateDate());
                            throw new Exception(validasi);
                        }
                    }
                } catch (Exception e) {
                    log.error("Transaksi gagal pembentukan jurnal KP: " + e.getMessage(), e);
                    throw new RuntimeException(e);
                }
            });
            result.put("Status", "200");
            result.put("Message", "Data Berhasil Terintegrasi");
            response = new ResponseEntity(result, HttpStatus.OK);
        } catch (Exception e) {
            result.put("Status", "500");
            result.put("Message", result.get("Message"));
            result.put("Logs", e);
            response = new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return response;
    }

    @GetMapping("/")
    public String index() {
        String response = "";
        try {
            response = "<h3>AM INTEGRASI PPD SUBSCRIBER JAVA V.1</>";
        } catch (Exception e) {
            response = "Gagal";
            e.printStackTrace();
        }
        return response;
    }

//    @GetMapping("/get_json")
//    public String getJson(@RequestBody String jsonData) throws Exception {
//        ObjectMapper mapper = new ObjectMapper();
//        Map<String, Object> request = mapper.readValue(jsonData, Map.class);
//        String contractNo = HelpersAM.parsingContractNo(request);
//        ContractDTO contractMaster = contractMasterRepository.findByContractNo(contractNo).orElse(null);
//        String logid = contractMasterRepository.findLogidByContractNo(contractNo).orElse(null);
//
//        contractAmortizeService.insertData(request,contractMaster, logid);
//        return contractNo;
//    }

    @Transactional
    public void handleRetryIntegration(String contractNo, Map<String, Object> data, String createdBy, Date createdDate, String branchCode) {
        //bridging data
        processretryIntegrasi(contractNo,data,createdBy,createdDate,branchCode);

        //update data mapping param
        processretryParam(contractNo,data,createdBy,createdDate);

        //pembentukan jurnal kp
        consumer.processKafkaJournal(contractNo,createdBy,createdDate);
    }
    @Transactional
    public void processretryIntegrasi(String contractNo, Map<String, Object> data, String createdBy, Date createdDate, String branchCode){
        try {
            LogidDTO logidDTO = callingProcedureRepository.generateLogid();

            String statusIntegrasi = consumer.cekStatusIntegrasi(contractNo);
            String statusJurnalKp = consumer.cekStatusJurnalKp(contractNo);

            if ("3".equals(statusIntegrasi) && "0".equals(statusJurnalKp)) {
                String result = consumer.performCombinedInsertion(data, logidDTO.getLogid());
                if ("Success".equals(result)) {
                    log.info("Transaksi berhasil di retry integrasi");
                    consumer.saveToFlaggingTable(contractNo, FLAG_RETRY, FLAG_INITIAL, "BERHASIL INTEGRASI", createdBy, createdDate);
                } else {
                    consumer.saveToFlaggingTable(contractNo, FLAG_FAILURE, FLAG_INITIAL, result, createdBy, createdDate);
                    throw new Exception(result);
                }
            }
            callingProcedure.insertLogs(logidDTO.getLogid(), createdBy,"INTEGRASI","1",branchCode);
        } catch (Exception e) {
            log.error("Transaksi gagal di retry integrasi: " + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Transactional
    public void processretryParam(String contractNo, Map<String, Object> data, String createdBy, Date createdDate){
        try {
            String logid = contractMasterRepository.findLogidByContractNo(contractNo).orElse(null);
            String statusIntegrasi = consumer.cekStatusIntegrasi(contractNo);
            String statusJurnalKp = consumer.cekStatusJurnalKp(contractNo);
            if ("5".equals(statusIntegrasi) && "0".equals(statusJurnalKp)) {
                ContractDTO contractDTO = contractMasterRepository.findByContractNo(contractNo).orElse(null);
                ParamOutDTO paramOutDTO = callingProcedureRepository.updateParam(contractDTO.getContractId());
                System.out.println(paramOutDTO);
                if (paramOutDTO.getPOut() == null) {
                    try {
                        switch (paramOutDTO.getPTypeId()) {
                            case "01":
                                customerPersonalProfessionalService.insertData(data, paramOutDTO.getPEconomicSector(),logid);
                                break;
                            case "02":
                                customerPersonalEnterpriseService.insertData(data, paramOutDTO.getPEconomicSector(),logid);
                                break;
                            case "03":
                                customerPersonalEmployeesService.insertData(data, paramOutDTO.getPEconomicSector(),logid);
                                break;
                        }
                        consumer.saveToFlaggingTable(contractNo, FLAG_SUCCESS, FLAG_INITIAL, "BERHASIL INTEGRASI DAN MAPPING PARAMETER", createdBy, createdDate);
                        log.info("Transaksi berhasil di retry update param");
                    } catch (Exception e) {
                        consumer.saveToFlaggingTable(contractNo, FLAG_MAPPING, FLAG_INITIAL, e.getMessage(), createdBy, createdDate);
                        throw new Exception(e);
                    }
                } else {
                    consumer.saveToFlaggingTable(contractNo, FLAG_MAPPING, FLAG_INITIAL, paramOutDTO.getPOut(), createdBy, createdDate);
                    throw new Exception(paramOutDTO.getPOut());
                }
            }
        } catch (Exception e) {
            log.error("Transaksi gagal di mapping parameter: " + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
    }
}
Editor is loading...
Leave a Comment