001/*
002 * Copyright 2008 The Kuali Foundation
003 * 
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * 
008 * http://www.opensource.org/licenses/ecl2.php
009 * 
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.ole.module.purap.document.web.struts;
017
018import org.apache.commons.lang.StringUtils;
019import org.apache.log4j.Logger;
020import org.apache.struts.action.ActionForm;
021import org.apache.struts.action.ActionForward;
022import org.apache.struts.action.ActionMapping;
023import org.kuali.ole.module.purap.PurapConstants;
024import org.kuali.ole.module.purap.PurapPropertyConstants;
025import org.kuali.ole.module.purap.document.BulkReceivingDocument;
026import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
027import org.kuali.ole.module.purap.document.service.BulkReceivingService;
028import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
029import org.kuali.ole.sys.OLEConstants;
030import org.kuali.ole.sys.OLEPropertyConstants;
031import org.kuali.ole.sys.context.SpringContext;
032import org.kuali.ole.vnd.VendorConstants;
033import org.kuali.ole.vnd.businessobject.VendorAddress;
034import org.kuali.ole.vnd.document.service.VendorService;
035import org.kuali.ole.vnd.service.PhoneNumberService;
036import org.kuali.rice.kew.api.KewApiConstants;
037import org.kuali.rice.kew.api.exception.WorkflowException;
038import org.kuali.rice.kim.api.KimConstants;
039import org.kuali.rice.kns.document.authorization.DocumentAuthorizer;
040import org.kuali.rice.kns.question.ConfirmationQuestion;
041import org.kuali.rice.kns.service.DataDictionaryService;
042import org.kuali.rice.kns.service.DocumentHelperService;
043import org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase;
044import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
045import org.kuali.rice.krad.document.Document;
046import org.kuali.rice.krad.service.BusinessObjectService;
047import org.kuali.rice.krad.util.GlobalVariables;
048import org.kuali.rice.krad.util.KRADConstants;
049import org.kuali.rice.krad.util.ObjectUtils;
050
051import javax.servlet.ServletOutputStream;
052import javax.servlet.http.HttpServletRequest;
053import javax.servlet.http.HttpServletResponse;
054import java.io.ByteArrayOutputStream;
055import java.util.HashMap;
056import java.util.Map;
057
058public class BulkReceivingAction extends KualiTransactionalDocumentActionBase {
059    protected static final Logger LOG = Logger.getLogger(BulkReceivingAction.class);
060
061    protected void createDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
062        super.createDocument(kualiDocumentFormBase);
063        BulkReceivingForm blkForm = (BulkReceivingForm) kualiDocumentFormBase;
064        BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkForm.getDocument();
065
066        blkRecDoc.setPurchaseOrderIdentifier(blkForm.getPurchaseOrderId());
067
068        blkRecDoc.initiateDocument();
069    }
070
071    public ActionForward continueBulkReceiving(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
072        BulkReceivingForm blkForm = (BulkReceivingForm) form;
073        BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkForm.getDocument();
074
075        PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(blkRecDoc.getPurchaseOrderIdentifier());
076        if (ObjectUtils.isNotNull(po)) {
077            // TODO figure out a more straightforward way to do this. ailish put this in so the link id would be set and the perm
078            // check would work
079            blkRecDoc.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
080
081            // TODO hjs-check to see if user is allowed to initiate doc based on PO sensitive data (add this to all other docs
082            // except acm doc)
083            if (!SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(blkRecDoc).isAuthorizedByTemplate(blkRecDoc, KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_DOCUMENT, GlobalVariables.getUserSession().getPrincipalId())) {
084                throw buildAuthorizationException("initiate document", blkRecDoc);
085            }
086        }
087
088        // perform duplicate check
089        ActionForward forward = isDuplicateDocumentEntry(mapping, form, request, response, blkRecDoc);
090        if (forward != null) {
091            return forward;
092        }
093
094        // populate and save bulk Receiving Document from Purchase Order
095        SpringContext.getBean(BulkReceivingService.class).populateAndSaveBulkReceivingDocument(blkRecDoc);
096
097        return mapping.findForward(OLEConstants.MAPPING_BASIC);
098    }
099
100    public ActionForward clearInitFields(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
101        BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
102        BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkRecForm.getDocument();
103
104        blkRecDoc.clearInitFields();
105
106        return mapping.findForward(OLEConstants.MAPPING_BASIC);
107    }
108
109    protected ActionForward isDuplicateDocumentEntry(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, BulkReceivingDocument bulkReceivingDocument) throws Exception {
110        ActionForward forward = null;
111        HashMap<String, String> duplicateMessages = SpringContext.getBean(BulkReceivingService.class).bulkReceivingDuplicateMessages(bulkReceivingDocument);
112
113        if (duplicateMessages != null && !duplicateMessages.isEmpty()) {
114            Object question = request.getParameter(OLEConstants.QUESTION_INST_ATTRIBUTE_NAME);
115            if (question == null) {
116
117                return this.performQuestionWithoutInput(mapping, form, request, response, PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION, duplicateMessages.get(PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION), OLEConstants.CONFIRMATION_QUESTION, OLEConstants.ROUTE_METHOD, "");
118            }
119
120            Object buttonClicked = request.getParameter(OLEConstants.QUESTION_CLICKED_BUTTON);
121            if ((PurapConstants.BulkReceivingDocumentStrings.DUPLICATE_BULK_RECEIVING_DOCUMENT_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
122                forward = mapping.findForward(OLEConstants.MAPPING_BASIC);
123            }
124        }
125
126        return forward;
127    }
128
129    public ActionForward printReceivingTicket(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
130        String blkDocId = request.getParameter("docId");
131        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
132
133        try {
134            // will throw validation exception if errors occur
135            SpringContext.getBean(BulkReceivingService.class).performPrintReceivingTicketPDF(blkDocId, baosPDF);
136
137            response.setHeader("Cache-Control", "max-age=30");
138            response.setContentType("application/pdf");
139            StringBuffer sbContentDispValue = new StringBuffer();
140            String useJavascript = request.getParameter("useJavascript");
141            if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
142                sbContentDispValue.append("attachment");
143            } else {
144                sbContentDispValue.append("inline");
145            }
146            StringBuffer sbFilename = new StringBuffer();
147            sbFilename.append("PURAP_RECEIVING_TICKET_");
148            sbFilename.append(blkDocId);
149            sbFilename.append("_");
150            sbFilename.append(System.currentTimeMillis());
151            sbFilename.append(".pdf");
152            sbContentDispValue.append("; filename=");
153            sbContentDispValue.append(sbFilename);
154
155            response.setHeader("Content-disposition", sbContentDispValue.toString());
156
157            response.setContentLength(baosPDF.size());
158
159            ServletOutputStream sos = response.getOutputStream();
160            baosPDF.writeTo(sos);
161            sos.flush();
162
163        } finally {
164            if (baosPDF != null) {
165                baosPDF.reset();
166            }
167        }
168
169        return null;
170    }
171
172    public ActionForward printReceivingTicketPDF(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
173        BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
174        BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkRecForm.getDocument();
175
176        String basePath = getApplicationBaseUrl();
177        String docId = blkRecDoc.getDocumentNumber();
178        String methodToCallPrintPurchaseOrderPDF = "printReceivingTicket";
179        String methodToCallDocHandler = "docHandler";
180        String printReceivingTicketPDFUrl = getUrlForPrintReceivingTicket(basePath, docId, methodToCallPrintPurchaseOrderPDF);
181        String displayReceivingDocTabbedPageUrl = getUrlForPrintReceivingTicket(basePath, docId, methodToCallDocHandler);
182        request.setAttribute("printReceivingTicketPDFUrl", printReceivingTicketPDFUrl);
183        request.setAttribute("displayReceivingDocTabbedPageUrl", displayReceivingDocTabbedPageUrl);
184        String label = SpringContext.getBean(DataDictionaryService.class).getDocumentLabelByTypeName(OLEConstants.FinancialDocumentTypeCodes.BULK_RECEIVING);
185        request.setAttribute("receivingDocLabel", label);
186
187        return mapping.findForward("printReceivingTicketPDF");
188    }
189
190    protected String getUrlForPrintReceivingTicket(String basePath, String docId, String methodToCall) {
191
192        StringBuffer result = new StringBuffer(basePath);
193        result.append("/purapBulkReceiving.do?methodToCall=");
194        result.append(methodToCall);
195        result.append("&docId=");
196        result.append(docId);
197        result.append("&command=displayDocSearchView");
198
199        return result.toString();
200    }
201
202    @Override
203    public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
204        BulkReceivingForm blkRecForm = (BulkReceivingForm) form;
205
206        BulkReceivingDocument blkRecDoc = (BulkReceivingDocument) blkRecForm.getDocument();
207        String refreshCaller = blkRecForm.getRefreshCaller();
208        PhoneNumberService phoneNumberService = SpringContext.getBean(PhoneNumberService.class);
209
210        // Format phone numbers
211        blkRecDoc.setInstitutionContactPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getInstitutionContactPhoneNumber()));
212        blkRecDoc.setRequestorPersonPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getRequestorPersonPhoneNumber()));
213        blkRecDoc.setDeliveryToPhoneNumber(phoneNumberService.formatNumberIfPossible(blkRecDoc.getDeliveryToPhoneNumber()));
214
215        // Refreshing the fields after returning from a vendor lookup in the vendor tab
216        if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_LOOKUPABLE_IMPL) && blkRecDoc.getVendorDetailAssignedIdentifier() != null && blkRecDoc.getVendorHeaderGeneratedIdentifier() != null) {
217
218            // retrieve vendor based on selection from vendor lookup
219            blkRecDoc.refreshReferenceObject("vendorDetail");
220            blkRecDoc.setVendorName(blkRecDoc.getVendorDetail().getVendorName());
221
222            // populate default address based on selected vendor
223            VendorAddress defaultAddress = SpringContext.getBean(VendorService.class).getVendorDefaultAddress(blkRecDoc.getVendorDetail().getVendorAddresses(), blkRecDoc.getVendorDetail().getVendorHeader().getVendorType().getAddressType().getVendorAddressTypeCode(), "");
224            if (ObjectUtils.isNotNull(defaultAddress)) {
225                blkRecDoc.setVendorLine1Address(defaultAddress.getVendorLine1Address());
226                blkRecDoc.setVendorLine2Address(defaultAddress.getVendorLine2Address());
227                blkRecDoc.setVendorCityName(defaultAddress.getVendorCityName());
228                blkRecDoc.setVendorStateCode(defaultAddress.getVendorStateCode());
229                blkRecDoc.setVendorPostalCode(defaultAddress.getVendorZipCode());
230                blkRecDoc.setVendorCountryCode(defaultAddress.getVendorCountryCode());
231            }
232        }
233
234        // Refreshing the fields after returning from an address lookup in the vendor tab
235        if (StringUtils.equals(refreshCaller, VendorConstants.VENDOR_ADDRESS_LOOKUPABLE_IMPL)) {
236            if (StringUtils.isNotEmpty(request.getParameter(OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.VENDOR_ADDRESS_ID))) {
237                // retrieve address based on selection from address lookup
238                VendorAddress refreshVendorAddress = new VendorAddress();
239                refreshVendorAddress.setVendorAddressGeneratedIdentifier(blkRecDoc.getVendorAddressGeneratedIdentifier());
240                refreshVendorAddress = (VendorAddress) SpringContext.getBean(BusinessObjectService.class).retrieve(refreshVendorAddress);
241                if (ObjectUtils.isNotNull(refreshVendorAddress)) {
242                    blkRecDoc.setVendorLine1Address(refreshVendorAddress.getVendorLine1Address());
243                    blkRecDoc.setVendorLine2Address(refreshVendorAddress.getVendorLine2Address());
244                    blkRecDoc.setVendorCityName(refreshVendorAddress.getVendorCityName());
245                    blkRecDoc.setVendorStateCode(refreshVendorAddress.getVendorStateCode());
246                    blkRecDoc.setVendorPostalCode(refreshVendorAddress.getVendorZipCode());
247                    blkRecDoc.setVendorCountryCode(refreshVendorAddress.getVendorCountryCode());
248                }
249            }
250        }
251
252        // Refreshing corresponding fields after returning from various kuali lookups
253        if (StringUtils.equals(refreshCaller, OLEConstants.KUALI_LOOKUPABLE_IMPL)) {
254            if (request.getParameter("document.deliveryCampusCode") != null) {
255                // returning from a building or campus lookup on the delivery tab
256
257                if (request.getParameter("document.deliveryBuildingName") == null) {
258                    // came from campus lookup not building, so clear building
259                    blkRecDoc.setDeliveryBuildingCode("");
260                    blkRecDoc.setDeliveryBuildingLine1Address("");
261                    blkRecDoc.setDeliveryBuildingLine2Address("");
262                    blkRecDoc.setDeliveryBuildingRoomNumber("");
263                    blkRecDoc.setDeliveryCityName("");
264                    blkRecDoc.setDeliveryStateCode("");
265                    blkRecDoc.setDeliveryPostalCode("");
266                    blkRecDoc.setDeliveryCountryCode("");
267                } else {
268                    // came from building lookup then turn off "OTHER" and clear room and line2address
269                    blkRecDoc.setDeliveryBuildingOtherIndicator(false);
270                    blkRecDoc.setDeliveryBuildingRoomNumber("");
271                    blkRecDoc.setDeliveryBuildingLine2Address("");
272                }
273            }
274        }
275
276        return super.refresh(mapping, form, request, response);
277    }
278
279    /**
280     * Setup document to use "OTHER" building
281     *
282     * @param mapping  An ActionMapping
283     * @param form     An ActionForm
284     * @param request  A HttpServletRequest
285     * @param response A HttpServletResponse
286     * @return An ActionForward
287     * @throws Exception
288     */
289    public ActionForward useOtherDeliveryBuilding(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
290        BulkReceivingForm baseForm = (BulkReceivingForm) form;
291        BulkReceivingDocument document = (BulkReceivingDocument) baseForm.getDocument();
292
293        document.setDeliveryBuildingOtherIndicator(true);
294        document.setDeliveryBuildingName("");
295        document.setDeliveryBuildingCode("");
296        document.setDeliveryBuildingLine1Address("");
297        document.setDeliveryBuildingLine2Address("");
298        document.setDeliveryBuildingRoomNumber("");
299        document.setDeliveryCityName("");
300        document.setDeliveryStateCode("");
301        document.setDeliveryCountryCode("");
302        document.setDeliveryPostalCode("");
303
304        return mapping.findForward(OLEConstants.MAPPING_BASIC);
305    }
306
307    @Override
308    protected void populateAdHocActionRequestCodes(KualiDocumentFormBase formBase) {
309        Document document = formBase.getDocument();
310        DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
311        Map<String, String> adHocActionRequestCodes = new HashMap<String, String>();
312
313        if (documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_FYI_REQ, GlobalVariables.getUserSession().getPerson())) {
314            adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_FYI_REQ, KewApiConstants.ACTION_REQUEST_FYI_REQ_LABEL);
315        }
316        if ((document.getDocumentHeader().getWorkflowDocument().isInitiated()
317                || document.getDocumentHeader().getWorkflowDocument().isSaved()
318                || document.getDocumentHeader().getWorkflowDocument().isEnroute()
319        ) && documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, GlobalVariables.getUserSession().getPerson())) {
320            adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL);
321        }
322        formBase.setAdHocActionRequestCodes(adHocActionRequestCodes);
323
324    }
325
326}