Search in sources :

Example 1 with ElectronicInvoiceLoadSummary

use of org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary in project cu-kfs by CU-CommunityApps.

the class CuElectronicInvoiceHelperServiceImpl method saveLoadSummary.

protected StringBuffer saveLoadSummary(ElectronicInvoiceLoad eInvoiceLoad) {
    NumberFormat twoDecForm = DecimalFormat.getCurrencyInstance();
    Map<String, ElectronicInvoiceLoadSummary> savedLoadSummariesMap = new HashMap<String, ElectronicInvoiceLoadSummary>();
    StringBuffer summaryMessage = new StringBuffer();
    for (Iterator iter = eInvoiceLoad.getInvoiceLoadSummaries().keySet().iterator(); iter.hasNext(); ) {
        String dunsNumber = (String) iter.next();
        ElectronicInvoiceLoadSummary eInvoiceLoadSummary = (ElectronicInvoiceLoadSummary) eInvoiceLoad.getInvoiceLoadSummaries().get(dunsNumber);
        if (!eInvoiceLoadSummary.isEmpty().booleanValue()) {
            LOG.info("Saving Load Summary for DUNS '" + dunsNumber + "'");
            ElectronicInvoiceLoadSummary currentLoadSummary = saveElectronicInvoiceLoadSummary(eInvoiceLoadSummary);
            summaryMessage.append("DUNS Number - ").append(eInvoiceLoadSummary.getVendorDescriptor()).append(":\n");
            summaryMessage.append("     ").append(eInvoiceLoadSummary.getInvoiceLoadSuccessCount());
            summaryMessage.append(" successfully processed invoices for a total of ");
            summaryMessage.append(twoDecForm.format(eInvoiceLoadSummary.getInvoiceLoadSuccessAmount().doubleValue()));
            summaryMessage.append("\n");
            summaryMessage.append("     ").append(eInvoiceLoadSummary.getInvoiceLoadFailCount());
            summaryMessage.append(" rejected invoices for an approximate total of ");
            summaryMessage.append(twoDecForm.format(eInvoiceLoadSummary.getInvoiceLoadFailAmount().doubleValue()));
            summaryMessage.append("\n");
            summaryMessage.append("\n\n");
            savedLoadSummariesMap.put(currentLoadSummary.getVendorDunsNumber(), eInvoiceLoadSummary);
        } else {
            LOG.info("Not saving Load Summary for DUNS '" + dunsNumber + "' because empty indicator is '" + eInvoiceLoadSummary.isEmpty().booleanValue() + "'");
        }
    }
    summaryMessage.append("\n\n");
    for (Iterator rejectIter = eInvoiceLoad.getRejectDocuments().iterator(); rejectIter.hasNext(); ) {
        ElectronicInvoiceRejectDocument rejectDoc = (ElectronicInvoiceRejectDocument) rejectIter.next();
        saveRejectDocument(rejectDoc, savedLoadSummariesMap);
    }
    return summaryMessage;
}
Also used : ElectronicInvoiceLoadSummary(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary) HashMap(java.util.HashMap) ElectronicInvoiceRejectDocument(org.kuali.kfs.module.purap.document.ElectronicInvoiceRejectDocument) CuElectronicInvoiceRejectDocument(edu.cornell.kfs.module.purap.document.CuElectronicInvoiceRejectDocument) Iterator(java.util.Iterator) NumberFormat(java.text.NumberFormat)

Example 2 with ElectronicInvoiceLoadSummary

use of org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary in project cu-kfs by CU-CommunityApps.

the class CuElectronicInvoiceHelperServiceImpl method processElectronicInvoice.

