<commit_before>/*

 * Copyright 2005-2010 The Kuali Foundation
 * 
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kra.award.maintenance;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.kra.award.home.AwardTemplate;
import org.kuali.kra.award.home.AwardTemplateReportTerm;
import org.kuali.kra.award.home.AwardTemplateReportTermRecipient;
import org.kuali.kra.award.home.ValidBasisMethodPayment;
import org.kuali.kra.award.paymentreports.ValidClassReportFrequency;
import org.kuali.kra.award.paymentreports.ValidFrequencyBase;
import org.kuali.kra.bo.Rolodex;
import org.kuali.kra.bo.SponsorTerm;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.maintenance.KraMaintainableImpl;
import org.kuali.kra.rules.ErrorReporter;
import org.kuali.rice.kns.bo.PersistableBusinessObject;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.lookup.LookupUtils;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.util.TypedArrayList;

/**
 * This class is for adding validation rules to maintain Award Template
 */
public class AwardTemplateMaintainableImpl extends KraMaintainableImpl {
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = -3368480537790330757L;
    
    private static final String ERROR_KEY_PREFIX = "document.newMaintainableObject.add.templateReportTerms[0].";
    
    private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(AwardTemplateMaintainableImpl.class); 

    public void addMultipleValueLookupResults(MaintenanceDocument document, String collectionName, Collection<PersistableBusinessObject> rawValues, boolean needsBlank, PersistableBusinessObject bo) {
        Collection maintCollection = (Collection) ObjectUtils.getPropertyValue(bo, collectionName);
        String docTypeName = document.getDocumentHeader().getWorkflowDocument().getDocumentType();
        BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class);
        
        
        if( StringUtils.equals( collectionName, "templateTerms") ) {
            for (PersistableBusinessObject nextBo : rawValues) {
                SponsorTerm aTerm = (SponsorTerm)nextBo;
                aTerm.refreshNonUpdateableReferences();
            }
        }
        super.addMultipleValueLookupResults(document, collectionName, rawValues, needsBlank, bo);
        
    }
    
    /**
     * This method is for performing any new validations while adding new items to the list.
     */
    @Override
    public void addNewLineToCollection(String collectionName) {
        if (collectionName.equals("templateReportTerms")) {
            ErrorReporter errorReporter = new ErrorReporter();
            AwardTemplateReportTerm awardTemplateReportTerm = (AwardTemplateReportTerm) newCollectionLines.get(collectionName);
            if (awardTemplateReportTerm != null) {
                if (!isValid(awardTemplateReportTerm)) {
                    reportReportTermError(errorReporter, awardTemplateReportTerm);
                } else {
                    super.addNewLineToCollection(collectionName);
                }
            }
        } else if (collectionName.endsWith("awardTemplateReportTermRecipients")) {
            addNewRecipientToCollection(collectionName);
        } else {
            super.addNewLineToCollection(collectionName);
        }
    }
    
    /**
     * 
     * This method is for add a new AwardTemplateReportTermRecipient.
     * @param collectionName
     */
    public void addNewRecipientToCollection(String collectionName) {
        
        if (LOG.isDebugEnabled()) {
            LOG.debug("addNewRecipientToCollection( " + collectionName + " )");
        }
        // get the new line from the map
        AwardTemplateReportTermRecipient addLine = (AwardTemplateReportTermRecipient) newCollectionLines.get(collectionName);
        ErrorReporter errorReporter = new ErrorReporter();
        if (addLine != null) {
            // mark the isNewCollectionRecord so the option to delete this line will be presented
            addLine.setNewCollectionRecord(true);
            addLine.setRolodexNameOrganization("");
            // parse contactTypeCodeAndRolodexId to get ContactTypeCode and RolodexId separately
            String contactTypeCodeAndRolodexIdString = addLine.getContactTypeCodeAndRolodexId();
            //Integer rolodexIdInt = addLine.getRolodexId();
            if (StringUtils.isNotEmpty(contactTypeCodeAndRolodexIdString) && addLine.getRolodexId() != null) {
                //add error only one can be selected
                addLine.setRolodexNameOrganization("");                
                errorReporter.reportError(
                        ERROR_KEY_PREFIX + "awardTemplateReportTermRecipients.rolodexId", 
                        KeyConstants.ERROR_CAN_NOT_SELECT_BOTH_FIELDS,
                        contactTypeCodeAndRolodexIdString, addLine.getRolodexId().toString());
                return;
            }
            if (StringUtils.isNotEmpty(contactTypeCodeAndRolodexIdString)) {
                int index1 = contactTypeCodeAndRolodexIdString.indexOf(Constants.AWARD_TEMP_RECPNT_CONTACT_TYPE_CODE_ROLODEX_ID_SEPARATOR);
                if (index1 > 0) {
                    String contactTypeCode = contactTypeCodeAndRolodexIdString.substring(0, index1);
                    Integer rolodexId = Integer.parseInt(contactTypeCodeAndRolodexIdString.substring(
                                                                index1 + Constants.AWARD_TEMP_RECPNT_CONTACT_TYPE_CODE_ROLODEX_ID_SEPARATOR.length(), 
                                                                contactTypeCodeAndRolodexIdString.length()));
                    addLine.setContactTypeCode(contactTypeCode);
                    addLine.setRolodexId(rolodexId);
                    addLine.setRolodexNameOrganization(this.rolodexNameAndOrganization(rolodexId));
                }
            } else if (addLine.getRolodexId() != null) {
                addLine.setContactTypeCode("-1");  // use default contact type code
                addLine.setRolodexId(addLine.getRolodexId());
                addLine.setRolodexNameOrganization(this.rolodexNameAndOrganization(addLine.getRolodexId()));
            } else { 
                // add error, one of the fields has to be selected
                addLine.setRolodexNameOrganization("");
                errorReporter.reportError(
                        ERROR_KEY_PREFIX + "awardTemplateReportTermRecipients.contactTypeCodeAndRolodexId", 
                        KeyConstants.ERROR_ONE_FIELD_MUST_BE_SELECTED);
                return;
            }
            
            // get the collection from the business object
            Collection maintCollection = (Collection) ObjectUtils.getPropertyValue(getBusinessObject(), collectionName);
            
            if (maintCollection.size() > 0) {
                List<AwardTemplateReportTermRecipient> aList = new TypedArrayList(AwardTemplateReportTermRecipient.class);
                aList.addAll(maintCollection);
                Integer id = addLine.getRolodexId();
                for (int i = 0; i < aList.size(); i++) {
                    AwardTemplateReportTermRecipient aRecipient = (AwardTemplateReportTermRecipient) aList.get(i);
                    if (aRecipient.getRolodexId().equals(id)) {
                        errorReporter.reportError(
                                ERROR_KEY_PREFIX + collectionName, <commit_msg>KRACOEUS-4211 updated error reporting, need one more change in a bit<commit_after>/*

 * Copyright 2005-2010 The Kuali Foundation
 * 
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.opensource.org/licenses/ecl1.php
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kra.award.maintenance;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.kra.award.home.AwardTemplate;
import org.kuali.kra.award.home.AwardTemplateReportTerm;
import org.kuali.kra.award.home.AwardTemplateReportTermRecipient;
import org.kuali.kra.award.home.ValidBasisMethodPayment;
import org.kuali.kra.award.paymentreports.ValidClassReportFrequency;
import org.kuali.kra.award.paymentreports.ValidFrequencyBase;
import org.kuali.kra.bo.Rolodex;
import org.kuali.kra.bo.SponsorTerm;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.maintenance.KraMaintainableImpl;
import org.kuali.kra.rules.ErrorReporter;
import org.kuali.rice.kns.bo.PersistableBusinessObject;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.lookup.LookupUtils;
import org.kuali.rice.kns.service.BusinessObjectService;
import org.kuali.rice.kns.util.ObjectUtils;
import org.kuali.rice.kns.util.TypedArrayList;

/**
 * This class is for adding validation rules to maintain Award Template
 */
public class AwardTemplateMaintainableImpl extends KraMaintainableImpl {
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = -3368480537790330757L;
    
    //private static final String ERROR_KEY_PREFIX = "document.newMaintainableObject.add.templateReportTerms[0].";
    private static final String ERROR_KEY_PREFIX2 = "document.newMaintainableObject.add.templateReportTerms[";
    
    private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory.getLog(AwardTemplateMaintainableImpl.class); 

    public void addMultipleValueLookupResults(MaintenanceDocument document, String collectionName, Collection<PersistableBusinessObject> rawValues, boolean needsBlank, PersistableBusinessObject bo) {
        Collection maintCollection = (Collection) ObjectUtils.getPropertyValue(bo, collectionName);
        String docTypeName = document.getDocumentHeader().getWorkflowDocument().getDocumentType();
        BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class);
        
        
        if( StringUtils.equals( collectionName, "templateTerms") ) {
            for (PersistableBusinessObject nextBo : rawValues) {
                SponsorTerm aTerm = (SponsorTerm)nextBo;
                aTerm.refreshNonUpdateableReferences();
            }
        }
        super.addMultipleValueLookupResults(document, collectionName, rawValues, needsBlank, bo);
        
    }
    
    /**
     * This method is for performing any new validations while adding new items to the list.
     */
    @Override
    public void addNewLineToCollection(String collectionName) {
        if (collectionName.equals("templateReportTerms")) {
            ErrorReporter errorReporter = new ErrorReporter();
            AwardTemplateReportTerm awardTemplateReportTerm = (AwardTemplateReportTerm) newCollectionLines.get(collectionName);
            if (awardTemplateReportTerm != null) {
                if (!isValid(awardTemplateReportTerm)) {
                    reportReportTermError(errorReporter, awardTemplateReportTerm);
                } else {
                    super.addNewLineToCollection(collectionName);
                }
            }
        } else if (collectionName.endsWith("awardTemplateReportTermRecipients")) {
            addNewRecipientToCollection(collectionName);
        } else {
            super.addNewLineToCollection(collectionName);
        }
    }
    
    /**
     * 
     * This method is for add a new AwardTemplateReportTermRecipient.
     * @param collectionName
     */
    public void addNewRecipientToCollection(String collectionName) {
        
        if (LOG.isDebugEnabled()) {
            LOG.debug("addNewRecipientToCollection( " + collectionName + " )");
        }
        // get the new line from the map
        AwardTemplateReportTermRecipient addLine = (AwardTemplateReportTermRecipient) newCollectionLines.get(collectionName);
        ErrorReporter errorReporter = new ErrorReporter();
        if (addLine != null) {
            // mark the isNewCollectionRecord so the option to delete this line will be presented
            addLine.setNewCollectionRecord(true);
            addLine.setRolodexNameOrganization("");
            // parse contactTypeCodeAndRolodexId to get ContactTypeCode and RolodexId separately
            String contactTypeCodeAndRolodexIdString = addLine.getContactTypeCodeAndRolodexId();
            //Integer rolodexIdInt = addLine.getRolodexId();
            if (StringUtils.isNotEmpty(contactTypeCodeAndRolodexIdString) && addLine.getRolodexId() != null) {
                //add error only one can be selected
                addLine.setRolodexNameOrganization("");   
                String errorKey = ERROR_KEY_PREFIX2 + 0 + "].awardTemplateReportTermRecipients.rolodexId";
                errorReporter.reportError(errorKey, 
                        KeyConstants.ERROR_CAN_NOT_SELECT_BOTH_FIELDS,
                        contactTypeCodeAndRolodexIdString, addLine.getRolodexId().toString());
                return;
            }
            if (StringUtils.isNotEmpty(contactTypeCodeAndRolodexIdString)) {
                int index1 = contactTypeCodeAndRolodexIdString.indexOf(Constants.AWARD_TEMP_RECPNT_CONTACT_TYPE_CODE_ROLODEX_ID_SEPARATOR);
                if (index1 > 0) {
                    String contactTypeCode = contactTypeCodeAndRolodexIdString.substring(0, index1);
                    Integer rolodexId = Integer.parseInt(contactTypeCodeAndRolodexIdString.substring(
                                                                index1 + Constants.AWARD_TEMP_RECPNT_CONTACT_TYPE_CODE_ROLODEX_ID_SEPARATOR.length(), 
                                                                contactTypeCodeAndRolodexIdString.length()));
                    addLine.setContactTypeCode(contactTypeCode);
                    addLine.setRolodexId(rolodexId);
                    addLine.setRolodexNameOrganization(this.rolodexNameAndOrganization(rolodexId));
                }
            } else if (addLine.getRolodexId() != null) {
                addLine.setContactTypeCode("-1");  // use default contact type code
                addLine.setRolodexId(addLine.getRolodexId());
                addLine.setRolodexNameOrganization(this.rolodexNameAndOrganization(addLine.getRolodexId()));
            } else { 
                // add error, one of the fields has to be selected
                addLine.setRolodexNameOrganization("");
                String errorKey = ERROR_KEY_PREFIX2 + 0 + "].awardTemplateReportTermRecipients.contactTypeCodeAndRolodexId";
                //System.err.println("errorKey:     " + errorKey);
                //System.err.println("Traditionals: " + ERROR_KEY_PREFIX + "awardTemplateReportTermRecipients.contactTypeCodeAndRolodexId");
                
                errorReporter.reportError(
                        errorKey, 
                        KeyConstants.ERROR_ONE_FIELD_MUST_BE_SELECTED);
                return;
            }
            
            // get the collection from the business object
            Collection maintCollection = (Collection) ObjectUtils.getPropertyValue(getBusinessObject(), collectionName);
            
            if (maintCollection.size() > 0) {
                List<AwardTemplateReportTermRecipient> aList = new TypedArrayList(AwardTemplateReportTermRecipient.class);
                aList.addAll(maintCollection);
                Integer id = addLine.getRolodexId();
                for (int i = 0; i < aList.size(); i++) {
                    AwardTemplateReportTermRecipient aRecipient = (AwardTemplateReportTermRecipient) aList.get(i);
                    if (aRecipient.getRolodexId().equals(id)) {
                        String errorKey = ERROR_KEY_PREFIX2 + 0 + "].awardTemplateReportTermRecipients.rolodexId";
                        errorReporter.reportError(errorKey, 
{'fraction_non_alphanumeric': 0.07878017789072427, 'fraction_numerical': 0.005255862307958877, 'mean_word_length': 2.7584111135229, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4048113', 'n_tokens_mistral': 4829, 'n_tokens_neox': 4576, 'n_words': 891}