001package org.kuali.ole.select.service.impl;
002
003import org.kuali.ole.module.purap.PurapConstants.LicenseRequestStatus;
004import org.kuali.ole.select.businessobject.OleRequisitionItem;
005import org.kuali.ole.select.document.OleRequisitionDocument;
006import org.kuali.ole.select.service.OleRequisitionWebService;
007import org.kuali.ole.sys.OLEConstants;
008import org.kuali.ole.sys.OLEKeyConstants;
009import org.kuali.ole.sys.context.SpringContext;
010import org.kuali.rice.core.api.datetime.DateTimeService;
011import org.kuali.rice.kew.actionitem.ActionItem;
012import org.kuali.rice.kew.actionlist.service.ActionListService;
013import org.kuali.rice.kew.actionrequest.ActionRequestValue;
014import org.kuali.rice.kew.actionrequest.service.ActionRequestService;
015import org.kuali.rice.kew.api.WorkflowDocument;
016import org.kuali.rice.kew.api.action.ActionRequestType;
017import org.kuali.rice.kew.api.document.DocumentStatus;
018import org.kuali.rice.kew.api.exception.WorkflowException;
019import org.kuali.rice.kew.service.KEWServiceLocator;
020import org.kuali.rice.kim.api.identity.Person;
021import org.kuali.rice.kim.api.services.KimApiServiceLocator;
022import org.kuali.rice.krad.service.DocumentService;
023import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
024import org.kuali.rice.krad.util.GlobalVariables;
025
026import java.sql.Timestamp;
027import java.util.ArrayList;
028import java.util.List;
029import java.util.Set;
030//import org.kuali.rice.kew.routeheader.service.WorkflowDocumentService;
031
032/**
033 * Created by IntelliJ IDEA.
034 * User: pvsubrah
035 * Date: 5/9/12
036 * Time: 2:35 PM
037 * To change this template use File | Settings | File Templates.
038 */
039public class OleRequisitionWebServiceImpl implements OleRequisitionWebService {
040    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleRequisitionWebServiceImpl.class);
041    private DocumentService documentService;
042    public List<OleRequisitionItem> requisitionItems = new ArrayList<OleRequisitionItem>();
043
044    @Override
045    public void updateRequisitionStatus(String documentNumber, String reqStatus) {
046        try {
047            //  OleRequisitionDocument requisitionDocument = (OleRequisitionDocument)
048            //  SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(documentNumber);
049            // String status = PurapConstants.RequisitionStatuses.DAPRVD_LICENSE;
050            //requisitionDocument.setLicensingRequirementCode(reqStatus);
051            // requisitionDocument.updateStatusAndSave(status);
052        /*  //  @SuppressWarnings("restriction")
053          //  String currentNodeName = getCurrentRouteNodeName(doc.getDocumentHeader().getWorkflowDocument());
054         //   System.out.println("currentNodeName >>>>>>>>>" + currentNodeName);
055           // String currentUser = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
056           // System.out.println("11111111111 >>>>>>>>>" + GlobalVariables.getUserSession().getPrincipalName());
057         //   System.out.println("@@@@@@@@@@@@@@@@@@ >>>>>>>>>" + GlobalVariables.getUserSession().getPrincipalName());
058            //GlobalVariables.getUserSession().clearBackdoorUser();
059          //  System.out.println("22222222222222 >>>>>>>>>" + GlobalVariables.getUserSession().getWorkflowDocument(doc.getDocumentHeader().getDocumentNumber()));
060          //  System.out.println("get user name  >>>>>>>>>" +KIMServiceLocator.getPersonService().getPerson(doc.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()).getPrincipalName());
061           // GlobalVariables.getUserSession().setBackdoorUser((KIMServiceLocator.getPersonService().getPerson(doc.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()).getPrincipalName()));
062
063            //GlobalVariables.setUserSession(new UserSession(KIMServiceLocator.getPersonService().getPerson(doc.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()).getPrincipalName()));
064            System.out.println("333333333 >>>>>>>>>" + doc.getDocumentHeader().getWorkflowDocument().isApprovalRequested());
065            System.out.println("@@@@@@@@@@@@@@ >>>>>>>>>" + doc.getDocumentHeader().getWorkflowDocument().isCompletionRequested());
066            System.out.println("@@@@@@@@@@@@@@ >>>>>>>>>" + doc.getDocumentHeader().getWorkflowDocument().isBlanketApproveCapable());
067       //     System.out.println("444444444444444 >>>>>>>>>" + GlobalVariables.getUserSession().getPrincipalName());
068
069           // KNSServiceLocator.getDocumentService().approveDocument(doc, GlobalVariables.getUserSession().getPerson().getName() + "License Request Approved" , null);
070
071
072           // OleRequisitionDocument requisitionDocument = (OleRequisitionDocument) KNSServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleRequisitionDocument.class,requisitionDocumentId);
073            doc.setDocumentHeader(KNSServiceLocator.getDocumentHeaderService().getDocumentHeaderById(documentNumber));
074            Person principalPerson = KIMServiceLocator.getPersonService().getPerson(doc.getDocumentHeader().getWorkflowDocument().getRouteHeader().getInitiatorPrincipalId());
075
076            System.out.println("User is initiator >>>>>>>>>>>>>" + doc.getDocumentHeader().getWorkflowDocument().userIsInitiator(principalPerson));
077            //         KIMServiceLocator.getPersonService().getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
078            try{
079                doc.getDocumentHeader().setWorkflowDocument(KNSServiceLocator.getWorkflowDocumentService().createWorkflowDocument(new Long(documentNumber), principalPerson));
080                KNSServiceLocator.getDocumentService().approveDocument(doc, principalPerson.getName() + OLEConstants.OrderQueue.APPROVE_ANNOTATION + "KR-WKFLW Initiator" , null);
081             //   return true;
082            }catch(WorkflowException wfe) {
083                GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_APPROVE_WFE, new String[]{documentNumber,wfe.getMessage()});
084               // return false;
085            }
086
087
088            //   SpringContext.getBean(DocumentService.class).approveDocument(doc, "Test",null);
089
090            doc.getDocumentHeader().getWorkflowDocument().setClearFutureRequests();
091            // GlobalVariables.getUserSession().clearBackdoorUser();
092            //DocumentRouteStatusChangeDTO documentRouteStatusChangeDTO = new DocumentRouteStatusChangeDTO();
093           // documentRouteStatusChangeDTO.setNewRouteStatus("CLOSED");
094            //CLOSED
095           // GlobalVariables.setUserSession(new UserSession(currentUser));
096
097
098        */
099            //    OleRequisitionDocument requisitionDocument = (OleRequisitionDocument)
100            //          SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(documentNumber);
101
102            //  requisitionDocument.setLicensingRequirementCode(reqStatus);
103            // requisitionDocument.setStatusCode(PurapConstants.RequisitionStatuses.DAPRVD_LICENSE);
104            //   requisitionDocument.updateStatusAndSave(PurapConstants.RequisitionStatuses.DAPRVD_LICENSE);
105            // reqStatus="LRC";
106
107            ActionListService actionListSrv = KEWServiceLocator.getActionListService();
108            ActionRequestService actionReqSrv = KEWServiceLocator.getActionRequestService();
109            OleRequisitionDocument requisitionDocument = (OleRequisitionDocument)
110                    SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(documentNumber);
111            Person person = KimApiServiceLocator.getPersonService().getPerson(requisitionDocument.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
112
113            try {
114                WorkflowDocument workflowDocument = KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(requisitionDocument.getDocumentNumber(), person);
115                if (DocumentStatus.ENROUTE.equals(workflowDocument.getStatus())) {
116                    List<ActionRequestValue> actionReqValues = actionReqSrv.findAllPendingRequests(workflowDocument.getDocumentId());
117                    for (ActionRequestValue actionRequest : actionReqValues) {
118                        if (ActionRequestType.APPROVE.getCode().equals(actionRequest.getActionRequested())) {
119                            Timestamp currentTime = SpringContext.getBean(DateTimeService.class).getCurrentTimestamp();
120                            List<ActionItem> actionItems = actionRequest.getActionItems();
121                            for (ActionItem actionItem : actionItems) {
122                                if (ActionRequestType.APPROVE.getLabel().equals(actionItem.getActionRequestLabel())) {
123                                    actionItem.setPrincipalId(person.getPrincipalId());
124                                    actionItem.setDateAssigned(currentTime);
125                                    actionListSrv.saveActionItem(actionItem);
126                                }
127                            }
128                            actionRequest.setPrincipalId(person.getPrincipalId());
129                            actionRequest.setCreateDate(currentTime);
130                            actionReqSrv.saveActionRequest(actionRequest);
131                            if (reqStatus.equals(LicenseRequestStatus.LICENSE_REQUEST_COMPLETE)) {
132                                boolean documentApproved = approveDocument(requisitionDocument, requisitionDocument.getDocumentNumber(), actionRequest.getAnnotation(), person, reqStatus);
133                            } else if (reqStatus.equals(LicenseRequestStatus.NEGOTIATION_FAILED)) {
134                                boolean documentCanceled = cancelDocument(requisitionDocument, requisitionDocument.getDocumentNumber(), actionRequest.getAnnotation(), person, reqStatus);
135                            }
136                        }
137                    }
138                }
139            } catch (Exception e) {
140                LOG.error("Exception while updateRequisitionStatus"+e.getMessage());
141                throw new RuntimeException(e);
142            }
143        } catch (Exception e) {
144            LOG.error("Exception while updateRequisitionStatus"+e.getMessage());
145            throw new RuntimeException(e);
146        }
147    }
148
149    private boolean approveDocument(OleRequisitionDocument requisitionDocument, String documentNumber, String annotation, Person principalPerson, String reqStatus) {
150        LOG.debug("Inside approveDocument of OleOrderQueueDocument");
151        requisitionDocument.setDocumentHeader(KRADServiceLocatorWeb.getDocumentHeaderService().getDocumentHeaderById(documentNumber));
152        /*requisitionDocument.setLicensingRequirementCode(PurapConstants.LicenseRequestStatus.LICENSE_REQUEST_COMPLETE);*/
153        try {
154            requisitionDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(documentNumber, principalPerson));
155            KRADServiceLocatorWeb.getDocumentService().approveDocument(requisitionDocument, principalPerson.getName() + OLEConstants.LicenseRequest.APPROVE_ANNOTATION + annotation, null);
156            return true;
157        } catch (WorkflowException wfe) {
158            GlobalVariables.getMessageMap().putError(OLEConstants.LicenseRequest.REQUISITIONS, OLEKeyConstants.ERROR_REQUISITION_APPROVE_WFE, new String[]{documentNumber, wfe.getMessage()});
159            return false;
160        }
161    }
162
163    private boolean cancelDocument(OleRequisitionDocument requisitionDocument, String documentNumber, String annotation, Person principalPerson, String reqStatus) {
164        LOG.debug("Inside cancelDocument of OleOrderQueueDocument");
165        requisitionDocument.setDocumentHeader(KRADServiceLocatorWeb.getDocumentHeaderService().getDocumentHeaderById(documentNumber));
166        /*requisitionDocument.setLicensingRequirementCode(PurapConstants.LicenseRequestStatus.NEGOTIATION_FAILED);*/
167        try {
168            requisitionDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(documentNumber, principalPerson));
169            KRADServiceLocatorWeb.getDocumentService().cancelDocument(requisitionDocument, principalPerson.getName() + OLEConstants.LicenseRequest.CANCEL_ANNOTATION + annotation);
170            return true;
171        } catch (WorkflowException wfe) {
172            GlobalVariables.getMessageMap().putError(OLEConstants.LicenseRequest.REQUISITIONS, OLEKeyConstants.ERROR_REQUISITION_CANCELED_WFE, new String[]{documentNumber, wfe.getMessage()});
173            return false;
174        }
175    }
176
177
178    public void setDocumentService(DocumentService documentService) {
179        this.documentService = documentService;
180    }
181
182    protected String getCurrentRouteNodeName(WorkflowDocument wd) throws WorkflowException {
183        Set<String> nodeNames = wd.getCurrentNodeNames();
184        if ((nodeNames == null) || (nodeNames.isEmpty())) {
185            return null;
186        } else {
187            return nodeNames.iterator().next();
188        }
189    }
190
191}