BOESearchResultHelper.java

package com.tradecloud.dto.consignment;

import com.tradecloud.common.base.HibernateUtils;
import com.tradecloud.domain.base.utils.MathUtils;
import com.tradecloud.domain.container.ShipmentContainer;
import com.tradecloud.domain.document.invoice.DeclarationInvoice;
import com.tradecloud.domain.duties.RulesOfOrigin;
import com.tradecloud.domain.event.Event;
import com.tradecloud.domain.export.EdifactStatus;
import com.tradecloud.domain.model.shipment.ShippingMode;
import com.tradecloud.domain.shipment.AirShipment;
import com.tradecloud.domain.shipment.SeaShipment;
import com.tradecloud.domain.shipment.Shipment;
import com.tradecloud.domain.shipment.clearing.*;
import com.tradecloud.dto.api.invoice.DeclarationInvoiceDTO;
import com.tradecloud.dto.api.invoice.DeclarationInvoiceItemDTO;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

import java.util.*;

public class BOESearchResultHelper {

    public static <T> T getNonProxyObject(T potentialProxy) {
        if (potentialProxy instanceof HibernateProxy) {
            HibernateProxy hibernateProxy = (HibernateProxy) potentialProxy;
            LazyInitializer hibernateLazyInitializer = hibernateProxy.getHibernateLazyInitializer();

            if (!hibernateLazyInitializer.isUninitialized()) {
                return (T) hibernateLazyInitializer.getImplementation();
            }
        }
        return potentialProxy;
    }

    public static BOEReport populateBOEReport(CustomsDeclaration customsDeclaration,
                                              Map<DeclarationInvoice, DeclarationInvoiceDTO> invoices) {
        BOEReport boeReport = new BOEReport();
        boeReport.setCustomsDeclaration(customsDeclaration);
        boeReport.setImports(customsDeclaration.getShipment().isImports());
        List<BOEReportLine> lines = new ArrayList<>();
        for (DeclarationInvoice invoice : invoices.keySet()) {
            DeclarationInvoiceDTO invoiceDTO = invoices.get(invoice);

            for (DeclarationInvoiceItemDTO item : invoiceDTO.getInvoiceItemDTOS()) {
                BOEReportLine result = new BOEReportLine();
                result.setBoeReport(boeReport);
                setBoeInfo(customsDeclaration, invoice, invoiceDTO, item, result);
                lines.add(result);
            }
        }

        boeReport.setBoeReportLines(new HashSet<>(lines));
        return boeReport;
    }

    public static BOEReport updateBOEReport(BOEReport boeReport, CustomsDeclaration customsDeclaration,
                                            Map<DeclarationInvoice, DeclarationInvoiceDTO> invoices) {
//        boeReport.setCustomsDeclaration(customsDeclaration);
        Set<BOEReportLine> boeReportLines = boeReport.getBoeReportLines();
        for (BOEReportLine reportLine : boeReportLines) {
            for (DeclarationInvoice invoice : invoices.keySet()) {
                DeclarationInvoiceDTO invoiceDTO = invoices.get(invoice);
                for (DeclarationInvoiceItemDTO item : invoiceDTO.getInvoiceItemDTOS()) {
                    boolean equals = new EqualsBuilder().append(reportLine.getItemReference(), item.getReference())
                            .append(reportLine.getInvoiceNumber(), invoice.getReference())
                            .append(reportLine.getLineNumber(), String.valueOf(item.getBeLine())).isEquals();
                    if (equals) {
                        setBoeInfo(customsDeclaration, invoice, invoiceDTO, item, reportLine);
                    }
                }
            }
        }

        return boeReport;
    }

