Search in sources :

Example 1 with ProcurementCardDocument

use of org.kuali.kfs.fp.document.ProcurementCardDocument in project cu-kfs by CU-CommunityApps.

the class CuCapitalAssetManagementModuleServiceImpl method checkNewCapitalAssetFieldsExist.

protected boolean checkNewCapitalAssetFieldsExist(CapitalAssetInformation capitalAssetInformation, AccountingDocument accountingDocument, int caLineIndex) {
    boolean valid = true;
    if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetTypeCode())) {
        String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE);
        GlobalVariables.getMessageMap().putError(KFSPropertyConstants.CAPITAL_ASSET_TYPE_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
        valid = false;
    }
    if (capitalAssetInformation.getCapitalAssetQuantity() == null || capitalAssetInformation.getCapitalAssetQuantity() <= 0) {
        String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_QUANTITY);
        GlobalVariables.getMessageMap().putError(KFSPropertyConstants.CAPITAL_ASSET_QUANTITY, KFSKeyConstants.ERROR_REQUIRED, label);
        valid = false;
    }
    // VENDOR_IS_REQUIRED_FOR_NON_MOVEABLE_ASSET parameter determines if we need to check
    // vendor name entered.
    String vendorNameRequired = getParameterService().getParameterValueAsString(Asset.class, CamsParameterConstants.CapitalAsset.VENDOR_REQUIRED_FOR_NON_MOVEABLE_ASSET_IND);
    if ("Y".equalsIgnoreCase(vendorNameRequired)) {
        // skip vendor name required validation for procurement card document
        // skip vendor name required validation for FP Docs
        String pid = KEWServiceLocator.getDocumentTypeService().findByDocumentId(accountingDocument.getDocumentNumber()).getDocTypeParentId();
        String docType = KEWServiceLocator.getDocumentTypeService().findById(pid).getName();
        if (!(docType.equals("FP")) && !(accountingDocument instanceof ProcurementCardDocument) && StringUtils.isBlank(capitalAssetInformation.getVendorName())) {
            String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.VENDOR_NAME);
            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.VENDOR_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
            valid = false;
        }
    }
    // MANUFACTURER_IS_REQUIRED_FOR_NON_MOVEABLE_ASSET parameter determines if we need to check
    // vendor name entered.
    String manufacturerNameRequired = getParameterService().getParameterValueAsString(Asset.class, CamsParameterConstants.CapitalAsset.MANUFACTURER_REQUIRED_FOR_NON_MOVEABLE_ASSET_IND);
    if ("Y".equalsIgnoreCase(manufacturerNameRequired)) {
        if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetManufacturerName())) {
            String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME);
            GlobalVariables.getMessageMap().putError(KFSPropertyConstants.CAPITAL_ASSET_MANUFACTURE_NAME, KFSKeyConstants.ERROR_REQUIRED, label);
            valid = false;
        }
    }
    if (StringUtils.isBlank(capitalAssetInformation.getCapitalAssetDescription())) {
        String label = this.getDataDictionaryService().getAttributeLabel(CapitalAssetInformation.class, CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION);
        GlobalVariables.getMessageMap().putError(CamsPropertyConstants.Asset.CAPITAL_ASSET_DESCRIPTION, KFSKeyConstants.ERROR_REQUIRED, label);
        valid = false;
    }
    int index = 0;
    List<CapitalAssetInformationDetail> capitalAssetInformationDetails = capitalAssetInformation.getCapitalAssetInformationDetails();
    for (CapitalAssetInformationDetail dtl : capitalAssetInformationDetails) {
        String errorPathPrefix = KFSPropertyConstants.DOCUMENT + "." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION + "[" + caLineIndex + "]." + KFSPropertyConstants.CAPITAL_ASSET_INFORMATION_DETAILS;
        CapitalAssetInformationDetailExtendedAttribute capDetailExt = (CapitalAssetInformationDetailExtendedAttribute) dtl.getExtension();
        String buildingCd = dtl.getBuildingCode();
        String roomCd = dtl.getBuildingRoomNumber();
        String assetLocationCityName = capDetailExt.getAssetLocationCityName();
        String assetLocationCountryCode = capDetailExt.getAssetLocationCountryCode();
        String assetLocationStateCode = capDetailExt.getAssetLocationStateCode();
        String assetLocationStreetAddress = capDetailExt.getAssetLocationStreetAddress();
        String assetLocationZipCode = capDetailExt.getAssetLocationZipCode();
        // Room is not required for non-moveable
        AssetType assetType = getAssetType(capitalAssetInformation.getCapitalAssetTypeCode());
        if (StringUtils.isBlank(assetLocationCityName) && StringUtils.isBlank(assetLocationStateCode) && StringUtils.isBlank(assetLocationCountryCode) && StringUtils.isBlank(assetLocationStreetAddress) && StringUtils.isBlank(assetLocationZipCode)) {
            // Building code required for moveable assets or assets that require building
            if (ObjectUtils.isNull(assetType) || assetType.isMovingIndicator() || assetType.isRequiredBuildingIndicator()) {
                if (StringUtils.isBlank(dtl.getBuildingCode())) {
                    String label = this.getDataDictionaryService().getAttributeLabel(Building.class, KFSPropertyConstants.BUILDING_CODE);
                    GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_REQUIRED, label);
                    valid = false;
                }
            }
            // Room is not required for non-moveable
            if (ObjectUtils.isNull(assetType) || assetType.isMovingIndicator()) {
                // Room is required for moveable
                if (StringUtils.isBlank(roomCd)) {
                    String label = this.getDataDictionaryService().getAttributeLabel(Room.class, KFSPropertyConstants.BUILDING_ROOM_NUMBER);
                    GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_REQUIRED, label);
                    valid = false;
                }
            }
        }
        if (StringUtils.isNotBlank(assetLocationCityName) || StringUtils.isNotBlank(assetLocationStateCode) || StringUtils.isNotBlank(assetLocationCountryCode) || StringUtils.isNotBlank(assetLocationStreetAddress) || StringUtils.isNotBlank(assetLocationZipCode)) {
            if (StringUtils.isNotBlank(buildingCd)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_CODE, KFSKeyConstants.ERROR_CUSTOM, "Building Code not allowed with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isNotBlank(roomCd)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + KFSPropertyConstants.BUILDING_ROOM_NUMBER, KFSKeyConstants.ERROR_CUSTOM, "Room Number not allowed with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isBlank(assetLocationCityName)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + "extension.assetLocationCityName", KFSKeyConstants.ERROR_CUSTOM, "City Name is required with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isBlank(assetLocationStateCode)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + "extension.assetLocationStateCode", KFSKeyConstants.ERROR_CUSTOM, "State Code is required with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isBlank(assetLocationCountryCode)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + "extension.assetLocationCountryCode", KFSKeyConstants.ERROR_CUSTOM, "Country Code is required with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isBlank(assetLocationStreetAddress)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + "extension.assetLocationStreetAddress", KFSKeyConstants.ERROR_CUSTOM, "Street Address is required with off-campus Asset Location Address");
                valid = false;
            }
            if (StringUtils.isBlank(assetLocationZipCode)) {
                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(errorPathPrefix + "[" + index + "]" + "." + "extension.assetLocationZipCode", KFSKeyConstants.ERROR_CUSTOM, "Zipcode is required with off-campus Asset Location Address");
                valid = false;
            }
        }
        index++;
    }
    return valid;
}
Also used : AssetType(org.kuali.kfs.module.cam.businessobject.AssetType) CapitalAssetInformationDetailExtendedAttribute(edu.cornell.kfs.fp.businessobject.CapitalAssetInformationDetailExtendedAttribute) CapitalAssetInformationDetail(org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail) ProcurementCardDocument(org.kuali.kfs.fp.document.ProcurementCardDocument)

