001package org.kuali.ole.sip2.service.impl;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.apache.commons.lang3.StringUtils;
005import org.apache.log4j.Logger;
006import org.kuali.ole.OLEConstants;
007import org.kuali.ole.deliver.bo.*;
008import org.kuali.ole.deliver.service.OleLoanDocumentDaoOjb;
009import org.kuali.ole.ncip.bo.OLEItemFine;
010import org.kuali.ole.sip2.constants.OLESIP2Constants;
011import org.kuali.ole.sip2.service.OLENettyServer;
012import org.kuali.ole.sip2.service.OLESIP2HelperService;
013import org.kuali.ole.sys.context.SpringContext;
014import org.kuali.rice.core.api.config.property.ConfigContext;
015import org.kuali.rice.core.api.util.type.KualiDecimal;
016import org.kuali.rice.core.web.format.CurrencyFormatter;
017import org.kuali.rice.krad.service.BusinessObjectService;
018import org.kuali.rice.krad.service.KRADServiceLocator;
019
020import java.math.BigDecimal;
021import java.sql.Timestamp;
022import java.util.ArrayList;
023import java.util.HashMap;
024import java.util.List;
025import java.util.Map;
026
027/**
028 * Created by sheiksalahudeenm on 12/29/14.
029 */
030public class OLESIP2HelperServiceImpl implements OLESIP2HelperService {
031
032    Logger LOG = Logger.getLogger(OLESIP2HelperServiceImpl.class);
033
034    private BusinessObjectService businessObjectService;
035
036    private BusinessObjectService getBusinessObjectService() {
037        if (null == businessObjectService) {
038            businessObjectService = KRADServiceLocator.getBusinessObjectService();
039        }
040        return businessObjectService;
041    }
042
043    public void setBusinessObjectService(BusinessObjectService businessObjectService) {
044        this.businessObjectService = businessObjectService;
045    }
046
047
048    @Override
049    public OLENettyServer doActionForSocketServer(String action, StringBuffer responseString, OLENettyServer olesip2Server) {
050        if (action.equalsIgnoreCase("start")) {
051            olesip2Server = startOLESip2Server(responseString, olesip2Server);
052        } else if (action.equalsIgnoreCase("stop")) {
053            LOG.info("******** Request for stop OLE Socket server ********");
054            if (olesip2Server != null) {
055                olesip2Server.stop();
056                responseString.append(OLESIP2Constants.SERVER_STOPPED);
057                LOG.info("******** " + OLESIP2Constants.SERVER_STOPPED + " ********");
058            }
059        } else if (action.equalsIgnoreCase("status")) {
060            LOG.info("******** Request for getting status of OLE Socket server ********");
061            if (olesip2Server != null) {
062                if (olesip2Server.isStopped()) {
063                    responseString.append(OLESIP2Constants.SERVER_DOWN);
064                    LOG.info("******** " + OLESIP2Constants.SERVER_DOWN + " ********");
065                } else {
066                    responseString.append(OLESIP2Constants.SERVER_RUNNING);
067                    LOG.info("******** " + OLESIP2Constants.SERVER_RUNNING + " ********");
068                }
069            } else {
070                responseString.append(OLESIP2Constants.SERVER_DOWN);
071                LOG.info("******** " + OLESIP2Constants.SERVER_DOWN + " ********");
072
073            }
074        }
075        return olesip2Server;
076    }
077
078    @Override
079    public OLENettyServer startOLESip2Server(StringBuffer responseString, OLENettyServer olesip2Server) {
080        LOG.info("******** Request for starting OLE Socket server ********");
081        String portNo = ConfigContext.getCurrentContextConfig().getProperty("sip2.port");
082        String serverUrl = ConfigContext.getCurrentContextConfig().getProperty("sip2.url");
083        //String circulationService=parameterMap.get("circulationService")[0];
084        if (StringUtils.isNotBlank(portNo) && StringUtils.isNotBlank(serverUrl)) {
085
086            olesip2Server = new OLENettyServer(Integer.parseInt(portNo), serverUrl, "/circulationsip?service=");
087
088            try {
089                Thread thread = new Thread(olesip2Server);
090                thread.start();
091                try {
092                    Thread.sleep(5 * 1000);
093                    if (olesip2Server.getMessage() != null) {
094                        responseString.append(olesip2Server.getMessage());
095                    } else {
096                        responseString.append(OLESIP2Constants.STARTED_SUCCESSFULLY);
097                        LOG.info("******** " + OLESIP2Constants.STARTED_SUCCESSFULLY + " ********");
098                    }
099                } catch (Exception e) {
100                    e.printStackTrace();
101                    responseString.append(OLESIP2Constants.PROBLEM_WITH_SERVER + "\n");
102                    responseString.append("Exception: \n" + e);
103                }
104            } catch (Exception e) {
105                e.printStackTrace();
106                responseString.append(OLESIP2Constants.PROBLEM_WITH_SERVER + "\n");
107                responseString.append("Exception: \n" + e);
108            }
109
110            //}
111
112        } else {
113            responseString.append(OLESIP2Constants.FAIL_TO_LOAD + "\n");
114            responseString.append(OLESIP2Constants.PARAMETER_MISSING);
115            LOG.info("******** " + OLESIP2Constants.FAIL_TO_LOAD + " ********");
116            LOG.info("******** " + OLESIP2Constants.PARAMETER_MISSING + " ********");
117        }
118        return olesip2Server;
119
120    }
121
122
123    @Override
124    public void stopOLESip2Server(StringBuffer responseString, OLENettyServer olesip2Server) {
125        LOG.info("******** Request for stop OLE Socket server ********");
126        if (olesip2Server != null) {
127            olesip2Server.stop();
128            responseString.append(OLESIP2Constants.SERVER_STOPPED);
129            LOG.info("******** " + OLESIP2Constants.SERVER_STOPPED + " ********");
130        }
131
132    }
133
134    @Override
135    public void startOLESip2Server() {
136        boolean onLoadStartup = ConfigContext.getCurrentContextConfig().getBooleanProperty("sip2.startOnLoad");
137        if (onLoadStartup) {
138            StringBuffer responseString = new StringBuffer();
139            OLESIP2Constants.olesip2Server = startOLESip2Server(responseString, OLESIP2Constants.olesip2Server);
140            LOG.info(responseString.toString());
141        }
142
143    }
144
145    @Override
146    public void stopOLESip2Server() {
147        StringBuffer responseString = new StringBuffer();
148        stopOLESip2Server(responseString, OLESIP2Constants.olesip2Server);
149        LOG.info(responseString.toString());
150
151    }
152
153    @Override
154    public OlePaymentStatus getPaymentStatus(String paymentStatus) {
155        LOG.debug("Inside the getPaymentStatus method");
156        Map statusMap = new HashMap();
157        statusMap.put("paymentStatusCode", paymentStatus);
158        List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
159        return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
160    }
161
162    @Override
163    public KualiDecimal itemWiseFeePaid(List<FeeType> feeTypes, KualiDecimal paymentAmount, String paymentMethod,
164                                        String fullyPaidStatus, String partiallyPaidStatus, String forgiveErrorNote,
165                                        String transactionNumber, String transactionNote, String paidByUser, List<OleItemLevelBillPayment> currentSessionTransactions) {
166        KualiDecimal payAmt = paymentAmount;
167        LOG.debug("Inside itemWiseFeePaid");
168        String operatorId = OLESIP2Constants.OPERATOR_ID;
169        KualiDecimal unPaidAmount;
170        for (FeeType feeType : feeTypes) {
171            if (((feeType.getPaymentStatusCode().equalsIgnoreCase(OLEConstants.PAY_OUTSTANDING) || feeType.getPaymentStatusCode().equalsIgnoreCase(OLEConstants.PAY_PARTIALLY))
172                    && paymentAmount.compareTo(OLEConstants.KUALI_BIGDECIMAL_DEF_VALUE) > 0)) {
173                HashMap<String, String> map = new HashMap<String, String>();
174                map.put("billNumber", feeType.getBillNumber());
175                PatronBillPayment patronBillPayment = getBusinessObjectService().findByPrimaryKey(PatronBillPayment.class, map);
176                List<FeeType> patronFeeTypes = patronBillPayment.getFeeType();
177                for (FeeType patronFeeType : patronFeeTypes) {
178                    if (patronFeeType.getId().equalsIgnoreCase(feeType.getId())) {
179                        if (paymentAmount.compareTo(patronFeeType.getBalFeeAmount()) >= 0) {
180                            unPaidAmount = patronBillPayment.getUnPaidBalance().subtract(feeType.getBalFeeAmount());
181                            paymentAmount = paymentAmount.subtract(patronFeeType.getBalFeeAmount());
182                            OlePaymentStatus olePaymentStatus = getPaymentStatus(fullyPaidStatus);
183                            patronFeeType.setOlePaymentStatus(olePaymentStatus);
184                            patronFeeType.setPaymentStatus(olePaymentStatus.getPaymentStatusId());
185                            List<OleItemLevelBillPayment> oleItemLevelBillPayments = patronFeeType.getItemLevelBillPaymentList() != null && patronFeeType.getItemLevelBillPaymentList().size() > 0
186                                    ? patronFeeType.getItemLevelBillPaymentList() : new ArrayList<OleItemLevelBillPayment>();
187                            OleItemLevelBillPayment oleItemLevelBillPayment = new OleItemLevelBillPayment();
188                            oleItemLevelBillPayment.setPaymentDate(new Timestamp(System.currentTimeMillis()));
189                            oleItemLevelBillPayment.setAmount(patronFeeType.getBalFeeAmount());
190                            oleItemLevelBillPayment.setCreatedUser(operatorId);
191                            oleItemLevelBillPayment.setTransactionNote(transactionNote);
192                            oleItemLevelBillPayment.setTransactionNumber(transactionNumber);
193                            oleItemLevelBillPayment.setPaymentMode(paymentMethod);
194                            oleItemLevelBillPayments.add(oleItemLevelBillPayment);
195                            currentSessionTransactions.add(oleItemLevelBillPayment);
196                            patronFeeType.setBalFeeAmount(OLEConstants.KUALI_BIGDECIMAL_DEF_VALUE);
197                            patronFeeType.setItemLevelBillPaymentList(oleItemLevelBillPayments);
198                            if (paymentMethod != null && paymentMethod.equalsIgnoreCase(OLEConstants.ERROR)) {
199                                patronFeeType.setErrorNote(forgiveErrorNote);
200                            }
201                            if (paymentMethod != null && paymentMethod.equalsIgnoreCase(OLEConstants.FORGIVE)) {
202                                patronFeeType.setForgiveNote(forgiveErrorNote);
203                            }
204                            feeType.setActiveItem(false);
205                            patronBillPayment.setPaymentAmount(payAmt.subtract(paymentAmount));
206                            payAmt = paymentAmount;
207                        } else {
208                            unPaidAmount = patronBillPayment.getUnPaidBalance().subtract(paymentAmount);
209                            KualiDecimal updatedFeeAmount = patronFeeType.getBalFeeAmount().subtract(paymentAmount);
210                            KualiDecimal transAmount = paymentAmount;
211                            paymentAmount = paymentAmount.subtract(patronFeeType.getBalFeeAmount());
212                            OlePaymentStatus olePaymentStatus = getPaymentStatus(partiallyPaidStatus);
213                            patronFeeType.setOlePaymentStatus(olePaymentStatus);
214                            patronFeeType.setPaymentStatus(olePaymentStatus.getPaymentStatusId());
215                            List<OleItemLevelBillPayment> oleItemLevelBillPayments = patronFeeType.getItemLevelBillPaymentList() != null && patronFeeType.getItemLevelBillPaymentList().size() > 0
216                                    ? patronFeeType.getItemLevelBillPaymentList() : new ArrayList<OleItemLevelBillPayment>();
217                            OleItemLevelBillPayment oleItemLevelBillPayment = new OleItemLevelBillPayment();
218                            oleItemLevelBillPayment.setPaymentDate(new Timestamp(System.currentTimeMillis()));
219                            oleItemLevelBillPayment.setAmount(transAmount.compareTo(OLEConstants.KUALI_BIGDECIMAL_DEF_VALUE) < 0 ? transAmount : transAmount);
220                            oleItemLevelBillPayment.setCreatedUser(operatorId);
221                            oleItemLevelBillPayment.setTransactionNote(transactionNote);
222                            oleItemLevelBillPayment.setTransactionNumber(transactionNumber);
223                            oleItemLevelBillPayment.setPaymentMode(paymentMethod);
224                            oleItemLevelBillPayments.add(oleItemLevelBillPayment);
225                            currentSessionTransactions.add(oleItemLevelBillPayment);
226                            patronFeeType.setBalFeeAmount(updatedFeeAmount);
227                            patronFeeType.setItemLevelBillPaymentList(oleItemLevelBillPayments);
228                            if (paymentMethod != null && paymentMethod.equalsIgnoreCase(OLEConstants.ERROR)) {
229                                patronFeeType.setErrorNote(forgiveErrorNote);
230                            }
231                            if (paymentMethod != null && paymentMethod.equalsIgnoreCase(OLEConstants.FORGIVE)) {
232                                patronFeeType.setForgiveNote(forgiveErrorNote);
233                            }
234                            patronBillPayment.setPaymentAmount(payAmt);
235                        }
236                        //feeType = patronFeeType;
237                        patronBillPayment.setUnPaidBalance(unPaidAmount);
238                        if (LOG.isDebugEnabled()) {
239                            LOG.debug("unPaidAmount" + patronBillPayment.getUnPaidBalance());
240                        }
241                        patronBillPayment.setPaymentOperatorId(OLESIP2Constants.OPERATOR_ID);
242                        patronBillPayment.setPayDate(new java.sql.Date((new java.util.Date()).getTime()));
243                        patronBillPayment.setPaymentMethod(paymentMethod);
244                        if (patronBillPayment.getPaymentMethod().equals(OLEConstants.FORGIVE) || patronBillPayment.getPaymentMethod().equals(OLEConstants.CANCEL) || patronBillPayment.getPaymentMethod().equals(OLEConstants.ERROR)) {
245                            if (patronBillPayment.getPaymentMethod().equalsIgnoreCase(OLEConstants.FORGIVE)) {
246                                patronBillPayment.setFreeTextNote(CurrencyFormatter.getSymbolForCurrencyPattern() + patronBillPayment.getPaymentAmount() +" "+ OLEConstants.FORGIVE_MESSAGE);
247                            }
248                            if (patronBillPayment.getPaymentMethod().equalsIgnoreCase(OLEConstants.CANCEL)) {
249                                patronBillPayment.setFreeTextNote(OLEConstants.CANCEL_MESSAGE_AMT + " " +CurrencyFormatter.getSymbolForCurrencyPattern() + patronBillPayment.getPaymentAmount());
250                            }
251                            if (patronBillPayment.getPaymentMethod().equalsIgnoreCase(OLEConstants.ERROR)) {
252                                patronBillPayment.setFreeTextNote(CurrencyFormatter.getSymbolForCurrencyPattern() + patronBillPayment.getPaymentAmount() + OLEConstants.ERROR_MESSAGE);
253                            }
254                        } else {
255                            patronBillPayment.setFreeTextNote(CurrencyFormatter.getSymbolForCurrencyPattern() + patronBillPayment.getPaymentAmount() + " paid through " + patronBillPayment.getPaymentMethod());
256                            patronBillPayment.setNote(null);
257                        }
258                        getBusinessObjectService().save(patronBillPayment);
259                    }
260                }
261            }
262        }
263        return paymentAmount;
264    }
265
266    @Override
267    public String feePaid(String patronBarcode, String feeTypeCode, String feeTypeId, String paymentMethod, KualiDecimal paymentAmount, String transactionNumber, String paidByUser) {
268        String responseString = "";
269        List<FeeType> feeTypes = new ArrayList<FeeType>();
270        String patronId = "";
271        Map barMap = new HashMap();
272        barMap.put(OLEConstants.OlePatron.BARCODE, patronBarcode);
273        List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
274        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(patronDocumentList)) {
275            patronId = patronDocumentList.get(0).getOlePatronId();
276        }
277        if (org.apache.commons.lang.StringUtils.isNotBlank(patronId)) {
278            List<PatronBillPayment> patronBills = (List<PatronBillPayment>) ((OleLoanDocumentDaoOjb) SpringContext.getBean("oleLoanDao")).getPatronBills(patronId);
279            String forgiveErrorNote = "";
280            String transactionNote = "";
281            for (PatronBillPayment olPatronBillPayment : patronBills) {
282                for (FeeType feeType : olPatronBillPayment.getFeeType()) {
283                    if (org.apache.commons.lang.StringUtils.isNotBlank(feeTypeId)) {
284                        if (feeType.getBillNumber().equalsIgnoreCase(feeTypeId) && feeType.getOleFeeType().getFeeTypeCode().equalsIgnoreCase(feeTypeCode)) {
285                            feeTypes.add(feeType);
286                        }
287                    } else {
288                        if (feeType.getOleFeeType().getFeeTypeCode().equalsIgnoreCase(feeTypeCode)) {
289                            feeTypes.add(feeType);
290                        }
291                    }
292                }
293            }
294            if (feeTypes.size() == 1) {
295                List<OleItemLevelBillPayment> oleItemLevelBillPaymentList = new ArrayList<OleItemLevelBillPayment>();
296                for (FeeType feeType : feeTypes) {
297                    if (org.apache.commons.collections.CollectionUtils.isNotEmpty(feeType.getItemLevelBillPaymentList())) {
298                        oleItemLevelBillPaymentList.addAll(feeType.getItemLevelBillPaymentList());
299                    }
300                }
301                KualiDecimal unPaidAmount = itemWiseFeePaid(feeTypes, paymentAmount, paymentMethod, OLEConstants.FULL_PAID, OLEConstants.PAR_PAID, forgiveErrorNote,
302                        transactionNumber, transactionNote, paidByUser, oleItemLevelBillPaymentList);
303                LOG.info("unPaidAmount : " + unPaidAmount);
304                responseString = "Successfully Paid the Amount";
305            } else {
306                LOG.info("More than one fee is there");
307                responseString = "Having more than one fee";
308            }
309        }
310        return responseString;
311    }
312
313    @Override
314    public BigDecimal calculateTotalFineBalance(List<OLEItemFine> oleItemFineList) {
315        BigDecimal balanceAmount = new BigDecimal(0);
316        if (CollectionUtils.isNotEmpty(oleItemFineList)) {
317            for (OLEItemFine oleItemFine : oleItemFineList) {
318                balanceAmount = balanceAmount.add(oleItemFine.getBalance());
319            }
320        }
321
322        return balanceAmount;
323    }
324
325}