private void UpdateExistingOrdersFromLibris() { try { var orders = GetSearchResultsForAllActiveOrdersThatAreOrderedFromLibris(); foreach (var order in orders) { var addressStr = ConfigurationManager.AppSettings["librisApiBaseAddress"] + "/api/illrequests/Z/" + order.ProviderOrderId; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("api-key", ConfigurationManager.AppSettings["librisApiKey"]); var task = httpClient.GetStringAsync(new Uri(addressStr)); task.Wait(); var illRequestsQueryResult = JsonConvert.DeserializeObject <dynamic>(task.Result); var illRequests = illRequestsQueryResult.ill_requests; var illRequestsCount = illRequestsQueryResult.count.Value; if (illRequestsCount == 0) { _result.Errors++; _result.Messages.Add("Couldn't find any Libris ILL request with the ID: " + order.ProviderOrderId); } else { for (int index = 0; index < illRequestsCount; index++) { var req = illRequests[index]; if (order.Status == "03:Beställd" && req.status_code.Value == "6") // Status code 6 is "Negativt svar" in Libris { var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_LIBRIS_DATA_EVENT_TYPE); _orderItemManager.SetStatus(order.NodeId, "02:Åtgärda", eventId, false, false); _orderItemManager.AddLogItem(order.NodeId, "LIBRIS", "Negativt svar. " + ConfigurationManager.AppSettings["librisApiBaseAddress"] + "/lf.php?action=notfullfilled&id=" + req.request_id.Value, eventId); } else if (order.Status == "03:Beställd" && req.status_code.Value == "7") // Status code 7 is "Kan reserveras" in Libris { var eventId = _orderItemManager.GenerateEventId(UPDATE_ORDER_FROM_LIBRIS_DATA_EVENT_TYPE); _orderItemManager.SetStatus(order.NodeId, "02:Åtgärda", eventId, false, false); _orderItemManager.AddLogItem(order.NodeId, "LIBRIS", "Kan reserveras." + ConfigurationManager.AppSettings["librisApiBaseAddress"] + "/lf.php?action=may_reserve&id=" + req.request_id.Value, eventId); } } } } } catch (Exception e) { throw new SourcePollingException("Error when updating existing orders from Libris.", e); } }
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)); }
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); } }
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)); }
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 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 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); }