001    /*
002     * Copyright 2011 The Kuali Foundation.
003     * 
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     * 
008     * http://www.opensource.org/licenses/ecl2.php
009     * 
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.kfs.module.purap.document.web.struts;
017    
018    import java.math.BigDecimal;
019    import java.util.Enumeration;
020    import java.util.List;
021    import java.util.Map;
022    import java.util.Set;
023    
024    import javax.servlet.http.HttpServletRequest;
025    import javax.servlet.http.HttpServletResponse;
026    
027    import org.apache.commons.lang.StringUtils;
028    import org.apache.struts.action.ActionForm;
029    import org.apache.struts.action.ActionForward;
030    import org.apache.struts.action.ActionMapping;
031    import org.apache.struts.upload.FormFile;
032    import org.kuali.kfs.integration.purap.CapitalAssetLocation;
033    import org.kuali.kfs.integration.purap.CapitalAssetSystem;
034    import org.kuali.kfs.integration.purap.ItemCapitalAsset;
035    import org.kuali.kfs.module.purap.PurapConstants;
036    import org.kuali.kfs.module.purap.PurapKeyConstants;
037    import org.kuali.kfs.module.purap.PurapParameterConstants;
038    import org.kuali.kfs.module.purap.PurapPropertyConstants;
039    import org.kuali.kfs.module.purap.businessobject.BillingAddress;
040    import org.kuali.kfs.module.purap.businessobject.CapitalAssetSystemType;
041    import org.kuali.kfs.module.purap.businessobject.PurApAccountingLine;
042    import org.kuali.kfs.module.purap.businessobject.PurApItem;
043    import org.kuali.kfs.module.purap.businessobject.PurchaseOrderItem;
044    import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetItem;
045    import org.kuali.kfs.module.purap.businessobject.PurchasingCapitalAssetSystemBase;
046    import org.kuali.kfs.module.purap.businessobject.PurchasingItemBase;
047    import org.kuali.kfs.module.purap.document.PurchaseOrderAmendmentDocument;
048    import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
049    import org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument;
050    import org.kuali.kfs.module.purap.document.PurchasingDocument;
051    import org.kuali.kfs.module.purap.document.PurchasingDocumentBase;
052    import org.kuali.kfs.module.purap.document.service.PurapService;
053    import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
054    import org.kuali.kfs.module.purap.document.service.PurchasingService;
055    import org.kuali.kfs.module.purap.document.validation.event.AttributedAddPurchasingAccountsPayableItemEvent;
056    import org.kuali.kfs.module.purap.document.validation.event.AttributedAddPurchasingCapitalAssetLocationEvent;
057    import org.kuali.kfs.module.purap.document.validation.event.AttributedAddPurchasingItemCapitalAssetEvent;
058    import org.kuali.kfs.module.purap.document.validation.event.AttributedCommodityCodesForDistributionEvent;
059    import org.kuali.kfs.module.purap.document.validation.event.AttributedImportPurchasingAccountsPayableItemEvent;
060    import org.kuali.kfs.module.purap.document.validation.event.AttributedUpdateCamsViewPurapEvent;
061    import org.kuali.kfs.module.purap.exception.ItemParserException;
062    import org.kuali.kfs.module.purap.util.ItemParser;
063    import org.kuali.kfs.sys.KFSConstants;
064    import org.kuali.kfs.sys.KFSKeyConstants;
065    import org.kuali.kfs.sys.KFSPropertyConstants;
066    import org.kuali.kfs.sys.businessobject.Building;
067    import org.kuali.kfs.sys.businessobject.SourceAccountingLine;
068    import org.kuali.kfs.sys.context.SpringContext;
069    import org.kuali.kfs.sys.document.validation.event.AddAccountingLineEvent;
070    import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
071    import org.kuali.kfs.vnd.VendorConstants;
072    import org.kuali.kfs.vnd.businessobject.VendorAddress;
073    import org.kuali.kfs.vnd.businessobject.VendorContract;
074    import org.kuali.kfs.vnd.document.service.VendorService;
075    import org.kuali.kfs.vnd.service.PhoneNumberService;
076    import org.kuali.rice.kew.exception.WorkflowException;
077    import org.kuali.rice.kns.bo.Note;
078    import org.kuali.rice.kns.document.Document;
079    import org.kuali.rice.kns.question.ConfirmationQuestion;
080    import org.kuali.rice.kns.service.BusinessObjectService;
081    import org.kuali.rice.kns.service.DataDictionaryService;
082    import org.kuali.rice.kns.service.KualiConfigurationService;
083    import org.kuali.rice.kns.service.KualiRuleService;
084    import org.kuali.rice.kns.service.ParameterService;
085    import org.kuali.rice.kns.service.PersistenceService;
086    import org.kuali.rice.kns.util.GlobalVariables;
087    import org.kuali.rice.kns.util.KNSConstants;
088    import org.kuali.rice.kns.util.KualiDecimal;
089    import org.kuali.rice.kns.util.ObjectUtils;
090    import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
091    
092    
093    /**
094     * Struts Action for Purchasing documents.
095     */
096    public class PurchasingActionBase extends PurchasingAccountsPayableActionBase {
097        protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurchasingActionBase.class);
098    
099        /**
100         * @see org.kuali.kfs.sys.web.struts.KualiAccountingDocumentActionBase#refresh(org.apache.struts.action.ActionMapping,
101         *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
102         */
103        @Override
104        public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
105            PurchasingAccountsPayableFormBase baseForm = (PurchasingAccountsPayableFormBase) form;
106    
107            PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
108            String refreshCaller = baseForm.getRefreshCaller();
109            BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
110            PhoneNumberService phoneNumberService = SpringContext.getBean(PhoneNumberService.class);
111    
112            // Format phone numbers
113            document.setInstitutionContactPhoneNumber(phoneNumberService.formatNumberIfPossible(document.getInstitutionContactPhoneNumber()));
114            document.setRequestorPersonPhoneNumber(phoneNumberService.formatNumberIfPossible(document.getRequestorPersonPhoneNumber()));
115            document.setDeliveryToPhoneNumber(phoneNumberService.formatNumberIfPossible(document.getDeliveryToPhoneNumber()));
116    
117            //names in KIM are longer than what we store these names at; truncate them to match our data dictionary maxlengths
118            if (StringUtils.equals(refreshCaller, "kimPersonLookupable")) {
119                Integer deliveryToNameMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(document.getClass(), PurapPropertyConstants.DELIVERY_TO_NAME);
120                if (StringUtils.isNotEmpty(document.getDeliveryToName()) && ObjectUtils.isNotNull(deliveryToNameMaxLength) && document.getDeliveryToName().length() > deliveryToNameMaxLength.intValue()) {
121                    document.setDeliveryToName(document.getDeliveryToName().substring(0, deliveryToNameMaxLength));
122                    GlobalVariables.getMessageMap().clearErrorPath();
123                    GlobalVariables.getMessageMap().addToErrorPath(PurapConstants.DELIVERY_TAB_ERRORS);
124                    GlobalVariables.getMessageMap().putWarning(PurapPropertyConstants.DELIVERY_TO_NAME, PurapKeyConstants.WARNING_DELIVERY_TO_NAME_TRUNCATED);
125                    GlobalVariables.getMessageMap().removeFromErrorPath(PurapConstants.DELIVERY_TAB_ERRORS);
126                }
127    
128                Integer requestorNameMaxLength = SpringContext.getBean(DataDictionaryService.class).getAttributeMaxLength(document.getClass(), PurapPropertyConstants.REQUESTOR_PERSON_NAME);
129                if (StringUtils.isNotEmpty(document.getRequestorPersonName()) && ObjectUtils.isNotNull(requestorNameMaxLength) && document.getRequestorPersonName().length() > requestorNameMaxLength.intValue()) {
130                    document.setRequestorPersonName(document.getRequestorPersonName().substring(0, requestorNameMaxLength));
131                    GlobalVariables.getMessageMap().clearErrorPath();
132                    GlobalVariables.getMessageMap().addToErrorPath(PurapConstants.ADDITIONAL_TAB_ERRORS);
133                    GlobalVariables.getMessageMap().putWarning(PurapPropertyConstants.REQUESTOR_PERSON_NAME, PurapKeyConstants.WARNING_REQUESTOR_NAME_TRUNCATED);
134                    GlobalVariables.getMessageMap().removeFromErrorPath(PurapConstants.ADDITIONAL_TAB_ERRORS);
135                }
136            }
137            
138            // Refreshing the fields after returning from a vendor lookup in the vendor tab
139            if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && document.getVendorDetailAssignedIdentifier() != null && document.getVendorHeaderGeneratedIdentifier() != null) {
140                document.setVendorContractGeneratedIdentifier(null);
141                document.refreshReferenceObject("vendorContract");
142    
143                // retrieve vendor based on selection from vendor lookup
144                document.refreshReferenceObject("vendorDetail");
145                document.templateVendorDetail(document.getVendorDetail());
146    
147                // populate default address based on selected vendor
148                VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), document.getDeliveryCampusCode());
149                document.templateVendorAddress(defaultAddress);
150    
151            }
152    
153            // Refreshing the fields after returning from a contract lookup in the vendor tab
154            if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_CONTRACT_LOOKUPABLE_IMPL)) {
155                if (StringUtils.isNotEmpty(request.getParameter(KFSPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_CONTRACT_ID))) {
156                    // retrieve Contract based on selection from contract lookup
157                    VendorContract refreshVendorContract = new VendorContract();
158                    refreshVendorContract.setVendorContractGeneratedIdentifier(document.getVendorContractGeneratedIdentifier());
159                    refreshVendorContract = (VendorContract) businessObjectService.retrieve(refreshVendorContract);
160    
161                    // retrieve Vendor based on selected contract
162                    document.setVendorHeaderGeneratedIdentifier(refreshVendorContract.getVendorHeaderGeneratedIdentifier());
163                    document.setVendorDetailAssignedIdentifier(refreshVendorContract.getVendorDetailAssignedIdentifier());
164                    document.refreshReferenceObject("vendorDetail");
165                    document.templateVendorDetail(document.getVendorDetail());
166    
167                    // always template contract after vendor to keep contract defaults last
168                    document.templateVendorContract(refreshVendorContract);
169    
170                    // populate default address from selected vendor
171                    VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(document.getVendorDetail().getVendorAddresses(), document.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), "");
172                    document.templateVendorAddress(defaultAddress);
173    
174                    // update internal dollar limit for PO since the contract might affect this value
175                    if (document instanceof PurchaseOrderDocument) {
176                        PurchaseOrderDocument poDoc = (PurchaseOrderDocument) document;
177                        KualiDecimal limit = SpringContext.getBean(PurchaseOrderService.class).getInternalPurchasingDollarLimit(poDoc);
178                        poDoc.setInternalPurchasingLimit(limit);
179                    }
180                }
181            }
182    
183            // Refreshing the fields after returning from an address lookup in the vendor tab
184            if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_ADDRESS_LOOKUPABLE_IMPL)) {
185                if (StringUtils.isNotEmpty(request.getParameter(KFSPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_ADDRESS_ID))) {
186                    // retrieve address based on selection from address lookup
187                    VendorAddress refreshVendorAddress = new VendorAddress();
188                    refreshVendorAddress.setVendorAddressGeneratedIdentifier(document.getVendorAddressGeneratedIdentifier());
189                    refreshVendorAddress = (VendorAddress) businessObjectService.retrieve(refreshVendorAddress);
190                    document.templateVendorAddress(refreshVendorAddress);
191                }
192            }
193    
194            // Refreshing corresponding fields after returning from various kuali lookups
195            if (StringUtils.equals(refreshCaller, KFSConstants.KUALI_LOOKUPABLE_IMPL)) {
196                if (request.getParameter("document.deliveryCampusCode") != null) {
197                    // returning from a building or campus lookup on the delivery tab (update billing address)
198                    BillingAddress billingAddress = new BillingAddress();
199                    billingAddress.setBillingCampusCode(document.getDeliveryCampusCode());
200                    Map keys = SpringContext.getBean(PersistenceService.class).getPrimaryKeyFieldValues(billingAddress);
201                    billingAddress = (BillingAddress) SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(BillingAddress.class, keys);
202                    document.templateBillingAddress(billingAddress);
203    
204                    if (request.getParameter("document.deliveryBuildingName") == null) {
205                        // came from campus lookup not building, so clear building
206                        document.setDeliveryBuildingCode("");
207                        document.setDeliveryBuildingName("");
208                        document.setDeliveryBuildingLine1Address("");
209                        document.setDeliveryBuildingLine2Address("");
210                        document.setDeliveryBuildingRoomNumber("");
211                        document.setDeliveryCityName("");
212                        document.setDeliveryStateCode("");
213                        document.setDeliveryPostalCode("");
214                        document.setDeliveryCountryCode("");
215                    }
216                    else {
217                        // came from building lookup then turn off "OTHER" and clear room and line2address
218                        document.setDeliveryBuildingOtherIndicator(false);
219                        document.setDeliveryBuildingRoomNumber("");
220                        document.setDeliveryBuildingLine2Address("");
221                    }
222                }
223                else if (request.getParameter("document.chartOfAccountsCode") != null) {
224                    // returning from a chart/org lookup on the document detail tab (update receiving address)
225                    document.loadReceivingAddress();
226                }
227                else {
228                    String buildingCodeParam = findBuildingCodeFromCapitalAssetBuildingLookup(request);
229                    if (!StringUtils.isEmpty(buildingCodeParam)) {
230                        // returning from a building lookup in a capital asset tab location (update location address)
231                        PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
232                        CapitalAssetLocation location = null;
233    
234                        // get building code
235                        String buildingCode = request.getParameterValues(buildingCodeParam)[0];
236                        // get campus code
237                        String campusCodeParam = buildingCodeParam.replace("buildingCode", "campusCode");
238                        String campusCode = request.getParameterValues(campusCodeParam)[0];
239                        // lookup building
240                        Building locationBuilding = new Building();
241                        locationBuilding.setCampusCode(campusCode);
242                        locationBuilding.setBuildingCode(buildingCode);
243                        Map<String, String> keys = SpringContext.getBean(PersistenceService.class).getPrimaryKeyFieldValues(locationBuilding);
244                        locationBuilding = (Building) SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Building.class, keys);
245    
246                        Map<String, String> parameters = request.getParameterMap();
247                        Set<String> parameterKeys = parameters.keySet();
248                        String locationCapitalAssetLocationNumber = "";
249                        String locationCapitalAssetItemNumber = "";
250                        for (String parameterKey : parameterKeys) {
251                            if (StringUtils.containsIgnoreCase(parameterKey, "newPurchasingCapitalAssetLocationLine")) {
252                                // its the new line
253                                if (document.getCapitalAssetSystemType().getCapitalAssetSystemTypeCode().equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
254                                    // get the item number
255                                    locationCapitalAssetItemNumber = getCaptialAssetItemNumberFromParameter(parameterKey);
256                                    PurchasingCapitalAssetItem capitalAssetItem = document.getPurchasingCapitalAssetItems().get(Integer.parseInt(locationCapitalAssetItemNumber));
257                                    location = capitalAssetItem.getPurchasingCapitalAssetSystem().getNewPurchasingCapitalAssetLocationLine();
258                                }
259                                else {
260                                    // no item number
261                                    location = purchasingForm.getNewPurchasingCapitalAssetLocationLine();
262                                }
263                                break;
264                            }
265                            else if (StringUtils.containsIgnoreCase(parameterKey, "purchasingCapitalAssetLocationLine")) {
266                                // its one of the numbered lines, lets
267                                locationCapitalAssetLocationNumber = getCaptialAssetLocationNumberFromParameter(parameterKey);
268    
269                                if (document.getCapitalAssetSystemType().getCapitalAssetSystemTypeCode().equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
270                                    // get the item number
271                                    locationCapitalAssetItemNumber = getCaptialAssetItemNumberFromParameter(parameterKey);
272                                    PurchasingCapitalAssetItem capitalAssetItem = document.getPurchasingCapitalAssetItems().get(Integer.parseInt(locationCapitalAssetItemNumber));
273                                    location = capitalAssetItem.getPurchasingCapitalAssetSystem().getCapitalAssetLocations().get(Integer.parseInt(locationCapitalAssetLocationNumber));
274                                }
275                                break;
276                            }
277                            else if (StringUtils.containsIgnoreCase(parameterKey, "purchasingCapitalAssetSystems")) {
278                                // its one of the numbered lines, lets
279                                locationCapitalAssetLocationNumber = getCaptialAssetLocationNumberFromParameter(parameterKey);
280    
281                                if (!document.getCapitalAssetSystemType().getCapitalAssetSystemTypeCode().equals(PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL)) {
282                                    CapitalAssetSystem capitalAssetSystem = document.getPurchasingCapitalAssetSystems().get(0);
283                                    location = capitalAssetSystem.getCapitalAssetLocations().get(Integer.parseInt(locationCapitalAssetLocationNumber));
284                                }
285                                break;
286                            }
287                        }
288    
289                        if ((location != null) && (locationBuilding != null)) {
290                            location.templateBuilding(locationBuilding);
291                        }
292                    }
293                }
294            }
295            return super.refresh(mapping, form, request, response);
296        }
297    
298        protected String getCaptialAssetLocationNumberFromParameter(String parameterKey) {
299            int beginIndex = parameterKey.lastIndexOf("[") + 1;
300            int endIndex = parameterKey.lastIndexOf("]");
301            return parameterKey.substring(beginIndex, endIndex);
302        }
303    
304        protected String getCaptialAssetItemNumberFromParameter(String parameterKey) {
305            int beginIndex = parameterKey.indexOf("[") + 1;
306            int endIndex = parameterKey.indexOf("]");
307            return parameterKey.substring(beginIndex, endIndex);
308        }
309    
310        /**
311         * Setup document to use "OTHER" building
312         * 
313         * @param mapping An ActionMapping
314         * @param form An ActionForm
315         * @param request A HttpServletRequest
316         * @param response A HttpServletResponse
317         * @return An ActionForward
318         * @throws Exception
319         */
320        public ActionForward useOtherDeliveryBuilding(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
321            PurchasingFormBase baseForm = (PurchasingFormBase) form;
322            PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
323    
324            document.setDeliveryBuildingOtherIndicator(true);
325            document.setDeliveryBuildingName("");
326            document.setDeliveryBuildingCode("");
327            document.setDeliveryBuildingLine1Address("");
328            document.setDeliveryBuildingLine2Address("");
329            document.setDeliveryBuildingRoomNumber("");
330            document.setDeliveryCityName("");
331            document.setDeliveryStateCode("");
332            document.setDeliveryCountryCode("");
333            document.setDeliveryPostalCode("");
334    
335            return mapping.findForward(KFSConstants.MAPPING_BASIC);
336        }
337    
338        public ActionForward useOffCampusAssetLocationBuildingByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
339            PurchasingFormBase baseForm = (PurchasingFormBase) form;
340            PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
341    
342            String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
343            String systemIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
344            String assetLocationIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
345    
346            CapitalAssetSystem system = document.getPurchasingCapitalAssetSystems().get(Integer.parseInt(systemIndex));
347    
348            if ("new".equals(assetLocationIndex)) {
349                useOffCampusAssetLocationBuilding(baseForm.getNewPurchasingCapitalAssetLocationLine());
350            }
351            else {
352                useOffCampusAssetLocationBuilding(system.getCapitalAssetLocations().get(Integer.parseInt(assetLocationIndex)));
353            }
354    
355            return mapping.findForward(KFSConstants.MAPPING_BASIC);
356        }
357    
358        public ActionForward useOffCampusAssetLocationBuildingByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
359            PurchasingFormBase baseForm = (PurchasingFormBase) form;
360            PurchasingDocument document = (PurchasingDocument) baseForm.getDocument();
361    
362            String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
363            String assetItemIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
364            String assetLocationIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
365    
366            PurchasingCapitalAssetItem assetItem = document.getPurchasingCapitalAssetItems().get(Integer.parseInt(assetItemIndex));
367            CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
368    
369            if ("new".equals(assetLocationIndex)) {
370                useOffCampusAssetLocationBuilding(system.getNewPurchasingCapitalAssetLocationLine());
371            }
372            else {
373                useOffCampusAssetLocationBuilding(system.getCapitalAssetLocations().get(Integer.parseInt(assetLocationIndex)));
374            }
375    
376            return mapping.findForward(KFSConstants.MAPPING_BASIC);
377        }
378    
379        protected void useOffCampusAssetLocationBuilding(CapitalAssetLocation location) {
380            if (location != null) {
381                location.setOffCampusIndicator(true);
382                location.setBuildingCode("");
383                location.setCapitalAssetLine1Address("");
384                location.setCapitalAssetCityName("");
385                location.setCapitalAssetStateCode("");
386                location.setCapitalAssetPostalCode("");
387                location.setCapitalAssetCountryCode("");
388                location.setBuildingRoomNumber("");
389            }
390        }
391    
392        /**
393         * Add a new item to the document.
394         * 
395         * @param mapping An ActionMapping
396         * @param form An ActionForm
397         * @param request The HttpServletRequest
398         * @param response The HttpServletResponse
399         * @throws Exception
400         * @return An ActionForward
401         */
402        public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
403            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
404            PurApItem item = purchasingForm.getNewPurchasingItemLine();
405            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
406            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddPurchasingAccountsPayableItemEvent("", purDocument, item));
407    
408            if (rulePassed) {
409                item = purchasingForm.getAndResetNewPurchasingItemLine();
410                purDocument.addItem(item);
411            }
412    
413            return mapping.findForward(KFSConstants.MAPPING_BASIC);
414        }
415    
416        /**
417         * Import items to the document from a spreadsheet.
418         * 
419         * @param mapping An ActionMapping
420         * @param form An ActionForm
421         * @param request The HttpServletRequest
422         * @param response The HttpServletResponse
423         * @throws Exception
424         * @return An ActionForward
425         */
426        public ActionForward importItems(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
427            LOG.info("Importing item lines");
428    
429            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
430            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
431            String documentNumber = purDocument.getDocumentNumber();
432            FormFile itemFile = purchasingForm.getItemImportFile();
433            Class itemClass = purDocument.getItemClass();
434            List<PurApItem> importedItems = null;
435            String errorPath = PurapConstants.ITEM_TAB_ERRORS;
436            ItemParser itemParser = purDocument.getItemParser();
437            int itemLinePosition = purDocument.getItemLinePosition(); // starting position of the imported items, equals the # of
438            // existing above-the-line items.
439    
440            try {
441                importedItems = itemParser.importItems(itemFile, itemClass, documentNumber);
442                // validate imported items
443                boolean allPassed = true;
444                int itemLineNumber = 0;
445                for (PurApItem item : importedItems) {
446                    // Before the validation, set the item line number to the same as the line number in the import file (starting from
447                    // 1)
448                    // so that the error message will use the correct line number if there're errors for the current item line.
449                    item.setItemLineNumber(++itemLineNumber);
450                    allPassed &= SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedImportPurchasingAccountsPayableItemEvent("", purDocument, item));
451                    // After the validation, set the item line number to the correct value as if it's added to the item list.
452                    item.setItemLineNumber(itemLineNumber + itemLinePosition);
453                }
454                if (allPassed) {
455                    updateBOReferenceforNewItems(importedItems, (PurchasingDocumentBase) purDocument);
456                    purDocument.getItems().addAll(itemLinePosition, importedItems);
457    
458                }
459            }
460            catch (ItemParserException e) {
461                GlobalVariables.getMessageMap().putError(errorPath, e.getErrorKey(), e.getErrorParameters());
462            }
463    
464            return mapping.findForward(KFSConstants.MAPPING_BASIC);
465        }
466    
467        /**
468         * Whenever add a new item, we need to keep track of the reference from Item to Doc and from Account to Item
469         * 
470         * @param importedItems
471         */
472        protected void updateBOReferenceforNewItems(List<PurApItem> importedItems, PurchasingDocumentBase purDocument) {
473            // update reference from Item to Document and from Account to Item.
474            for (PurApItem item : (List<PurApItem>) importedItems) {
475                item.setPurapDocument(purDocument);
476                // set the PurapDocumentIdentifier so in the future, item acquire the object again by calling refreshReferenceObject for
477                // purApDocument.
478                if (purDocument.getPurapDocumentIdentifier() != null) {
479                    item.setPurapDocumentIdentifier(purDocument.getPurapDocumentIdentifier());
480                }
481                for (PurApAccountingLine account : item.getSourceAccountingLines()) {
482                    account.setPurapItem(item);
483                    if (item.getItemIdentifier() != null) {
484                        account.setItemIdentifier(item.getItemIdentifier());
485                    }
486                }
487            }
488        }
489    
490        /**
491         * Delete an item from the document.
492         * 
493         * @param mapping An ActionMapping
494         * @param form An ActionForm
495         * @param request The HttpServletRequest
496         * @param response The HttpServletResponse
497         * @throws Exception
498         * @return An ActionForward
499         */
500        public ActionForward deleteItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
501            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
502    
503            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
504            purDocument.deleteItem(getSelectedLine(request));
505    
506            return mapping.findForward(KFSConstants.MAPPING_BASIC);
507        }
508    
509        /**
510         * Moves the selected item up one position.
511         * 
512         * @param mapping An ActionMapping
513         * @param form An ActionForm
514         * @param request The HttpServletRequest
515         * @param response The HttpServletResponse
516         * @throws Exception
517         * @return An ActionForward
518         */
519        public ActionForward upItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
520            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
521            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
522            int line = getSelectedLine(request);
523            purDocument.itemSwap(line, line - 1);
524    
525            return mapping.findForward(KFSConstants.MAPPING_BASIC);
526        }
527    
528        /**
529         * Moves the selected item down one position (These two methods up/down could easily be consolidated. For now, it seems more
530         * straightforward to keep them separate.)
531         * 
532         * @param mapping An ActionMapping
533         * @param form An ActionForm
534         * @param request The HttpServletRequest
535         * @param response The HttpServletResponse
536         * @throws Exception
537         * @return An ActionForward
538         */
539        public ActionForward downItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
540            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
541            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
542            int line = getSelectedLine(request);
543            purDocument.itemSwap(line, line + 1);
544    
545            return mapping.findForward(KFSConstants.MAPPING_BASIC);
546        }
547    
548        /**
549         * Reveals the account distribution section.
550         * 
551         * @param mapping An ActionMapping
552         * @param form An ActionForm
553         * @param request The HttpServletRequest
554         * @param response The HttpServletResponse
555         * @throws Exception
556         * @return An ActionForward
557         */
558        public ActionForward setupAccountDistribution(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
559            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
560    
561            purchasingForm.setHideDistributeAccounts(false);
562    
563            return mapping.findForward(KFSConstants.MAPPING_BASIC);
564        }
565    
566        /**
567         * Clear out the accounting lines from all the items.
568         * 
569         * @param mapping An ActionMapping
570         * @param form An ActionForm
571         * @param request The HttpServletRequest
572         * @param response The HttpServletResponse
573         * @throws Exception
574         * @return An ActionForward
575         */
576        public ActionForward removeAccounts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
577            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
578    
579            Object question = request.getParameter(PurapConstants.QUESTION_INDEX);
580            Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
581    
582            if (question == null) {
583                String questionText = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapConstants.QUESTION_REMOVE_ACCOUNTS);
584    
585                return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.REMOVE_ACCOUNTS_QUESTION, questionText, KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, "0");
586            }
587            else if (ConfirmationQuestion.YES.equals(buttonClicked)) {
588                for (PurApItem item : ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems()) {
589                    item.getSourceAccountingLines().clear();
590                }
591    
592                GlobalVariables.getMessageList().add(PurapKeyConstants.PURAP_GENERAL_ACCOUNTS_REMOVED);
593            }
594    
595            return mapping.findForward(KFSConstants.MAPPING_BASIC);
596        }
597    
598        /**
599         * Clear out the commodity codes from all the items.
600         * 
601         * @param mapping An ActionMapping
602         * @param form An ActionForm
603         * @param request The HttpServletRequest
604         * @param response The HttpServletResponse
605         * @throws Exception
606         * @return An ActionForward
607         */
608        public ActionForward clearItemsCommodityCodes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
609            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
610    
611            Object question = request.getParameter(PurapConstants.QUESTION_INDEX);
612            Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
613    
614            if (question == null) {
615                String questionText = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapConstants.QUESTION_CLEAR_ALL_COMMODITY_CODES);
616    
617                return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.CLEAR_COMMODITY_CODES_QUESTION, questionText, KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, "0");
618            }
619            else if (ConfirmationQuestion.YES.equals(buttonClicked)) {
620                for (PurApItem item : ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems()) {
621                    PurchasingItemBase purItem = ((PurchasingItemBase) item);
622                    purItem.setPurchasingCommodityCode(null);
623                    purItem.setCommodityCode(null);
624                }
625    
626                GlobalVariables.getMessageList().add(PurapKeyConstants.PUR_COMMODITY_CODES_CLEARED);
627            }
628    
629            return mapping.findForward(KFSConstants.MAPPING_BASIC);
630        }
631    
632        /**
633         * Validates that the accounting lines while a distribute accounts action is being taken.
634         * 
635         * @param document
636         * @param distributionsourceAccountingLines
637         * @return
638         */
639        protected boolean validateDistributeAccounts(Document document, List<PurApAccountingLine> distributionsourceAccountingLines) {
640            boolean rulePassed = true;
641            String errorPrefix = null;
642            int i = 0;
643    
644            for (PurApAccountingLine accountingLine : distributionsourceAccountingLines) {
645                errorPrefix = "accountDistributionsourceAccountingLine" + "[" + Integer.toString(i) + "]";
646                rulePassed &= SpringContext.getBean(KualiRuleService.class).applyRules(new AddAccountingLineEvent(errorPrefix, document, accountingLine));
647                i++;
648            }
649    
650            return rulePassed;
651        }
652    
653        /**
654         * Distribute accounting line(s) to the item(s). Does not distribute the accounting line(s) to an item if there are already
655         * accounting lines associated with that item, if the item is a below-the-line item and has no unit cost, or if the item is
656         * inactive. Distribute commodity code to the item(s). Does not distribute the commodity code to an item if the item is not
657         * above the line item, is inactive or if the commodity code fails the validation (i.e. inactive commodity code or non existence
658         * commodity code).
659         * 
660         * @param mapping An ActionMapping
661         * @param form An ActionForm
662         * @param request The HttpServletRequest
663         * @param response The HttpServletResponse
664         * @throws Exception
665         * @return An ActionForward
666         */
667        public ActionForward doDistribution(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
668            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
669            boolean needToDistributeCommodityCode = false;
670    
671            if (StringUtils.isNotBlank(purchasingForm.getDistributePurchasingCommodityCode())) {
672                // Do the logic for distributing purchasing commodity code to all the items.
673                needToDistributeCommodityCode = true;
674            }
675    
676            boolean needToDistributeAccount = false;
677            List<PurApAccountingLine> distributionsourceAccountingLines = purchasingForm.getAccountDistributionsourceAccountingLines();
678            if (distributionsourceAccountingLines.size() > 0) {
679                needToDistributeAccount = true;
680            }
681            if (needToDistributeAccount || needToDistributeCommodityCode) {
682    
683                boolean institutionNeedsDistributeAccountValidation = SpringContext.getBean(ParameterService.class).getIndicatorParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.VALIDATE_ACCOUNT_DISTRIBUTION_IND);
684                boolean foundAccountDistributionError = false;
685                boolean foundCommodityCodeDistributionError = false;
686                boolean performedAccountDistribution = false;
687                boolean performedCommodityCodeDistribution = false;
688    
689                // If the institution's validate account distribution indicator is true and
690                // the total percentage in the distribute account list does not equal 100 % then we should display error
691                if (institutionNeedsDistributeAccountValidation && needToDistributeAccount && purchasingForm.getTotalPercentageOfAccountDistributionsourceAccountingLines().compareTo(new BigDecimal(100)) != 0) {
692                    GlobalVariables.getMessageMap().putError(PurapConstants.ACCOUNT_DISTRIBUTION_ERROR_KEY, PurapKeyConstants.ERROR_DISTRIBUTE_ACCOUNTS_NOT_100_PERCENT);
693                    foundAccountDistributionError = true;
694                }
695                // if the institution's validate account distribution indicator is true and
696                // there is a validation error in the accounts to distribute then we should display an error
697                if (institutionNeedsDistributeAccountValidation && needToDistributeAccount && (validateDistributeAccounts(purchasingForm.getDocument(), distributionsourceAccountingLines) == false)) {
698                    foundAccountDistributionError = true;
699                }
700    
701                for (PurApItem item : ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItems()) {
702                    boolean itemIsActive = true;
703                    if (item instanceof PurchaseOrderItem) {
704                        // if item is PO item... only validate active items
705                        itemIsActive = ((PurchaseOrderItem) item).isItemActiveIndicator();
706                    }
707                    if (needToDistributeCommodityCode) {
708                        // only the above the line items need the commodity code.
709                        if (item.getItemType().isLineItemIndicator() && StringUtils.isBlank(((PurchasingItemBase) item).getPurchasingCommodityCode()) && itemIsActive) {
710                            // Ideally we should invoke rules to check whether the commodity code is valid (active, not restricted,
711                            // not missing, etc), probably somewhere here or invoke the rule class from here.
712    
713                            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCommodityCodesForDistributionEvent("", purchasingForm.getDocument(), purchasingForm.getDistributePurchasingCommodityCode()));
714                            if (rulePassed) {
715                                ((PurchasingItemBase) item).setPurchasingCommodityCode(purchasingForm.getDistributePurchasingCommodityCode());
716                                performedCommodityCodeDistribution = true;
717                            }
718                            else {
719                                foundCommodityCodeDistributionError = true;
720                            }
721                        }else if(item.getItemType().isLineItemIndicator() && !StringUtils.isBlank(((PurchasingItemBase) item).getPurchasingCommodityCode()) && itemIsActive){
722                            //could not apply to line, as it wasn't blank
723                            foundCommodityCodeDistributionError = true;
724                        }
725                    }
726                    if (needToDistributeAccount && !foundAccountDistributionError) {
727                        BigDecimal zero = new BigDecimal(0);
728                        // We should be distributing accounting lines to above the line items all the time;
729                        // but only to the below the line items when there is a unit cost.
730                        boolean unitCostNotZeroForBelowLineItems = item.getItemType().isLineItemIndicator() ? true : item.getItemUnitPrice() != null && zero.compareTo(item.getItemUnitPrice()) < 0;
731                        Document document = ((PurchasingFormBase) form).getDocument();
732                        Class clazz = document instanceof PurchaseOrderAmendmentDocument ? PurchaseOrderDocument.class : document.getClass();
733                        List<String> typesNotAllowingEdit = SpringContext.getBean(ParameterService.class).getParameterValues(clazz, PurapParameterConstants.PURAP_ITEM_TYPES_RESTRICTING_ACCOUNT_EDIT);
734                        boolean itemOnExcludeList = (typesNotAllowingEdit == null) ? false : typesNotAllowingEdit.contains(item.getItemTypeCode());
735                        if (item.getSourceAccountingLines().size() == 0 && unitCostNotZeroForBelowLineItems && !itemOnExcludeList && itemIsActive) {
736                            for (PurApAccountingLine purApAccountingLine : distributionsourceAccountingLines) {
737                                item.getSourceAccountingLines().add((PurApAccountingLine) ObjectUtils.deepCopy(purApAccountingLine));
738                            }
739    
740                            performedAccountDistribution = true;
741                        }
742                    }
743                }
744    
745                if ((needToDistributeCommodityCode && performedCommodityCodeDistribution && !foundCommodityCodeDistributionError) || (needToDistributeAccount && performedAccountDistribution && !foundAccountDistributionError)) {
746                    if (needToDistributeCommodityCode && !foundCommodityCodeDistributionError && performedCommodityCodeDistribution) {
747                        GlobalVariables.getMessageList().add(PurapKeyConstants.PUR_COMMODITY_CODE_DISTRIBUTED);
748                        purchasingForm.setDistributePurchasingCommodityCode(null);
749                    }
750                    if (needToDistributeAccount && !foundAccountDistributionError && performedAccountDistribution) {
751                        GlobalVariables.getMessageList().add(PurapKeyConstants.PURAP_GENERAL_ACCOUNTS_DISTRIBUTED);
752                        distributionsourceAccountingLines.clear();
753                    }
754                    purchasingForm.setHideDistributeAccounts(true);
755                }
756    
757                if ((needToDistributeAccount && !performedAccountDistribution && foundAccountDistributionError)) {
758                    GlobalVariables.getMessageMap().putError(PurapConstants.ACCOUNT_DISTRIBUTION_ERROR_KEY, PurapKeyConstants.PURAP_GENERAL_NO_ITEMS_TO_DISTRIBUTE_TO, "account numbers");
759                }
760                if (needToDistributeCommodityCode && !performedCommodityCodeDistribution && foundCommodityCodeDistributionError) {
761                    GlobalVariables.getMessageMap().putError(PurapConstants.ACCOUNT_DISTRIBUTION_ERROR_KEY, PurapKeyConstants.PURAP_GENERAL_NO_ITEMS_TO_DISTRIBUTE_TO, "commodity codes");
762                }
763            }
764            else {
765                GlobalVariables.getMessageMap().putError(PurapConstants.ACCOUNT_DISTRIBUTION_ERROR_KEY, PurapKeyConstants.PURAP_GENERAL_NO_ACCOUNTS_TO_DISTRIBUTE);
766            }
767    
768    
769            return mapping.findForward(KFSConstants.MAPPING_BASIC);
770        }
771    
772        /**
773         * Simply hides the account distribution section.
774         * 
775         * @param mapping An ActionMapping
776         * @param form An ActionForm
777         * @param request The HttpServletRequest
778         * @param response The HttpServletResponse
779         * @throws Exception
780         * @return An ActionForward
781         */
782        public ActionForward cancelAccountDistribution(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
783            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
784            purchasingForm.setHideDistributeAccounts(true);
785            return mapping.findForward(KFSConstants.MAPPING_BASIC);
786        }
787    
788        /**
789         * @see org.kuali.kfs.module.purap.document.web.struts.PurchasingAccountsPayableActionBase#processCustomInsertAccountingLine(org.kuali.kfs.module.purap.document.web.struts.PurchasingAccountsPayableFormBase)
790         */
791        @Override
792        public boolean processCustomInsertAccountingLine(PurchasingAccountsPayableFormBase purapForm, HttpServletRequest request) {
793            boolean success = false;
794            PurchasingFormBase purchasingForm = (PurchasingFormBase) purapForm;
795    
796            // index of item selected
797            int itemIndex = getSelectedLine(request);
798            PurApItem item = null;
799    
800            boolean institutionNeedsDistributeAccountValidation = SpringContext.getBean(ParameterService.class).getIndicatorParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.VALIDATE_ACCOUNT_DISTRIBUTION_IND);
801    
802            if (itemIndex == -2 && !institutionNeedsDistributeAccountValidation) {
803                PurApAccountingLine line = purchasingForm.getAccountDistributionnewSourceLine();
804                purchasingForm.addAccountDistributionsourceAccountingLine(line);
805                success = true;
806            }
807    
808            return success;
809        }
810    
811        /**
812         * @see org.kuali.kfs.sys.web.struts.KualiAccountingDocumentActionBase#deleteSourceLine(org.apache.struts.action.ActionMapping,
813         *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
814         */
815        @Override
816        public ActionForward deleteSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
817            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
818    
819            String[] indexes = getSelectedLineForAccounts(request);
820            int itemIndex = Integer.parseInt(indexes[0]);
821            int accountIndex = Integer.parseInt(indexes[1]);
822            if (itemIndex == -2) {
823                purchasingForm.getAccountDistributionsourceAccountingLines().remove(accountIndex);
824            }
825            else {
826                PurApItem item = (PurApItem) ((PurchasingAccountsPayableDocument) purchasingForm.getDocument()).getItem((itemIndex));
827                item.getSourceAccountingLines().remove(accountIndex);
828            }
829    
830            return mapping.findForward(KFSConstants.MAPPING_BASIC);
831        }
832    
833        /**
834         * Sets the line for account distribution.
835         * 
836         * @param accountIndex The index of the account into the request parameter
837         * @param purchasingAccountsPayableForm A form which inherits from PurchasingAccountsPayableFormBase
838         * @return A SourceAccountingLine
839         */
840        protected SourceAccountingLine customAccountRetrieval(int accountIndex, PurchasingAccountsPayableFormBase purchasingAccountsPayableForm) {
841            PurchasingFormBase purchasingForm = (PurchasingFormBase) purchasingAccountsPayableForm;
842            SourceAccountingLine line;
843            line = (SourceAccountingLine) ObjectUtils.deepCopy(purchasingForm.getAccountDistributionsourceAccountingLines().get(accountIndex));
844            return line;
845        }
846    
847        /**
848         * This method...
849         * 
850         * @param mapping
851         * @param form
852         * @param request
853         * @param response
854         * @return
855         * @throws Exception
856         */
857        public ActionForward selectSystemType(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
858    
859            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
860            PurchasingDocumentBase document = (PurchasingDocumentBase) purchasingForm.getDocument();
861    
862            Object question = request.getParameter(PurapConstants.QUESTION_INDEX);
863            Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
864    
865            String systemTypeCode = (String) request.getAttribute(KNSConstants.METHOD_TO_CALL_ATTRIBUTE);
866            systemTypeCode = StringUtils.substringBetween(systemTypeCode, "selectSystemType.", ".");
867    
868            if (question == null) {
869                String questionText = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapConstants.CapitalAssetTabStrings.QUESTION_SYSTEM_SWITCHING);
870    
871                return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.CapitalAssetTabStrings.SYSTEM_SWITCHING_QUESTION, questionText, KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, "0");
872            }
873            else if (ConfirmationQuestion.YES.equals(buttonClicked)) {
874    
875                // document.setCapitalAssetSystemTypeCode(systemTypeCode);
876                document.refreshReferenceObject(PurapPropertyConstants.CAPITAL_ASSET_SYSTEM_TYPE);
877    
878                GlobalVariables.getMessageList().add(PurapKeyConstants.PUR_CAPITAL_ASSET_SYSTEM_TYPE_SWITCHED);
879            }
880    
881            return mapping.findForward(KFSConstants.MAPPING_BASIC);
882        }
883    
884        public ActionForward addItemCapitalAssetByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
885            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
886            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
887            ItemCapitalAsset asset = purDocument.getPurchasingCapitalAssetItems().get(0).getNewPurchasingItemCapitalAssetLine();
888    
889            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddPurchasingItemCapitalAssetEvent("", purDocument, asset));
890    
891            if (rulePassed) {
892                // get specific asset item and grab system as well and attach asset number
893                CapitalAssetSystem system = purDocument.getPurchasingCapitalAssetSystems().get(getSelectedLine(request));
894                asset = purDocument.getPurchasingCapitalAssetItems().get(0).getAndResetNewPurchasingItemCapitalAssetLine();
895                asset.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
896                system.getItemCapitalAssets().add(asset);
897            }
898    
899            return mapping.findForward(KFSConstants.MAPPING_BASIC);
900        }
901    
902        public ActionForward addItemCapitalAssetByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
903            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
904            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
905            // get specific asset item
906            PurchasingCapitalAssetItem assetItem = purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
907    
908            ItemCapitalAsset asset = assetItem.getNewPurchasingItemCapitalAssetLine();
909    
910            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddPurchasingItemCapitalAssetEvent("", purDocument, asset));
911    
912            if (rulePassed) {
913                // grab system as well and attach asset number
914                CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
915                asset = assetItem.getAndResetNewPurchasingItemCapitalAssetLine();
916                asset.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
917                system.getItemCapitalAssets().add(asset);
918            }
919    
920            return mapping.findForward(KFSConstants.MAPPING_BASIC);
921        }
922    
923        public ActionForward deleteItemCapitalAssetByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
924            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
925            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
926            // get specific asset item
927            PurchasingCapitalAssetItem assetItem = purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
928            ItemCapitalAsset asset = assetItem.getNewPurchasingItemCapitalAssetLine();
929    
930            boolean rulePassed = true; // SpringContext.getBean(KualiRuleService.class).applyRules(new
931            // AddPurchasingAccountsPayableItemEvent("", purDocument, item));
932    
933            if (rulePassed) {
934                String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
935                String systemIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
936                String assetIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
937    
938                PurchasingCapitalAssetSystemBase system = (PurchasingCapitalAssetSystemBase) purDocument.getPurchasingCapitalAssetSystems().get(Integer.parseInt(systemIndex));
939                system.getItemCapitalAssets().remove(Integer.parseInt(assetIndex));
940            }
941    
942            return mapping.findForward(KFSConstants.MAPPING_BASIC);
943        }
944    
945        public ActionForward deleteItemCapitalAssetByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
946            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
947            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
948            // get specific asset item
949            PurchasingCapitalAssetItem assetItem = purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
950    
951            ItemCapitalAsset asset = assetItem.getNewPurchasingItemCapitalAssetLine();
952    
953            boolean rulePassed = true; // SpringContext.getBean(KualiRuleService.class).applyRules(new
954            // AddPurchasingAccountsPayableItemEvent("", purDocument, item));
955    
956            if (rulePassed) {
957                String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
958                String assetIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
959                PurchasingCapitalAssetSystemBase system = (PurchasingCapitalAssetSystemBase) assetItem.getPurchasingCapitalAssetSystem();
960                system.getItemCapitalAssets().remove(Integer.parseInt(assetIndex));
961            }
962    
963            return mapping.findForward(KFSConstants.MAPPING_BASIC);
964        }
965    
966        public ActionForward addCapitalAssetLocationByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
967            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
968            CapitalAssetLocation location = purchasingForm.getAndResetNewPurchasingCapitalAssetLocationLine();
969            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
970    
971            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddPurchasingCapitalAssetLocationEvent("", purDocument, location));
972            rulePassed = rulePassed && SpringContext.getBean(PurchasingService.class).checkCapitalAssetLocation(location);
973    
974            if (rulePassed) {
975                // get specific asset item and grab system as well and attach asset number
976                CapitalAssetSystem system = purDocument.getPurchasingCapitalAssetSystems().get(getSelectedLine(request));
977                location.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
978                system.getCapitalAssetLocations().add(location);
979            }
980    
981            return mapping.findForward(KFSConstants.MAPPING_BASIC);
982        }
983    
984        public ActionForward addCapitalAssetLocationByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
985            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
986            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
987            CapitalAssetLocation location = purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request)).getPurchasingCapitalAssetSystem().getNewPurchasingCapitalAssetLocationLine();
988            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedAddPurchasingCapitalAssetLocationEvent("", purDocument, location));
989    
990            if (rulePassed) {
991                // get specific asset item and grab system as well and attach asset location
992                PurchasingCapitalAssetItem assetItem = purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
993                CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
994                location.setCapitalAssetSystemIdentifier(system.getCapitalAssetSystemIdentifier());
995                system.getCapitalAssetLocations().add(location);
996                // now reset the location as all the rules are passed successfully
997                purDocument.getPurchasingCapitalAssetItems().get(getSelectedLine(request)).getPurchasingCapitalAssetSystem().resetNewPurchasingCapitalAssetLocationLine();
998            }
999    
1000            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1001        }
1002    
1003        public ActionForward deleteCapitalAssetLocationByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1004            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1005            CapitalAssetLocation location = purchasingForm.getNewPurchasingCapitalAssetLocationLine();
1006            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
1007    
1008            boolean rulePassed = true; // SpringContext.getBean(KualiRuleService.class).applyRules(new
1009            // AddPurchasingAccountsPayableItemEvent("", purDocument, item));
1010    
1011            if (rulePassed) {
1012                String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
1013                String systemIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
1014                String locationIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
1015    
1016                // get specific asset item and grab system as well and attach asset number
1017                CapitalAssetSystem system = purDocument.getPurchasingCapitalAssetSystems().get(Integer.parseInt(systemIndex));
1018                system.getCapitalAssetLocations().remove(Integer.parseInt(locationIndex));
1019            }
1020    
1021            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1022        }
1023    
1024        public ActionForward deleteCapitalAssetLocationByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1025            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1026            CapitalAssetLocation location = purchasingForm.getNewPurchasingCapitalAssetLocationLine();
1027            PurchasingDocument purDocument = (PurchasingDocument) purchasingForm.getDocument();
1028    
1029            boolean rulePassed = true; // SpringContext.getBean(KualiRuleService.class).applyRules(new
1030            // AddPurchasingAccountsPayableItemEvent("", purDocument, item));
1031    
1032            if (rulePassed) {
1033                String fullParameter = (String) request.getAttribute(KFSConstants.METHOD_TO_CALL_ATTRIBUTE);
1034                String assetItemIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
1035                String locationIndex = StringUtils.substringBetween(fullParameter, KFSConstants.METHOD_TO_CALL_PARM2_LEFT_DEL, KFSConstants.METHOD_TO_CALL_PARM2_RIGHT_DEL);
1036    
1037                // get specific asset item and grab system as well and attach asset number
1038                PurchasingCapitalAssetItem assetItem = purDocument.getPurchasingCapitalAssetItems().get(Integer.parseInt(assetItemIndex));
1039                CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
1040                system.getCapitalAssetLocations().remove(Integer.parseInt(locationIndex));
1041            }
1042    
1043            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1044        }
1045    
1046        public ActionForward setupCAMSSystem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1047            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1048            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1049            SpringContext.getBean(PurchasingService.class).setupCapitalAssetSystem(document);
1050            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1051        }
1052    
1053        public ActionForward selectSystem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1054            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1055            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1056            String errorPath = PurapConstants.CAPITAL_ASSET_TAB_ERRORS;
1057            // validate entry is selected for each field
1058            if (StringUtils.isEmpty(document.getCapitalAssetSystemTypeCode())) {
1059                GlobalVariables.getMessageMap().putError(errorPath, KFSKeyConstants.ERROR_MISSING, "Capital Assets System Type Code");
1060            }
1061            else if (StringUtils.isEmpty(document.getCapitalAssetSystemStateCode())) {
1062                GlobalVariables.getMessageMap().putError(errorPath, KFSKeyConstants.ERROR_MISSING, "Capital Assets System State Code");
1063            }
1064            else {
1065                SpringContext.getBean(PurchasingService.class).setupCapitalAssetSystem(document);
1066                SpringContext.getBean(PurchasingService.class).setupCapitalAssetItems(document);
1067                if (!document.getPurchasingCapitalAssetItems().isEmpty()) {
1068                    SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
1069                }
1070                else {
1071                    // TODO: extract this and above strings to app resources
1072                    GlobalVariables.getMessageMap().putError(errorPath, KFSKeyConstants.ERROR_CUSTOM, "No items were found that met the requirements for Capital Asset data collection");
1073                }
1074                SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
1075            }
1076    
1077            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1078        }
1079    
1080        public ActionForward changeSystem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1081            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1082            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1083    
1084            Object question = request.getParameter(PurapConstants.QUESTION_INDEX);
1085            Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON);
1086    
1087            if (question == null) {
1088                String questionText = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASING_QUESTION_CONFIRM_CHANGE_SYSTEM);
1089    
1090                return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.CapitalAssetTabStrings.SYSTEM_SWITCHING_QUESTION, questionText, KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, "0");
1091            }
1092            else if (ConfirmationQuestion.YES.equals(buttonClicked)) {
1093                // Add a note if system change occurs when the document is a PO that is being amended.
1094                if ((document instanceof PurchaseOrderDocument) && (PurapConstants.PurchaseOrderStatuses.CHANGE_IN_PROCESS.equals(document.getStatusCode()))) {
1095                    Integer poId = document.getPurapDocumentIdentifier();
1096                    PurchaseOrderDocument currentPO = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(poId);
1097                    String oldSystemTypeCode = "";
1098                    if (currentPO != null) {
1099                        oldSystemTypeCode = currentPO.getCapitalAssetSystemTypeCode();
1100                    }
1101                    CapitalAssetSystemType oldSystemType = new CapitalAssetSystemType();
1102                    oldSystemType.setCapitalAssetSystemTypeCode(oldSystemTypeCode);
1103                    Map<String, String> keys = SpringContext.getBean(PersistenceService.class).getPrimaryKeyFieldValues(oldSystemType);
1104                    oldSystemType = (CapitalAssetSystemType) SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(CapitalAssetSystemType.class, keys);
1105                    String description = ((oldSystemType == null) ? "(NONE)" : oldSystemType.getCapitalAssetSystemTypeDescription());
1106    
1107                    if (document instanceof PurchaseOrderAmendmentDocument) {
1108                        String noteText = SpringContext.getBean(KualiConfigurationService.class).getPropertyString(PurapKeyConstants.PURCHASE_ORDER_AMEND_MESSAGE_CHANGE_SYSTEM_TYPE);
1109                        noteText = StringUtils.replace(noteText, "{0}", description);
1110    
1111                        try {
1112                            Note systemTypeChangeNote = getDocumentService().createNoteFromDocument(document, noteText);
1113                            purchasingForm.setNewNote(systemTypeChangeNote);
1114                            insertBONote(mapping, purchasingForm, request, response);
1115                        }
1116                        catch (Exception e) {
1117                            throw new RuntimeException(e);
1118                        }
1119                    }
1120                }
1121                document.clearCapitalAssetFields();
1122                SpringContext.getBean(PurapService.class).saveDocumentNoValidation(document);
1123                GlobalVariables.getMessageList().add(PurapKeyConstants.PURCHASING_MESSAGE_SYSTEM_CHANGED);
1124            }
1125    
1126            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1127        }
1128    
1129        public ActionForward updateCamsView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1130            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1131            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1132    
1133            boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedUpdateCamsViewPurapEvent(document));
1134    
1135            if (rulePassed) {
1136                SpringContext.getBean(PurchasingService.class).setupCapitalAssetItems(document);
1137            }
1138            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1139        }
1140    
1141    
1142        public ActionForward setManufacturerFromVendorByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1143            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1144            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1145    
1146            String vendorName = document.getVendorName();
1147            if (StringUtils.isEmpty(vendorName)) {
1148                GlobalVariables.getMessageMap().putError(PurapConstants.CAPITAL_ASSET_TAB_ERRORS, PurapKeyConstants.ERROR_CAPITAL_ASSET_NO_VENDOR, (String[])null);
1149            }
1150            else {
1151                CapitalAssetSystem system = document.getPurchasingCapitalAssetSystems().get(getSelectedLine(request));
1152                if (system != null) {
1153                    system.setCapitalAssetManufacturerName(vendorName);
1154                }
1155            }
1156    
1157            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1158        }
1159    
1160        public ActionForward setManufacturerFromVendorByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1161            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1162            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1163    
1164            String vendorName = document.getVendorName();
1165            if (StringUtils.isEmpty(vendorName)) {
1166                GlobalVariables.getMessageMap().putError(PurapConstants.CAPITAL_ASSET_TAB_ERRORS, PurapKeyConstants.ERROR_CAPITAL_ASSET_NO_VENDOR, (String[])null);
1167            }
1168            else {
1169                PurchasingCapitalAssetItem assetItem = document.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
1170                CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
1171                if (system != null) {
1172                    system.setCapitalAssetManufacturerName(vendorName);
1173                }
1174            }
1175            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1176        }
1177    
1178        public ActionForward selectNotCurrentYearByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1179            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1180            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1181    
1182            CapitalAssetSystem system = document.getPurchasingCapitalAssetSystems().get(getSelectedLine(request));
1183            if (system != null) {
1184                system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(true);
1185                system.setCapitalAssetTypeCode(SpringContext.getBean(PurchasingService.class).getDefaultAssetTypeCodeNotThisFiscalYear());
1186            }
1187    
1188            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1189        }
1190    
1191        public ActionForward selectNotCurrentYearByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1192            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1193            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1194    
1195            PurchasingCapitalAssetItem assetItem = document.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
1196            CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
1197            if (system != null) {
1198                system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(true);
1199                system.setCapitalAssetTypeCode(SpringContext.getBean(PurchasingService.class).getDefaultAssetTypeCodeNotThisFiscalYear());
1200            }
1201    
1202            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1203        }
1204    
1205        public ActionForward clearNotCurrentYearByDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1206            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1207            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1208    
1209            CapitalAssetSystem system = document.getPurchasingCapitalAssetSystems().get(getSelectedLine(request));
1210            if (system != null) {
1211                system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(false);
1212                system.setCapitalAssetTypeCode("");
1213            }
1214    
1215            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1216        }
1217    
1218        public ActionForward clearNotCurrentYearByItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1219            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1220            PurchasingDocument document = (PurchasingDocument) purchasingForm.getDocument();
1221    
1222            PurchasingCapitalAssetItem assetItem = document.getPurchasingCapitalAssetItems().get(getSelectedLine(request));
1223            CapitalAssetSystem system = assetItem.getPurchasingCapitalAssetSystem();
1224            if (system != null) {
1225                system.setCapitalAssetNotReceivedCurrentFiscalYearIndicator(false);
1226                system.setCapitalAssetTypeCode("");
1227            }
1228    
1229            return mapping.findForward(KFSConstants.MAPPING_BASIC);
1230        }
1231    
1232        @Override
1233        public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1234            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1235            PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
1236    
1237            boolean defaultUseTaxIndicatorValue = SpringContext.getBean(PurchasingService.class).getDefaultUseTaxIndicatorValue(purDoc);
1238            SpringContext.getBean(PurapService.class).updateUseTaxIndicator(purDoc, defaultUseTaxIndicatorValue);
1239            SpringContext.getBean(PurapService.class).calculateTax(purDoc);
1240    
1241            // call prorateDiscountTradeIn
1242            SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
1243    
1244            customCalculate(purDoc);
1245    
1246            PurchasingFormBase formBase = (PurchasingFormBase) form;
1247            formBase.setInitialZipCode(purDoc.getDeliveryPostalCode());
1248            formBase.setCalculated(true);
1249            
1250            return super.calculate(mapping, form, request, response);
1251        }
1252    
1253        @Override
1254        protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
1255            super.loadDocument(kualiDocumentFormBase);
1256            PurchasingFormBase formBase = (PurchasingFormBase) kualiDocumentFormBase;
1257            if (StringUtils.isEmpty(formBase.getInitialZipCode())) {
1258                formBase.setInitialZipCode(((PurchasingDocument) formBase.getDocument()).getDeliveryPostalCode());
1259            }
1260        }
1261    
1262        @Override
1263        public ActionForward clearAllTaxes(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1264            PurchasingAccountsPayableFormBase purchasingForm = (PurchasingAccountsPayableFormBase) form;
1265            PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
1266    
1267            SpringContext.getBean(PurapService.class).clearAllTaxes(purDoc);
1268    
1269            return super.clearAllTaxes(mapping, form, request, response);
1270        }
1271    
1272        /**
1273         * Determine from request parameters if user is returning from capital asset building lookup. Parameter will start with either
1274         * document.purchasingCapitalAssetItems or document.purchasingCapitalAssetSystems
1275         * 
1276         * @param request
1277         * @return
1278         */
1279        protected String findBuildingCodeFromCapitalAssetBuildingLookup(HttpServletRequest request) {
1280            Enumeration anEnum = request.getParameterNames();
1281            while (anEnum.hasMoreElements()) {
1282                String paramName = (String) anEnum.nextElement();
1283                if (paramName.contains("urchasingCapitalAsset") && paramName.contains("buildingCode")) {
1284                    return paramName;
1285                }
1286            }
1287            return "";
1288        }
1289    
1290        /**
1291         * Overrides the superclass method so that it will also do proration for trade in and full order discount when the user clicks
1292         * on the submit button.
1293         * 
1294         * @see org.kuali.kfs.sys.web.struts.KualiAccountingDocumentActionBase#route(org.apache.struts.action.ActionMapping,
1295         *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1296         */
1297        @Override
1298        public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1299            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1300            PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
1301         
1302            // if form is not yet calculated, return and prompt user to calculate
1303            if (requiresCalculate(purchasingForm)) {
1304                GlobalVariables.getMessageMap().putError(KFSConstants.DOCUMENT_ERRORS, PurapKeyConstants.ERROR_PURCHASING_REQUIRES_CALCULATE);
1305    
1306                return mapping.findForward(KFSConstants.MAPPING_BASIC);
1307            }
1308            
1309            // call prorateDiscountTradeIn
1310            SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
1311    
1312            return super.route(mapping, form, request, response);
1313        }
1314    
1315        /**
1316         * Overrides the superclass method so that it will also do proration for trade in and full order discount when the user clicks
1317         * on the approve button.
1318         * 
1319         * @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#approve(org.apache.struts.action.ActionMapping,
1320         *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1321         */
1322        @Override
1323        public ActionForward approve(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1324            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1325            PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
1326    
1327            // call prorateDiscountTradeIn
1328            SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
1329            
1330            return super.approve(mapping, form, request, response);
1331        }
1332    
1333        @Override
1334        public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1335            PurchasingFormBase purchasingForm = (PurchasingFormBase) form;
1336            PurchasingDocument purDoc = (PurchasingDocument) purchasingForm.getDocument();
1337            // call prorateDiscountTradeIn
1338            SpringContext.getBean(PurapService.class).prorateForTradeInAndFullOrderDiscount(purDoc);
1339            return super.blanketApprove(mapping, form, request, response);
1340        }
1341    
1342        /**
1343         * Checks if calculation is required. Currently it is required when it has not already been calculated and if the user can perform calculate
1344         * 
1345         * @return true if calculation is required, false otherwise
1346         */
1347        protected boolean requiresCalculate(PurchasingFormBase purForm) {
1348            boolean requiresCalculate = true;
1349            boolean salesTaxInd = SpringContext.getBean(ParameterService.class).getIndicatorParameter(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND);
1350            
1351            requiresCalculate = salesTaxInd && (!purForm.isCalculated() && purForm.canUserCalculate());
1352    
1353            return requiresCalculate;
1354        }
1355    }