ManagePartSalesRepositoryImpl.java 9.31 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 60 61 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
package com.eksad.masterdata.repository;

import com.eksad.masterdata.common.dto.DetailSOManagePartSalesDTO;
import com.eksad.masterdata.common.dto.HeaderSOManagePartSalesDTO;
import com.eksad.masterdata.common.dto.PartsManageSalesDetailTempDTO;
import com.eksad.masterdata.common.dto.responseDto.ResponseManagePartSalesDTO;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

@Repository
public class ManagePartSalesRepositoryImpl implements ManagePartSalesRepository {

    ResponseManagePartSalesDTO responseManagePartSalesDTO = new ResponseManagePartSalesDTO();
    HeaderSOManagePartSalesDTO headerDTOTemp = new HeaderSOManagePartSalesDTO();
    List<HeaderSOManagePartSalesDTO> headerDTOs = new ArrayList<>();
    List<HeaderSOManagePartSalesDTO> headerDTOsTemp = new ArrayList<>();
    List<DetailSOManagePartSalesDTO> detailDTOs = new ArrayList<>();
    DetailSOManagePartSalesDTO detailDTO = new DetailSOManagePartSalesDTO();
    List<PartsManageSalesDetailTempDTO> detailDTOsTemp = new ArrayList<>();
    PartsManageSalesDetailTempDTO detailDTOTemp = new PartsManageSalesDetailTempDTO();

    @PersistenceContext
    private EntityManager entity;

