Search in sources :

Example 1 with PurError

use of org.kuali.kfs.module.purap.exception.PurError in project cu-kfs by CU-CommunityApps.

the class PaymentRequestItem method getPurchaseOrderItem.

/**
 * Retrieves a purchase order item by inspecting the item type to see if its above the line or below the line and returns the
 * appropriate type.
 *
 * @return - purchase order item
 */
@Override
public PurchaseOrderItem getPurchaseOrderItem() {
    if (ObjectUtils.isNotNull(this.getPurapDocumentIdentifier())) {
        if (ObjectUtils.isNull(this.getPaymentRequest())) {
            this.refreshReferenceObject(PurapPropertyConstants.PURAP_DOC);
        }
    }
    // update though)
    if (getPaymentRequest() != null) {
        PurchaseOrderDocument po = getPaymentRequest().getPurchaseOrderDocument();
        PurchaseOrderItem poi = null;
        if (this.getItemType().isLineItemIndicator()) {
            List items = po.getItems();
            if (items != null) {
                for (Object object : items) {
                    PurchaseOrderItem item = (PurchaseOrderItem) object;
                    if (item != null && item.getItemLineNumber().equals(this.getItemLineNumber())) {
                        poi = item;
                        break;
                    }
                }
            }
        } else {
            poi = (PurchaseOrderItem) SpringContext.getBean(PurapService.class).getBelowTheLineByType(po, this.getItemType());
        }
        if (poi != null) {
            return poi;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("getPurchaseOrderItem() Returning null because PurchaseOrderItem object for line number" + getItemLineNumber() + "or itemType " + getItemTypeCode() + " is null");
            }
            return null;
        }
    } else {
        LOG.error("getPurchaseOrderItem() Returning null because paymentRequest object is null");
        throw new PurError("Payment Request Object in Purchase Order item line number " + getItemLineNumber() + "or itemType " + getItemTypeCode() + " is null");
    }
}
Also used : PurapService(org.kuali.kfs.module.purap.document.service.PurapService) PurchaseOrderDocument(org.kuali.kfs.module.purap.document.PurchaseOrderDocument) ArrayList(java.util.ArrayList) List(java.util.List) PurError(org.kuali.kfs.module.purap.exception.PurError)

Example 2 with PurError

use of org.kuali.kfs.module.purap.exception.PurError 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 PurError

use of org.kuali.kfs.module.purap.exception.PurError in project cu-kfs by CU-CommunityApps.

the class CuElectronicInvoiceHelperServiceImpl method loadElectronicInvoices.

