View Javadoc
1   /*
2    * The Kuali Financial System, a comprehensive financial management system for higher education.
3    * 
4    * Copyright 2005-2014 The Kuali Foundation
5    * 
6    * This program is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU Affero General Public License as
8    * published by the Free Software Foundation, either version 3 of the
9    * License, or (at your option) any later version.
10   * 
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU Affero General Public License for more details.
15   * 
16   * You should have received a copy of the GNU Affero General Public License
17   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  package org.kuali.kfs.module.purap.document.service.impl;
20  
21  import java.io.ByteArrayOutputStream;
22  import java.text.MessageFormat;
23  import java.util.Collection;
24  import java.util.HashMap;
25  import java.util.List;
26  
27  import org.apache.commons.lang.StringUtils;
28  import org.apache.log4j.Logger;
29  import org.kuali.kfs.module.purap.PurapConstants;
30  import org.kuali.kfs.module.purap.PurapKeyConstants;
31  import org.kuali.kfs.module.purap.document.BulkReceivingDocument;
32  import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
33  import org.kuali.kfs.module.purap.document.dataaccess.BulkReceivingDao;
34  import org.kuali.kfs.module.purap.document.service.BulkReceivingService;
35  import org.kuali.kfs.module.purap.document.service.PrintService;
36  import org.kuali.kfs.module.purap.document.service.PurchaseOrderService;
37  import org.kuali.kfs.module.purap.document.validation.event.AttributedContinuePurapEvent;
38  import org.kuali.kfs.sys.KFSConstants;
39  import org.kuali.kfs.sys.KFSPropertyConstants;
40  import org.kuali.rice.core.api.config.property.ConfigurationService;
41  import org.kuali.rice.kew.api.WorkflowDocument;
42  import org.kuali.rice.kew.api.exception.WorkflowException;
43  import org.kuali.rice.krad.exception.ValidationException;
44  import org.kuali.rice.krad.service.DocumentService;
45  import org.kuali.rice.krad.util.GlobalVariables;
46  import org.kuali.rice.krad.util.ObjectUtils;
47  import org.kuali.rice.krad.workflow.service.WorkflowDocumentService;
48  import org.springframework.transaction.annotation.Transactional;
49  
50  @Transactional
51  public class BulkReceivingServiceImpl implements BulkReceivingService {
52  
53      private static final Logger LOG = Logger.getLogger(BulkReceivingServiceImpl.class);
54      
55      protected PurchaseOrderService purchaseOrderService;
56      protected BulkReceivingDao bulkReceivingDao;
57      protected DocumentService documentService;
58      protected WorkflowDocumentService workflowDocumentService;
59      protected ConfigurationService configurationService;    
60      protected PrintService printService;
61      
62      public boolean canPrintReceivingTicket(BulkReceivingDocument blkRecDoc) {
63  
64          boolean canCreate = false;
65          WorkflowDocument workflowDocument = null;
66          
67          try{
68              workflowDocument = workflowDocumentService.createWorkflowDocument(blkRecDoc.getDocumentHeader().getWorkflowDocument().getDocumentTypeName(), GlobalVariables.getUserSession().getPerson());
69          }catch(WorkflowException we){
70              throw new RuntimeException(we);
71          }
72  
73          if( workflowDocument.isFinal()){            
74              canCreate = true;
75          }
76          
77          return canCreate;
78      }
79      
80      public void populateAndSaveBulkReceivingDocument(BulkReceivingDocument blkRecDoc) 
81      throws WorkflowException {
82          try {            
83              documentService.saveDocument(blkRecDoc, AttributedContinuePurapEvent.class);
84          }
85          catch (WorkflowException we) {
86              String errorMsg = "Error saving document # " + blkRecDoc.getDocumentHeader().getDocumentNumber() + " " + we.getMessage();
87              throw new RuntimeException(errorMsg, we);
88          }
89      }
90      
91      public HashMap<String, String> bulkReceivingDuplicateMessages(BulkReceivingDocument blkRecDoc) {
92          HashMap<String, String> msgs;
93          msgs = new HashMap<String, String>();
94          Integer poId = blkRecDoc.getPurchaseOrderIdentifier();
95          StringBuffer currentMessage = new StringBuffer("");
96          List<String> docNumbers = null;
97          
98          //check vendor date for duplicates
99          if( blkRecDoc.getShipmentReceivedDate() != null ){
100             docNumbers = bulkReceivingDao.duplicateVendorDate(poId, blkRecDoc.getShipmentReceivedDate());
101             if( hasDuplicateEntry(docNumbers) ){
102                 appendDuplicateMessage(currentMessage, PurapKeyConstants.MESSAGE_DUPLICATE_RECEIVING_LINE_VENDOR_DATE, blkRecDoc.getPurchaseOrderIdentifier());                                
103             }
104         }
105         
106         //check packing slip number for duplicates
107         if( !StringUtils.isEmpty(blkRecDoc.getShipmentPackingSlipNumber()) ){
108             docNumbers = bulkReceivingDao.duplicatePackingSlipNumber(poId, blkRecDoc.getShipmentPackingSlipNumber());
109             if( hasDuplicateEntry(docNumbers) ){
110                 appendDuplicateMessage(currentMessage, PurapKeyConstants.MESSAGE_DUPLICATE_RECEIVING_LINE_PACKING_SLIP_NUMBER, blkRecDoc.getPurchaseOrderIdentifier());                                
111             }
112         }
113         
114         //check bill of lading number for duplicates
115         if( !StringUtils.isEmpty(blkRecDoc.getShipmentBillOfLadingNumber()) ){
116             docNumbers = bulkReceivingDao.duplicateBillOfLadingNumber(poId, blkRecDoc.getShipmentBillOfLadingNumber());
117             if( hasDuplicateEntry(docNumbers) ){
118                 appendDuplicateMessage(currentMessage, PurapKeyConstants.MESSAGE_DUPLICATE_RECEIVING_LINE_BILL_OF_LADING_NUMBER, blkRecDoc.getPurchaseOrderIdentifier());                
119             }
120         }
121         
122        //add message if one exists
123        if(currentMessage.length() > 0){
124            //add suffix
125            appendDuplicateMessage(currentMessage, PurapKeyConstants.MESSAGE_DUPLICATE_RECEIVING_LINE_SUFFIX, blkRecDoc.getPurchaseOrderIdentifier() );
126            
127            //add msg to map
128            msgs.put(PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION, currentMessage.toString());
129        }
130        
131        return msgs;
132     }
133 
134     /**
135      * Looks at a list of doc numbers, but only considers an entry duplicate
136      * if the document is in a Final status.
137      * 
138      * @param docNumbers
139      * @return
140      */
141     protected boolean hasDuplicateEntry(List<String> docNumbers){
142         
143         boolean isDuplicate = false;
144         WorkflowDocument workflowDocument = null;
145         
146         for (String docNumber : docNumbers) {
147         
148             try{
149                 workflowDocument = workflowDocumentService.loadWorkflowDocument(docNumber, GlobalVariables.getUserSession().getPerson());
150             }catch(WorkflowException we){
151                 throw new RuntimeException(we);
152             }
153             
154             //if the doc number exists, and is in final status, consider this a dupe and return
155             if(workflowDocument.isFinal()){
156                 isDuplicate = true;
157                 break;
158             }
159         }
160         
161         return isDuplicate;
162 
163     }
164     
165     protected void appendDuplicateMessage(StringBuffer currentMessage, 
166                                         String duplicateMessageKey, 
167                                         Integer poId){
168         
169         //append prefix if this is first call
170         if(currentMessage.length() == 0){
171             String messageText = configurationService.getPropertyValueAsString(PurapKeyConstants.MESSAGE_BULK_RECEIVING_DUPLICATE_PREFIX);
172             String prefix = MessageFormat.format(messageText, poId.toString() );
173             
174             currentMessage.append(prefix);
175         }
176         
177         //append message
178         currentMessage.append( configurationService.getPropertyValueAsString(duplicateMessageKey) );                
179     }
180     
181     public String getBulkReceivingDocumentNumberInProcessForPurchaseOrder(Integer poId, 
182                                                                           String bulkReceivingDocumentNumber){
183         
184         String docNumberInProcess = StringUtils.EMPTY;
185         
186         List<String> docNumbers = bulkReceivingDao.getDocumentNumbersByPurchaseOrderId(poId);
187         WorkflowDocument workflowDocument = null;
188                 
189         for (String docNumber : docNumbers) {
190         
191             try{
192                 workflowDocument = workflowDocumentService.loadWorkflowDocument(docNumber, 
193                                                                                   GlobalVariables.getUserSession().getPerson());
194             }catch(WorkflowException we){
195                 throw new RuntimeException(we);
196             }
197             
198             if(!(workflowDocument.isCanceled() ||
199                  workflowDocument.isException() ||
200                  workflowDocument.isFinal()) &&
201                  !docNumber.equals(bulkReceivingDocumentNumber)){
202                      
203                 docNumberInProcess = docNumber;
204                 break;
205             }
206         }
207 
208         return docNumberInProcess;
209     }
210 
211     public void populateBulkReceivingFromPurchaseOrder(BulkReceivingDocument blkRecDoc) {
212         
213         if (blkRecDoc != null){
214             PurchaseOrderDocument poDoc = purchaseOrderService.getCurrentPurchaseOrder(blkRecDoc.getPurchaseOrderIdentifier());
215             if(poDoc != null){
216                 blkRecDoc.populateBulkReceivingFromPurchaseOrder(poDoc);
217             }
218         }
219         
220     }
221 
222     public BulkReceivingDocument getBulkReceivingByDocumentNumber(String documentNumber){
223         
224         if (ObjectUtils.isNotNull(documentNumber)) {
225             try {
226                 BulkReceivingDocument doc = (BulkReceivingDocument) documentService.getByDocumentHeaderId(documentNumber);
227                 if (ObjectUtils.isNotNull(doc)) {
228                     WorkflowDocument workflowDocument = doc.getDocumentHeader().getWorkflowDocument();
229                     doc.refreshReferenceObject(KFSPropertyConstants.DOCUMENT_HEADER);
230                     doc.getDocumentHeader().setWorkflowDocument(workflowDocument);
231                 }
232                 return doc;
233             }
234             catch (WorkflowException e) {
235                 String errorMessage = "Error getting bulk receiving document from document service";
236                 throw new RuntimeException(errorMessage, e);
237             }
238         }
239         return null;
240     }
241     
242     public void performPrintReceivingTicketPDF(String blkDocId, 
243                                                ByteArrayOutputStream baosPDF){
244         
245         BulkReceivingDocument blkRecDoc = getBulkReceivingByDocumentNumber(blkDocId);
246         Collection<String> generatePDFErrors = printService.generateBulkReceivingPDF(blkRecDoc, baosPDF);
247         
248         if (!generatePDFErrors.isEmpty()) {
249             addStringErrorMessagesToMessageMap(PurapKeyConstants.ERROR_BULK_RECEIVING_PDF, generatePDFErrors);
250             throw new ValidationException("printing bulk receiving ticket failed");
251         }
252         
253     }
254     
255     protected void addStringErrorMessagesToMessageMap(String errorKey, 
256                                                   Collection<String> errors) {
257         
258         if (ObjectUtils.isNotNull(errors)) {
259             for (String error : errors) {
260                 LOG.error("Adding error message using error key '" + errorKey + "' with text '" + error + "'");
261                 GlobalVariables.getMessageMap().putError(KFSConstants.GLOBAL_ERRORS, errorKey, error);
262             }
263         }
264         
265     }
266 
267     public void setPrintService(PrintService printService) {
268         this.printService = printService;
269     }
270     
271     public void setPurchaseOrderService(PurchaseOrderService purchaseOrderService) {
272         this.purchaseOrderService = purchaseOrderService;
273     }
274 
275     public void setBulkReceivingDao(BulkReceivingDao bulkReceivingDao) {
276         this.bulkReceivingDao = bulkReceivingDao;
277     }
278 
279     public void setDocumentService(DocumentService documentService){
280         this.documentService = documentService;
281     }
282 
283     public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService){
284         this.workflowDocumentService = workflowDocumentService;
285     }
286 
287     public void setConfigurationService(ConfigurationService configurationService) {
288         this.configurationService = configurationService;
289     }
290 }
291