    @Override
    public ResponseManagePartSalesDTO getManagePartSalesBySONumber(String soNumber) {
        headerDTOs = new ArrayList<>();
        responseManagePartSalesDTO = new ResponseManagePartSalesDTO();
        detailDTOsTemp = new ArrayList<>();
        headerDTOsTemp = new ArrayList<>();
        Session session = entity.unwrap(Session.class);
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {

                PreparedStatement statement = connection.prepareStatement("select * from managepartsalesbysonumber (?)");
                statement.setString(1, soNumber);

                ResultSet result = statement.executeQuery();
                while (result.next()) {
                    try {
                        headerDTOTemp = new HeaderSOManagePartSalesDTO();
                        detailDTOTemp = new PartsManageSalesDetailTempDTO();
                        headerDTOTemp.setNoSO(result.getString("salesorderid"));
                        headerDTOTemp.setDealerId(result.getString("dealerid"));
                        headerDTOTemp.setDiscSO(result.getInt("discamaount"));
                        headerDTOTemp.setIdCustomer(result.getString("idcustomer"));
                        headerDTOTemp.setNamaCustomer(result.getString("namacustomer"));
                        headerDTOTemp.setCreatedTime(formatDate24Hour(result.getString("createdtime")));
                        headerDTOTemp.setModifiedTime(formatDate24Hour(result.getString("modifiedtime")));
                        headerDTOTemp.setTglSO(result.getDate("createdtime").toString());
                        headerDTOTemp.setTotalHargaSO(result.getInt("totalhargaso"));

                        detailDTOTemp.setBookingIdReference(result.getString("bookingidref"));
                        detailDTOTemp.setCreatedTime(result.getDate("createdtime"));
                        detailDTOTemp.setDiscAmount((int) Math.round(result.getDouble("discamaount")));
                        detailDTOTemp.setHargaParts(result.getInt("hargapart"));
                        detailDTOTemp.setKuantitas(result.getInt("qty"));
                        detailDTOTemp.setModifiedTime(result.getDate("modifiedtime"));
                        detailDTOTemp.setPartsNumber(result.getString("partnumber"));
                        detailDTOTemp.setPpn(result.getInt("ppn"));
                        detailDTOTemp.setPromoidParts(result.getString("promoid"));
                        detailDTOTemp.setSoNumber(result.getString("salesorderid"));
                        detailDTOTemp.setTotalHargaParts(result.getInt("totalhargapart"));
                        detailDTOTemp.setUangMuka((int) Math.round(result.getDouble("dp")));
                        detailDTOTemp.setDiscPercentage(result.getDouble("discpercentage"));
//                    if (detailDTOTemp.getDiscAmount() > 0) {
//                        detailDTOTemp.setDiscPercentage(new Double(detailDTOTemp.getDiscAmount() / detailDTOTemp.getTotalHargaParts() * 100));
//                    } else {
//                        detailDTOTemp.setDiscPercentage(0.0);
//                    }

                        detailDTOsTemp.add(detailDTOTemp);
                        headerDTOsTemp.add(headerDTOTemp);
                    } catch (Exception e) {
                        responseManagePartSalesDTO.setStatus("0");
                        responseManagePartSalesDTO.setMessage("Terjadi kesalahan");
                        Logger.getLogger(ManagePartSalesRepositoryImpl.class.getName()).log(Level.SEVERE, null, e);
                    }
                }
                statement.close();
                connection.close();
            }
        });
        if (!headerDTOsTemp.isEmpty() && !detailDTOsTemp.isEmpty()) {
            headerDTOs = headerDTOsTemp.stream().filter(distinctByKey(p -> p.getNoSO())).collect(Collectors.toList());
            for (HeaderSOManagePartSalesDTO loopHeader : headerDTOs) {
                Integer discTotal = 0;
                Integer totalHargaSO = 0;

                detailDTOs = new ArrayList<>();
                for (PartsManageSalesDetailTempDTO loopDetail : detailDTOsTemp) {
                    if (loopDetail.getSoNumber().equalsIgnoreCase(loopHeader.getNoSO())) {
                        discTotal += (loopDetail.getDiscAmount() * loopDetail.getKuantitas());
                        loopDetail.setDiscAmount(0);   // reset disc amount

                        totalHargaSO += loopDetail.getTotalHargaParts();
                        detailDTO = new DetailSOManagePartSalesDTO();
                        detailDTO = toDetailDTO(loopDetail);
                        detailDTOs.add(detailDTO);
                    }
                }
                loopHeader.setDiscSO(discTotal);
                loopHeader.setTotalHargaSO(totalHargaSO);
                loopHeader.setParts(detailDTOs);
            }

        }
        session.close();
        entity.close();
        responseManagePartSalesDTO.setData(headerDTOs);
        return responseManagePartSalesDTO;
    }

    @Override
    public ResponseManagePartSalesDTO getManagePartSalesByRangeDate(String ahmCode, String startDate, String toTime, String ahassCode) {
        return null;
    }

    @Override
    public ResponseManagePartSalesDTO getManagePartSalesByRangeDateSO(String ahmCode, String startDate, String toTime, String soNumber, String ahassCode) {
        return null;
    }

    public Date formatDate24Hour(String date) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = dateFormat.parse(date);
        return newDate;
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    public DetailSOManagePartSalesDTO toDetailDTO(PartsManageSalesDetailTempDTO dto) {
        DetailSOManagePartSalesDTO detailSOManagePartSalesDTO = new DetailSOManagePartSalesDTO();
        detailSOManagePartSalesDTO.setBookingIdReference(dto.getBookingIdReference() == null ? "" : dto.getBookingIdReference());
        detailSOManagePartSalesDTO.setCreatedTime(dto.getCreatedTime());
        detailSOManagePartSalesDTO.setDiscAmount(dto.getDiscAmount());
        detailSOManagePartSalesDTO.setDiscPercentage(getRoundingHalfDownOnePlace(dto.getDiscPercentage()));
        detailSOManagePartSalesDTO.setHargaParts(dto.getHargaParts());
        detailSOManagePartSalesDTO.setKuantitas(dto.getKuantitas());
        detailSOManagePartSalesDTO.setModifiedTime(dto.getModifiedTime());
        detailSOManagePartSalesDTO.setPartsNumber(dto.getPartsNumber().toUpperCase());
        detailSOManagePartSalesDTO.setPpn(dto.getPpn());
        detailSOManagePartSalesDTO.setPromoidParts(getMaxLengthPromoID(dto.getPromoidParts()));
        detailSOManagePartSalesDTO.setTotalHargaParts(dto.getTotalHargaParts());
        detailSOManagePartSalesDTO.setUangMuka(dto.getUangMuka());
        return detailSOManagePartSalesDTO;
    }

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

    private static String getMaxLengthPromoID(String id) {
        if (id == null) return "";
        if (id.length() > 10) {
            return id.substring(0, 10);
        }
        return id;
    }
}