예제 #1
0
        private void CreateNewOrdersFromSeeds()
        {
            try
            {
                foreach (var seed in _seeds)
                {
                    try
                    {
                        int orderItemNodeId = _orderItemManager.CreateOrderItemInDbFromOrderItemSeedModel(seed, false, false);

                        var eventId = _orderItemManager.GenerateEventId(CREATE_ORDER_FROM_LIBRIS_DATA_EVENT_TYPE);
                        _orderItemManager.AddSierraDataToLog(orderItemNodeId, seed.SierraPatronInfo, eventId);

                        _result.NewOrders++;
                    }
                    catch (Exception e)
                    {
                        var msg = "Error creating new OrderItem node. ";
                        _umbraco.LogError <LibrisOrderItemsSource>(msg, e);
                        _result.Errors++;
                        _result.Messages.Add(msg + e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                throw new SourcePollingException("Error when creating new orders from seeds.", e);
            }
        }
예제 #2
0
        public ActionResult ImportFromUrl(int orderItemNodeId, string url)
        {
            // Json response
            var json = new ResultResponse();

            Stream stream = null;

            try
            {
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
                fileReq.CookieContainer   = new CookieContainer();
                fileReq.AllowAutoRedirect = true;
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
                stream = fileResp.GetResponseStream();

                var    orderItem         = _orderItemManager.GetOrderItem(orderItemNodeId);
                var    cdPattern         = new Regex("filename=\"?(.*)\"?(?:;|$)");
                var    fileEndingPattern = new Regex("(?i)\\.(?:pdf|txt|tif|tiff)$");
                string name = "";
                if (fileEndingPattern.IsMatch(url))
                {
                    name = fileResp.ResponseUri.AbsoluteUri.Substring(fileResp.ResponseUri.AbsoluteUri.LastIndexOf("/") + 1);
                }
                else
                {
                    name = cdPattern.Match(fileResp.Headers["Content-Disposition"]).Groups[1].Value;
                }

                if (String.IsNullOrEmpty(name))
                {
                    throw new Exception("Not a valid document.");
                }
                else
                {
                    var savedMediaItem = _mediaItemManager.CreateMediaItem(name, orderItem.NodeId, orderItem.OrderId, stream, fileResp.ContentType);

                    var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);
                    _orderItemManager.AddExistingMediaItemAsAnAttachment(orderItem.NodeId, savedMediaItem.Id, name, savedMediaItem.Url, eventId);

                    json.Success = true;
                    json.Message = "Document imported successfully.";
                }
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Failed to import document: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #3
0
        public ActionResult SetOrderItemStatus(int orderNodeId, int statusId, int cancellationReasonId = -1, int purchasedMaterialId = -1)
        {
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                if (cancellationReasonId != -1)
                {
                    _orderItemManager.SetCancellationReason(orderNodeId, cancellationReasonId, eventId, false, false);
                }

                if (purchasedMaterialId != -1)
                {
                    _orderItemManager.SetPurchasedMaterial(orderNodeId, purchasedMaterialId, eventId, false, false);
                }

                // Use internal method to set status property and log the result
                _orderItemManager.SetStatus(orderNodeId, statusId, eventId);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Changed status to " + statusId;
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        public ActionResult Returned(int nodeId)
        {
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(BOOK_RETURNED_FROM_BORROWER_EVENT_TYPE);
                _orderItemManager.SetStatus(nodeId, "13:Transport", eventId);

                json.Success = true;
                json.Message = "Lyckades med att återlämna bok till filial.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Misslyckades med att returnera från filial: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #5
0
        public ActionResult WriteLogItem(int nodeId, string Type, string Message, string newFollowUpDate, int statusId, int cancellationReasonId, int purchasedMaterialId)
        {
            // Json response
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                // Set FollowUpDate property if it differs from current
                DateTime currentFollowUpDate = _orderItemManager.GetOrderItem(nodeId).FollowUpDate;

                if (!String.IsNullOrEmpty(newFollowUpDate))
                {
                    DateTime parsedNewFollowUpDate = Convert.ToDateTime(newFollowUpDate);
                    if (currentFollowUpDate != parsedNewFollowUpDate)
                    {
                        _orderItemManager.SetFollowUpDate(nodeId, parsedNewFollowUpDate, eventId, false, false);
                    }
                }

                if (statusId != -1)
                {
                    _orderItemManager.SetStatus(nodeId, statusId, eventId, false, false);
                }

                if (cancellationReasonId != -1)
                {
                    _orderItemManager.SetCancellationReason(nodeId, cancellationReasonId, eventId, false, false);
                }

                if (purchasedMaterialId != -1)
                {
                    _orderItemManager.SetPurchasedMaterial(nodeId, purchasedMaterialId, eventId, false, false);
                }

                // Use internal method to set type property and log the result
                _orderItemManager.AddLogItem(nodeId, Type, Message, eventId);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Wrote log entry to node" + nodeId;
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #6
0
        public ActionResult FetchPatronDataUsingLcnOrPnr(int orderItemNodeId, string lcn, string pnr, bool cache = true)
        {
            var json = new ResultResponse();

            try
            {
                var content = _orderItemManager.GetOrderItem(orderItemNodeId);
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                SierraModel sm = null;
                if (cache)
                {
                    sm = _patronDataProviderSierraCache.GetPatronInfoFromLibraryCardNumberOrPersonnummer(lcn, pnr);
                }
                else
                {
                    sm = _patronDataProviderSierra.GetPatronInfoFromLibraryCardNumberOrPersonnummer(lcn, pnr);
                }

                if (!String.IsNullOrEmpty(sm.id))
                {
                    _orderItemManager.SetPatronData(content.NodeId, JsonConvert.SerializeObject(sm), sm.record_id, sm.ptype, sm.home_library, sm.aff);
                    _orderItemManager.SaveWithoutEventsAndWithSynchronousReindexing(content.NodeId, false, false);
                }
                _orderItemManager.AddSierraDataToLog(orderItemNodeId, sm, eventId);

                json.Success = true;
                json.Message = "Succcessfully loaded Sierra data from \"personnummer\" or library card number.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Failed to load Sierra data from \"personnummer\" or library card number: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        private void ConvertOrdersWithExpiredFollowUpDateAndCertainStatusToNewStatus()
        {
            var query = @"status:04\:Väntar AND 
                followUpDate:[1975-01-01T00:00:00.000Z TO " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + "]";

            // -1 means that we haven't checked edited by properly and should disregard it
            var memberId = -1;

            // Search for our items and signal the ones that have expired recently.
            var ids = _orderItemsSearcher.Search(query).Select(x => x.NodeId).ToList();

            foreach (var id in ids)
            {
                var eventId = _orderItemManager.GenerateEventId(TIME_BASED_UPDATE_OF_ORDER_EVENT_TYPE);
                _orderItemManager.AddLogItem(id, "LOG", "Automatisk statusändring på grund av att uppföljningsdatum löpt ut.", eventId, false, false);
                _orderItemManager.SetStatus(id, _dataTypes.GetAvailableStatuses().First(x => x.Value.Contains("Åtgärda")).Id, eventId);
                _notifier.UpdateOrderItemUpdate(id, memberId.ToString(), "", true, true);
            }
        }
예제 #8
0
        public ActionResult SetProvider(int nodeId, string providerName, string providerOrderId, string providerInformation, string newFollowUpDate, bool updateStatusAndFollowUpDate = true)
        {
            var json = new ResultResponse();

            try
            {
                var eventType = PROVIDER_DATA_UPDATED_EVENT_TYPE;
                if (updateStatusAndFollowUpDate)
                {
                    eventType = EVENT_TYPE;
                }

                var eventId = _orderItemManager.GenerateEventId(eventType);
                if (updateStatusAndFollowUpDate)
                {
                    _orderItemManager.SetFollowUpDate(nodeId, Convert.ToDateTime(newFollowUpDate), eventId, false, false);
                }

                _orderItemManager.SetProviderName(nodeId, providerName, eventId, false, false);
                _orderItemManager.SetProviderOrderId(nodeId, providerOrderId, eventId, false, false);
                _orderItemManager.SetProviderInformation(nodeId, providerInformation, eventId, false, false);

                if (updateStatusAndFollowUpDate)
                {
                    _orderItemManager.SetStatus(nodeId, "03:Beställd", eventId, false, false);
                }

                _orderItemManager.SaveWithoutEventsAndWithSynchronousReindexing(nodeId);

                json.Success = true;
                json.Message = "Sparade data för beställning.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #9
0
        public ActionResult SetReference(int nodeId, string reference)
        {
            var json = new ResultResponse();

            try
            {
                // Find OrderItem
                var orderItem = _orderItemManager.GetOrderItem(nodeId);

                _orderItemManager.SetReference(nodeId, reference, _orderItemManager.GenerateEventId(EVENT_TYPE), false, false);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Saved reference.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        public ActionResult SetOrderItemType(int orderNodeId, int typeId)
        {
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                // Use internal method to set type property and log the result
                _orderItemManager.SetType(orderNodeId, typeId, eventId);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Changed type to " + typeId;
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #11
0
        public ActionResult SetOrderItemPurchaseLibrary(int orderNodeId, PurchaseLibraries purchaseLibrary)
        {
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                // Use internal method to set status property and log the result
                _orderItemManager.SetPurchaseLibrary(orderNodeId, purchaseLibrary, eventId);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Changed purchase library to " + purchaseLibrary.ToString();
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        public ActionResult ReturnItem(int nodeId, string bookId, int status)
        {
            var json = new ResultResponse();

            try
            {
                if (status == STATUS_FOLIO)
                {
                    _folioService.SetItemToWithdrawn(bookId);
                }
                var eventId = _orderItemManager.GenerateEventId(BOOK_RETURNED_HOME_EVENT_TYPE);
                _orderItemManager.SetStatus(nodeId, "10:Återsänd", eventId);

                json.Success = true;
                json.Message = "Returnering genomförd.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Misslyckades med att returnera: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        public ActionResult SetDelivery(int nodeId, string logEntry, string delivery)
        {
            var json = new ResultResponse();

            try
            {
                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);
                _orderItemManager.AddLogItem(nodeId, "LEVERERAD", "Leveranstyp: " + delivery, eventId, false, false);
                _orderItemManager.AddLogItem(nodeId, "LOG", logEntry, eventId, false, false);
                _orderItemManager.SetStatus(nodeId, "05:Levererad", eventId);

                json.Success = true;
                json.Message = "Saved provider data.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
        public ActionResult SendMail(OutgoingMailPackageModel m)
        {
            var json = new ResultResponse();

            try
            {
                // Read current values that can be affected
                var orderItem          = _orderItemManager.GetOrderItem(m.nodeId);
                var currentPatronEmail = orderItem.PatronEmail;
                var currentStatus      = orderItem.Status;

                var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                // Send mail to recipient
                _mailService.SendMail(new OutgoingMailModel(orderItem.OrderId, m));

                _orderItemManager.AddLogItem(m.nodeId, "MAIL_NOTE", "Skickat mail till " + m.recipientEmail, eventId, false, false);
                _orderItemManager.AddLogItem(m.nodeId, "MAIL", m.message, eventId, false, false);

                // Set PatronEmail property if it differs from recipientEmail
                if (currentPatronEmail != m.recipientEmail)
                {
                    _orderItemManager.SetPatronEmail(m.nodeId, m.recipientEmail, eventId, false, false);
                }

                // Set FollowUpDate property if it differs from current
                DateTime currentFollowUpDate = orderItem.FollowUpDate;

                if (!String.IsNullOrEmpty(m.newFollowUpDate))
                {
                    DateTime parsedNewFollowUpDate = Convert.ToDateTime(m.newFollowUpDate);
                    if (currentFollowUpDate != parsedNewFollowUpDate)
                    {
                        _orderItemManager.SetFollowUpDate(m.nodeId, parsedNewFollowUpDate, eventId, false, false);
                    }
                }

                // Set status property if it differs from newStatus and if it is not -1 (no change)
                if (orderItem.StatusId != m.newStatusId && orderItem.StatusId != -1)
                {
                    _orderItemManager.SetStatus(m.nodeId, m.newStatusId, eventId, false, false);
                }

                // Update cancellation reason if we have a value that is not -1 (no change)
                if (orderItem.CancellationReasonId != m.newCancellationReasonId && m.newCancellationReasonId != -1)
                {
                    _orderItemManager.SetCancellationReason(m.nodeId, m.newCancellationReasonId, eventId, false, false);
                }

                // Update purchased material if we have a value that is not -1 (no change)
                if (orderItem.PurchasedMaterialId != m.newPurchasedMaterialId && m.newPurchasedMaterialId != -1)
                {
                    _orderItemManager.SetPurchasedMaterial(m.nodeId, m.newPurchasedMaterialId, eventId, false, false);
                }

                _orderItemManager.SaveWithoutEventsAndWithSynchronousReindexing(m.nodeId);

                // Construct JSON response for client (ie jQuery/getJSON)
                json.Success = true;
                json.Message = "Sent mail and eventually changed some properties.";
            }
            catch (Exception e)
            {
                json.Success = false;
                json.Message = "Error: " + e.Message;
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #15
0
        public SourcePollingResult Poll()
        {
            _result = new SourcePollingResult("Huvudpostlåda");

            // List of read mails
            List <MailQueueModel> list = null;

            // Connect to Exchange Service
            try
            {
                _exchangeMailWebApi.ConnectToExchangeService(ConfigurationManager.AppSettings["chalmersIllExhangeLogin"], ConfigurationManager.AppSettings["chalmersIllExhangePass"]);
            }
            catch (Exception e)
            {
                throw new SourcePollingException("Error connecting to Exchange Service.", e);
            }

            // Get a list of mails from Inbox folder
            try
            {
                list = _exchangeMailWebApi.ReadMailQueue();
            }
            catch (Exception e)
            {
                throw new SourcePollingException("Error reading mail from Exchange.", e);
            }

            // Post processing of e-mails
            if (list.Count > 0)
            {
                try
                {
                    string deliveryOrderId;
                    foreach (MailQueueModel item in list)
                    {
                        try
                        {
                            var orderIdPattern = new Regex("#+(cthb-.{8}-[0-9]+)");
                            deliveryOrderId = getBoundOrder(item);
                            // Bind the type of messages we have (NEW or REPLY)
                            if ((item.Subject != null && item.Subject.Contains("#new")) || item.To.Contains("+new"))
                            {
                                item.Type = MailQueueType.NEW;
                            }
                            else if ((item.Subject != null && item.Subject.Contains("#cthb-")))
                            {
                                item.OrderId         = orderIdPattern.Match(item.Subject).Groups[1].Value;
                                item.OrderItemNodeId = Convert.ToInt32(item.OrderId.Split('-').Last());
                                item.Type            = MailQueueType.REPLY;

                                FixLegacyNodeIds(item);
                            }
                            else if (item.To.Contains("+cthb-"))
                            {
                                item.OrderId         = orderIdPattern.Match(item.To).Groups[1].Value;
                                item.OrderItemNodeId = Convert.ToInt32(item.OrderId.Split('-').Last());
                                item.Type            = MailQueueType.REPLY;

                                FixLegacyNodeIds(item);
                            }
                            else if (deliveryOrderId != null)
                            {
                                item.OrderId         = deliveryOrderId;
                                item.OrderItemNodeId = Convert.ToInt32(deliveryOrderId.Split('-').Last());
                                item.Type            = MailQueueType.DELIVERY;

                                FixLegacyNodeIds(item);
                            }
                            else
                            {
                                item.Type = MailQueueType.UNKNOWN;
                            }
                        }
                        catch (Exception e)
                        {
                            item.Type = MailQueueType.ERROR;
                            item.ParseErrorMessage = "Chillin failed to process E-mail. Reason: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Failed to process one E-mail, tagging it with ERROR.", e);
                            _result.Errors++;
                            _result.Messages.Add(item.ParseErrorMessage);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new SourcePollingException("Error when post processing E-mails.", e);
                }

                // Get SierraInfo to the list
                try
                {
                    int indexet = 0;

                    foreach (MailQueueModel item in list)
                    {
                        // New order received from someone
                        if (item.Type == MailQueueType.NEW)
                        {
                            list[indexet].SierraPatronInfo = _patronDataProvider.GetPatronInfoFromLibraryCardNumberOrPersonnummer(item.PatronCardNo, item.PatronCardNo);
                        }

                        indexet++;
                    }
                }
                catch (Exception e)
                {
                    throw new SourcePollingException("Error connecting to Sierra.", e);
                }


                // Continues if we have a list of mail messages...
                int index = 0;

                // For each fetched mail to process
                foreach (MailQueueModel item in list)
                {
                    // New order received from someone
                    if (item.Type == MailQueueType.NEW)
                    {
                        try
                        {
                            // Write a new OrderItem
                            int orderItemNodeId = _orderItemManager.CreateOrderItemInDbFromMailQueueModel(item, false, false);

                            var eventId = _orderItemManager.GenerateEventId(CREATE_ORDER_FROM_MAIL_DATA_EVENT_TYPE);
                            _orderItemManager.AddSierraDataToLog(orderItemNodeId, item.SierraPatronInfo, eventId);

                            // Archive the mail message to correct folder
                            if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true")
                            {
                                FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id);
                                list[index].ArchiveFolderId = archiveFolderId;
                            }

                            // Update item with some useful data
                            list[index].OrderItemNodeId = orderItemNodeId;
                            list[index].StatusResult    = "Created new OrderItem node.";

                            _result.NewOrders++;
                        }
                        catch (Exception e)
                        {
                            list[index].OrderItemNodeId = -1;
                            list[index].StatusResult    = "Error creating new OrderItem node: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Error creating new OrderItem node", e);
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                    }

                    // Reply from user to existing order
                    else if (item.Type == MailQueueType.REPLY)
                    {
                        try
                        {
                            var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_MAIL_DATA_PATRON_EVENT_TYPE);
                            // Set the OrderItem Status so it appears in lists
                            try
                            {
                                _orderItemManager.SetStatus(item.OrderItemNodeId, "02:Åtgärda", eventId, false, false);
                            }
                            catch (Exception es)
                            {
                                throw new Exception("Exception during SetOrderItemStatusInternal: " + es.Message);
                            }

                            // Set new FollowUpDate for the OrderItem
                            try
                            {
                                _orderItemManager.SetFollowUpDateWithoutLogging(item.OrderItemNodeId, DateTime.Now, false, false);
                            }
                            catch (Exception ef)
                            {
                                throw new Exception("Exception during SetFollowUpDate: " + ef.Message);
                            }

                            // Write LogItem with the mail received and metadata
                            try
                            {
                                _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL", getTextFromHtml(item.MessageBody), eventId, false, false);
                                _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL_NOTE", "Svar från " + item.Sender + " [" + item.From + "]", eventId);
                            }
                            catch (Exception el)
                            {
                                throw new Exception("Exception during WriteLogItemInternal: " + el.Message);
                            }

                            // Archive the mail message to correct folder
                            try
                            {
                                if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true")
                                {
                                    FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id);
                                    list[index].ArchiveFolderId = archiveFolderId;
                                }
                            }
                            catch (Exception ea)
                            {
                                throw new Exception("Exception during Archiving: " + ea.Message);
                            }

                            // Update item with some useful data
                            list[index].StatusResult = "Wrote LogItem type MAIL for this OrderId.";

                            _notifier.UpdateOrderItemUpdate(item.OrderItemNodeId, "-1", "", true, true, true);

                            _result.UpdatedOrders++;
                        }
                        catch (Exception e)
                        {
                            list[index].StatusResult = "Error following up reply on OrderItem: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Error following up reply on OrderItem", e);
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                    }

                    else if (item.Type == MailQueueType.DELIVERY)
                    {
                        try
                        {
                            var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_MAIL_DATA_NOT_PATRON_EVENT_TYPE);
                            // Set the OrderItem Status so it appears in lists
                            try
                            {
                                _orderItemManager.SetStatus(item.OrderItemNodeId, "09:Mottagen", eventId, false, false);
                            }
                            catch (Exception es)
                            {
                                throw new Exception("Exception during SetOrderItemStatusInternal: " + es.Message);
                            }

                            // Check if the incoming mail mentions drm content.
                            try
                            {
                                if (item.MessageBody.ToLower().Contains("drm"))
                                {
                                    _orderItemManager.SetDrmWarningWithoutLogging(item.OrderItemNodeId, true, false, false);
                                }
                            }
                            catch (Exception es)
                            {
                                throw new Exception("Exception during toggling of DrmWarning" + es.Message);
                            }

                            // Set new FollowUpDate for the OrderItem
                            try
                            {
                                _orderItemManager.SetFollowUpDateWithoutLogging(item.OrderItemNodeId, DateTime.Now, false, false);
                            }
                            catch (Exception ef)
                            {
                                throw new Exception("Exception during SetFollowUpDate: " + ef.Message);
                            }

                            // Pick out attachments and save them in Umbracos media repository.
                            try
                            {
                                if (item.Attachments.Count > 0)
                                {
                                    foreach (var attachment in item.Attachments)
                                    {
                                        var savedMediaItem = _mediaItemManager.CreateMediaItem(attachment.Title, item.OrderItemNodeId, item.OrderId, attachment.Data, attachment.ContentType);

                                        if (attachment.Data != null)
                                        {
                                            attachment.Data.Dispose();
                                        }

                                        _orderItemManager.AddExistingMediaItemAsAnAttachment(item.OrderItemNodeId, savedMediaItem.Id, attachment.Title, savedMediaItem.Url, eventId, false, false);
                                    }
                                }
                            }
                            catch (Exception el)
                            {
                                throw new Exception("Failed to extract attachments from delivery mail: " + el.Message);
                            }

                            // Write LogItem with the mail received and metadata
                            try
                            {
                                _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL", getTextFromHtml(item.MessageBody), eventId, false, false);
                                _orderItemManager.AddLogItem(item.OrderItemNodeId, "MAIL_NOTE", "Leverans från " + item.Sender + " [" + item.From + "]", eventId);
                            }
                            catch (Exception el)
                            {
                                throw new Exception("Exception during WriteLogItemInternal: " + el.Message);
                            }

                            // Archive the mail message to correct folder
                            try
                            {
                                if (ConfigurationManager.AppSettings["chalmersILLArchiveProcessedMails"] == "true")
                                {
                                    FolderId archiveFolderId = _exchangeMailWebApi.ArchiveMailMessage(item.Id);
                                    list[index].ArchiveFolderId = archiveFolderId;
                                }
                            }
                            catch (Exception ea)
                            {
                                throw new Exception("Exception during Archiving: " + ea.Message);
                            }

                            // Update item with some useful data
                            list[index].StatusResult = "Wrote LogItem type MAIL for this OrderId.";

                            _notifier.UpdateOrderItemUpdate(item.OrderItemNodeId, "-1", "", true, true, true);

                            _result.UpdatedOrders++;
                        }
                        catch (Exception e)
                        {
                            list[index].StatusResult = "Error following up delivery on OrderItem: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Error following up delivery on OrderItem", e);
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                    }
                    else if (item.Type == MailQueueType.ERROR)
                    {
                        try
                        {
                            // Forward failed mail to bug fixers.
                            try
                            {
                                foreach (var addressWithPotentialWs in ConfigurationManager.AppSettings["bugFixersMailingList"].Split(','))
                                {
                                    var address = addressWithPotentialWs.Trim();
                                    try
                                    {
                                        _exchangeMailWebApi.ForwardMailMessage(item.Id, address, item.ParseErrorMessage, false);
                                    }
                                    catch (Exception innerInnerExc)
                                    {
                                        LogHelper.Error <SystemSurfaceController>("Failed to forward message to " + address + ".", innerInnerExc);
                                    }
                                }
                            }
                            catch (Exception innerExc)
                            {
                                LogHelper.Error <SystemSurfaceController>("Failed to forward message to bug fixers.", innerExc);
                            }

                            // Forward failed mail to manual handling.
                            _exchangeMailWebApi.ForwardMailMessage(item.Id, ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]);
                            list[index].StatusResult = "This message has been forwarded to " + ConfigurationManager.AppSettings["chalmersILLForwardingAddress"];
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                        catch (Exception e)
                        {
                            list[index].StatusResult = "Error forwarding mail: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Error forwarding mail", e);
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                    }
                    else // UNKNOWN, forward to mailbox configured in web.config
                    {
                        try
                        {
                            _exchangeMailWebApi.ForwardMailMessage(item.Id, ConfigurationManager.AppSettings["chalmersILLForwardingAddress"]);
                            list[index].StatusResult = "This message has been forwarded to " + ConfigurationManager.AppSettings["chalmersILLForwardingAddress"];
                        }
                        catch (Exception e)
                        {
                            list[index].StatusResult = "Error forwarding mail: " + e.Message;
                            LogHelper.Error <SystemSurfaceController>("Error forwarding mail", e);
                            _result.Errors++;
                            _result.Messages.Add(list[index].StatusResult);
                        }
                    }

                    item.Attachments = null;

                    index++;
                }
            }

            return(Result);
        }
        public IEnumerable <MailOperationResult> SendOutMailsThatAreDue()
        {
            var res = new List <MailOperationResult>();

            // Grab the date and use it for all e-mails during this run.
            var now = DateTime.Now;

            var orderItems = GetOrderItemsThatAreRelevantForAutomaticMailSending();

            var delayedMailOperations = new List <DelayedMailOperation>();

            foreach (var orderItem in orderItems)
            {
                var dueDate      = orderItem.DueDate;
                var deliveryDate = orderItem.DeliveryDate;
                var status       = orderItem.Status;

                var delayedMailOperation = new DelayedMailOperation(
                    orderItem.NodeId,
                    orderItem.OrderId,
                    orderItem.PatronName,
                    orderItem.PatronEmail);

                if (status.Contains("Utlånad") || status.Contains("Krävd"))
                {
                    if (status.Contains("Utlånad") && now.Date == dueDate.AddDays(-5).Date)
                    {
                        delayedMailOperation.Mail.message = _templateService.GetTemplateData("CourtesyNoticeMailTemplate", _orderItemManager.GetOrderItem(orderItem.NodeId));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL_NOTE", "Skickat automatiskt \"courtesy notice\" till " + delayedMailOperation.Mail.recipientEmail));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL", delayedMailOperation.Mail.message));
                        delayedMailOperation.ShouldBeProcessed = true;
                    }
                    else if (status.Contains("Utlånad") && now.Date == dueDate.AddDays(1).Date)
                    {
                        delayedMailOperation.Mail.message = _templateService.GetTemplateData("LoanPeriodOverMailTemplate", _orderItemManager.GetOrderItem(orderItem.NodeId));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL_NOTE", "Skickat automatiskt påminnelsemail nummer ett till " + delayedMailOperation.Mail.recipientEmail));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL", delayedMailOperation.Mail.message));
                        delayedMailOperation.ShouldBeProcessed = true;
                    }
                    else if (now.Date == dueDate.AddDays(5).Date)
                    {
                        delayedMailOperation.Mail.message = _templateService.GetTemplateData("LoanPeriodReallyOverMailTemplate", _orderItemManager.GetOrderItem(orderItem.NodeId));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL_NOTE", "Skickat automatiskt påminnelsemail nummer två till " + delayedMailOperation.Mail.recipientEmail));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL", delayedMailOperation.Mail.message));
                        delayedMailOperation.ShouldBeProcessed = true;
                    }
                    else if (now.Date == dueDate.AddDays(10).Date)
                    {
                        delayedMailOperation.Mail.message = _templateService.GetTemplateData("LoanPeriodReallyReallyOverMailTemplate", _orderItemManager.GetOrderItem(orderItem.NodeId));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL_NOTE", "Skickat automatiskt påminnelsemail nummer tre till " + delayedMailOperation.Mail.recipientEmail));
                        delayedMailOperation.LogMessages.Add(new LogMessage("MAIL", delayedMailOperation.Mail.message));
                        delayedMailOperation.ShouldBeProcessed = true;
                    }
                    else if (now.Date >= dueDate.AddDays(17).Date)
                    {
                        delayedMailOperation.LogMessages.Add(new LogMessage("LOG", "Bok mycket försenad."));
                        delayedMailOperation.Mail              = null;
                        delayedMailOperation.NewStatus         = "02:Åtgärda";
                        delayedMailOperation.ShouldBeProcessed = true;
                    }
                }

                if (delayedMailOperation.ShouldBeProcessed)
                {
                    delayedMailOperations.Add(delayedMailOperation);
                }
            }

            // Send out all the delayed mails now, so that the IndexReader is not used and gets broken.
            foreach (var delayedMailOperation in delayedMailOperations)
            {
                var mailOperationResult = new MailOperationResult()
                {
                    Success       = true,
                    Message       = "Mail operation successfull.",
                    MailOperation = delayedMailOperation
                };
                try
                {
                    var eventId = _orderItemManager.GenerateEventId(EVENT_TYPE);

                    if (delayedMailOperation.Mail != null)
                    {
                        _mailService.SendMail(delayedMailOperation.Mail);
                    }

                    for (int i = 0; i < delayedMailOperation.LogMessages.Count; i++)
                    {
                        var logMsg = delayedMailOperation.LogMessages[i];
                        var shouldReindexAndSignal = String.IsNullOrWhiteSpace(delayedMailOperation.NewStatus) && i == delayedMailOperation.LogMessages.Count - 1;
                        _orderItemManager.AddLogItem(delayedMailOperation.InternalOrderId, logMsg.type, logMsg.message, eventId, shouldReindexAndSignal, shouldReindexAndSignal);
                    }

                    if (!String.IsNullOrWhiteSpace(delayedMailOperation.NewStatus))
                    {
                        _orderItemManager.SetStatus(delayedMailOperation.InternalOrderId, delayedMailOperation.NewStatus, eventId, true, true);
                    }
                }
                catch (Exception e)
                {
                    mailOperationResult.Success = false;
                    mailOperationResult.Message = "Delayed mail operation failed: " + e.Message;
                }
                res.Add(mailOperationResult);
            }

            return(res);
        }