Search in sources :

Example 1 with ReceiptProcessing

use of edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing in project cu-kfs by CU-CommunityApps.

the class ReceiptProcessingServiceImpl method attachFiles.

/**
 */
public boolean attachFiles(String fileName, BatchInputFileType batchInputFileType, String customerName) {
    boolean result = true;
    // load up the file into a byte array
    byte[] fileByteContent = safelyLoadFileBytes(fileName);
    LOG.info("Attempting to parse the file");
    Object parsedObject = null;
    try {
        parsedObject = batchInputFileService.parse(batchInputFileType, fileByteContent);
    } catch (ParseException e) {
        String errorMessage = "Error parsing batch file: " + e.getMessage();
        LOG.error(errorMessage, e);
        throw new RuntimeException(errorMessage);
    }
    // make sure we got the type we expected, then cast it
    if (!(parsedObject instanceof List)) {
        String errorMessage = "Parsed file was not of the expected type.  Expected [" + List.class + "] but got [" + parsedObject.getClass() + "].";
        criticalError(errorMessage);
    }
    List<ReceiptProcessing> receipts = ((List<ReceiptProcessing>) parsedObject);
    final String attachmentsPath = pdfDirectory;
    String mimeTypeCode = "pdf";
    // determine in which mode we are: match& attach, match, attach
    // if first 5 fields ate not blank then it is a match and attach
    boolean matchAndAttach = false;
    // if any receipt get the first one
    if (ObjectUtils.isNotNull(receipts) && receipts.size() > 0) {
        ReceiptProcessing receipt = receipts.get(0);
        // match and attach only occurs for CALS; for CALS files the source unique ID is blank
        matchAndAttach = StringUtils.isBlank(receipt.getSourceUniqueID());
    }
    if (matchAndAttach) {
        matchAndAttach(receipts, attachmentsPath, mimeTypeCode);
    } else {
        matchOrAttachOnly(fileName, batchInputFileType, receipts, attachmentsPath, mimeTypeCode);
    }
    return result;
}
Also used : ReceiptProcessing(edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing) ArrayList(java.util.ArrayList) List(java.util.List) ParseException(org.kuali.kfs.sys.exception.ParseException)

Example 2 with ReceiptProcessing

use of edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing in project cu-kfs by CU-CommunityApps.

the class ReceiptProcessingServiceImpl method matchAndAttach.

/**
 * Performs match and attach. It will search for a match PCDO document and attempt to attach the receipt.
 *
 * @param receipts
 * @param attachmentsPath
 * @param mimeTypeCode
 */
