001package org.kuali.ole.describe.controller;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.apache.commons.lang3.StringUtils;
005import org.apache.log4j.Logger;
006import org.apache.solr.client.solrj.SolrServerException;
007import org.kuali.ole.DocumentUniqueIDPrefix;
008import org.kuali.asr.service.ASRHelperServiceImpl;
009import org.kuali.ole.OLEConstants;
010import org.kuali.ole.OLEParameterConstants;
011import org.kuali.ole.deliver.bo.ASRItem;
012import org.kuali.ole.deliver.bo.OLELoanIntransitRecordHistory;
013import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
014import org.kuali.ole.deliver.bo.OleLoanDocument;
015import org.kuali.ole.deliver.calendar.service.DateUtil;
016import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
017import org.kuali.ole.describe.bo.DocumentSelectionTree;
018import org.kuali.ole.describe.bo.DocumentTreeNode;
019import org.kuali.ole.describe.bo.InstanceEditorFormDataHandler;
020import org.kuali.ole.describe.form.EditorForm;
021import org.kuali.ole.describe.form.WorkBibMarcForm;
022import org.kuali.ole.describe.form.WorkInstanceOlemlForm;
023import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
024import org.kuali.ole.docstore.common.client.DocstoreClient;
025import org.kuali.ole.docstore.common.document.*;
026import org.kuali.ole.docstore.common.document.HoldingsTree;
027import org.kuali.ole.docstore.common.document.content.enums.DocCategory;
028import org.kuali.ole.docstore.common.document.content.enums.DocFormat;
029import org.kuali.ole.docstore.common.document.content.enums.DocType;
030import org.kuali.ole.docstore.common.document.content.instance.*;
031import org.kuali.ole.docstore.common.document.content.instance.Item;
032import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
033import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
034import org.kuali.ole.docstore.common.exception.DocstoreException;
035import org.kuali.ole.docstore.engine.client.DocstoreLocalClient;
036import org.kuali.ole.select.bo.OLEDonor;
037import org.kuali.ole.select.bo.OLELinkPurapDonor;
038import org.kuali.ole.select.businessobject.OleCopy;
039import org.kuali.ole.select.document.OlePurchaseOrderDocument;
040import org.kuali.ole.sys.context.SpringContext;
041import org.kuali.ole.utility.Constants;
042import org.kuali.rice.core.api.config.property.ConfigurationService;
043import org.kuali.rice.core.api.datetime.DateTimeService;
044import org.kuali.rice.core.api.util.RiceConstants;
045import org.kuali.rice.core.api.util.tree.Node;
046import org.kuali.rice.kim.api.permission.PermissionService;
047import org.kuali.rice.kim.api.services.KimApiServiceLocator;
048import org.kuali.rice.krad.service.BusinessObjectService;
049import org.kuali.rice.krad.service.KRADServiceLocator;
050import org.kuali.rice.krad.uif.UifParameters;
051import org.kuali.rice.krad.util.GlobalVariables;
052import org.kuali.rice.krad.util.KRADConstants;
053
054import javax.servlet.http.HttpServletRequest;
055import java.text.DateFormat;
056import java.text.Format;
057import java.text.ParseException;
058import java.text.SimpleDateFormat;
059import java.util.*;
060
061/**
062 * Created with IntelliJ IDEA.
063 * User: sambasivam
064 * Date: 1/9/14
065 * Time: 5:01 PM
066 * To change this template use File | Settings | File Templates.
067 */
068public class WorkItemOlemlEditor extends AbstractEditor {
069
070    private static final Logger LOG = Logger.getLogger(WorkItemOlemlEditor.class);
071    HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
072    ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
073    ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
074    BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
075
076    private static WorkItemOlemlEditor workItemOlemlEditor = null;
077    private InstanceEditorFormDataHandler instanceEditorFormDataHandler = null;
078
079    DocstoreClient docstoreClient = getDocstoreLocalClient();
080
081    private OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService;
082
083    private OleDeliverRequestDocumentHelperServiceImpl getOleDeliverRequestDocumentHelperService() {
084        if (oleDeliverRequestDocumentHelperService == null) {
085            oleDeliverRequestDocumentHelperService = new OleDeliverRequestDocumentHelperServiceImpl();
086        }
087        return oleDeliverRequestDocumentHelperService;
088    }
089
090    public static WorkItemOlemlEditor getInstance() {
091        if (workItemOlemlEditor == null) {
092            workItemOlemlEditor = new WorkItemOlemlEditor();
093        }
094        return workItemOlemlEditor;
095    }
096
097    private WorkItemOlemlEditor() {
098
099    }
100
101    @Override
102    public EditorForm loadDocument(EditorForm editorForm) {
103        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
104        String directory = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(org.kuali.ole.sys.OLEConstants.EXTERNALIZABLE_HELP_URL_KEY);
105        editorForm.setExternalHelpUrl(directory+"/reference/webhelp/OLE/content/ch04s01.html#_Item");
106        editorForm.setHeaderText("Item");
107        editorForm.setHasLink(true);
108        String bibId = editorForm.getBibId();
109        String holdingsId = editorForm.getInstanceId();
110        String docId = editorForm.getDocId();
111        OleHoldings oleHoldings = new OleHoldings();
112        String docStoreData = null;
113        List<BibTree> bibTreeList = new ArrayList<>();
114        Date date = new Date();
115        SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE+" HH:mm:ss");
116        String dateStr = sdf.format(date);
117        BibTree bibTree = null;
118        try {
119            bibTree = docstoreClient.retrieveBibTree(bibId);
120            bibTreeList.add(bibTree);
121            workInstanceOlemlForm.setBibTreeList(bibTreeList);
122            if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bibTree.getBib().getFormat())) {
123                editorForm.setTitle(bibTree.getBib().getTitle() + " / " + bibTree.getBib().getAuthor());
124            }
125            Holdings holdings = docstoreClient.retrieveHoldings(holdingsId);
126            oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
127            workInstanceOlemlForm.setSelectedHolding(oleHoldings);
128        } catch (DocstoreException e) {
129            LOG.error(e);
130            DocstoreException docstoreException = (DocstoreException) e;
131            if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
132                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
133            } else {
134                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
135            }
136            return workInstanceOlemlForm;
137        } catch (Exception e) {
138            LOG.error("Exception ", e);
139            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
140        }
141
142        try {
143            if (StringUtils.isNotEmpty(docId)) {
144                editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(docId));
145                org.kuali.ole.docstore.common.document.Item itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
146                docStoreData = itemDocument.getContent();
147                Item item = itemOlemlRecordProcessor.fromXML(docStoreData);
148                ensureAccessInformation(item);
149                //TODO : set additional attributes
150                if (item != null && item.getItemStatusEffectiveDate() != null) {
151                    String[] itemStatusEffectiveDate = item.getItemStatusEffectiveDate().split(" ");
152                    item.setItemStatusEffectiveDate(itemStatusEffectiveDate[0]);
153                }
154                String itemStatus = null;
155                if (item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null) {
156                    itemStatus = item.getItemStatus().getCodeValue();
157                    workInstanceOlemlForm.setOldItemStatus(itemStatus);
158                }
159
160               /* if (item.getDueDateTime() != null && !item.getDueDateTime().equals("")) {
161                    String dueDate = item.getDueDateTime();
162                    if (dueDate.contains(" ")) {
163                        DateUtil dateUtil = new DateUtil();
164                        String dueTime = null;
165                        try {
166                            dueTime = dateUtil.convertTo12HoursFormat(dueDate.split(" ")[1]);
167                        } catch (ParseException e) {
168                            LOG.error("Exception :", e);
169                            e.printStackTrace();
170                        }
171                        item.setDueDateTime(dueDate.split(" ")[0] + " " + dueTime);
172                    }
173                }*/
174               /* SimpleDateFormat format1 = new SimpleDateFormat(CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString("info.DateFormat")+" HH:mm:ss");
175                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
176                String DATE_FORMAT_HH_MM_SS_REGX = "^(1[0-2]|0[1-9])/(3[0|1]|[1|2][0-9]|0[1-9])/[0-9]{4}(\\s)((([1|0][0-9])|([2][0-4]))):[0-5][0-9]:[0-5][0-9]:[0-5][0-9]$";
177                Date dueDateTime = null;
178                DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mma");
179                DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
180                try {
181                    dueDateTime = format2.parse(item.getDueDateTime());
182                   // item.setDueDateTime(format1.format(dueDateTime).toString());
183                    String dateString = format1.format(dueDateTime).toString();
184                    if (org.apache.commons.lang.StringUtils.isNotBlank(dateString) && dateString.matches(DATE_FORMAT_HH_MM_SS_REGX)) {
185                        dueDateTime = df1.parse(dateString);
186                        item.setDueDateTime(df.format(dueDateTime));
187                    }else {
188                        item.setDueDateTime(dateString);
189                    }
190                } catch (ParseException e) {
191                    LOG.error("format string to Date " + e);
192                }*/
193                String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "ITEM_STATUS_READONLY");
194                String[] itemArray = itemProperty.split(",");
195                for (String status : itemArray) {
196                    if (status.equalsIgnoreCase(itemStatus)) {
197                        workInstanceOlemlForm.setItemStatusNonEditable(true);
198                        break;
199                    }
200                    workInstanceOlemlForm.setItemStatusNonEditable(false);
201                }
202                itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
203                boolean editable;
204                if (itemProperty != null) {
205                    editable = Boolean.valueOf(itemProperty);
206                    workInstanceOlemlForm.setHoldingsDataInItemReadOnly(editable);
207                }
208                editorForm.setStaffOnlyFlagForItem(itemDocument.isStaffOnly());
209                editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
210                editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
211                editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
212                editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
213
214                List<Note> notes = ensureAtleastOneNote(item.getNote());
215                item.setNote(notes);
216                workInstanceOlemlForm.setSelectedItem(item);
217                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
218                workInstanceOlemlForm.setViewId("WorkItemViewPage");
219                if (item.getAccessInformation()!=null && StringUtils.isNotEmpty(item.getAccessInformation().getBarcode())) {
220                    Map map = new HashMap();
221                    map.put("itemBarcode", item.getAccessInformation().getBarcode());
222                    List<OLELoanIntransitRecordHistory> oleLoanIntransitRecordHistories = (List<OLELoanIntransitRecordHistory>) KRADServiceLocator.getBusinessObjectService().findMatching(OLELoanIntransitRecordHistory.class, map);
223                    if (CollectionUtils.isNotEmpty(oleLoanIntransitRecordHistories)) {
224                        editorForm.setOleLoanIntransitRecordHistories(oleLoanIntransitRecordHistories);
225                    }
226                }
227                //workInstanceOlemlForm.setMessage("Item record loaded successfully.");
228                if (editorForm.getEditable().equalsIgnoreCase("false")) {
229                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
230                } else {
231                    boolean hasPermission = canEditItem(GlobalVariables.getUserSession().getPrincipalId());
232                    if (hasPermission) {
233                        GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, "item.record.load.message");
234                    } else {
235                        editorForm.setHideFooter(false);
236                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_EDIT_ITEM);
237                    }
238                }
239            } else {
240
241                Item item = new Item();
242                String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
243                String[] itemArray = null;
244                if (itemProperty != null) {
245                    itemArray = itemProperty.split(",");
246                }
247                if (itemArray != null) {
248                    for (String status : itemArray) {
249                        if (status.equalsIgnoreCase("TRUE")) {
250                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
251                        } else if (status.equalsIgnoreCase("FALSE")) {
252                            workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
253                        }
254                    }
255                }
256                List<Note> notes = ensureAtleastOneNote(item.getNote());
257                item.setNote(notes);
258                ensureAccessInformation(item);
259                workInstanceOlemlForm.setSelectedItem(item);
260                this.addItemInformation(editorForm);
261                editorForm.setStaffOnlyFlagForItem(false);
262                editorForm.setItemCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
263                editorForm.setItemCreatedDate(dateStr);
264                editorForm.setItemUpdatedBy(null);
265                editorForm.setItemUpdatedDate(null);
266                workInstanceOlemlForm.setViewId("WorkItemViewPage");
267                boolean hasPermission = canCreateItem(GlobalVariables.getUserSession().getPrincipalId());
268                if (hasPermission) {
269                    GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
270                            "item.details.new.message");
271                } else {
272                    editorForm.setHideFooter(false);
273                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_CREATE_ITEM);
274                }
275                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
276            }
277        } catch (DocstoreException e) {
278            LOG.error(e);
279            DocstoreException docstoreException = (DocstoreException) e;
280            if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
281                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
282            } else {
283                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
284            }
285            return workInstanceOlemlForm;
286        } catch (Exception e) {
287            LOG.error("Exception ", e);
288            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
289        }
290        return workInstanceOlemlForm;
291    }
292
293    private void ensureAccessInformation(Item item) {
294        if(item.getAccessInformation() == null) {
295            AccessInformation accessInformation = new AccessInformation();
296            Uri uri = new Uri();
297            uri.setValue("");
298            uri.setResolvable("");
299            accessInformation.setUri(uri);
300            item.setAccessInformation(accessInformation);
301        }
302    }
303
304    @Override
305    public EditorForm saveDocument(EditorForm editorForm) {
306        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
307        Item itemData = workInstanceOlemlForm.getSelectedItem();
308        Date date = new Date();
309        SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT);
310        String dateStr = sdf.format(date);
311        String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
312        String docId = editorForm.getDocId();
313        String instanceId = editorForm.getInstanceId();
314        String editorMessage = "";
315        String callNumber;
316        String prefix;
317        Bib bib = null;
318//        editorForm.setHeaderText("Instance Editor (Item)- OLEML Format");
319        editorForm.setHeaderText("Item");
320        try {
321            bib = docstoreClient.retrieveBib(editorForm.getBibId());
322            if (!org.kuali.ole.docstore.model.enums.DocFormat.DUBLIN_UNQUALIFIED.getCode().equals(bib.getFormat())) {
323                editorForm.setTitle(bib.getTitle() + " / " + bib.getAuthor());
324            }
325        } catch (DocstoreException e) {
326            LOG.error(e);
327            DocstoreException docstoreException = (DocstoreException) e;
328            if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
329                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
330            } else {
331                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
332            }
333            getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
334            return workInstanceOlemlForm;
335        } catch (Exception e) {
336            LOG.error("Exception ", e);
337            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
338        }
339
340        try {
341            if (StringUtils.isNotEmpty(docId)) {
342                //Item itemData = workInstanceOlemlForm.getSelectedItem();
343                if (editorForm.getItemStatusSelection().equals("true")) {
344                    Format formatter = new SimpleDateFormat("MM/dd/yyyy");
345                    itemData.setItemStatusEffectiveDate(formatter.format(new Date()));
346                }
347                DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
348                if (!itemData.isClaimsReturnedFlag()) {
349                    itemData.setClaimsReturnedNote(null);
350                    itemData.setClaimsReturnedFlagCreateDate(null);
351                } else {
352                    org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
353                    ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
354                    org.kuali.ole.docstore.common.document.content.instance.Item oleItem = itemOlemlRecordProcessor.fromXML(item.getContent());
355                    ItemClaimsReturnedRecord itemClaimsReturnedRecord = new ItemClaimsReturnedRecord();
356                    List<ItemClaimsReturnedRecord> itemClaimsReturnedRecords = new ArrayList<>();
357                    if(!oleItem.isClaimsReturnedFlag()){
358                        itemClaimsReturnedRecord.setClaimsReturnedNote(itemData.getClaimsReturnedNote());
359                        if (itemData.getClaimsReturnedFlagCreateDate() != null && !itemData.getClaimsReturnedFlagCreateDate().isEmpty()) {
360                            itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(itemData.getClaimsReturnedFlagCreateDate());
361                        }
362                        else{
363                            itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
364                        }
365                        itemClaimsReturnedRecord.setClaimsReturnedOperatorId(user);
366                        itemClaimsReturnedRecord.setItemId(itemData.getItemIdentifier());
367                        itemClaimsReturnedRecord.setClaimsReturnedPatronBarcode(null);
368                        if(itemData.getItemClaimsReturnedRecords() != null && itemData.getItemClaimsReturnedRecords().size() > 0){
369                            itemData.getItemClaimsReturnedRecords().add(itemClaimsReturnedRecord);
370                        }
371                        else{
372                            itemClaimsReturnedRecords.add(itemClaimsReturnedRecord);
373                            itemData.setItemClaimsReturnedRecords(itemClaimsReturnedRecords);
374                        }
375                    } else{
376                        Map<String,String> map = new HashMap<>();
377                        map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
378                        List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord> claimsReturnedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord>) KRADServiceLocator.getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord.class, map, "claimsReturnedId", true);
379                        List<ItemClaimsReturnedRecord> itemClaimsReturnedRecordList = new ArrayList<>();
380                        for(int index=0 ; index < claimsReturnedRecordList.size() ; index++){
381                            ItemClaimsReturnedRecord claimsReturnedRecord = new ItemClaimsReturnedRecord();
382                            if(index == claimsReturnedRecordList.size()-1){
383                                if (itemData.getClaimsReturnedFlagCreateDate() != null && !itemData.getClaimsReturnedFlagCreateDate().isEmpty()) {
384                                    claimsReturnedRecord.setClaimsReturnedFlagCreateDate(itemData.getClaimsReturnedFlagCreateDate());
385                                }
386                                else{
387                                    claimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
388                                }
389                                claimsReturnedRecord.setClaimsReturnedNote(itemData.getClaimsReturnedNote());
390                                claimsReturnedRecord.setClaimsReturnedPatronBarcode(null);
391                                claimsReturnedRecord.setClaimsReturnedOperatorId(user);
392                                claimsReturnedRecord.setItemId(itemData.getItemIdentifier());
393                            } else {
394                                if (claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString() != null) {
395                                    SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
396                                    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
397                                    Date claimsReturnedDate = null;
398                                    try {
399                                        claimsReturnedDate = format2.parse(claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString());
400                                    } catch (ParseException e) {
401                                        LOG.error("format string to Date " + e);
402                                    }
403                                    claimsReturnedRecord.setClaimsReturnedFlagCreateDate(format1.format(claimsReturnedDate).toString());
404                                }
405                                claimsReturnedRecord.setClaimsReturnedNote(claimsReturnedRecordList.get(index).getClaimsReturnedNote());
406                                claimsReturnedRecord.setClaimsReturnedPatronBarcode(claimsReturnedRecordList.get(index).getClaimsReturnedPatronBarcode());
407                                claimsReturnedRecord.setClaimsReturnedOperatorId(claimsReturnedRecordList.get(index).getClaimsReturnedOperatorId());
408                                claimsReturnedRecord.setItemId(claimsReturnedRecordList.get(index).getItemId());
409                            }
410                            itemClaimsReturnedRecordList.add(claimsReturnedRecord);
411                        }
412                        itemData.setItemClaimsReturnedRecords(itemClaimsReturnedRecordList);
413                    }
414                    getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(itemData.getItemIdentifier());
415                }
416
417                if(itemData.isItemDamagedStatus()){
418                    org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
419                    ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
420                    org.kuali.ole.docstore.common.document.content.instance.Item oleItem = itemOlemlRecordProcessor.fromXML(item.getContent());
421                    ItemDamagedRecord itemDamagedRecord = new ItemDamagedRecord();
422                    List<ItemDamagedRecord> itemDamagedRecords = new ArrayList<>();
423                    if(!oleItem.isItemDamagedStatus()){
424                        itemDamagedRecord.setDamagedItemNote(itemData.getDamagedItemNote());
425                        itemDamagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
426                        itemDamagedRecord.setPatronBarcode(null);
427                        itemDamagedRecord.setOperatorId(user);
428                        itemDamagedRecord.setItemId(itemData.getItemIdentifier());
429                        if(itemData.getItemDamagedRecords() != null && itemData.getItemDamagedRecords().size() > 0){
430                            itemData.getItemDamagedRecords().add(itemDamagedRecord);
431                        } else {
432                            itemDamagedRecords.add(itemDamagedRecord);
433                            itemData.setItemDamagedRecords(itemDamagedRecords);
434                        }
435                    } else {
436                        Map<String,String> map = new HashMap<>();
437                        map.put("itemId",DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
438                        List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord> itemDamagedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord>) KRADServiceLocator.getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord.class, map, "itemDamagedId", true);
439                        List<ItemDamagedRecord> damagedRecordList = new ArrayList<>();
440                        for(int index=0 ; index < itemDamagedRecordList.size() ; index++){
441                            ItemDamagedRecord damagedRecord = new ItemDamagedRecord();
442                            if(index == itemDamagedRecordList.size()-1){
443                                damagedRecord.setDamagedItemNote(itemData.getDamagedItemNote());
444                                damagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
445                                damagedRecord.setPatronBarcode(null);
446                                damagedRecord.setOperatorId(user);
447                                damagedRecord.setItemId(itemData.getItemIdentifier());
448                            } else {
449                                if (itemDamagedRecordList.get(index).getDamagedItemDate() != null && !itemDamagedRecordList.get(index).getDamagedItemDate().toString().isEmpty()) {
450                                    SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
451                                    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
452                                    Date itemDamagedDate = null;
453                                    try {
454                                        itemDamagedDate = format2.parse(itemDamagedRecordList.get(index).getDamagedItemDate().toString());
455                                    } catch (ParseException e) {
456                                        LOG.error("format string to Date " + e);
457                                    }
458                                    damagedRecord.setDamagedItemDate(format1.format(itemDamagedDate).toString());
459                                }
460                                damagedRecord.setDamagedItemNote(itemDamagedRecordList.get(index).getDamagedItemNote());
461                                damagedRecord.setPatronBarcode(itemDamagedRecordList.get(index).getPatronBarcode());
462                                damagedRecord.setOperatorId(itemDamagedRecordList.get(index).getOperatorId());
463                                damagedRecord.setItemId(itemDamagedRecordList.get(index).getItemId());
464                            }
465                            damagedRecordList.add(damagedRecord);
466                        }
467                        itemData.setItemDamagedRecords(damagedRecordList);
468                    }
469                }
470                try {
471                    org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemData.getItemIdentifier());
472                    ItemOlemlRecordProcessor itemOlemlRecordProcessor1 = new ItemOlemlRecordProcessor();
473                    org.kuali.ole.docstore.common.document.content.instance.Item oleItem = itemOlemlRecordProcessor1.fromXML(item.getContent());
474                    MissingPieceItemRecord missingPieceItemRecord = new MissingPieceItemRecord();
475                    List<MissingPieceItemRecord> missingPieceItemRecordList = new ArrayList<>();
476                    if (itemData.isMissingPieceFlag() && !oleItem.isMissingPieceFlag()) {
477                        missingPieceItemRecord.setMissingPieceFlagNote(itemData.getMissingPieceFlagNote());
478                        missingPieceItemRecord.setMissingPieceCount(itemData.getMissingPiecesCount());
479                        String parsedDate = df.format((new Date()));
480                        missingPieceItemRecord.setMissingPieceDate(parsedDate);
481                        missingPieceItemRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
482                        missingPieceItemRecord.setPatronBarcode(itemData.getBarcodeARSL());
483                        missingPieceItemRecord.setItemId(itemData.getItemIdentifier());
484                        if (itemData.getMissingPieceItemRecordList() != null && itemData.getMissingPieceItemRecordList().size() > 0) {
485                            itemData.getMissingPieceItemRecordList().add(missingPieceItemRecord);
486                        } else {
487                            missingPieceItemRecordList.add(missingPieceItemRecord);
488                            itemData.setMissingPieceItemRecordList(missingPieceItemRecordList);
489                        }
490
491
492                    } else {
493                        if (itemData.isMissingPieceFlag() && oleItem.isMissingPieceFlag()) {
494                            Map<String, String> map = new HashMap<>();
495                            map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(itemData.getItemIdentifier()));
496                            List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord> missingPieceItemRecordList1 = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord>) KRADServiceLocator.getBusinessObjectService()
497                                    .findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.MissingPieceItemRecord.class, map, "missingPieceItemId", true);
498                            List<MissingPieceItemRecord> missingPieceItemRecords = new ArrayList<>();
499                            for (int index = 0; index < missingPieceItemRecordList1.size(); index++) {
500                                MissingPieceItemRecord missingPieceItemRecord1 = new MissingPieceItemRecord();
501                                if (index == missingPieceItemRecordList1.size() - 1) {
502                                /*if (oleLoanForm.getMissi != null) {
503                                    claimsReturnedRecord.setClaimsReturnedFlagCreateDate(convertToString(loanObject.getClaimsReturnedDate()));
504                                }
505                                else{
506                                    DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
507                                    claimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
508                                }*/
509                                    DateFormat dfs = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
510                                    String missingPieceItemDate = dfs.format((new Date()));
511                                    missingPieceItemRecord1.setMissingPieceDate(missingPieceItemDate);
512                                    missingPieceItemRecord1.setMissingPieceCount(itemData.getMissingPiecesCount());
513                                    missingPieceItemRecord1.setPatronBarcode(itemData.getBarcodeARSL());
514                                    missingPieceItemRecord1.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
515                                    missingPieceItemRecord1.setItemId(itemData.getItemIdentifier());
516                                    missingPieceItemRecord1.setMissingPieceFlagNote(itemData.getMissingPieceFlagNote());
517                                    missingPieceItemRecords.add(missingPieceItemRecord1);
518
519                                } else {
520                                    if (missingPieceItemRecordList1.get(index).getMissingPieceDate() != null && !missingPieceItemRecordList1.get(index).getMissingPieceDate().toString().isEmpty()) {
521                                        SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
522                                        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
523                                        Date missingPieceItemDate = null;
524                                        try {
525                                            missingPieceItemDate = format2.parse(missingPieceItemRecordList1.get(index).getMissingPieceDate().toString());
526                                        } catch (org.kuali.ole.sys.exception.ParseException e) {
527                                            LOG.error("format string to Date " + e);
528                                        }
529                                        missingPieceItemRecord1.setMissingPieceDate(format1.format(missingPieceItemDate).toString());
530                                    }
531                                    missingPieceItemRecord1.setMissingPieceFlagNote(missingPieceItemRecordList1.get(index).getMissingPieceFlagNote());
532                                    missingPieceItemRecord1.setMissingPieceCount(missingPieceItemRecordList1.get(index).getMissingPieceCount());
533                                    missingPieceItemRecord1.setOperatorId(missingPieceItemRecordList1.get(index).getOperatorId());
534                                    missingPieceItemRecord1.setPatronBarcode(missingPieceItemRecordList1.get(index).getPatronBarcode());
535                                    missingPieceItemRecord1.setItemId(missingPieceItemRecordList1.get(index).getItemId());
536                                    missingPieceItemRecords.add(missingPieceItemRecord1);
537                                }
538                            }
539                            itemData.setMissingPieceItemRecordList(missingPieceItemRecords);
540                        }
541                    }
542                } catch (Exception e) {
543                    LOG.error("Exception ", e);
544                }
545                workInstanceOlemlForm.setViewId("WorkItemViewPage");
546                if (!isValidItemData(workInstanceOlemlForm)) {
547//                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
548                    return workInstanceOlemlForm;
549                }
550
551                String itemId = editorForm.getDocId();
552                itemData.setItemIdentifier(itemId);
553                String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(itemData);
554
555                ItemOleml itemOleml = new ItemOleml();
556                itemOleml.setContent(itemXmlContent);
557                itemOleml.setId(itemId);
558                itemOleml.setType(editorForm.getDocType());
559                itemOleml.setFormat(editorForm.getDocFormat());
560                itemOleml.setUpdatedBy(user);
561                itemOleml.setUpdatedOn(dateStr);
562                itemOleml.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
563                itemOleml.setCategory(editorForm.getDocCategory());
564                long startTime = System.currentTimeMillis();
565                try {
566                    docstoreClient.updateItem(itemOleml);
567                } catch (DocstoreException e) {
568                    LOG.error(e);
569                    DocstoreException docstoreException = (DocstoreException) e;
570                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
571                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
572                    } else {
573                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
574                    }
575
576                    Holdings holdings = null;
577                    try {
578                        holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
579                    } catch (Exception e1) {
580                        LOG.error("Exception :", e1);
581                        docstoreException = (DocstoreException) e1;
582                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
583                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
584                        } else {
585                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
586                        }
587                    }
588                    String docStoreData = holdings.getContent();
589                    OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
590                    workInstanceOlemlForm.setSelectedHolding(oleHoldings);
591
592                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
593                    return workInstanceOlemlForm;
594                } catch (Exception e) {
595                    LOG.error("Exception ", e);
596                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
597                }
598                long endTime = System.currentTimeMillis();
599                editorForm.setSolrTime(String.valueOf((endTime - startTime) / 1000));
600                if(itemData.getLocation()!=null){
601                    String location = instanceEditorFormDataHandler.getLocationCode(itemData.getLocation().getLocationLevel());
602                    if(asrHelperService.isAnASRItem(location)){
603
604                        Map<String,String> asrItemMap = new HashMap<String,String>();
605                        asrItemMap.put("itemBarcode",itemData.getAccessInformation().getBarcode());
606                        List<ASRItem> asrItems = (List<ASRItem>)businessObjectService.findMatching(ASRItem.class,asrItemMap);
607                        if(asrItems.size()==0){
608                            ASRItem asrItem = new ASRItem();
609                            if(itemData.getAccessInformation()!=null && itemData.getAccessInformation().getBarcode()!=null){
610                                asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
611                            }
612                            if(bib.getTitle()!=null){
613                                asrItem.setTitle((bib.getTitle().length()>37)?bib.getTitle().substring(0,36):bib.getTitle());
614                            }
615                            if(bib.getAuthor()!=null){
616                                asrItem.setAuthor((bib.getAuthor().length()>37)?bib.getAuthor().substring(0,36):bib.getAuthor());
617                            }
618                            if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()){
619                                callNumber=(itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
620                                prefix=itemData.getCallNumber().getPrefix()!=null&&!itemData.getCallNumber().getPrefix().isEmpty()?itemData.getCallNumber().getPrefix():"";
621                                asrItem.setCallNumber(prefix+" "+callNumber);
622                            }
623                            else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
624                                callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
625                                prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
626                                asrItem.setCallNumber(prefix+" "+callNumber);
627                            }
628                            businessObjectService.save(asrItem);
629                        }
630                    }
631                }else if(workInstanceOlemlForm.getSelectedHolding().getLocation()!=null){
632                    OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
633                    String location = oleHoldings.getLocation().getLocationLevel().getName();
634                    if(asrHelperService.isAnASRItem(location)){
635                        Map<String,String> asrItemMap = new HashMap<String,String>();
636                        asrItemMap.put("itemBarcode",itemData.getAccessInformation().getBarcode());
637                        List<ASRItem> asrItems = (List<ASRItem>)businessObjectService.findMatching(ASRItem.class,asrItemMap);
638                        if(asrItems.size()==0){
639                            ASRItem asrItem = new ASRItem();
640                            if(itemData.getAccessInformation()!=null && itemData.getAccessInformation().getBarcode()!=null){
641                                asrItem.setItemBarcode(itemData.getAccessInformation().getBarcode());
642                            }
643                            if(bib.getTitle()!=null){
644                                asrItem.setTitle((bib.getTitle().length()>37)?bib.getTitle().substring(0,36):bib.getTitle());
645                            }
646                            if(bib.getAuthor()!=null){
647                                asrItem.setAuthor((bib.getAuthor().length()>37)?bib.getAuthor().substring(0,36):bib.getAuthor());
648                            }
649                            if (itemData.getCallNumber() != null && itemData.getCallNumber().getNumber() != null && !itemData.getCallNumber().getNumber().isEmpty()){
650                                callNumber=(itemData.getCallNumber().getNumber().length() > 37) ? itemData.getCallNumber().getNumber().substring(0, 36) : itemData.getCallNumber().getNumber();
651                                prefix=itemData.getCallNumber().getPrefix()!=null&&!itemData.getCallNumber().getPrefix().isEmpty()?itemData.getCallNumber().getPrefix():"";
652                                asrItem.setCallNumber(prefix+" "+callNumber);
653                            }
654                            else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
655                                callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
656                                prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
657                                asrItem.setCallNumber(prefix+" "+callNumber);
658
659                            }
660                            businessObjectService.save(asrItem);
661                        }
662                    }
663                }
664                String itemProperty = getInstanceEditorFormDataHandler().getParameter("OLE-DESC", "Describe", "EDIT_HOLDINGS_INFO_IN_ITEM_SCREEN");
665                String[] itemArray = null;
666                if (itemProperty != null) {
667                    itemArray = itemProperty.split(",");
668                }
669                for (String status : itemArray) {
670                    if (status.equalsIgnoreCase("TRUE")) {
671                        workInstanceOlemlForm.setHoldingsDataInItemReadOnly(true);
672                    } else if (status.equalsIgnoreCase("FALSE")) {
673                        workInstanceOlemlForm.setHoldingsDataInItemReadOnly(false);
674                    }
675                }
676                String holdingId = workInstanceOlemlForm.getSelectedHolding().getHoldingsIdentifier();
677                OleHoldings holdingData = workInstanceOlemlForm.getSelectedHolding();
678                String holdingXmlContent = getInstanceEditorFormDataHandler().buildHoldingContent(holdingData);
679                Holdings holdings = docstoreClient.retrieveHoldings(holdingId);
680                holdings.setBib(bib);
681                holdings.setContent(holdingXmlContent);
682                holdings.setCategory(editorForm.getDocCategory());
683                holdings.setType(DocType.HOLDINGS.getCode());
684                holdings.setFormat(editorForm.getDocFormat());
685                docstoreClient.updateHoldings(holdings);
686                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
687                if (!isValidHoldingsData(workInstanceOlemlForm)) {
688                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
689                    return workInstanceOlemlForm;
690                }
691                editorMessage = "item.record.update.message";
692
693            } else {
694
695                if (!isValidItemData(workInstanceOlemlForm)) {
696//                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
697                    return workInstanceOlemlForm;
698                }
699                String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
700                Item oleItem = workInstanceOlemlForm.getSelectedItem();
701                String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
702                ItemOleml itemDoc = new ItemOleml();
703                itemDoc.setCategory(DocCategory.WORK.getCode());
704                itemDoc.setType(DocType.ITEM.getCode());
705                itemDoc.setFormat(DocFormat.OLEML.getCode());
706                itemDoc.setCreatedOn(dateStr);
707                itemDoc.setCreatedBy(user);
708                itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
709                itemDoc.setContent(itemXmlContent);
710                Holdings holdings = new PHoldings();
711                holdings.setId(editorForm.getInstanceId());
712                itemDoc.setHolding(holdings);
713                long startTime = System.currentTimeMillis();
714                try {
715                    docstoreClient.createItem(itemDoc);
716                } catch (Exception e) {
717                    LOG.error("Exception :", e);
718                    DocstoreException docstoreException = (DocstoreException) e;
719                    String errorCode = docstoreException.getErrorCode();
720                    if (StringUtils.isNotEmpty(errorCode)) {
721                        Map<String, String> paramsMap = docstoreException.getErrorParams();
722                        if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
723                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
724                        } else {
725                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
726                        }
727                    } else {
728                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
729                    }
730
731                    try {
732                        holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
733                    } catch (Exception e1) {
734                        LOG.error("Exception :", e1);
735                        docstoreException = (DocstoreException) e1;
736                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
737                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
738                        } else {
739                            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
740                        }
741                    }
742                    String docStoreData = holdings.getContent();
743                    OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
744                    workInstanceOlemlForm.setSelectedHolding(oleHoldings);
745
746                    getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
747                    return workInstanceOlemlForm;
748                }
749                long endtime = System.currentTimeMillis();
750                editorForm.setSolrTime(String.valueOf((endtime-startTime)/1000));
751                if(oleItem.getLocation()!=null){
752                    String location =  oleItem.getLocation().getLocationLevel().getName();
753                    if (asrHelperService.isAnASRItem(location)) {
754                        Map<String, String> asrItemMap = new HashMap<String, String>();
755                        asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
756                        List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
757                        if (asrItems.size() == 0) {
758                            ASRItem asrItem = new ASRItem();
759                            if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
760                                asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
761                            }
762                            if (bib.getTitle() != null) {
763                                asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
764                            }
765                            if (bib.getAuthor() != null) {
766                                asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
767                            }
768                            if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()){
769                                callNumber=(oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
770                                prefix=oleItem.getCallNumber().getPrefix()!=null&&!oleItem.getCallNumber().getPrefix().isEmpty()?oleItem.getCallNumber().getPrefix():"";
771                                asrItem.setCallNumber(prefix+" "+callNumber);
772                            }
773                            else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
774                                callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
775                                prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
776                                asrItem.setCallNumber(prefix+" "+callNumber);
777                            }
778                            businessObjectService.save(asrItem);
779                        }
780                    }
781                }else if(workInstanceOlemlForm.getSelectedHolding().getLocation()!=null){
782                    OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
783                    String location = oleHoldings.getLocation().getLocationLevel().getName();
784                    if (asrHelperService.isAnASRItem(location)) {
785                        Map<String, String> asrItemMap = new HashMap<String, String>();
786                        asrItemMap.put("itemBarcode", oleItem.getAccessInformation().getBarcode());
787                        List<ASRItem> asrItems = (List<ASRItem>) businessObjectService.findMatching(ASRItem.class, asrItemMap);
788                        if (asrItems.size() == 0) {
789                            ASRItem asrItem = new ASRItem();
790                            if (oleItem.getAccessInformation() != null && oleItem.getAccessInformation().getBarcode() != null) {
791                                asrItem.setItemBarcode(oleItem.getAccessInformation().getBarcode());
792                            }
793                            if (bib.getTitle() != null) {
794                                asrItem.setTitle((bib.getTitle().length() > 37) ? bib.getTitle().substring(0, 36) : bib.getTitle());
795                            }
796                            if (bib.getAuthor() != null) {
797                                asrItem.setAuthor((bib.getAuthor().length() > 37) ? bib.getAuthor().substring(0, 36) : bib.getAuthor());
798                            }
799                            if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()){
800                                callNumber=(oleItem.getCallNumber().getNumber().length() > 37) ? oleItem.getCallNumber().getNumber().substring(0, 36) : oleItem.getCallNumber().getNumber();
801                                prefix=oleItem.getCallNumber().getPrefix()!=null&&!oleItem.getCallNumber().getPrefix().isEmpty()?oleItem.getCallNumber().getPrefix():"";
802                                asrItem.setCallNumber(prefix+" "+callNumber);
803                            }
804                            else if(workInstanceOlemlForm.getSelectedHolding()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber()!=null && workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber()!=null && !workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().isEmpty()){
805                                callNumber=(workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().length() > 37) ? workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber().substring(0, 36) : workInstanceOlemlForm.getSelectedHolding().getCallNumber().getNumber();
806                                prefix=workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix()!=null&&!workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix().isEmpty()?workInstanceOlemlForm.getSelectedHolding().getCallNumber().getPrefix():"";
807                                asrItem.setCallNumber(prefix+" "+callNumber);
808
809                            }
810                            businessObjectService.save(asrItem);
811                        }
812                    }
813                }
814                editorForm.setDocId(itemDoc.getId());
815                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
816                editorMessage = "item.record.load.message";
817            }
818        } catch (Exception e) {
819            LOG.error("Exception :", e);
820            DocstoreException docstoreException = (DocstoreException) e;
821            if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
822                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
823            } else {
824                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
825            }
826            getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
827            return workInstanceOlemlForm;
828        }
829        org.kuali.ole.docstore.common.document.Item itemDocument = null;
830        try {
831            Holdings holdings = null;
832            try {
833                holdings = docstoreClient.retrieveHoldings(editorForm.getInstanceId());
834            } catch (Exception e) {
835                LOG.error("Exception :", e);
836                DocstoreException docstoreException = (DocstoreException) e;
837                if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
838                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
839                } else {
840                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
841                }
842            }
843            String docStoreData = holdings.getContent();
844            OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(docStoreData);
845            workInstanceOlemlForm.setSelectedHolding(oleHoldings);
846            try {
847                itemDocument = docstoreClient.retrieveItem(editorForm.getDocId());
848            } catch (DocstoreException e) {
849                LOG.error(e);
850                DocstoreException docstoreException = (DocstoreException) e;
851                if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
852                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
853                } else {
854                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
855                }
856                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
857                return workInstanceOlemlForm;
858            } catch (Exception e) {
859                LOG.error("Exception ", e);
860                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
861            }
862            Item item = itemOlemlRecordProcessor.fromXML(itemDocument.getContent());
863            editorForm.setItemLocalIdentifier(DocumentUniqueIDPrefix.getDocumentId(item.getItemIdentifier()));
864            editorForm.setItemCreatedBy(itemDocument.getCreatedBy());
865            editorForm.setItemCreatedDate(itemDocument.getCreatedOn());
866            editorForm.setItemUpdatedBy(itemDocument.getUpdatedBy());
867            editorForm.setItemUpdatedDate(itemDocument.getUpdatedOn());
868            workInstanceOlemlForm.setSelectedItem(item);
869            getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
870            GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
871        } catch (Exception e) {
872            LOG.error("Exception :", e);
873            GlobalVariables.getMessageMap().clearErrorMessages();
874            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "record.submit.fail.message");
875        }
876        if (StringUtils.isNotBlank(workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier())) {
877            Map poMap = new HashMap();
878            poMap.put(OLEConstants.PURAP_DOC_IDENTIFIER, workInstanceOlemlForm.getSelectedItem().getPurchaseOrderLineItemIdentifier());
879            OlePurchaseOrderDocument olePurchaseOrderDocument = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OlePurchaseOrderDocument.class, poMap);
880            if (olePurchaseOrderDocument != null) {
881                String poId = olePurchaseOrderDocument.getDocumentNumber();
882                Map<String, String> map = new HashMap<>();
883                map.put(org.kuali.ole.sys.OLEConstants.OleCopy.PO_DOC_NUM, poId);
884                KRADServiceLocator.getBusinessObjectService().deleteMatching(OLELinkPurapDonor.class, map);
885                if (workInstanceOlemlForm.getSelectedItem().getDonorInfo().size() > 0) {
886                    for (DonorInfo donorInfo : workInstanceOlemlForm.getSelectedItem().getDonorInfo()) {
887                        if (donorInfo.getDonorCode() != null && !donorInfo.getDonorCode().isEmpty()) {
888                            map.clear();
889                            map.put(OLEConstants.DONOR_CODE, donorInfo.getDonorCode());
890                            OLELinkPurapDonor newOleLinkPurapDonor = new OLELinkPurapDonor();
891                            List<OLEDonor> oleDonors = (List<OLEDonor>) KRADServiceLocator.getBusinessObjectService().findMatching(OLEDonor.class, map);
892                            map.clear();
893                            if (StringUtils.isNotBlank(workInstanceOlemlForm.getSelectedItem().getItemIdentifier())) {
894                                map.put(OLEConstants.OleDeliverRequest.ITEM_UUID, workInstanceOlemlForm.getSelectedItem().getItemIdentifier());
895                            }
896                            map.put(org.kuali.ole.sys.OLEConstants.OleCopy.PO_DOC_NUM, poId);
897                            List<OleCopy> oleCopy = (List<OleCopy>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCopy.class, map);
898                            if (oleCopy != null && oleCopy.size() > 0) {
899                                newOleLinkPurapDonor.setCorrectionItemId(oleCopy.get(0).getCorrectionItemId());
900                                newOleLinkPurapDonor.setReqItemId(oleCopy.get(0).getReqItemId());
901                                newOleLinkPurapDonor.setPoDocNum(oleCopy.get(0).getPoDocNum());
902                                newOleLinkPurapDonor.setReceivingItemId(oleCopy.get(0).getReceivingItemId());
903                                newOleLinkPurapDonor.setDonorId(oleDonors.get(0).getDonorId());
904                                newOleLinkPurapDonor.setDonorCode(donorInfo.getDonorCode());
905                                newOleLinkPurapDonor.setPoItemId(oleCopy.get(0).getPoItemId());
906                                KRADServiceLocator.getBusinessObjectService().save(newOleLinkPurapDonor);
907                            }
908                            map.clear();
909                        }
910                    }
911                }
912            }
913        }
914        // To remove existing item from bib tree
915        removeDocumentFromTree(editorForm);
916        // To add new item or updated item in bib tree
917        addItemToBibTree(workInstanceOlemlForm.getBibTreeList(), itemDocument);
918        return workInstanceOlemlForm;
919    }
920
921    /**
922     * This methods adds the new item or updated item to the bib tree to build left pane tree.
923     * @param bibTreeList
924     * @param selectedItemDocument
925     */
926    private void addItemToBibTree(List<BibTree> bibTreeList, org.kuali.ole.docstore.common.document.Item selectedItemDocument) {
927        if (CollectionUtils.isNotEmpty(bibTreeList)) {
928            for (BibTree bibTree : bibTreeList) {
929                if (CollectionUtils.isNotEmpty(bibTree.getHoldingsTrees())) {
930                    for (HoldingsTree holdingsTree : bibTree.getHoldingsTrees()) {
931                        if (null != holdingsTree.getHoldings() && null != selectedItemDocument.getHolding()) {
932                            String holdingsId = holdingsTree.getHoldings().getId();
933                            String selectedItemHoldingsId = selectedItemDocument.getHolding().getId();
934                            if (null != holdingsId && null != selectedItemHoldingsId) {
935                                if (holdingsId.equals(selectedItemHoldingsId)) {
936                                    holdingsTree.setHoldings(selectedItemDocument.getHolding());
937                                    holdingsTree.getItems().add(selectedItemDocument);
938                                }
939                            }
940                        }
941                    }
942                }
943            }
944        }
945    }
946
947    @Override
948    public EditorForm createNewRecord(EditorForm editorForm, BibTree bibTree) {
949
950        if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
951            editorForm.setNeedToCreateInstance(true);
952        }
953        editNewRecord(editorForm, bibTree);
954        return editorForm.getDocumentForm();
955    }
956
957    @Override
958    public EditorForm editNewRecord(EditorForm editorForm, BibTree bibTree) {
959        WorkInstanceOlemlForm workInstanceOlemlForm = new WorkInstanceOlemlForm();
960        if ((editorForm.getDocumentForm() instanceof WorkInstanceOlemlForm)) {
961            workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
962            workInstanceOlemlForm.setViewId(editorForm.getDocumentForm().getViewId());
963        }
964
965        workInstanceOlemlForm.setDocCategory("work");
966        workInstanceOlemlForm.setDocType("item");
967        workInstanceOlemlForm.setDocFormat("oleml");
968
969        if (bibTree != null && bibTree.getHoldingsTrees() != null) {
970            HoldingsTree holdingsTree = bibTree.getHoldingsTrees().get(0);
971            if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkHoldingsViewPage")) {
972//                editorForm.setHeaderText("Import Bib Step-4 Instance Editor (Item)- OLEML Format");
973                editorForm.setHeaderText("Import Bib Step-4 Item");
974                // validate user entered holding data before going to item tab
975                if (!isValidHoldingsData(workInstanceOlemlForm)) {
976                    return workInstanceOlemlForm;
977                }
978                holdingsTree.getHoldings().setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
979                holdingsTree.getHoldings().setCreatedBy(GlobalVariables.getUserSession().getPrincipalName());
980                Item item = itemOlemlRecordProcessor.fromXML(holdingsTree.getItems().get(0).getContent());
981                List<Note> notes = ensureAtleastOneNote(item.getNote());
982                item.setNote(notes);
983                workInstanceOlemlForm.setSelectedItem(item);
984                workInstanceOlemlForm.setViewId("WorkItemViewPage");
985                //workInstanceOlemlForm.setMessage("Please enter details for new Item record.");
986                GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO,
987                        "item.details.new.message");
988            } else if (editorForm.getDocumentForm().getViewId().equalsIgnoreCase("WorkItemViewPage")) {
989                if (!isValidItemData(workInstanceOlemlForm)) {
990                    return workInstanceOlemlForm;
991                }
992                Item item = workInstanceOlemlForm.getSelectedItem();
993                Map<String, String> mapObject = new HashMap<String, String>();
994                String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
995                try {
996                    String holdingXmlContent = getInstanceEditorFormDataHandler()
997                            .buildHoldingContent(workInstanceOlemlForm.getSelectedHolding());
998                    holdingsTree.getHoldings().setContent(holdingXmlContent);
999
1000                    String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(item, staffOnlyFlagForItem);
1001                    holdingsTree.getItems().get(0).setContent(itemXmlContent);
1002
1003                } catch (Exception e) {
1004                    LOG.error("Exception :", e);
1005                    StringBuffer instanceEditorErrorMessage = new StringBuffer(
1006                            OLEConstants.INSTANCE_EDITOR_FAILURE).append(" :: \n" + e.getMessage());
1007                    workInstanceOlemlForm.setMessage(instanceEditorErrorMessage.toString());
1008                    LOG.error(instanceEditorErrorMessage);
1009                }
1010            }
1011        }
1012        editorForm.setDocumentForm(workInstanceOlemlForm);
1013        return editorForm;
1014    }
1015
1016    @Override
1017    public String saveDocument(BibTree bibTree, EditorForm editorForm) {
1018        String responseFromDocstore = "success";
1019        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1020        if (bibTree != null) {
1021            try {
1022                docstoreClient.createBibTree(bibTree);
1023            } catch (DocstoreException e) {
1024                LOG.error(e);
1025                DocstoreException docstoreException = (DocstoreException) e;
1026                if (org.apache.commons.lang3.StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1027                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1028                } else {
1029                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1030                }
1031            } catch (Exception e) {
1032                LOG.error("Exception ", e);
1033                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,"docstore.response", e.getMessage() );
1034            }
1035        }
1036        editorForm.setDocumentForm(workInstanceOlemlForm);
1037        return responseFromDocstore;
1038    }
1039
1040
1041    /**
1042     * Gets the InstanceEditorFormDataHandler attribute.
1043     *
1044     * @return Returns InstanceEditorFormDataHandler.
1045     */
1046    private InstanceEditorFormDataHandler getInstanceEditorFormDataHandler() {
1047        if (null == instanceEditorFormDataHandler) {
1048            instanceEditorFormDataHandler = new InstanceEditorFormDataHandler();
1049        }
1050        return instanceEditorFormDataHandler;
1051    }
1052
1053    private List<Note> ensureAtleastOneNote(List<Note> notes) {
1054        if (notes == null) {
1055            notes = new ArrayList<Note>();
1056        }
1057        if (notes.size() == 0) {
1058            Note note = new Note();
1059            notes.add(note);
1060        }
1061        return notes;
1062    }
1063
1064    private boolean canCreateItem(String principalId) {
1065        PermissionService service = KimApiServiceLocator.getPermissionService();
1066        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_ADD_ITEM);
1067    }
1068
1069    private boolean canEditItem(String principalId) {
1070        PermissionService service = KimApiServiceLocator.getPermissionService();
1071        return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.INSTANCE_EDITOR_EDIT_ITEM);
1072    }
1073
1074    private void addItemInformation(EditorForm editorForm) {
1075        //TODO: do as per tree structure
1076    }
1077
1078    /**
1079     * Validates the item data and returns true if it is valid
1080     *
1081     * @param workInstanceOlemlForm
1082     * @return
1083     */
1084    private boolean isValidItemData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1085        Item item = workInstanceOlemlForm.getSelectedItem();
1086        boolean isValidItem = true;
1087//        StringBuffer stringBuffer = new StringBuffer();
1088        String oldItemStatus = workInstanceOlemlForm.getOldItemStatus();
1089        String itemStatus = item.getItemStatus().getCodeValue();
1090        String itemProperty = getInstanceEditorFormDataHandler()
1091                .getParameter(OLEConstants.DESC_NMSPC, OLEConstants.DESCRIBE_COMPONENT, OLEParameterConstants.ITEM_STATUS_READONLY);
1092        String[] itemArray = itemProperty.split(",");
1093        //If current item status is changed when compared with previous status
1094        if ((org.apache.commons.lang.StringUtils.isNotEmpty(itemStatus)) && (!itemStatus.equals(oldItemStatus))) {
1095            for (String status : itemArray) {
1096                if (status.equalsIgnoreCase(itemStatus)) {
1097//                    stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_INVALID + "</font>");
1098                    //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1099                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "invalid.item.status");
1100                    return false;
1101                }
1102            }
1103        }
1104        String location = "";
1105        String holdingsLocation = "";
1106        if (item.getLocation() != null) {
1107            location = item.getLocation().getLocationLevel().getName();
1108        }
1109        OleHoldings holdings = workInstanceOlemlForm.getSelectedHolding();
1110        if (holdings.getLocation() != null) {
1111            holdingsLocation = holdings.getLocation().getLocationLevel().getName();
1112        }
1113
1114
1115        //Display error message when item status is empty
1116        if ( workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
1117                (item.getItemStatus() == null || item.getItemStatus().getCodeValue() == "" ||
1118                        item.getItemStatus().getCodeValue().length() < 0)) {
1119            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_STATUS_ERRORMESSAGE + "</font>");
1120            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus.codeValue", "error.item.status.required");
1121            workInstanceOlemlForm.setValidInput(false);
1122            isValidItem = false;
1123        }
1124
1125        //Display error message when item type is empty
1126        if (workInstanceOlemlForm.getGlobalEditFlag().equalsIgnoreCase("false") &&
1127                (item.getItemType() == null || item.getItemType().getCodeValue() == null || item.getItemType().getCodeValue()=="" || item.getItemType().getCodeValue().length()==0 ||   item.getItemType().getCodeValue().length() < 0)) {
1128//            stringBuffer.append("<br>");
1129            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERRORMESSAGE + "</font>");
1130            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemType.codeValue", "error.item.type.required");
1131            workInstanceOlemlForm.setValidInput(false);
1132            isValidItem = false;
1133        }
1134
1135        if (holdingsLocation != null && holdingsLocation.length() != 0 && !isValidLocation(holdingsLocation)) {
1136//            stringBuffer.append("<br>");
1137            GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1138            workInstanceOlemlForm.setValidInput(false);
1139            isValidItem = false;
1140        }
1141        //Display error message when location is invalid
1142        if (location != null && location.length() != 0 && !isValidLocation(location)) {
1143//            stringBuffer.append("<br>");
1144            //stringBuffer.append("<font size='3' color='red'>Please enter the valid location.</font>");
1145            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.location.locationLevel.name", "error.location");
1146            workInstanceOlemlForm.setValidInput(false);
1147            isValidItem = false;
1148        }
1149
1150        boolean hasPermission = canUpdateItemStatus(GlobalVariables.getUserSession().getPrincipalId());
1151        if (hasPermission) {
1152//            if (org.apache.commons.lang.StringUtils.isEmpty(stringBuffer.toString())) {
1153//                isValidItem = true;
1154//            } else {
1155//                isValidItem = false;
1156//            }
1157        } else {
1158            //stringBuffer.append("<font size='3' color='red'>" + OLEConstants.ITEM_TYPE_ERROR_MESSAGE + "</font>");
1159            //workInstanceOlemlForm.setMessage(stringBuffer.toString());
1160            GlobalVariables.getMessageMap().putError("documentForm.selectedItem.itemStatus", "error.item.type.authorization");
1161            return false;
1162        }
1163        return isValidItem;
1164    }
1165
1166    private boolean isValidLocation(String location) {
1167
1168        List<String> locationList = LocationValuesBuilder.retrieveLocationDetailsForSuggest(location);
1169        if (locationList != null && locationList.size() > 0) {
1170            for (String locationValue : locationList) {
1171                if (locationValue.equalsIgnoreCase(location)) {
1172                    return true;
1173                }
1174            }
1175        }
1176        return false;
1177    }
1178
1179    private boolean canUpdateItemStatus(String principalId) {
1180        LOG.debug("Inside the canUpdateItemStatus method");
1181        PermissionService service = KimApiServiceLocator.getPermissionService();
1182        return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_UPDATE_IEM_STATUS);
1183    }
1184
1185    /**
1186     * Validates the Holdings data and returns true if it is valid
1187     *
1188     * @param workInstanceOlemlForm
1189     * @return
1190     */
1191    private boolean isValidHoldingsData(WorkInstanceOlemlForm workInstanceOlemlForm) {
1192        OleHoldings oleHoldings = workInstanceOlemlForm.getSelectedHolding();
1193        String location = null;
1194        if (oleHoldings != null && oleHoldings.getLocation() != null && oleHoldings.getLocation().getLocationLevel() != null) {
1195            location = oleHoldings.getLocation().getLocationLevel().getName();
1196        }
1197        if (location != null && location.length() != 0 && !isValidLocation(location)) {
1198            //workInstanceOlemlForm.setMessage("<font size='3' color='red'>Please enter valid location.</font>");
1199            GlobalVariables.getMessageMap().putError("documentForm.selectedHolding.location.locationLevel.name", "error.location");
1200            workInstanceOlemlForm.setValidInput(false);
1201            return false;
1202        }
1203        return true;
1204    }
1205
1206
1207    public EditorForm deleteVerify(EditorForm editorForm) {
1208        //LOG.info("in instance editor class");
1209        String docId = editorForm.getDocId();
1210        String operation = "deleteVerify";
1211        //        String responseXml = getResponseFromDocStore(editorForm, docId, operation);
1212        //        LOG.info("deleteVerify responseXml-->" + responseXml);
1213        //        editorForm.setDeleteVerifyResponse(responseXml);
1214        editorForm.setShowDeleteTree(true);
1215        editorForm.setHasLink(true);
1216        //        Node<DocumentTreeNode, String> docTree = buildDocSelectionTree(responseXml);
1217        List<String> uuidList = new ArrayList<>(0);
1218        uuidList.add(editorForm.getDocId());
1219        DocumentSelectionTree documentSelectionTree = new DocumentSelectionTree();
1220        Node<DocumentTreeNode, String> docTree = null;
1221        try {
1222            docTree = documentSelectionTree.add(uuidList, editorForm.getDocType());
1223        } catch (SolrServerException e) {
1224            LOG.error("Exception :", e);
1225            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
1226        }
1227        editorForm.getDocTree().setRootElement(docTree);
1228        editorForm.setViewId("DeleteViewPage");
1229        return editorForm;
1230
1231    }
1232
1233    /**
1234     * This method deletes the item record from docstore by the doc id.
1235     * @param editorForm
1236     * @return
1237     * @throws Exception
1238     */
1239    public EditorForm delete(EditorForm editorForm) throws Exception {
1240        return deleteFromDocStore(editorForm);
1241    }
1242
1243    @Override
1244    public EditorForm addORRemoveItemNote(EditorForm editorForm, HttpServletRequest request) {
1245        String methodName = request.getParameter("methodToCall");
1246        if (methodName.equalsIgnoreCase("addItemNote")) {
1247            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1248            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1249            index++;
1250            List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1251            itemNote.add(index, new Note());
1252            editorForm.setDocumentForm(workInstanceOlemlForm);
1253        } else if (methodName.equalsIgnoreCase("removeItemNote")) {
1254            WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1255            int index = Integer.parseInt(editorForm.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
1256            List<Note> itemNote = workInstanceOlemlForm.getSelectedItem().getNote();
1257            if (itemNote.size() > 1) {
1258                itemNote.remove(index);
1259            } else {
1260                if (itemNote.size() == 1) {
1261                    itemNote.remove(index);
1262                    Note note = new Note();
1263                    itemNote.add(note);
1264                }
1265            }
1266            editorForm.setDocumentForm(workInstanceOlemlForm);
1267        }
1268        return editorForm;
1269    }
1270
1271    @Override
1272    public EditorForm bulkUpdate(EditorForm editorForm, List<String> ids) {
1273        WorkInstanceOlemlForm workInstanceOlemlForm = (WorkInstanceOlemlForm) editorForm.getDocumentForm();
1274        Date date = new Date();
1275        SimpleDateFormat sdf = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE+" HH:mm:ss");
1276        String dateStr = sdf.format(date);
1277        String user = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
1278        String docId = editorForm.getDocId();
1279        String instanceId = editorForm.getInstanceId();
1280        String editorMessage = "";
1281        Bib bib = null;
1282        editorForm.setHeaderText("Global Edit - Item");
1283
1284        try {
1285
1286            workInstanceOlemlForm.setGlobalEditFlag("true");
1287            if (!isValidItemData(workInstanceOlemlForm)) {
1288                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1289                return workInstanceOlemlForm;
1290            }
1291            String staffOnlyFlagForItem = String.valueOf(editorForm.isStaffOnlyFlagForItem());
1292            Item oleItem = workInstanceOlemlForm.getSelectedItem();
1293            String itemXmlContent = getInstanceEditorFormDataHandler().buildItemContent(oleItem, staffOnlyFlagForItem);
1294            ItemOleml itemDoc = new ItemOleml();
1295            itemDoc.setCategory(DocCategory.WORK.getCode());
1296            itemDoc.setType(DocType.ITEM.getCode());
1297            itemDoc.setFormat(DocFormat.OLEML.getCode());
1298            itemDoc.setCreatedOn(dateStr);
1299            itemDoc.setCreatedBy(user);
1300            String canUpdateStaffOnlyFlag = "false";
1301            if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("Y")) {
1302                canUpdateStaffOnlyFlag = "true";
1303                editorForm.setStaffOnlyFlagForItem(true);
1304                itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1305            }
1306            else if (editorForm.getStaffOnlyFlagInGlobalEdit() != null && editorForm.getStaffOnlyFlagInGlobalEdit().equalsIgnoreCase("N")) {
1307                canUpdateStaffOnlyFlag = "true";
1308                editorForm.setStaffOnlyFlagForItem(false);
1309                itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForHoldings());
1310            }
1311            itemDoc.setStaffOnly(editorForm.isStaffOnlyFlagForItem());
1312            itemDoc.setContent(itemXmlContent);
1313            /*Holdings holdings = new PHoldings();
1314            holdings.setId(editorForm.getInstanceId());
1315            itemDoc.setHolding(holdings);*/
1316            try {
1317                getDocstoreClientLocator().getDocstoreClient().bulkUpdateItem(itemDoc,ids,canUpdateStaffOnlyFlag);
1318            } catch (Exception e) {
1319                LOG.error("Exception :", e);
1320                DocstoreException docstoreException = (DocstoreException) e;
1321                String errorCode = docstoreException.getErrorCode();
1322                if (StringUtils.isNotEmpty(errorCode)) {
1323                    Map<String, String> paramsMap = docstoreException.getErrorParams();
1324                    if (paramsMap != null && paramsMap.size() > 0 && paramsMap.containsKey("barcode")) {
1325                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode, paramsMap.get("barcode"));
1326                    } else {
1327                        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, errorCode);
1328                    }
1329                } else {
1330                    GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1331                }
1332                getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1333                return workInstanceOlemlForm;
1334            }
1335            editorForm.setDocId(itemDoc.getId());
1336            getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1337            editorMessage = "item.record.load.message";
1338
1339        } catch (Exception e) {
1340            LOG.error("Exception :", e);
1341            DocstoreException docstoreException = (DocstoreException) e;
1342            if (StringUtils.isNotEmpty(docstoreException.getErrorCode())) {
1343                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, docstoreException.getErrorCode());
1344            } else {
1345                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, e.getMessage());
1346            }
1347            getInstanceEditorFormDataHandler().setLocationDetails(workInstanceOlemlForm);
1348            return workInstanceOlemlForm;
1349        }
1350        GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, editorMessage);
1351        return workInstanceOlemlForm;
1352    }
1353
1354    public DateTimeService getDateTimeService() {
1355        return (DateTimeService)SpringContext.getService("dateTimeService");
1356    }
1357}