    private static void setBoeInfo(CustomsDeclaration customsDeclaration, DeclarationInvoice invoice,
                                   DeclarationInvoiceDTO invoiceDTO, DeclarationInvoiceItemDTO item, BOEReportLine result) {
        result.setItemReference(item.getReference());

        if (customsDeclaration.getShipment().isImports()) {
            if (invoice.getCommercialInvoice().getSupplier() != null) {
                result.setSupplierCode(invoice.getCommercialInvoice().getSupplier().getSupplier().getCode());
                result.setSupplierName(invoice.getCommercialInvoice().getSupplier().getSupplier().getName());
            }
            result.setImporterCode(customsDeclaration.getImporter().getCustomsCode());
            result.setImporterName(customsDeclaration.getImporter().getName());
        } else {
            result.setSupplierCode(customsDeclaration.getImporter().getCode());
            result.setSupplierName(customsDeclaration.getImporter().getName());
            if (invoice.getCommercialInvoice().getExportParty() != null) {
                result.setImporterCode(invoice.getCommercialInvoice().getExportParty().getCode());
                result.setImporterName(invoice.getCommercialInvoice().getExportParty().getName());
            }
        }

        result.setClearingAgent(customsDeclaration.getShipment().getShippingInfo().getClearingAgent() != null ?
                customsDeclaration.getShipment().getShippingInfo().getClearingAgent().getName() : "");

        result.setIncoTerm(customsDeclaration.getShipment().getIncoterm().getName());

        result.setMrn(customsDeclaration.getMrnNumber());
        result.setPlaceOfEntry(customsDeclaration.getPlaceOfCustomsEntry() == null ? null : customsDeclaration.getPlaceOfCustomsEntry()
                .getCode());
        result.setInvoiceNumber(invoice.getReference());
        result.setDeliveryNoteNumber(invoice.getCommercialInvoice().getAdditionalReference());
        result.setBoePurposeCode(customsDeclaration.getPurposeCode().getSarsCode());
        result.setBoeNumber(customsDeclaration.getMrnNumber() != null ? customsDeclaration.getMrnNumber().substring(11,
                customsDeclaration.getMrnNumber().length()) : "");
        result.setBoeDate(customsDeclaration.getBillOfEntryDate());
        result.setLineNumber(String.valueOf(item.getBeLine()));
        result.setCpcCode("" + customsDeclaration.getPurposeCode().getCpcCode());
        result.setPccCode("" + ((customsDeclaration.getPrcc() != null
                && !customsDeclaration.getPrcc().isEmpty()) ? customsDeclaration.getPrcc() : "00"));
        result.setCurrency(invoiceDTO.getCurrency());
        result.setCountryOfOrigin(item.getCoo());
        result.setCostingQty(item.getStatQty());
        result.setBasicCost(item.getValue());
        result.setUnitForeignValue(item.getUnitValue());
        result.setInvoiceNumber(invoiceDTO.getReference());
        result.setDeliveryNoteNumber(invoice.getCommercialInvoice().getAdditionalReference());
        result.setShipmentReference(customsDeclaration.getShipment().getReference());
        result.setTariff(item.getTariffHeading());
        result.setDuty(item.getTotalDuty());
        result.setDutyPercentage(item.getDutyPercentage());
        result.setAgentReference(customsDeclaration.getShipment().getNumber());
//        SarsEvent lastSarsEvent =customsDeclaration.getLastSarsEvent() does not work before transaction commit
        SarsEvent lastSarsEvent = Event.getLastEvent(customsDeclaration.getSarsEvents());
        if (lastSarsEvent != null &&
                lastSarsEvent.getEventType() != null) {
            if (lastSarsEvent.getEventType().equals(EdifactStatus.BLANK)) {
                result.setCustomsStatus("");
            } else {
                result.setCustomsStatus("" + lastSarsEvent.getEventType().getStatusNumber());
                result.setCustomsStatusDate(lastSarsEvent.getCreated());
            }
        } else if (customsDeclaration.getEdifactStatus() != null) {
            if (customsDeclaration.getEdifactStatus().equals(EdifactStatus.BLANK)) {
                result.setCustomsStatus("");
            } else {
                result.setCustomsStatus("" + customsDeclaration.getEdifactStatus().getStatusNumber());
                result.setCustomsStatusDate(lastSarsEvent.getCreated());
            }
        } else {
            result.setCustomsStatus("");
        }

        result.setDivision(customsDeclaration.getShipment().getActiveConsignments().get(0).getActiveOrders().get(0)
                .getOrganisationalUnit().getNameCode());
        Set<ShipmentContainer> containers = customsDeclaration.getShipment().getContainers();
        if (!containers.isEmpty() && containers != null) {
            for (ShipmentContainer container : containers) {
                result.setFinalDestination(container.getFinalDestination() != null ?
                        container.getFinalDestination().getName() : "");
                break;
            }
        }
        Shipment shipment = customsDeclaration.getShipment();
        shipment = HibernateUtils.initializeAndUnproxy(shipment);
        if (shipment instanceof AirShipment) {
            result.setMasterBill(((AirShipment) shipment).getMasterAirwayBillNumber());
            result.setHouseBill(((AirShipment) shipment).getHouseAirwayBillNumber());
        } else if (shipment instanceof SeaShipment) {
            result.setMasterBill(((SeaShipment) shipment).getMasterBillOfLadingReference());
            result.setHouseBill(((SeaShipment) shipment).getBillOfLadingReference());
        }
        result.setLrnNumber(customsDeclaration.getLrnNumber());
        result.setCustomsQty(item.getSuppQty1());
        result.setCustomsUQ(item.getStatQty());
        result.setCustomsUnit("" + item.getSuppUnit1());
        //BigDecimal grossWeight = BigDecimal.ZERO;
        //if (item.getStatQty() != null && item.getGrossWeight() != null)
        //    grossWeight = item.getStatQty().multiply(item.getGrossWeight());
        //result.setGrossWeight(grossWeight);
        result.setFreightForwarder(customsDeclaration.getShipment().getShippingInfo().getFreightForwarder().getName());
        result.setRateInverted(item.getFactor());
        result.setZarFobHd(item.getCustomsValue());
        result.setVat(item.getVat());
        result.setRulesOfOrigin(item.getRulesOfOrigin());
        result.setGoodsDescription(item.getDutyItemDescription());
        result.setInvoiceLineNumber("" + item.getLine());
        result.setAdditionalQuantity(item.getSuppQty2());
        result.setAdditionalQuantityUOM(item.getSuppUnit2());
        result.setAssessmentDate(customsDeclaration.getAssessmentDate());
        result.setAtvAmount(item.getAtv());
        result.setContainerMode(customsDeclaration.getContainerCargoState().getSarsCode());
        result.setCcdCreatedDate(customsDeclaration.getDeclarationDate());
        result.setDischargeDate(customsDeclaration.getShipment().getEstimatedArrivalDateAtPlaceOfDischarge());
        result.setRateOfExchangeDate(customsDeclaration.getShipment().getShippedOnBoardDate());
        if (shipment.getShippingInfo().getShippingMode() == ShippingMode.SEA) {
            result.setFlightVoyageNumber(((SeaShipment) shipment).getVoyageNumber());
            result.setMasterBillIssueDate(((SeaShipment) shipment).getMasterBillOfLadingDate());
        }
        if (shipment.getShippingInfo().getShippingMode() == ShippingMode.AIR) {
            result.setFlightVoyageNumber(((AirShipment) shipment).getFlightNumber());
            result.setMasterBillIssueDate(((AirShipment) shipment).getMasterAirwayBillIssueDate());
        }
        result.setFreightAmount(item.getFreight());
        result.setGrossWeight(item.getGrossWeight());
        result.setGrossWeightUOM(item.getUom());
        result.setInvoiceExchangeRate(invoice.getCustomsDutyROE());
        result.setInvoiceUQ(item.getStatQty());
        result.setPortOfDischarge(customsDeclaration.getPlaceOfDischarge().getName());
        result.setPortOfLoading(customsDeclaration.getPlaceOfLoading().getName());
        result.setRebateCode(item.getRebateCode());
        result.setSchedule1P2A(item.getSchedule1P2A());
        result.setSchedule1P2B(item.getSchedule1P2B());
        result.setSchedule1P3E(item.getSchedule1P3E());
        result.setSchedule1P7(item.getSchedule1P7());
        result.setRelationshipIndicator(customsDeclaration.getCustomsValuation().getSarsCode());
        result.setShipmentType(shipment.isImports() ? "IMP" : "EXP");

        CustomsDeclarationCostedValues before = customsDeclaration
                .getCostedValues(CustomsDeclarationCostedValues.Type.BEFORE_CORRECTION, 0);
        if (MathUtils.isNonZero(before.getCustomsVat()))
            result.setTaxOrFree("VAT");

        result.setTradeAgreementROO(item.getRulesOfOrigin());
        result.setShippingMode(customsDeclaration.getShipment().getShippingMode().name());
        result.setValuationCode(customsDeclaration.getValuationMethod().getSarsCode());
        if (customsDeclaration.getPaymentMethod() != null)
            result.setPaymentMethod(customsDeclaration.getPaymentMethod().getLabel());
        if (customsDeclaration.getCustomsFinancialAccountOwner() != null)
            result.setCustomsFinancialAccountOwner(customsDeclaration.getCustomsFinancialAccountOwner().value());

        if (item.getRulesOfOrigin() != null) {
            if (item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.TACR.value()) ||
                    item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.IRDLT_6000.value()) ||
                    item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.IRDGT_6000WAN.value())) {
                result.setTradeStatistics("Compliant");
            } else if (item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.NOTEUO.value())) {
                result.setTradeStatistics(item.getRulesOfOrigin());
            } else if (item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.IRDGT_6000MAN.value()) ||
                    item.getRulesOfOrigin().equalsIgnoreCase(RulesOfOrigin.NODOO.value())) {
                result.setTradeStatistics("Non-Compliant");
            }
        } else if (item.getRulesOfOrigin() == null) {
            result.setTradeStatistics("Non-Compliant");
        }
    }
}