Example 2 with ProcurementCardDocument

use of org.kuali.kfs.fp.document.ProcurementCardDocument in project cu-kfs by CU-CommunityApps.

the class ProcurementCardCreateDocumentServiceImpl method createProcurementCardDocument.

/**
 * Creates a ProcurementCardDocument from the List of transactions given.
 *
 * @param transactions List of ProcurementCardTransaction objects to be used for creating the document.
 * @return A ProcurementCardDocument populated with the transactions provided.
 */
@SuppressWarnings({ "rawtypes", "deprecation" })
@Override
public ProcurementCardDocument createProcurementCardDocument(List transactions) {
    ProcurementCardDocument pcardDocument = null;
    dataDictionaryService = SpringContext.getBean(DataDictionaryService.class);
    try {
        // get new document from doc service
        pcardDocument = buildNewProcurementCardDocument();
        List<CapitalAssetInformation> capitalAssets = pcardDocument.getCapitalAssetInformation();
        for (CapitalAssetInformation capitalAsset : capitalAssets) {
            if (ObjectUtils.isNotNull(capitalAsset) && ObjectUtils.isNotNull(capitalAsset.getCapitalAssetInformationDetails())) {
                capitalAsset.setDocumentNumber(pcardDocument.getDocumentNumber());
            }
        }
        ProcurementCardTransaction trans = (ProcurementCardTransaction) transactions.get(0);
        String errorText = validateTransaction(trans);
        createCardHolderRecord(pcardDocument, trans);
        // for each transaction, create transaction detail object and then acct lines for the detail
        int transactionLineNumber = 1;
        KualiDecimal documentTotalAmount = KualiDecimal.ZERO;
        ProcurementCardTransaction transaction = null;
        for (Iterator iter = transactions.iterator(); iter.hasNext(); ) {
            /*ProcurementCardTransaction*/
            transaction = (ProcurementCardTransaction) iter.next();
            // create transaction detail record with accounting lines
            errorText += createTransactionDetailRecord(pcardDocument, transaction, transactionLineNumber);
            // update document total
            documentTotalAmount = documentTotalAmount.add(transaction.getFinancialDocumentTotalAmount());
            transactionLineNumber++;
        }
        pcardDocument.getFinancialSystemDocumentHeader().setFinancialDocumentTotalAmount(documentTotalAmount);
        // pcardDocument.getDocumentHeader().setDocumentDescription("SYSTEM Generated");
        transaction = (ProcurementCardTransaction) transactions.get(0);
        String cardHolderName = transaction.getCardHolderName();
        String vendorName = transaction.getVendorName();
        String transactionType = ((ProcurementCardTransactionExtendedAttribute) transaction.getExtension()).getTransactionType();
        if (transactionType != null && StringUtils.isNotBlank(transactionType)) {
            VENDOR_NAME_MAX_LENGTH = 16;
        } else {
            VENDOR_NAME_MAX_LENGTH = 19;
        }
        if (cardHolderName.length() > CARD_HOLDER_MAX_LENGTH && vendorName.length() > VENDOR_NAME_MAX_LENGTH) {
            cardHolderName = cardHolderName.substring(0, CARD_HOLDER_MAX_LENGTH);
            vendorName = vendorName.substring(0, VENDOR_NAME_MAX_LENGTH);
        }
        if (cardHolderName.length() > CARD_HOLDER_MAX_LENGTH && vendorName.length() <= VENDOR_NAME_MAX_LENGTH) {
            Integer endIndice = 0;
            if ((CARD_HOLDER_MAX_LENGTH + (VENDOR_NAME_MAX_LENGTH - vendorName.length())) > cardHolderName.length()) {
                endIndice = cardHolderName.length();
            } else {
                endIndice = CARD_HOLDER_MAX_LENGTH + (VENDOR_NAME_MAX_LENGTH - vendorName.length());
            }
            cardHolderName = cardHolderName.substring(0, endIndice);
        }
        if (vendorName.length() > VENDOR_NAME_MAX_LENGTH && cardHolderName.length() <= CARD_HOLDER_MAX_LENGTH) {
            Integer endIndice = 0;
            if ((VENDOR_NAME_MAX_LENGTH + (CARD_HOLDER_MAX_LENGTH - cardHolderName.length())) > vendorName.length()) {
                endIndice = vendorName.length();
            } else {
                endIndice = VENDOR_NAME_MAX_LENGTH + (CARD_HOLDER_MAX_LENGTH - cardHolderName.length());
            }
            vendorName = vendorName.substring(0, endIndice);
        }
        String creditCardNumber = transaction.getTransactionCreditCardNumber();
        String lastFour = "";
        if (creditCardNumber.length() > CC_LAST_FOUR) {
            lastFour = creditCardNumber.substring(creditCardNumber.length() - CC_LAST_FOUR);
        }
        String docDesc = cardHolderName + "/" + vendorName + "/" + lastFour;
        if (transactionType != null && StringUtils.isNotBlank(transactionType)) {
            docDesc = transactionType + "/" + cardHolderName + "/" + vendorName + "/" + lastFour;
        }
        if (docDesc.length() > MAX_DOC_DESC_LENGTH) {
            docDesc = docDesc.substring(0, MAX_DOC_DESC_LENGTH);
        }
        pcardDocument.getDocumentHeader().setDocumentDescription(docDesc);
        // Remove duplicate messages from errorText
        String[] messages = StringUtils.split(errorText, ".");
        for (int i = 0; i < messages.length; i++) {
            int countMatches = StringUtils.countMatches(errorText, messages[i]) - 1;
            errorText = StringUtils.replace(errorText, messages[i] + ".", "", countMatches);
        }
        // In case errorText is still too long, truncate it and indicate so.
        Integer documentExplanationMaxLength = dataDictionaryService.getAttributeMaxLength(DocumentHeader.class.getName(), KFSPropertyConstants.EXPLANATION);
        if (documentExplanationMaxLength != null && errorText.length() > documentExplanationMaxLength.intValue()) {
            String truncatedMessage = " ... TRUNCATED.";
            errorText = errorText.substring(0, documentExplanationMaxLength - truncatedMessage.length()) + truncatedMessage;
        }
        pcardDocument.getDocumentHeader().setExplanation(errorText);
    } catch (WorkflowException e) {
        LOG.error("Error creating pcdo documents: " + e.getMessage(), e);
        throw new RuntimeException("Error creating pcdo documents: " + e.getMessage(), e);
    }
    return pcardDocument;
}
Also used : CapitalAssetInformation(org.kuali.kfs.fp.businessobject.CapitalAssetInformation) WorkflowException(org.kuali.rice.kew.api.exception.WorkflowException) DocumentHeader(org.kuali.kfs.krad.bo.DocumentHeader) DataDictionaryService(org.kuali.kfs.krad.service.DataDictionaryService) ProcurementCardDocument(org.kuali.kfs.fp.document.ProcurementCardDocument) ProcurementCardTransactionExtendedAttribute(edu.cornell.kfs.fp.businessobject.ProcurementCardTransactionExtendedAttribute) ProcurementCardTransaction(org.kuali.kfs.fp.businessobject.ProcurementCardTransaction) Iterator(java.util.Iterator) KualiDecimal(org.kuali.rice.core.api.util.type.KualiDecimal)