public ElectronicInvoiceLoad loadElectronicInvoices() {
    LOG.debug("loadElectronicInvoices() started");
    // add a step to check for directory paths
    prepareDirectories(getRequiredDirectoryNames());
    String rejectDirName = getRejectDirName();
    String acceptDirName = getAcceptDirName();
    String extractFailureDirName = getExtractFailureDirName();
    emailTextErrorList = new StringBuffer();
    int failedCnt = 0;
    LOG.info("Invoice Base Directory - " + electronicInvoiceInputFileType.getDirectoryPath());
    LOG.info("Invoice Accept Directory - " + acceptDirName);
    LOG.info("Invoice Reject Directory - " + rejectDirName);
    if (StringUtils.isBlank(rejectDirName)) {
        throw new RuntimeException("Reject directory name should not be empty");
    }
    if (StringUtils.isBlank(acceptDirName)) {
        throw new RuntimeException("Accept directory name should not be empty");
    }
    if (StringUtils.isBlank(extractFailureDirName)) {
        throw new RuntimeException("ExtractFailure directory name should not be empty");
    }
    File[] filesToBeProcessed = getFilesToBeProcessed();
    ElectronicInvoiceLoad eInvoiceLoad = new ElectronicInvoiceLoad();
    if (filesToBeProcessed == null || filesToBeProcessed.length == 0) {
        StringBuffer mailText = new StringBuffer();
        mailText.append("\n\n");
        mailText.append(PurapConstants.ElectronicInvoice.NO_FILES_PROCESSED_EMAIL_MESSAGE);
        mailText.append("\n\n");
        sendSummary(mailText);
        return eInvoiceLoad;
    }
    try {
        FileUtils.forceMkdir(new File(acceptDirName));
        FileUtils.forceMkdir(new File(rejectDirName));
        FileUtils.forceMkdir(new File(extractFailureDirName));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    LOG.info(filesToBeProcessed.length + " file(s) available for processing");
    StringBuilder emailMsg = new StringBuilder();
    for (File xmlFile : filesToBeProcessed) {
        LOG.info("Processing " + xmlFile.getName() + "....");
        byte[] modifiedXML = addNamespaceDefinition(eInvoiceLoad, xmlFile);
        try {
            processElectronicInvoice(eInvoiceLoad, xmlFile, modifiedXML);
        } catch (Exception e) {
            String msg = xmlFile.getName() + "\n";
            LOG.error(msg);
            // since getMessage() is empty we'll compose the stack trace and nicely format it.
            StackTraceElement[] elements = e.getStackTrace();
            StringBuffer trace = new StringBuffer();
            trace.append(e.getClass().getName());
            if (e.getMessage() != null) {
                trace.append(": ");
                trace.append(e.getMessage());
            }
            trace.append("\n");
            for (int j = 0; j < elements.length; ++j) {
                StackTraceElement element = elements[j];
                trace.append("    at ");
                trace.append(describeStackTraceElement(element));
                trace.append("\n");
            }
            LOG.error(trace);
            // KFSUPGRADE-480, KFSUPGRADE-484 : Cu channged email message, the failCnt and emailMsg are not referenced
            // in CU's email.  So, this is not critical.  But may be good to see these logs.
            emailMsg.append(msg);
            msg += "\n--------------------------------------------------------------------------------------\n" + trace;
            logProcessElectronicInvoiceError(msg);
            failedCnt++;
            // one of the scenario is that save EIRT failed vecause of validation failed.  So, no EIRT will
            // be created.
            boolean moveFiles = BooleanUtils.toBoolean(parameterService.getParameterValueAsString(ElectronicInvoiceStep.class, PurapParameterConstants.ElectronicInvoiceParameters.FILE_MOVE_AFTER_LOAD_IND));
            if (moveFiles) {
                if (LOG.isInfoEnabled()) {
                    LOG.info(xmlFile.getName() + " has caused by saving EIRT failure.");
                }
                boolean success = this.moveFile(xmlFile, getExtractFailureDirName());
                if (!success) {
                    String errorMessage = "File with name '" + xmlFile.getName() + "' could not be moved";
                    throw new PurError(errorMessage);
                }
                updateSummaryCounts(EXTRACT_FAILURES);
            }
            /**
             * Clear the error map, so that subsequent EIRT routing isn't prevented since rice
             * is throwing a ValidationException if the error map is not empty before routing the doc.
             */
            GlobalVariables.getMessageMap().clearErrorMessages();
        // Do not execute rest of code below
        // continue;
        }
    }
    StringBuffer finalText = buildLoadSummary(eInvoiceLoad);
    sendSummary(finalText);
    // Need to clear the counts after each run, so the totals don't show cumulative counts with each subsequent run.
    clearLoadCounts();
    LOG.info("Processing completed");
    return eInvoiceLoad;
}
Also used : ElectronicInvoiceLoad(org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceLoad) 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) PurError(org.kuali.kfs.module.purap.exception.PurError) File(java.io.File)

Aggregations

PurError (org.kuali.kfs.module.purap.exception.PurError)3 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 RemoteException (java.rmi.RemoteException)2 ValidationException (org.kuali.kfs.krad.exception.ValidationException)2 PurchaseOrderDocument (org.kuali.kfs.module.purap.document.PurchaseOrderDocument)2 CxmlParseException (org.kuali.kfs.module.purap.exception.CxmlParseException)2 WorkflowException (org.kuali.rice.kew.api.exception.WorkflowException)2 CuElectronicInvoiceRejectDocument (edu.cornell.kfs.module.purap.document.CuElectronicInvoiceRejectDocument)1 CuPaymentRequestDocument (edu.cornell.kfs.module.purap.document.CuPaymentRequestDocument)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 BusinessObjectService (org.kuali.kfs.krad.service.BusinessObjectService)1 ElectronicInvoiceStep (org.kuali.kfs.module.purap.batch.ElectronicInvoiceStep)1 ElectronicInvoice (org.kuali.kfs.module.purap.businessobject.ElectronicInvoice)1 ElectronicInvoiceItem (org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItem)1 ElectronicInvoiceItemMapping (org.kuali.kfs.module.purap.businessobject.ElectronicInvoiceItemMapping)1