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