Example 3 with ProcurementCardDocument

use of org.kuali.kfs.fp.document.ProcurementCardDocument 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 4 with ProcurementCardDocument

use of org.kuali.kfs.fp.document.ProcurementCardDocument 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)

Aggregations

ProcurementCardDocument (org.kuali.kfs.fp.document.ProcurementCardDocument)4 ReceiptProcessing (edu.cornell.kfs.module.receiptProcessing.businessobject.ReceiptProcessing)2 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 Attachment (org.kuali.kfs.krad.bo.Attachment)2 Note (org.kuali.kfs.krad.bo.Note)2 ParseException (org.kuali.kfs.sys.exception.ParseException)2 CapitalAssetInformationDetailExtendedAttribute (edu.cornell.kfs.fp.businessobject.CapitalAssetInformationDetailExtendedAttribute)1 ProcurementCardTransactionExtendedAttribute (edu.cornell.kfs.fp.businessobject.ProcurementCardTransactionExtendedAttribute)1 Iterator (java.util.Iterator)1 CapitalAssetInformation (org.kuali.kfs.fp.businessobject.CapitalAssetInformation)1 CapitalAssetInformationDetail (org.kuali.kfs.fp.businessobject.CapitalAssetInformationDetail)1 ProcurementCardTransaction (org.kuali.kfs.fp.businessobject.ProcurementCardTransaction)1 DocumentHeader (org.kuali.kfs.krad.bo.DocumentHeader)1 DataDictionaryService (org.kuali.kfs.krad.service.DataDictionaryService)1