// end KFSUPGRADE_483
// KFSUPGRADE-480/KFSUPGRADE-484
@Transactional
protected boolean processElectronicInvoice(ElectronicInvoiceLoad eInvoiceLoad, File invoiceFile, byte[] xmlAsBytes) {
    // Checks parameter to see if files should be moved to the accept/reject folders after load
    boolean moveFiles = BooleanUtils.toBoolean(parameterService.getParameterValueAsString(ElectronicInvoiceStep.class, PurapParameterConstants.ElectronicInvoiceParameters.FILE_MOVE_AFTER_LOAD_IND));
    ElectronicInvoice eInvoice = null;
    boolean isExtractFailure = false;
    boolean isCompleteFailure = false;
    try {
        eInvoice = loadElectronicInvoice(xmlAsBytes);
    } catch (CxmlParseException e) {
        LOG.info("Error loading file - " + e.getMessage());
        rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, e.getMessage(), PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
        isExtractFailure = true;
        updateSummaryCounts(EXTRACT_FAILURES);
    } catch (IllegalArgumentException iae) {
        LOG.info("Error loading file - " + iae.getMessage());
        // rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, iae.getMessage(), PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
        isExtractFailure = true;
        updateSummaryCounts(EXTRACT_FAILURES);
    }
    if (!isExtractFailure) {
        if (ObjectUtils.isNotNull(eInvoice)) {
            eInvoice.setFileName(invoiceFile.getName());
        }
        isCompleteFailure = checkForCompleteFailure(eInvoiceLoad, eInvoice, invoiceFile);
        if (!isCompleteFailure) {
            setVendorDUNSNumber(eInvoice);
            setVendorDetails(eInvoice);
            // CU also refactored getItemTypeMappings with overlay
            Map<String, ElectronicInvoiceItemMapping> itemTypeMappings = getItemTypeMappings(eInvoice.getVendorHeaderID(), eInvoice.getVendorDetailID());
            Map<String, ItemType> kualiItemTypes = getKualiItemTypes();
            if (LOG.isInfoEnabled()) {
                if (itemTypeMappings != null && itemTypeMappings.size() > 0) {
                    LOG.info("Item mappings found");
                }
            }
            boolean validateHeader = true;
            try {
                // ==== CU Customization: Added patterns to test for special characters and/or whitespace. ====
                Pattern specialCharsPattern = Pattern.compile("[^\\p{Graph}\\p{Space}]");
                Pattern specialCharsOrWhitespacePattern = Pattern.compile("[^\\p{Graph}]");
                for (ElectronicInvoiceOrder order : eInvoice.getInvoiceDetailOrders()) {
                    String poID = order.getOrderReferenceOrderID();
                    PurchaseOrderDocument po = null;
                    if (NumberUtils.isDigits(StringUtils.defaultString(poID)) && !isIntegerTooLarge(poID)) {
                        po = purchaseOrderService.getCurrentPurchaseOrder(new Integer(poID));
                        if (po != null) {
                            order.setInvoicePurchaseOrderID(poID);
                            order.setPurchaseOrderID(po.getPurapDocumentIdentifier());
                            order.setPurchaseOrderCampusCode(po.getDeliveryCampusCode());
                            if (LOG.isInfoEnabled()) {
                                LOG.info("PO matching Document found");
                            }
                        }
                    }
                    // ==== CU Customization: Remove special characters from certain ID and description fields. ====
                    Matcher tempMatcher;
                    if (StringUtils.isNotEmpty(order.getOrderReferenceDocumentRefPayloadID())) {
                        tempMatcher = specialCharsOrWhitespacePattern.matcher(order.getOrderReferenceDocumentRefPayloadID());
                        if (tempMatcher.find()) {
                            LOG.warn("Found document ref payload ID with special or whitespace characters; these will be removed. Order: " + order.getOrderReferenceOrderID());
                            order.setOrderReferenceDocumentRefPayloadID(tempMatcher.replaceAll(KRADConstants.EMPTY_STRING));
                        }
                    }
                    if (StringUtils.isNotEmpty(order.getOrderReferenceOrderID())) {
                        tempMatcher = specialCharsOrWhitespacePattern.matcher(order.getOrderReferenceOrderID());
                        if (tempMatcher.find()) {
                            LOG.warn("Found ref order ID with special or whitespace characters; these will be removed. Order: " + order.getOrderReferenceOrderID());
                            order.setOrderReferenceOrderID(tempMatcher.replaceAll(KRADConstants.EMPTY_STRING));
                        }
                    }
                    for (ElectronicInvoiceItem item : order.getInvoiceItems()) {
                        if (StringUtils.isNotEmpty(item.getReferenceDescription())) {
                            tempMatcher = specialCharsPattern.matcher(item.getReferenceDescription());
                            if (tempMatcher.find()) {
                                LOG.warn("Found item description with special characters; these will be removed. Line number: " + item.getInvoiceLineNumber());
                                item.setReferenceDescription(tempMatcher.replaceAll(KRADConstants.EMPTY_STRING));
                            }
                        }
                    }
                    CuElectronicInvoiceOrderHolder orderHolder = new CuElectronicInvoiceOrderHolder(eInvoice, order, po, itemTypeMappings, kualiItemTypes, validateHeader);
                    matchingService.doMatchingProcess(orderHolder);
                    if (orderHolder.isInvoiceRejected()) {
                        ElectronicInvoiceRejectDocument rejectDocument = createRejectDocument(eInvoice, order, eInvoiceLoad);
                        if (orderHolder.getAccountsPayablePurchasingDocumentLinkIdentifier() != null) {
                            rejectDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(orderHolder.getAccountsPayablePurchasingDocumentLinkIdentifier());
                        }
                        String dunsNumber = StringUtils.isEmpty(eInvoice.getDunsNumber()) ? UNKNOWN_DUNS_IDENTIFIER : eInvoice.getDunsNumber();
                        ElectronicInvoiceLoadSummary loadSummary = getOrCreateLoadSummary(eInvoiceLoad, dunsNumber);
                        loadSummary.addFailedInvoiceOrder(rejectDocument.getTotalAmount(), eInvoice);
                        eInvoiceLoad.insertInvoiceLoadSummary(loadSummary);
                        LOG.info("Saving Load Summary for DUNS '" + dunsNumber + "'");
                        SpringContext.getBean(BusinessObjectService.class).save(loadSummary);
                        updateSummaryCounts(REJECT);
                    } else {
                        PaymentRequestDocument preqDoc = createPaymentRequest(orderHolder);
                        if (orderHolder.isInvoiceRejected()) {
                            /**
                             * This is required. If there is anything in the error map, then it's not possible to route the doc since the rice
                             * is throwing error if errormap is not empty before routing the doc.
                             */
                            GlobalVariables.getMessageMap().clearErrorMessages();
                            ElectronicInvoiceRejectDocument rejectDocument = createRejectDocument(eInvoice, order, eInvoiceLoad);
                            if (orderHolder.getAccountsPayablePurchasingDocumentLinkIdentifier() != null) {
                                rejectDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(orderHolder.getAccountsPayablePurchasingDocumentLinkIdentifier());
                            }
                            ElectronicInvoiceLoadSummary loadSummary = getOrCreateLoadSummary(eInvoiceLoad, eInvoice.getDunsNumber());
                            loadSummary.addFailedInvoiceOrder(rejectDocument.getTotalAmount(), eInvoice);
                            eInvoiceLoad.insertInvoiceLoadSummary(loadSummary);
                            LOG.info("Saving Load Summary for DUNS '" + eInvoice.getDunsNumber() + "'");
                            SpringContext.getBean(BusinessObjectService.class).save(loadSummary);
                            updateSummaryCounts(REJECT);
                        } else {
                            ElectronicInvoiceLoadSummary loadSummary = getOrCreateLoadSummary(eInvoiceLoad, eInvoice.getDunsNumber());
                            loadSummary.addSuccessfulInvoiceOrder(preqDoc.getTotalDollarAmount(), eInvoice);
                            eInvoiceLoad.insertInvoiceLoadSummary(loadSummary);
                            LOG.info("Saving Load Summary for DUNS '" + eInvoice.getDunsNumber() + "'");
                            SpringContext.getBean(BusinessObjectService.class).save(loadSummary);
                            updateSummaryCounts(ACCEPT);
                        }
                    }
                    validateHeader = false;
                }
            } catch (Exception ex) {
                LOG.info("Error parsing file - " + ex.getMessage());
                LOG.info("Exception: " + ex.toString());
                rejectElectronicInvoiceFile(eInvoiceLoad, UNKNOWN_DUNS_IDENTIFIER, invoiceFile, ex.getMessage(), PurapConstants.ElectronicInvoice.FILE_FORMAT_INVALID);
                isExtractFailure = true;
                updateSummaryCounts(EXTRACT_FAILURES);
            }
        }
    }
    // Move files into accept/reject folder as appropriate
    boolean success = true;
    if (moveFiles) {
        if (isExtractFailure) {
            LOG.info(invoiceFile.getName() + " has caused a batch extract failure.");
            success = this.moveFile(invoiceFile, getExtractFailureDirName());
            if (!success) {
                String errorMessage = "File with name '" + invoiceFile.getName() + "' could not be moved";
                throw new PurError(errorMessage);
            }
        } else if (isCompleteFailure || (ObjectUtils.isNotNull(eInvoice) && eInvoice.isFileRejected())) {
            LOG.info(invoiceFile.getName() + " has been rejected.");
            success = this.moveFile(invoiceFile, getRejectDirName());
            if (!success) {
                String errorMessage = "File with name '" + invoiceFile.getName() + "' could not be moved";
                throw new PurError(errorMessage);
            }
        } else {
            LOG.info(invoiceFile.getName() + " has been accepted");
            success = this.moveFile(invoiceFile, getAcceptDirName());
            if (!success) {
                String errorMessage = "File with name '" + invoiceFile.getName() + "' could not be moved";
                throw new PurError(errorMessage);
            }
        }
    } else {
        // Add .processed file to each successfully processed einvoice file if move files is not enabled.
        if (!isExtractFailure) {
            String fullPath = FilenameUtils.getFullPath(invoiceFile.getAbsolutePath());
            String fileName = FilenameUtils.getBaseName(invoiceFile.getAbsolutePath());
            File processedFile = new File(fullPath + File.separator + fileName + ".processed");
            try {
                FileUtils.touch(processedFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    if (ObjectUtils.isNull(eInvoice)) {
        return true;
    }
    return eInvoice.isFileRejected();
}
Also used : Matcher(java.util.regex.Matcher) ItemType(org.kuali.kfs.module.purap.businessobject.ItemType) ElectronicInvoiceItem(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItem) PurchaseOrderDocument(org.kuali.kfs.module.purap.document.PurchaseOrderDocument) Pattern(java.util.regex.Pattern) ElectronicInvoiceStep(org.kuali.kfs.module.purap.batch.ElectronicInvoiceStep) ElectronicInvoiceOrder(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceOrder) ElectronicInvoiceLoadSummary(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary) ElectronicInvoiceItemMapping(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItemMapping) CuPaymentRequestDocument(edu.cornell.kfs.module.purap.document.CuPaymentRequestDocument) PaymentRequestDocument(org.kuali.kfs.module.purap.document.PaymentRequestDocument) IOException(java.io.IOException) ValidationException(org.kuali.kfs.krad.exception.ValidationException) IOException(java.io.IOException) WorkflowException(org.kuali.rice.kew.api.exception.WorkflowException) FileNotFoundException(java.io.FileNotFoundException) RemoteException(java.rmi.RemoteException) CxmlParseException(org.kuali.kfs.module.purap.exception.CxmlParseException) BusinessObjectService(org.kuali.kfs.krad.service.BusinessObjectService) CxmlParseException(org.kuali.kfs.module.purap.exception.CxmlParseException) ElectronicInvoiceRejectDocument(org.kuali.kfs.module.purap.document.ElectronicInvoiceRejectDocument) CuElectronicInvoiceRejectDocument(edu.cornell.kfs.module.purap.document.CuElectronicInvoiceRejectDocument) PurError(org.kuali.kfs.module.purap.exception.PurError) File(java.io.File) ElectronicInvoice(org.kuali.kfs.module.purap.businessobject.ElectronicInvoice) NonTransactional(org.kuali.kfs.sys.service.NonTransactional) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with ElectronicInvoiceLoadSummary

use of org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary in project cu-kfs by CU-CommunityApps.

the class CuElectronicInvoiceHelperServiceImpl method rejectElectronicInvoiceFile.

protected void rejectElectronicInvoiceFile(ElectronicInvoiceLoad eInvoiceLoad, String fileDunsNumber, File invoiceFile, String extraDescription, String rejectReasonTypeCode) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Rejecting the entire invoice file - " + invoiceFile.getName());
    }
    ElectronicInvoiceLoadSummary eInvoiceLoadSummary = getOrCreateLoadSummary(eInvoiceLoad, fileDunsNumber);
    eInvoiceLoadSummary.addFailedInvoiceOrder();
    eInvoiceLoad.insertInvoiceLoadSummary(eInvoiceLoadSummary);
    ElectronicInvoiceRejectDocument eInvoiceRejectDocument = null;
    try {
        eInvoiceRejectDocument = (ElectronicInvoiceRejectDocument) SpringContext.getBean(DocumentService.class).getNewDocument("EIRT");
        eInvoiceRejectDocument.setInvoiceProcessTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
        eInvoiceRejectDocument.setVendorDunsNumber(fileDunsNumber);
        eInvoiceRejectDocument.setDocumentCreationInProgress(true);
        if (invoiceFile != null) {
            eInvoiceRejectDocument.setInvoiceFileName(invoiceFile.getName());
        }
        List<ElectronicInvoiceRejectReason> list = new ArrayList<ElectronicInvoiceRejectReason>(1);
        String message = "Complete failure document has been created for the Invoice with Filename '" + invoiceFile.getName() + "' due to the following error:\n";
        emailTextErrorList.append(message);
        ElectronicInvoiceRejectReason rejectReason = matchingService.createRejectReason(rejectReasonTypeCode, extraDescription, invoiceFile.getName());
        list.add(rejectReason);
        emailTextErrorList.append("    - " + rejectReason.getInvoiceRejectReasonDescription());
        emailTextErrorList.append("\n\n");
        eInvoiceRejectDocument.setInvoiceRejectReasons(list);
        eInvoiceRejectDocument.getDocumentHeader().setDocumentDescription("Complete failure");
        // KFSCNTRB-1369: Need to Save document
        SpringContext.getBean(DocumentService.class).saveDocument(eInvoiceRejectDocument);
        String noteText = "Invoice file";
        // if (invoiceFile.length() > 0) {
        // empty file will casuse attachment creation exception.  Hence, job will be stopped
        attachInvoiceXMLWithRejectDoc(eInvoiceRejectDocument, invoiceFile, noteText);
        // }
        eInvoiceLoad.addInvoiceReject(eInvoiceRejectDocument);
    } catch (WorkflowException e) {
        throw new RuntimeException(e);
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("Complete failure document has been created (DocNo:" + eInvoiceRejectDocument.getDocumentNumber() + ")");
    }
}
Also used : ElectronicInvoiceLoadSummary(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary) ElectronicInvoiceRejectDocument(org.kuali.kfs.module.purap.document.ElectronicInvoiceRejectDocument) CuElectronicInvoiceRejectDocument(edu.cornell.kfs.module.purap.document.CuElectronicInvoiceRejectDocument) WorkflowException(org.kuali.rice.kew.api.exception.WorkflowException) ArrayList(java.util.ArrayList) ElectronicInvoiceRejectReason(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceRejectReason) WorkflowDocumentService(org.kuali.kfs.krad.workflow.service.WorkflowDocumentService) DocumentService(org.kuali.kfs.krad.service.DocumentService) FinancialSystemDocumentService(org.kuali.kfs.sys.document.service.FinancialSystemDocumentService)

Aggregations

CuElectronicInvoiceRejectDocument (edu.cornell.kfs.module.purap.document.CuElectronicInvoiceRejectDocument)3 ElectronicInvoiceLoadSummary (org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoadSummary)3 ElectronicInvoiceRejectDocument (org.kuali.kfs.module.purap.document.ElectronicInvoiceRejectDocument)3 WorkflowException (org.kuali.rice.kew.api.exception.WorkflowException)2 CuPaymentRequestDocument (edu.cornell.kfs.module.purap.document.CuPaymentRequestDocument)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 RemoteException (java.rmi.RemoteException)1 NumberFormat (java.text.NumberFormat)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 ValidationException (org.kuali.kfs.krad.exception.ValidationException)1 BusinessObjectService (org.kuali.kfs.krad.service.BusinessObjectService)1 DocumentService (org.kuali.kfs.krad.service.DocumentService)1 WorkflowDocumentService (org.kuali.kfs.krad.workflow.service.WorkflowDocumentService)1 ElectronicInvoiceStep (org.kuali.kfs.module.purap.batch.ElectronicInvoiceStep)1