protected void matchAndAttach(List<ReceiptProcessing> receipts, String attachmentsPath, String mimeTypeCode) {
    StringBuilder processResults = new StringBuilder();
    processResults.append(RESULT_FILE_HEADER_LINE);
    for (ReceiptProcessing receipt : receipts) {
        Note note = new Note();
        java.util.Date pdate = null;
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        try {
            pdate = (java.util.Date) df.parse(receipt.getPurchasedate());
        } catch (ParseException e) {
            processResults.append(receipt.badData(false));
            LOG.error("Bad date field on incoming csv");
            continue;
        } catch (java.text.ParseException e) {
            processResults.append(receipt.badData(false));
            LOG.error("Bad date field on incoming csv");
            continue;
        }
        Date pdateSQL = null;
        if (pdate != null) {
            pdateSQL = new Date(pdate.getTime());
        }
        List<ProcurementCardDocument> pcdoList = procurementCardDocumentDao.getDocumentByCarhdHolderAmountDateVendor(receipt.getCardHolder(), receipt.getAmount(), pdateSQL);
        ProcurementCardDocument pcdo = null;
        if (ObjectUtils.isNull(pcdoList) || pcdoList.isEmpty()) {
            processResults.append(receipt.noMatch(false));
            continue;
        }
        if (pcdoList.size() > 1) {
            processResults.append(receipt.multipleMatch(false));
            continue;
        }
        if (pcdoList.size() == 1) {
            pcdo = pcdoList.get(0);
        }
        String pdfFileName = attachmentsPath + "/" + receipt.getFilename();
        LOG.info("Start creating note and attaching pdf file " + pdfFileName + " to PCDO document #" + pcdo.getDocumentNumber());
        File f = null;
        FileInputStream fileInputStream = null;
        try {
            f = new File(pdfFileName);
            fileInputStream = new FileInputStream(pdfFileName);
        } catch (FileNotFoundException e) {
            LOG.error("File " + pdfFileName + " not found for Document " + pcdo.getDocumentNumber());
            processResults.append(receipt.badData(false));
            continue;
        } catch (IOException e) {
            LOG.error("generic Io exception for Document " + pcdo.getDocumentNumber());
            processResults.append(receipt.badData(false));
            continue;
        }
        long fileSizeLong = f.length();
        Integer fileSize = Integer.parseInt(Long.toString(fileSizeLong));
        String attachType = "";
        Attachment noteAttachment = null;
        try {
            noteAttachment = attachmentService.createAttachment(pcdo.getDocumentHeader(), pdfFileName, mimeTypeCode, fileSize, fileInputStream, attachType);
        } catch (IOException e) {
            LOG.error("Failed to attach file for Document " + pcdo.getDocumentNumber());
            processResults.append(receipt.noMatch(false));
            e.printStackTrace();
            continue;
        } catch (IllegalArgumentException e) {
            /*
			     * Our custom attachment service will throw an IllegalArgumentException if the virus scan fails.
			     * The virus scan could also end up failing if the file size is too large. In such cases,
			     * return an error code indicating such a problem (or a problem with invalid parameters).
			     */
            LOG.error("Failed to create attachment for Document " + pcdo.getDocumentNumber(), e);
            processResults.append(receipt.attachmentCreationError(false));
            continue;
        }
        if (noteAttachment != null) {
            note.setNoteText("Receipt Attached");
            note.addAttachment(noteAttachment);
            note.setRemoteObjectIdentifier(pcdo.getDocumentHeader().getObjectId());
            note.setAuthorUniversalIdentifier(getSystemUser().getPrincipalId());
            note.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
            note.setNotePostedTimestampToCurrent();
            try {
                noteService.save(note);
            } catch (Exception e) {
                LOG.error("Failed to save note for Document " + pcdo.getDocumentNumber());
                processResults.append(receipt.noMatch(false));
                e.printStackTrace();
                continue;
            }
            LOG.info("Attached pdf " + pdfFileName + " for document " + pcdo.getDocumentNumber());
            processResults.append(receipt.match(pcdo.getDocumentNumber(), false));
        }
    }
    String outputCsv = processResults.toString();
    // this is CALS output folder and it has to stay unchanged
    String reportDropFolder = pdfDirectory + "/CIT-csv-archive/";
    getcsvWriter(outputCsv, reportDropFolder);
}
Also used : ReceiptProcessing(edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing) FileNotFoundException(java.io.FileNotFoundException) Attachment(org.kuali.kfs.krad.bo.Attachment) IOException(java.io.IOException) Date(java.sql.Date) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.kuali.kfs.sys.exception.ParseException) ProcurementCardDocument(org.kuali.kfs.fp.document.ProcurementCardDocument) Note(org.kuali.kfs.krad.bo.Note) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ParseException(org.kuali.kfs.sys.exception.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 3 with ReceiptProcessing

use of edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing in project cu-kfs by CU-CommunityApps.

the class ReceiptProcessingServiceImpl method matchOrAttachOnly.

/**
 * Performs match or attach on each incoming record. The method determines
 * for each incoming record if a match only or attach only should be
 * performed. If first card holder, amount and purchase date are not blank
 * then a match only is performed. If the source unique id and edoc number
 * are not blank then an attach only is performed.
 *
 * @param fileName
 * @param receipts
 * @param attachmentsPath
 * @param mimeTypeCode
 */
protected void matchOrAttachOnly(String fileName, BatchInputFileType batchInputFileType, List<ReceiptProcessing> receipts, String attachmentsPath, String mimeTypeCode) {
    StringBuilder processResults = new StringBuilder();
    processResults.append(RESULT_FILE_HEADER_LINE_WITH_EXTRA_FIELDS);
    String customerName = getCustomerNameFromFileName(fileName, batchInputFileType);
    for (ReceiptProcessing receipt : receipts) {
        boolean matchOnly = StringUtils.isNotBlank(receipt.getCardHolder()) && StringUtils.isNotBlank(receipt.getAmount()) && StringUtils.isNotBlank(receipt.getPurchasedate()) && StringUtils.isBlank(receipt.getFilePath()) && StringUtils.isBlank(receipt.getFilename());
        boolean attachOnly = StringUtils.isNotBlank(receipt.getSourceUniqueID()) && StringUtils.isNotBlank(receipt.getFilePath()) && StringUtils.isNotBlank(receipt.getFilename());
        if (matchOnly) {
            java.util.Date pdate = null;
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            try {
                pdate = (java.util.Date) df.parse(receipt.getPurchasedate());
            } catch (ParseException e) {
                processResults.append(receipt.badData(true));
                LOG.error("Bad date field on incoming csv");
                continue;
            } catch (java.text.ParseException e) {
                processResults.append(receipt.badData(true));
                LOG.error("Bad date field on incoming csv");
                continue;
            }
            Date pdateSQL = null;
            if (pdate != null) {
                pdateSQL = new Date(pdate.getTime());
            }
            List<ProcurementCardDocument> pcdoList = procurementCardDocumentDao.getDocumentByCarhdHolderNameAmountDateCardHolderNetID(receipt.getAmount(), pdateSQL, receipt.getCardHolderNetID());
            ProcurementCardDocument pcdo = null;
            if (ObjectUtils.isNull(pcdoList) || pcdoList.isEmpty()) {
                processResults.append(receipt.noMatch(true));
                continue;
            }
            if (pcdoList.size() > 1) {
                processResults.append(receipt.multipleMatch(true));
                continue;
            }
            if (pcdoList.size() == 1) {
                pcdo = pcdoList.get(0);
                String eDocNumber = pcdo.getDocumentNumber();
                receipt.seteDocNumber(eDocNumber);
                processResults.append(receipt.match(eDocNumber, true));
            }
        }
        if (attachOnly) {
            Note note = new Note();
            List<ProcurementCardDocument> pcdoList = procurementCardDocumentDao.getDocumentByEdocNumber(receipt.geteDocNumber());
            ProcurementCardDocument pcdo = null;
            if (ObjectUtils.isNull(pcdoList) || pcdoList.isEmpty()) {
                processResults.append(receipt.attachOnlyError());
                continue;
            }
            if (pcdoList.size() > 1) {
                processResults.append(receipt.attachOnlyError());
                continue;
            }
            if (pcdoList.size() == 1) {
                pcdo = pcdoList.get(0);
            }
            if (StringUtils.isNotBlank(customerName)) {
                attachmentsPath = pdfDirectory + "/" + StringUtils.upperCase(customerName) + CUSTOMER_PDF_SUBFOLDER_SUFFIX;
            }
            String pdfFileName = attachmentsPath + "/" + receipt.getFilename();
            LOG.info("Start creating note and attaching pdf file " + pdfFileName + " to PCDO document #" + pcdo.getDocumentNumber());
            File f = null;
            FileInputStream fileInputStream = null;
            try {
                f = new File(pdfFileName);
                fileInputStream = new FileInputStream(pdfFileName);
            } catch (FileNotFoundException e) {
                LOG.error("File " + pdfFileName + " not found for Document " + pcdo.getDocumentNumber());
                processResults.append(receipt.attachOnlyError());
                continue;
            } catch (IOException e) {
                LOG.error("generic Io exception for Document " + pcdo.getDocumentNumber());
                processResults.append(receipt.attachOnlyError());
                continue;
            }
            long fileSizeLong = f.length();
            Integer fileSize = Integer.parseInt(Long.toString(fileSizeLong));
            String attachType = "";
            Attachment noteAttachment = null;
            try {
                noteAttachment = attachmentService.createAttachment(pcdo.getDocumentHeader(), pdfFileName, mimeTypeCode, fileSize, fileInputStream, attachType);
            } catch (IOException e) {
                LOG.error("Failed to attach file for Document " + pcdo.getDocumentNumber());
                processResults.append(receipt.attachOnlyError());
                e.printStackTrace();
                continue;
            } catch (IllegalArgumentException e) {
                /*
				     * Our custom attachment service will throw an IllegalArgumentException if the virus scan fails.
				     * The virus scan could also end up failing if the file size is too large. In such cases,
				     * return an error code indicating such a problem (or a problem with invalid parameters).
				     */
                LOG.error("Failed to create attachment for Document " + pcdo.getDocumentNumber(), e);
                processResults.append(receipt.attachmentCreationError(true));
                continue;
            }
            if (noteAttachment != null) {
                note.setNoteText("Receipt Attached");
                note.addAttachment(noteAttachment);
                note.setRemoteObjectIdentifier(pcdo.getDocumentHeader().getObjectId());
                note.setAuthorUniversalIdentifier(getSystemUser().getPrincipalId());
                note.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode());
                note.setNotePostedTimestampToCurrent();
                try {
                    noteService.save(note);
                } catch (Exception e) {
                    LOG.error("Failed to save note for Document " + pcdo.getDocumentNumber());
                    processResults.append(receipt.attachOnlyError());
                    e.printStackTrace();
                    continue;
                }
                LOG.info("Attached pdf " + pdfFileName + " for document " + pcdo.getDocumentNumber());
                processResults.append(receipt.match("8", true));
            }
        }
        if (!matchOnly && !attachOnly) {
            LOG.info("Invalid input data does not meet either match only nor attach only conditions: " + receipt.returnBoLine(true));
        }
    }
    String outputCsv = processResults.toString();
    // each customer will have a separate output folder for easier processing of the results files
    String reportDropFolder = pdfDirectory + "/CIT-" + customerName + "-csv-archive/";
    try {
        /**
         * Create, if not there
         */
        FileUtils.forceMkdir(new File(reportDropFolder));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    getcsvWriter(outputCsv, reportDropFolder);
}
Also used : FileNotFoundException(java.io.FileNotFoundException) Attachment(org.kuali.kfs.krad.bo.Attachment) ProcurementCardDocument(org.kuali.kfs.fp.document.ProcurementCardDocument) ReceiptProcessing(edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing) IOException(java.io.IOException) Date(java.sql.Date) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.kuali.kfs.sys.exception.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) Note(org.kuali.kfs.krad.bo.Note) ParseException(org.kuali.kfs.sys.exception.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 4 with ReceiptProcessing

use of edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing in project cu-kfs by CU-CommunityApps.

the class ReceiptProcessingCSVBuilder method buildReceiptsFromDataMap.

/**
 * build the ReceiptProcessing BO from the data row
 *
 * @param rowDataMap
 * @return
 */
private static ReceiptProcessing buildReceiptsFromDataMap(Map<String, String> rowDataMap) {
    ReceiptProcessing receipt = new ReceiptProcessing();
    receipt.setCardHolder(rowDataMap.get(ReceiptProcessingCSV.cardHolder.name()));
    receipt.setAmount(rowDataMap.get(ReceiptProcessingCSV.amount.name()));
    receipt.setPurchasedate(rowDataMap.get(ReceiptProcessingCSV.purchasedate.name()));
    receipt.setFilePath(rowDataMap.get(ReceiptProcessingCSV.filepath.name()));
    receipt.setFilename(rowDataMap.get(ReceiptProcessingCSV.filename.name()));
    receipt.setCardHolderNetID(rowDataMap.get(ReceiptProcessingCSV.cardHolderNetID.name()));
    receipt.setSourceUniqueID(rowDataMap.get(ReceiptProcessingCSV.sourceUniqueID.name()));
    receipt.seteDocNumber(rowDataMap.get(ReceiptProcessingCSV.eDocNumber.name()));
    return receipt;
}
Also used : ReceiptProcessing(edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing)

Example 5 with ReceiptProcessing

use of edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing in project cu-kfs by CU-CommunityApps.

the class ReceiptProcessingCSVBuilder method buildReceiptProcessing.

/**
 * Convert the parseData object into ReceiptProcessing BO
 *
 * @param parseDataList
 * @return
 */
public static List<ReceiptProcessing> buildReceiptProcessing(List<Map<String, String>> parseDataList) {
    List<ReceiptProcessing> receipts = new ArrayList<ReceiptProcessing>();
    ReceiptProcessing receipt = null, dataReceipt;
    for (Map<String, String> rowDataMap : parseDataList) {
        dataReceipt = buildReceiptsFromDataMap(rowDataMap);
        receipt = dataReceipt;
        receipts.add(receipt);
    }
    return receipts;
}
Also used : ReceiptProcessing(edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing) ArrayList(java.util.ArrayList)

Aggregations

ReceiptProcessing (edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing)5 ParseException (org.kuali.kfs.sys.exception.ParseException)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 Date (java.sql.Date)2 DateFormat (java.text.DateFormat)2 SimpleDateFormat (java.text.SimpleDateFormat)2 ArrayList (java.util.ArrayList)2 ProcurementCardDocument (org.kuali.kfs.fp.document.ProcurementCardDocument)2 Attachment (org.kuali.kfs.krad.bo.Attachment)2 Note (org.kuali.kfs.krad.bo.Note)2 List (java.util.List)1