001package org.kuali.ole.select.service.impl;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.apache.commons.lang.StringUtils;
005import org.kuali.ole.DocumentUniqueIDPrefix;
006import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
007import org.kuali.ole.docstore.common.document.Item;
008import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
009import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemRecord;
010import org.kuali.ole.module.purap.document.service.OlePurapService;
011import org.kuali.ole.select.OleSelectConstant;
012import org.kuali.ole.select.businessobject.OleCopy;
013import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
014import org.kuali.ole.select.businessobject.OleRequisitionItem;
015import org.kuali.ole.select.document.OlePurchaseOrderDocument;
016import org.kuali.ole.select.document.OleRequisitionDocument;
017import org.kuali.ole.select.document.service.OleCopyHelperService;
018import org.kuali.ole.sys.OLEConstants;
019import org.kuali.ole.sys.context.SpringContext;
020import org.kuali.rice.core.api.config.property.ConfigContext;
021import org.kuali.rice.core.api.util.type.KualiDecimal;
022import org.kuali.rice.core.api.util.type.KualiInteger;
023import org.kuali.rice.krad.service.KRADServiceLocator;
024import org.kuali.ole.docstore.common.document.BibTree;
025
026import org.kuali.ole.docstore.common.util.DataSource;
027
028import java.beans.PropertyVetoException;
029import java.io.File;
030import java.io.FileWriter;
031import java.io.IOException;
032import java.math.BigDecimal;
033import java.sql.Connection;
034import java.sql.PreparedStatement;
035import java.sql.SQLException;
036import java.util.*;
037
038/**
039 * Created with IntelliJ IDEA.
040 * User: aurojyotit
041 * Date: 12/12/14
042 * Time: 12:02 PM
043 * To change this template use File | Settings | File Templates.
044 */
045public class OLECopyUpdateImpl {
046    protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OLECopyUpdateImpl.class);
047    String directory = ConfigContext.getCurrentContextConfig().getProperty(org.kuali.ole.OLEConstants.STAGING_DIRECTORY) + File.separator + "olecopies";
048    String saveOleCopyFileName = "req_po_nocopies_process_info.txt";
049    String infoOleCopyFileName = "req_po_nocopies_info.txt";
050
051    private DocstoreClientLocator docstoreClientLocator;
052
053    public DocstoreClientLocator getDocstoreClientLocator() {
054        if (null == docstoreClientLocator) {
055            return SpringContext.getBean(DocstoreClientLocator.class);
056        }
057        return docstoreClientLocator;
058    }
059
060
061    public List<OlePurchaseOrderDocument> getOlePurchaseOrderDocuments() {
062        List result = new ArrayList();
063        List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = (List<OlePurchaseOrderDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePurchaseOrderDocument.class);
064        if (CollectionUtils.isNotEmpty(olePurchaseOrderDocuments)) {
065            result.addAll(olePurchaseOrderDocuments);
066        }
067        return result;
068    }
069
070
071    public void processUpdateOleCopies() {
072        StringBuffer buffer = new StringBuffer();
073        buffer = new StringBuffer();
074        List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = getOlePurchaseOrderDocuments();
075        if (CollectionUtils.isNotEmpty(olePurchaseOrderDocuments)) {
076            for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
077                olePurchaseOrderDocument.processAfterRetrieve();
078                Map map = new HashMap();
079                map.put("purapDocumentIdentifier", olePurchaseOrderDocument.getRequisitionIdentifier().toString());
080                List<OleRequisitionDocument> oleRequisitionDocuments = (List<OleRequisitionDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleRequisitionDocument.class, map);
081                if (CollectionUtils.isNotEmpty(oleRequisitionDocuments)) {
082                    OleRequisitionDocument oleRequisitionDocument = oleRequisitionDocuments.get(0);
083                    if (LOG.isInfoEnabled()) {
084                        LOG.info("#REQ DOC NO :" + oleRequisitionDocument.getDocumentNumber() + "  ######  " + "PO DOC NO :" + olePurchaseOrderDocument.getDocumentNumber());
085                        buffer.append("#REQ DOC NO :" + oleRequisitionDocument.getDocumentNumber() + "  ######  " + "PO DOC NO :" + olePurchaseOrderDocument.getDocumentNumber());
086                        buffer.append("\n");
087                    }
088                    if (CollectionUtils.isNotEmpty(olePurchaseOrderDocument.getItems())) {
089                        try {
090                            for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
091                                if (CollectionUtils.isEmpty(olePurchaseOrderItem.getCopyList())) {
092                                    if (olePurchaseOrderItem.getItemLineNumber() != null) {
093                                        prepareAndSaveOleCopy(oleRequisitionDocument, olePurchaseOrderDocument, olePurchaseOrderItem, buffer);
094                                    }
095                                }
096                            }
097                        } catch (Exception e) {
098                            LOG.info("###########  processUpdateOleCopies of OLECopyUpdateImpl ###########" + e);
099                        }
100                    }
101                }
102            }
103        }
104        try {
105            this.writeStatusToFile(directory, saveOleCopyFileName, buffer.toString());
106        } catch (Exception e) {
107            LOG.error("while writing the file error occurred" + e);
108        }
109    }
110
111    public void checkPoAndReqHaveOleCopies() {
112        StringBuffer buffer = new StringBuffer();
113        buffer = new StringBuffer();
114        if (LOG.isInfoEnabled()) {
115            LOG.info("###### Start of method execution for checking olecopies in Requisition and PurchaseOrder  #####");
116            buffer.append("###### Start of method execution for checking olecopies in Requisition and PurchaseOrder  #####");
117            buffer.append("\n");
118        }
119        List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = getOlePurchaseOrderDocuments();
120        if (CollectionUtils.isNotEmpty(olePurchaseOrderDocuments)) {
121            for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
122                olePurchaseOrderDocument.processAfterRetrieve();
123                Map map = new HashMap();
124                map.put("purapDocumentIdentifier", olePurchaseOrderDocument.getRequisitionIdentifier().toString());
125                List<OleRequisitionDocument> oleRequisitionDocuments = (List<OleRequisitionDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleRequisitionDocument.class, map);
126                if (CollectionUtils.isNotEmpty(oleRequisitionDocuments)) {
127                    OleRequisitionDocument oleRequisitionDocument = oleRequisitionDocuments.get(0);
128                    if (CollectionUtils.isNotEmpty(olePurchaseOrderDocument.getItems())) {
129                        try {
130                            for (OlePurchaseOrderItem olePurchaseOrderItem : (List<OlePurchaseOrderItem>) olePurchaseOrderDocument.getItems()) {
131                                if (CollectionUtils.isEmpty(olePurchaseOrderItem.getCopyList())) {
132                                    if (olePurchaseOrderItem.getItemLineNumber() != null) {
133                                        if (LOG.isInfoEnabled()) {
134                                            LOG.info("    #REQ DOC NO :" + oleRequisitionDocument.getDocumentNumber() + "  #PO ITEM ID :" + olePurchaseOrderItem.getItemIdentifier() + "  ######  " + "PO DOC NO :" + olePurchaseOrderDocument.getDocumentNumber());
135                                            buffer.append("    #REQ DOC NO :" + oleRequisitionDocument.getDocumentNumber() + "  #PO ITEM ID :" + olePurchaseOrderItem.getItemIdentifier() + "  ######  " + "PO DOC NO :" + olePurchaseOrderDocument.getDocumentNumber());
136                                            buffer.append("\n");
137                                        }
138                                    }
139                                }
140                            }
141                        } catch (Exception e) {
142                            LOG.info("###########  processUpdateOleCopies of OLECopyUpdateImpl ###########" + e);
143                        }
144                    }
145                }
146            }
147        }
148        if (LOG.isInfoEnabled()) {
149            LOG.info("###### End of method execution for checking olecopies in Requisition and PurchaseOrder  #####");
150            buffer.append("###### End of method execution for checking olecopies in Requisition and PurchaseOrder  #####");
151            buffer.append("\n");
152        }
153        try {
154            this.writeStatusToFile(directory, infoOleCopyFileName, buffer.toString());
155        } catch (Exception e) {
156            LOG.error("while writing the file error occurred" + e);
157        }
158    }
159
160    public void saveOleCopies(List<OleCopy> oleCopies, StringBuffer buffer) {
161        try {
162            if (LOG.isInfoEnabled()) {
163                LOG.info("################Inside saveOleCopies method#################");
164                buffer.append("################Inside saveOleCopies method#################");
165                buffer.append("\n");
166            }
167            KRADServiceLocator.getBusinessObjectService().save(oleCopies);
168            if (LOG.isInfoEnabled()) {
169                for (OleCopy oleCopy : oleCopies) {
170                    LOG.info("#OleCopy --> ID: " + oleCopy.getCopyId() + " REQ ITEM ID :  " + oleCopy.getReqItemId() + " PO ITEM ID : " + oleCopy.getPoItemId() + " PO DOC NUM : " + oleCopy.getPoDocNum() + " HOLDINGS ID : " + oleCopy.getInstanceId() + " ITEM ID : " + oleCopy.getItemUUID() + " BIB ID : " + oleCopy.getBibId());
171                    buffer.append("#OleCopy --> ID: " + oleCopy.getCopyId() + " REQ ITEM ID :  " + oleCopy.getReqItemId() + " PO ITEM ID : " + oleCopy.getPoItemId() + " PO DOC NUM : " + oleCopy.getPoDocNum() + " HOLDINGS ID : " + oleCopy.getInstanceId() + " ITEM ID : " + oleCopy.getItemUUID() + " BIB ID : " + oleCopy.getBibId());
172                    buffer.append("\n");
173                }
174                if (LOG.isInfoEnabled()) {
175                    LOG.info("################Copies record saved successfully#################");
176                }
177                buffer.append("################Copies record saved successfully#################");
178                buffer.append("\n");
179            }
180        } catch (Exception e) {
181            LOG.error("Error occured : while updating the copies for requisition document" + e.getMessage() + " " + e);
182            buffer.append("Error occured : while updating the copies for requisition document" + e.getMessage() + " " + e);
183            buffer.append("\n");
184        }
185    }
186
187    public void prepareAndSaveOleCopy(OleRequisitionDocument oleRequisitionDocument, OlePurchaseOrderDocument olePurchaseOrderDocument, OlePurchaseOrderItem olePurchaseOrderItem, StringBuffer buffer) {
188        if (CollectionUtils.isNotEmpty(oleRequisitionDocument.getItems())) {
189            List<OleRequisitionItem> oleRequisitionItems = (List<OleRequisitionItem>) oleRequisitionDocument.getItems();
190            if (CollectionUtils.isNotEmpty(oleRequisitionItems)) {
191                for (OleRequisitionItem item : oleRequisitionItems) {
192                    try {
193                        if (item.getItemLineNumber() != null && olePurchaseOrderItem.getItemLineNumber() != null && item.getItemLineNumber().equals(olePurchaseOrderItem.getItemLineNumber())) {
194                            try {
195                                if (null != item.getItemType() && item.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
196                                    if (item.getItemQuantity() != null && item.getItemNoOfParts() != null && !item.getItemQuantity().isGreaterThan(new KualiDecimal(1))
197                                            && !item.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
198                                        OleCopy oleCopy = new OleCopy();
199                                        oleCopy.setLocation(item.getItemLocation());
200                                        oleCopy.setBibId(item.getItemTitleId());
201                                        if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
202                                            oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
203                                        }
204                                        oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
205                                        oleCopy.setReqDocNum(olePurchaseOrderDocument.getPurapDocumentIdentifier());
206                                        oleCopy.setReqItemId(item.getItemIdentifier());
207                                        oleCopy.setPoDocNum(olePurchaseOrderDocument.getDocumentNumber());
208                                        oleCopy.setPoItemId(olePurchaseOrderItem.getItemIdentifier());
209                                        List<OleCopy> copyList = new ArrayList<>();
210                                        copyList.add(oleCopy);
211                                        item.setCopyList(copyList);
212                                        Map map = new HashMap();
213                                        map.put("purchaseOrderItemLineId", olePurchaseOrderDocument.getPurapDocumentIdentifier());
214                                        List<ItemRecord> itemRecords = (List<ItemRecord>) KRADServiceLocator.getBusinessObjectService().findMatching(ItemRecord.class, map);
215                                        if (CollectionUtils.isNotEmpty(itemRecords)) {
216                                            oleCopy.setItemUUID(DocumentUniqueIDPrefix.PREFIX_WORK_ITEM_OLEML + "-" + itemRecords.get(0).getItemId());
217                                            oleCopy.setInstanceId(DocumentUniqueIDPrefix.PREFIX_WORK_HOLDINGS_OLEML + "-" + itemRecords.get(0).getHoldingsId());
218                                        }
219                                        saveOleCopies(item.getCopyList(), buffer);
220                                    } else {
221                                        //oleRequisitionDocument.populateCopiesSection(item);
222                                        KualiInteger noOfParts = new KualiInteger((item.getItemNoOfParts().intValue()));
223                                        KualiInteger noOfCopies = new KualiInteger(item.getItemQuantity().intValue());
224                                        int copyNumberMax = noOfCopies.intValue();
225                                        KualiInteger noOfItems = new KualiInteger(1);
226                                        if (noOfParts != null && noOfItems != null) {
227                                            if (noOfItems.isZero() && noOfCopies.isZero()) {
228                                                noOfItems = new KualiInteger(1);
229                                            } else {
230                                                noOfItems = noOfCopies.multiply(noOfParts);
231                                            }
232                                        }
233                                        int enumNum = noOfParts.intValue();
234                                        String enumString = "";
235                                        for (int i = 1; i <= enumNum; i++) {
236                                            enumString = enumString + i;
237                                            int index = i;
238                                            if (index++ != enumNum) {
239                                                enumString = enumString + ",";
240                                            }
241                                        }
242                                        List<OleCopy> oleCopies = item.getCopyList();
243                                        for (int itemNo = 1, copyNumber = 1, partNumber = 1; itemNo <= noOfItems.intValue(); itemNo++, copyNumber++) {
244                                            OleCopy oleCopy = new OleCopy();
245                                            oleCopy.setLocation(item.getLocationCopies());
246                                            //volNum = volChar.size()>enumCount ? volChar.get(enumCount):"";
247                                            oleCopy.setEnumeration(item.getCaption() + " ");
248                                            oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
249                                            oleCopy.setLocation(item.getItemLocation());
250                                            oleCopy.setBibId(item.getItemTitleId());
251                                            if (StringUtils.isNotBlank(item.getLinkToOrderOption()) && (item.getLinkToOrderOption().equals(OLEConstants.NB_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.EB_PRINT))) {
252                                                oleCopy.setCopyNumber(item.getSingleCopyNumber() != null && !item.getSingleCopyNumber().isEmpty() ? item.getSingleCopyNumber() : null);
253                                            }
254                                            oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.NOT_RECEIVED_STATUS);
255                                            oleCopy.setReqDocNum(olePurchaseOrderDocument.getPurapDocumentIdentifier());
256                                            oleCopy.setReqItemId(item.getItemIdentifier());
257                                            oleCopy.setPoDocNum(olePurchaseOrderDocument.getDocumentNumber());
258                                            oleCopy.setPoItemId(olePurchaseOrderItem.getItemIdentifier());
259                                            oleCopy.setEnumeration(enumString + " " + copyNumber);
260                                            oleCopy.setCopyNumber(copyNumber + "");
261                                            oleCopy.setPartNumber(partNumber + "");
262                                            oleCopies.add(oleCopy);
263                                            if (copyNumber == copyNumberMax) {
264                                                copyNumber = 0;
265                                                partNumber++;
266                                            }
267
268                                        }
269                                        Map map = new HashMap();
270                                        map.put("purchaseOrderItemLineId", olePurchaseOrderDocument.getPurapDocumentIdentifier());
271                                        List<ItemRecord> itemRecords = (List<ItemRecord>) KRADServiceLocator.getBusinessObjectService().findMatching(ItemRecord.class, map);
272                                        if (CollectionUtils.isNotEmpty(itemRecords)) {
273                                            if (itemRecords.size() == oleCopies.size()) {
274                                                int index = 0;
275                                                for (OleCopy oleCopy : oleCopies) {
276                                                    oleCopy.setItemUUID(DocumentUniqueIDPrefix.PREFIX_WORK_ITEM_OLEML + "-" + itemRecords.get(index).getItemId());
277                                                    oleCopy.setInstanceId(DocumentUniqueIDPrefix.PREFIX_WORK_HOLDINGS_OLEML + "-" + itemRecords.get(index).getHoldingsId());
278                                                    index++;
279                                                }
280                                                saveOleCopies(oleCopies, buffer);
281                                            } else {
282                                                LOG.error("In Purchase order different purchase orderItem shouldn't use same bib id ");
283                                                buffer.append("In Purchase order different purchase orderItem shouldn't use same bib id ");
284                                                buffer.append("\n");
285                                            }
286                                        }
287
288                                    }
289                                }
290                            } catch (Exception e) {
291                                LOG.error(e);
292                                buffer.append("Error occurred while prepareAndSaveOleCopy " + e.getMessage());
293                                buffer.append("\n");
294                            }
295                        }
296                    } catch (Exception e) {
297                        if (LOG.isInfoEnabled()) {
298                            LOG.info("###########Exception while preparing  copy record  for save###########");
299                        }
300                        LOG.error(e);
301                        buffer.append("###########Exception while preparing  copy record  for save###########");
302                        buffer.append("\n");
303                        buffer.append(e.getStackTrace());
304                        buffer.append("\n");
305                    }
306                }
307            }
308        }
309
310
311    }
312
313    public void writeStatusToFile(String directoryPath, String fileName, String content) {
314        try {
315            String fileSeparator = File.separator;
316            Date date = new Date();
317            File file = new File(directory);
318            if (file.exists() && file.isDirectory()) {
319                file = new File(directory + File.separator + fileName);
320                file.createNewFile();
321
322            } else {
323                file.mkdir();
324                File newFile = file = new File(directory + File.separator + fileName);
325                if (!newFile.isDirectory() && !newFile.exists()) {
326                    newFile.createNewFile();
327                }
328            }
329            FileWriter fw = new FileWriter(directoryPath + fileSeparator + fileName, true);
330            fw.write("\n");
331            fw.write("*************************************************************************");
332            fw.write("\n");
333            fw.write("<!-----------------   " + date.toString() + "  ------------------!>");
334            fw.write("\n");
335            fw.write(content);
336            fw.write("\n");
337            fw.write("*************************************************************************");
338            fw.write("\n");
339            fw.close();
340        } catch (IOException ioe) {
341            System.err.println("IOException: " + ioe.getMessage());
342        }
343    }
344
345}