View Javadoc
1   /*
2               NoteService noteService = KRADServiceLocator.getNoteService();
3               notes = noteService.getByRemoteObjectId(this.getBusinessObject().getObjectId());
4    * Copyright 2007 The Kuali Foundation
5    * 
6    * Licensed under the Educational Community License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    * 
10   * http://www.opensource.org/licenses/ecl2.php
11   * 
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.kuali.ole.vnd.document;
19  
20  import java.sql.Timestamp;
21  import java.util.ArrayList;
22  import java.util.HashMap;
23  import java.util.List;
24  import java.util.Map;
25  
26  import org.apache.commons.lang.StringUtils;
27  import org.kuali.ole.OLEConstants;
28  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
29  import org.kuali.ole.docstore.common.search.*;
30  import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.HoldingsRecord;
31  import org.kuali.ole.select.gokb.OleGokbOrganization;
32  import org.kuali.ole.select.gokb.OleGokbReview;
33  import org.kuali.ole.sys.context.SpringContext;
34  import org.kuali.ole.sys.document.FinancialSystemMaintainable;
35  import org.kuali.ole.vnd.VendorConstants;
36  import org.kuali.ole.vnd.VendorKeyConstants;
37  import org.kuali.ole.vnd.VendorParameterConstants;
38  import org.kuali.ole.vnd.VendorPropertyConstants;
39  import org.kuali.ole.vnd.VendorUtils;
40  import org.kuali.ole.vnd.businessobject.*;
41  import org.kuali.ole.vnd.document.service.VendorService;
42  import org.kuali.rice.core.api.datetime.DateTimeService;
43  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
44  import org.kuali.rice.kew.api.WorkflowDocument;
45  import org.kuali.rice.kim.api.identity.Person;
46  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
47  import org.kuali.rice.kns.document.MaintenanceDocument;
48  import org.kuali.rice.krad.bo.DocumentHeader;
49  import org.kuali.rice.krad.bo.Note;
50  import org.kuali.rice.krad.bo.PersistableBusinessObject;
51  import org.kuali.rice.krad.maintenance.MaintenanceLock;
52  import org.kuali.rice.krad.service.BusinessObjectService;
53  import org.kuali.rice.krad.service.KRADServiceLocator;
54  import org.kuali.rice.krad.service.NoteService;
55  import org.kuali.rice.krad.util.GlobalVariables;
56  import org.kuali.rice.krad.util.ObjectUtils;
57  
58  public class VendorMaintainableImpl extends FinancialSystemMaintainable {
59      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(VendorMaintainableImpl.class);
60  
61      private DocstoreClientLocator docstoreClientLocator;
62      public DocstoreClientLocator getDocstoreClientLocator() {
63          if (null == docstoreClientLocator) {
64              return SpringContext.getBean(DocstoreClientLocator.class);
65          }
66          return docstoreClientLocator;
67      }
68  
69      /**
70       * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#setGenerateDefaultValues(boolean)
71       */
72  	@Override
73      public void setGenerateDefaultValues(String docTypeName) {
74          super.setGenerateDefaultValues(docTypeName);
75          
76          List<Note> notes = new ArrayList<Note>();
77  
78          if (getBusinessObject().getObjectId() != null) {
79              NoteService noteService = KRADServiceLocator.getNoteService();
80              notes = noteService.getByRemoteObjectId(this.getBusinessObject().getObjectId());
81                    
82              if (notes.isEmpty()) {
83                  notes.add(getNewBoNoteForAdding(VendorConstants.VendorCreateAndUpdateNotePrefixes.ADD));
84              }
85          }
86      }
87  
88      /**
89       * Overrides the kuali default documents title with a Vendor-specific document title style
90       * 
91       * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#getDocumentTitle(org.kuali.rice.kns.document.MaintenanceDocument)
92       */
93      @Override
94      public String getDocumentTitle(MaintenanceDocument document) {
95          String documentTitle = "";
96          // Check if we are choosing to override the Kuali default document title.
97          if (SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(VendorDetail.class, VendorParameterConstants.OVERRIDE_VENDOR_DOC_TITLE)) {
98              // We are overriding the standard with a Vendor-specific document title style.
99              if (document.isOldBusinessObjectInDocument()) {
100                 documentTitle = "Edit Vendor - ";
101             }
102             else {
103                 documentTitle = "New Vendor - ";
104             }
105 
106             try {
107                 Person initUser = KimApiServiceLocator.getPersonService().getPerson(document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
108                 documentTitle += initUser.getCampusCode();
109             }
110             catch (Exception e) {
111                 throw new RuntimeException("Document Initiator not found " + e.getMessage());
112             }
113 
114             VendorDetail newBo = (VendorDetail) document.getNewMaintainableObject().getBusinessObject();
115 
116             if (StringUtils.isNotBlank(newBo.getVendorName())) {
117                 documentTitle += " '" + newBo.getVendorName() + "'";
118             } 
119             else {            
120                 if (StringUtils.isNotBlank(newBo.getVendorFirstName())) {
121                     documentTitle += " '" + newBo.getVendorFirstName() + " ";
122                     if (StringUtils.isBlank(newBo.getVendorLastName())) {
123                         documentTitle += "'";
124                     }
125                 }
126                 
127                 if (StringUtils.isNotBlank(newBo.getVendorLastName())) {
128                     if (StringUtils.isBlank(newBo.getVendorFirstName())) {
129                         documentTitle += " '";
130                     }
131                     documentTitle += newBo.getVendorLastName() + "'";
132                 }
133             }
134 
135             if (newBo.getVendorHeader().getVendorForeignIndicator()) {
136                 documentTitle += " (F)";
137             }
138 
139             if (!newBo.isVendorParentIndicator()) {
140                 documentTitle += " (D)";
141             }
142         }
143         else { // We are using the Kuali default document title.
144             documentTitle = super.getDocumentTitle(document);
145         }
146         return documentTitle;
147     }
148 
149     @Override
150     public void doRouteStatusChange(DocumentHeader header) {
151         super.doRouteStatusChange(header);
152         VendorDetail vendorDetail = (VendorDetail) getBusinessObject();
153         WorkflowDocument workflowDoc = header.getWorkflowDocument();
154 
155         // This code is only executed when the final approval occurs
156         if (workflowDoc.isProcessed()) {
157             // This id and versionNumber null check is needed here since those fields are always null for a fresh maintenance doc.
158             if (vendorDetail.isVendorParentIndicator() && vendorDetail.getVendorHeaderGeneratedIdentifier() != null) { 
159                 VendorDetail previousParent = SpringContext.getBean(VendorService.class).getParentVendor(vendorDetail.getVendorHeaderGeneratedIdentifier());
160                 // We'll only need to do the following if the previousParent is not the same as the current vendorDetail, because
161                 // the following lines are for vendor parent indicator changes.
162                 if (vendorDetail.getVendorDetailAssignedIdentifier() == null || 
163                         previousParent.getVendorHeaderGeneratedIdentifier().intValue() != vendorDetail.getVendorHeaderGeneratedIdentifier().intValue() || 
164                         previousParent.getVendorDetailAssignedIdentifier().intValue() != vendorDetail.getVendorDetailAssignedIdentifier().intValue()) {
165                     previousParent.setVendorParentIndicator(false);
166                     addNoteForParentIndicatorChange(vendorDetail, previousParent, header.getDocumentNumber());
167                     SpringContext.getBean(BusinessObjectService.class).save(previousParent);
168                 }
169             }
170 
171             // If this is a pre-existing parent vendor, and if the Tax Number or the Tax Type Code will change, log the change in the
172             // Tax Change table.
173             if (vendorDetail.isVendorParentIndicator()) {
174                 VendorDetail oldVendorDetail = SpringContext.getBean(VendorService.class).getVendorDetail(vendorDetail.getVendorHeaderGeneratedIdentifier(), vendorDetail.getVendorDetailAssignedIdentifier());
175                 if (ObjectUtils.isNotNull(oldVendorDetail)) {
176                     VendorHeader oldVendorHeader = oldVendorDetail.getVendorHeader();
177                     VendorHeader newVendorHeader = vendorDetail.getVendorHeader();
178 
179                     if (ObjectUtils.isNotNull(oldVendorHeader)) { // Does not apply if this is a new parent vendor.
180                         String oldVendorTaxNumber = oldVendorHeader.getVendorTaxNumber();
181                         String oldVendorTaxTypeCode = oldVendorHeader.getVendorTaxTypeCode();
182 
183                         String vendorTaxNumber = newVendorHeader.getVendorTaxNumber();
184                         String vendorTaxTypeCode = newVendorHeader.getVendorTaxTypeCode();
185 
186                         if ((!StringUtils.equals(vendorTaxNumber, oldVendorTaxNumber)) || (!StringUtils.equals(vendorTaxTypeCode, oldVendorTaxTypeCode))) {
187                             VendorTaxChange taxChange = new VendorTaxChange(vendorDetail.getVendorHeaderGeneratedIdentifier(), SpringContext.getBean(DateTimeService.class).getCurrentTimestamp(), oldVendorTaxNumber, oldVendorTaxTypeCode, GlobalVariables.getUserSession().getPerson().getPrincipalId());
188                             SpringContext.getBean(BusinessObjectService.class).save(taxChange);
189                         }
190                     }
191                 }
192             }
193 
194         }//endif isProcessed()
195     }
196     
197     /**
198      * Add a note to the previous parent vendor to denote that parent vendor indicator change had occurred.
199      * 
200      * @param newVendorDetail The current vendor
201      * @param oldVendorDetail The parent vendor of the current vendor prior to this change.
202      * @param getDocumentNumber() The document number of the document where we're attempting the parent vendor indicator change.
203      */
204     private void addNoteForParentIndicatorChange(VendorDetail newVendorDetail, VendorDetail oldVendorDetail, String docNumber) {
205         String noteText = VendorUtils.buildMessageText(VendorKeyConstants.MESSAGE_VENDOR_PARENT_TO_DIVISION, docNumber, newVendorDetail.getVendorName() + " (" + newVendorDetail.getVendorNumber() + ")");   
206         Note newBONote = new Note();
207         newBONote.setNoteText(noteText);
208         try {
209             NoteService noteService = SpringContext.getBean(NoteService.class);
210             newBONote = noteService.createNote(newBONote, oldVendorDetail, GlobalVariables.getUserSession().getPrincipalId());
211             newBONote.setNotePostedTimestampToCurrent();
212             
213             noteService.save(newBONote);
214         }
215         catch (Exception e) {
216             throw new RuntimeException("Caught Exception While Trying To Add Note to Vendor", e);
217         }
218         
219         NoteService noteService = KRADServiceLocator.getNoteService();
220         List<Note> notes = noteService.getByRemoteObjectId(oldVendorDetail.getObjectId());
221         notes.add(newBONote);
222     }
223     
224     /**
225      * Refreshes the vendorDetail. Currently we need this mainly for refreshing the soldToVendor object after returning from the
226      * lookup for a sold to vendor.
227      * 
228      * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#refresh(java.lang.String, java.util.Map,
229      *      org.kuali.rice.kns.document.MaintenanceDocument)
230      */
231     @Override
232     public void refresh(String refreshCaller, Map fieldValues, MaintenanceDocument document) {
233         PersistableBusinessObject oldBo = (PersistableBusinessObject) document.getOldMaintainableObject().getBusinessObject();
234         if (ObjectUtils.isNotNull(oldBo)) {
235             oldBo.refreshNonUpdateableReferences();
236         }
237         VendorDetail newBo = (VendorDetail) document.getNewMaintainableObject().getBusinessObject();
238         // Here we have to temporarily save vendorHeader into a temp object, then put back
239         // the vendorHeader into the newBo after the refresh, so that we don't lose the
240         // values
241         VendorHeader tempHeader = newBo.getVendorHeader();
242         newBo.refreshNonUpdateableReferences();
243         newBo.setVendorHeader(tempHeader);
244         super.refresh(refreshCaller, fieldValues, document);
245     }
246 
247     /**
248      * Temporarily saves vendorHeader into a temp object, then put back the vendorHeader into the VendorDetail after the refresh, so
249      * that we don't lose the values
250      */
251     public void refreshBusinessObject() {
252         VendorDetail vd = (VendorDetail) getBusinessObject();
253         // Here we have to temporarily save vendorHeader into a temp object, then put back
254         // the vendorHeader into the VendorDetail after the refresh, so that we don't lose the
255         // values
256         VendorHeader tempHeader = vd.getVendorHeader();
257         vd.refreshNonUpdateableReferences();
258         vd.setVendorHeader(tempHeader);
259     }
260 
261 
262     /**
263      * Checks whether the vendor has already had a vendor detail assigned id. If not, it will call the private method to set the
264      * detail assigned id. The method will also call the vendorService to determine whether it should save the vendor header (i.e.
265      * if this is a parent) and will save the vendor header accordingly. This is because we are not going to save vendor header
266      * automatically along with the saving of vendor detail, so if the vendor is a parent, we have to save the vendor header
267      * separately. Restriction-related information will be changed based on whether the Vendor Restricted Indicator was changed. If
268      * the Tax Number or Tax Type code have changed, the fact will be recorded with a new record in the Tax Change table. Finally
269      * the method will call the saveBusinessObject( ) of the super class to save the vendor detail.
270      * 
271      * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#saveBusinessObject()
272      */
273     @Override
274     public void saveBusinessObject() {
275         VendorDetail vendorDetail = (VendorDetail) super.getBusinessObject();
276         VendorHeader vendorHeader = vendorDetail.getVendorHeader();
277         VendorEventLog eventLog = new VendorEventLog();
278         eventLog.setDate(new Timestamp(System.currentTimeMillis()));
279         eventLog.setLogTypeId("3");
280         eventLog.setUserId(GlobalVariables.getUserSession().getPrincipalId());
281         if (vendorDetail.getVendorHeaderGeneratedIdentifier() != null && vendorDetail.getVendorDetailAssignedIdentifier() != null) {
282             HashMap vendor = new HashMap();
283             vendor.put("vendorHeaderGeneratedIdentifier", vendorDetail.getVendorHeaderGeneratedIdentifier());
284             vendor.put("vendorDetailAssignedIdentifier", vendorDetail.getVendorDetailAssignedIdentifier());
285             List<VendorDetail> vendorDetails = (List<VendorDetail>) KRADServiceLocator.getBusinessObjectService().findMatching(VendorDetail.class, vendor);
286             if (vendorDetails.get(0).isActiveIndicator() && !vendorDetail.isActiveIndicator()) {
287                 eventLog.setNote("Vendor is inactive :" + vendorDetail.getVendorInactiveReason().getVendorInactiveReasonDescription());
288             }
289             if (!vendorDetails.get(0).isActiveIndicator() && vendorDetail.isActiveIndicator()) {
290                 Map vendorMap = new HashMap();
291                 vendorMap.put(OLEConstants.GOKB_ID, vendorDetail.getGokbId());
292                 vendorMap.put(OLEConstants.OlePatron.PATRON_ACTIVE_IND, vendorDetail.isActiveIndicator());
293                 List<VendorDetail> vendorDetailList = (List<VendorDetail>) KRADServiceLocator.getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
294                 if (vendorDetailList.size() < 0) {
295                     eventLog.setNote("Vendor is active :" + vendorDetail.getVendorInactiveReason().getVendorInactiveReasonDescription());
296                     vendorDetail.getEventLogs().add(eventLog);
297                 }
298             }
299             if(vendorDetail.getGokbId()!=null && vendorDetail.getGokbId()!=null){
300                 eventLog = new VendorEventLog();
301                 eventLog.setNote("GOKb :" + vendorDetail.getGokbId() + " linked to Document" );
302                 HashMap organization = new HashMap();
303                 organization.put("gokbOrganizationId",vendorDetail.getGokbId());
304                 List<OleGokbOrganization> oleGokbOrganizations = (List<OleGokbOrganization>)KRADServiceLocator.getBusinessObjectService().findMatching(OleGokbOrganization.class,organization);
305                 if(vendorDetail.getVendorAliases().size()==0){
306                     VendorAlias alias = new VendorAlias();
307                     alias.setVendorAliasName(oleGokbOrganizations.get(0).getVariantName());
308                     alias.setActive(true);
309                     vendorDetail.getVendorAliases().add(alias);
310 
311                 }
312             }
313             vendorDetail.getEventLogs().add(eventLog);
314         }else if(vendorDetail.getVendorDetailAssignedIdentifier() == null){
315             eventLog.setNote("Created Vendor ");
316             vendorDetail.getEventLogs().add(eventLog);
317         }
318         // Update miscellaneous information and save the Vendor Header if this is a parent vendor.
319         setVendorName(vendorDetail);
320         vendorHeader.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
321         if (ObjectUtils.isNull(vendorDetail.getVendorDetailAssignedIdentifier())) {
322             setDetailAssignedId(vendorDetail);
323         }
324         if (vendorDetail.isVendorParentIndicator()) {
325             SpringContext.getBean(VendorService.class).saveVendorHeader(vendorDetail);
326         }
327         super.saveBusinessObject();
328     }
329 
330     /**
331      * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#processAfterEdit()
332      */
333     @Override
334     public void processAfterEdit( MaintenanceDocument document, Map<String,String[]> parameters ) {
335 
336         List<Note> notes = new ArrayList<Note>();
337         if (document.getOldMaintainableObject().getBusinessObject().getObjectId() != null) {
338             NoteService noteService = KRADServiceLocator.getNoteService();
339             notes = noteService.getByRemoteObjectId(this.getBusinessObject().getObjectId());
340         }
341         setVendorCreateAndUpdateNote(notes, VendorConstants.VendorCreateAndUpdateNotePrefixes.CHANGE);
342         document.setNotes(notes);
343         VendorDetail vendorDetail = (VendorDetail) document.getNewMaintainableObject().getBusinessObject();
344         if(vendorDetail.getGokbId()!=null){
345         Map hash = new HashMap();
346             hash.put("publisherId",vendorDetail.getGokbId());
347             List<HoldingsRecord> holdingsRecords = (List<HoldingsRecord>) getBusinessObjectService().findMatching(HoldingsRecord.class,hash);
348             if(holdingsRecords.size()>0){
349                 vendorDetail.setLinkedToEHoldings(true);
350             }else{
351                 vendorDetail.setLinkedToEHoldings(false);
352             }
353         }
354         super.processAfterEdit(document, parameters);
355     }
356 
357     /**
358      * Checks whether the previous note was an "Add" with the same document number as this one
359      * 
360      * @param notes List of exisiting notes.
361      * @param prefix String to determine if it is a note "Add" or a note "Change"
362      */
363     private void setVendorCreateAndUpdateNote(List<Note> notes, String prefix) {
364         boolean shouldAddNote = true;
365         
366         if (prefix.equals(VendorConstants.VendorCreateAndUpdateNotePrefixes.CHANGE)) {
367             // Check whether the previous note was an "Add" with the same document number as this one
368             if (!notes.isEmpty()) {
369                 Note previousNote = notes.get(notes.size() - 1 );
370                 if (previousNote.getNoteText().contains(getDocumentNumber())) {
371                     shouldAddNote = false;
372                 }
373             }
374         }
375         if (shouldAddNote) {
376             notes.add(getNewBoNoteForAdding(prefix));
377         }
378     }
379 
380     /**
381      * creates a new bo note and sets the timestamp.
382      * 
383      * @return a newly created note
384      */
385     protected Note getNewBoNoteForAdding(String prefix) {
386         Note newBoNote = new Note();
387         newBoNote.setNoteText(prefix + " vendor document ID " + getDocumentNumber());
388         newBoNote.setNotePostedTimestampToCurrent();
389        
390             try {
391             newBoNote = SpringContext.getBean(NoteService.class).createNote(newBoNote, this.getBusinessObject(), GlobalVariables.getUserSession().getPrincipalId());
392             }
393             catch (Exception e) {
394                 throw new RuntimeException("Caught Exception While Trying To Add Note to Vendor", e);
395             }
396         
397         return newBoNote;
398     }
399 
400     /**
401      * Concatenates the vendorLastName and a delimiter and the vendorFirstName fields into vendorName field of the vendorDetail
402      * object.
403      * 
404      * @param vendorDetail VendorDetail The vendor whose name field we are trying to assign
405      */
406     private void setVendorName(VendorDetail vendorDetail) {
407         if (vendorDetail.isVendorFirstLastNameIndicator()) {
408             vendorDetail.setVendorName(vendorDetail.getVendorLastName() + VendorConstants.NAME_DELIM + vendorDetail.getVendorFirstName());
409         }
410     }
411 
412     /**
413      * If the vendorFirstLastNameIndicator is true, this method will set the vendor first name and vendor last name fields from the
414      * vendorName field, then set the vendorName field to null. Then it sets the businessObject of this maintainable to the
415      * VendorDetail object that contains our modification to the name fields.
416      * 
417      * @see org.kuali.rice.kns.maintenance.Maintainable#saveBusinessObject()
418      */
419     @Override
420     public void setBusinessObject(PersistableBusinessObject bo) {
421         VendorDetail originalBo = (VendorDetail) bo;
422         
423         String vendorName = originalBo.getVendorName();
424         if (originalBo.isVendorFirstLastNameIndicator() && ObjectUtils.isNotNull(vendorName)) {
425             int start = vendorName.indexOf(VendorConstants.NAME_DELIM);
426             if (start >= 0) {
427                 String lastName = vendorName.substring(0, start);
428                 String firstName = new String();
429                 if (start + VendorConstants.NAME_DELIM.length() <= vendorName.length()) {
430                     firstName = vendorName.substring(start + VendorConstants.NAME_DELIM.length(), vendorName.length());
431                 }
432 
433                 originalBo.setVendorFirstName((ObjectUtils.isNotNull(firstName) ? firstName.trim() : firstName));
434                 originalBo.setVendorLastName((ObjectUtils.isNotNull(lastName) ? lastName.trim() : lastName));
435                 originalBo.setVendorName(null);
436             }
437         }
438         
439         super.setBusinessObject(originalBo);
440     }
441 
442     /**
443      * Sets a valid detail assigned id to a vendor if the vendor has not had a detail assigned id yet. If this is a new parent whose
444      * header id is also null, this method will assign 0 as the detail assigned id. If this is a new division vendor, it will look
445      * for the count of vendor details in the database whose vendor header id match with the vendor header id of this new division,
446      * then look for the count of vendor details in the database, in a while loop, to find if a vendor detail with the same header
447      * id and detail id as the count has existed. If a vendor with such criteria exists, this method will increment the count
448      * by 1 and look up in the database again. If it does not exist, assign the count as the vendor detail id and change the
449      * boolean flag to stop the loop, because we have already found the valid detail assigned id that we were looking for
450      * 
451      * @param vendorDetail VendorDetail The vendor whose detail assigned id we're trying to assign.
452      */
453     private void setDetailAssignedId(VendorDetail vendorDetail) {
454         // If this is a new parent, let's set the detail id to 0.
455         if (ObjectUtils.isNull(vendorDetail.getVendorHeaderGeneratedIdentifier())) {
456             vendorDetail.setVendorDetailAssignedIdentifier(new Integer(0));
457         }
458         else {
459             // Try to get the count of all the vendor whose header id is the same as this header id.
460             Map criterias = new HashMap();
461             criterias.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID, vendorDetail.getVendorHeaderGeneratedIdentifier());
462             BusinessObjectService boService = SpringContext.getBean(BusinessObjectService.class);
463             int count = boService.countMatching(VendorDetail.class, criterias);
464             boolean validId = false;
465             while (!validId) {
466                 criterias.put(VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, count);
467                 int result = boService.countMatching(VendorDetail.class, criterias);
468                 if (result > 0) {
469                     // increment the detail id by 1
470                     count++;
471                 }
472                 else {
473                     // count is a validId, so we'll use count as our vendor detail assigned id
474                     validId = true;
475                     vendorDetail.setVendorDetailAssignedIdentifier(new Integer(count));
476                 }
477             }
478         }
479     }
480 
481     /**
482      * Returns the locking representation of the vendor. If the vendor detail id is not null, call the super class
483      * implementation of generateMaintenanceLocks which will set the locking key to be the header and detail ids. However, if the
484      * detail id is null, that means this is a new vendor (parent or division) and we should ignore locking.
485      * 
486      * @see org.kuali.rice.kns.maintenance.Maintainable#generateMaintenanceLocks()
487      */
488     @Override
489     public List<MaintenanceLock> generateMaintenanceLocks() {
490         if (ObjectUtils.isNotNull(((VendorDetail) getBusinessObject()).getVendorDetailAssignedIdentifier())) {
491             return super.generateMaintenanceLocks();
492         }
493         else {
494             return new ArrayList();
495         }
496     }
497 
498     /**
499      * Create a new division vendor if the user clicks on the "Create a new division" link. By default, the vendorParentIndicator is
500      * set to true in the constructor of VendorDetail, but if we're creating a new division, it's not a parent, so we need to set
501      * the vendorParentIndicator to false in this case.
502      * 
503      * @see org.kuali.rice.kns.maintenance.Maintainable#setupNewFromExisting()
504      */
505     @Override
506     public void setupNewFromExisting( MaintenanceDocument document, Map<String,String[]> parameters ) {
507         super.setupNewFromExisting(document, parameters);
508         
509         ((VendorDetail) super.getBusinessObject()).setVendorParentIndicator(false);
510         ((VendorDetail) super.getBusinessObject()).setActiveIndicator(true);
511 
512         List<Note> notes = new ArrayList<Note>();
513 
514         if (getBusinessObject().getObjectId() != null) {
515             NoteService noteService = KRADServiceLocator.getNoteService();
516             notes = noteService.getByRemoteObjectId(this.getBusinessObject().getObjectId());
517         }
518         
519         setVendorCreateAndUpdateNote(notes, VendorConstants.VendorCreateAndUpdateNotePrefixes.ADD);
520 
521         document.setNotes(notes);
522     }
523 
524     /**
525      * @see org.kuali.rice.kns.maintenance.KualiMaintainableImpl#isRelationshipRefreshable(java.lang.Class, java.lang.String)
526      */
527     @Override
528     protected boolean isRelationshipRefreshable(Class boClass, String relationshipName) {
529         if (VendorDetail.class.isAssignableFrom(boClass) && VendorConstants.VENDOR_HEADER_ATTR.equals(relationshipName)) {
530             return false;
531         }
532         return super.isRelationshipRefreshable(boClass, relationshipName);
533     }
534 
535     /**
536      * @see org.kuali.ole.sys.document.FinancialSystemMaintainable#answerSplitNodeQuestion(java.lang.String)
537      */
538     @Override
539     protected boolean answerSplitNodeQuestion(String nodeName) throws UnsupportedOperationException {
540         if (nodeName.equals("RequiresApproval")) return SpringContext.getBean(VendorService.class).shouldVendorRouteForApproval(getDocumentNumber());
541         return super.answerSplitNodeQuestion(nodeName);
542     }
543 }
544