AppendixNotificationPlugin.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. using GreenTree.Nachtragsmanagement.Core.Plugins;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using GreenTree.Nachtragsmanagement.Core.Domain.Misc;
  7. using GreenTree.Nachtragsmanagement.Services.User;
  8. using GreenTree.Nachtragsmanagement.Services.Configuration;
  9. using GreenTree.Nachtragsmanagement.Services.Appendix;
  10. using GreenTree.Nachtragsmanagement.Core.Domain.Appendix;
  11. using System.Net.Mail;
  12. using System.Net;
  13. using System.Globalization;
  14. using Quartz;
  15. using GreenTree.Nachtragsmanagement.Services.Logging;
  16. using Autofac;
  17. using GreenTree.Nachtragsmanagement.Core;
  18. using GreenTree.Nachtragsmanagement.Core.Helper;
  19. namespace GreenTree.Nachtragsmanagement.Web.Implementations
  20. {
  21. public class AppendixNotificationPlugin : INotificationPlugin, IJob
  22. {
  23. #region Services
  24. private readonly IUserService _userService;
  25. private readonly IConfigurationService _configurationService;
  26. private readonly IAppendixService _appendixService;
  27. private readonly IServiceLogger _logger;
  28. #endregion
  29. #region Properties
  30. /// <summary>
  31. /// Id
  32. /// </summary>
  33. public Guid Id
  34. {
  35. get
  36. {
  37. return Guid.Parse("E99CA4A1-B3A9-4AA6-BBAD-9254CEED0A45");
  38. }
  39. }
  40. /// <summary>
  41. /// System name
  42. /// </summary>
  43. public string SystemName
  44. {
  45. get
  46. {
  47. return "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin";
  48. }
  49. }
  50. /// <summary>
  51. /// List of available notification jobs
  52. /// </summary>
  53. public List<NotificationJob> AvailableNotificationJobs
  54. {
  55. get
  56. {
  57. return new List<NotificationJob>
  58. {
  59. new NotificationJob
  60. (
  61. Guid.Parse("2F3642E0-259D-466D-8629-CB279F740313"),
  62. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate",
  63. "Verhandlungstermine überprüfen",
  64. "Erstellt automatisch Benachrichtigungen für Nachträge, die nach 8 Wochen nach Einreichung noch keinen " +
  65. "Verhandlungstermin gesetzt haben und ändert den entsprechenden Status ab"
  66. ),
  67. new NotificationJob
  68. (
  69. Guid.Parse("2E46B32A-1912-47F9-951E-C8188AA9BA50"),
  70. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol",
  71. "Verhandlungsprotokolle überprüfen",
  72. "Erstellt automatisch Benachrichtigungen für Nachträge, die nach 2 Wochen zwar verhandelt sind, " +
  73. "jedoch noch kein Protokoll aufweisen."
  74. ),
  75. new NotificationJob
  76. (
  77. Guid.Parse("B39FB44A-6E57-458C-A403-2C4FA7581F15"),
  78. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder",
  79. "Bestellnummern überprüfen",
  80. "Erstellt automatisch Benachrichtigungen für Nachträge, die nach 2 Wochen zwar verhandelt sind, " +
  81. "jedoch noch keine Bestellnummer aufweisen."
  82. )
  83. };
  84. }
  85. }
  86. /// <summary>
  87. /// Displayed name
  88. /// </summary>
  89. public string Name
  90. {
  91. get
  92. {
  93. return "Nachtragsbenachrichtigung";
  94. }
  95. }
  96. /// <summary>
  97. /// Further description on how this plugin works
  98. /// </summary>
  99. public string Description
  100. {
  101. get
  102. {
  103. return
  104. "Erstellt automatisch Benachrichtigungen für Nachträge, die nach 8 Wochen nach Einreichung noch keinen " +
  105. "Verhandlungstermin gesetzt haben und ändert den entsprechenden Status ab. Außerdem werden alle 2 Wochen " +
  106. "Benachrichtigungen für Nachträge erstellt, die zwar verhandelt sind, jedoch noch kein Protokoll aufweisen oder " +
  107. "keine Bestellnummer aufweisen.";
  108. }
  109. }
  110. #endregion
  111. /// <summary>
  112. /// Initializes a new instance of the AppendixNotificationPlugin class
  113. /// </summary>
  114. public AppendixNotificationPlugin() { }
  115. /// <summary>
  116. /// Initializes a new instance of the AppendixNotificationPlugin class
  117. /// </summary>
  118. public AppendixNotificationPlugin(
  119. IUserService userService,
  120. IConfigurationService configurationService,
  121. IAppendixService appendixService,
  122. IServiceLogger logger)
  123. {
  124. _userService = userService;
  125. _configurationService = configurationService;
  126. _appendixService = appendixService;
  127. _logger = logger;
  128. }
  129. #region Quartz implmentation
  130. /// <summary>
  131. /// Executes the current job
  132. /// </summary>
  133. /// <param name="context"></param>
  134. public void Execute(IJobExecutionContext context)
  135. {
  136. if (!context.JobDetail.JobDataMap.ContainsKey("MailNotifications"))
  137. return;
  138. var mailNotifications = context.JobDetail.JobDataMap.Get("MailNotifications") as IEnumerable<MailNotification>;
  139. ProcessNotifications(mailNotifications);
  140. }
  141. #endregion
  142. #region Processing
  143. /// <summary>
  144. /// Process all mail notifications registered for that plugin
  145. /// </summary>
  146. /// <param name="mailNotifications">The notifications which shall be generated.</param>
  147. public void ProcessNotifications(IEnumerable<MailNotification> mailNotifications)
  148. {
  149. if (mailNotifications == null || (mailNotifications != null && !mailNotifications.Any())) return;
  150. _logger.Information(
  151. String.Format(
  152. "Starte Verarbeitung Mail-Benachrichtigung in \"{0}\" für \"{1} ...",
  153. SystemName, mailNotifications.First().NotificationJobSystemName));
  154. foreach (var notification in mailNotifications)
  155. {
  156. try
  157. {
  158. switch (notification.NotificationJobSystemName)
  159. {
  160. case "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate":
  161. {
  162. ProcessNegotiationDateNotification(notification);
  163. }
  164. break;
  165. case "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol":
  166. {
  167. ProcessNegotiationProtocolNotification(notification);
  168. }
  169. break;
  170. case "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder":
  171. {
  172. ProcessNegotiationOrderNotification(notification);
  173. }
  174. break;
  175. default:
  176. continue;
  177. }
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.Error(
  182. String.Format(
  183. "Fehler bei Mail-Benachrichtigung in \"{0}\" für \"{1}", SystemName, notification.NotificationJobSystemName), ex);
  184. continue;
  185. }
  186. }
  187. _logger.Information(
  188. String.Format(
  189. "Verarbeitung Mail-Benachrichtigung in \"{0}\" für \"{1} erfolgreich abgeschlossen!",
  190. SystemName, mailNotifications.First().NotificationJobSystemName));
  191. }
  192. /// <summary>
  193. /// Sets the corresponding status for appendices which offering date is older than N weeks and notifies
  194. /// the correspondig recipients
  195. /// </summary>
  196. /// <param name="mailNotification">The notification which shall be generated.</param>
  197. private void ProcessNegotiationDateNotification(MailNotification mailNotification)
  198. {
  199. var ageDays = _configurationService.TryGetConfigItemValue<int>(
  200. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.AgeDays", 56);
  201. var stateSetId = _configurationService.TryGetConfigItemValue<int[]>(
  202. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.StateSet", new[] { 13 })[0];
  203. var stateConditionIds = _configurationService.TryGetConfigItemValue<int[]>(
  204. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.StateCondition", new[] { 1, 5, 6, 12 });
  205. var interval = _configurationService.TryGetConfigItemValue<int>(
  206. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationDate.Interval", 2);
  207. interval = interval == 0
  208. ? 1
  209. : interval;
  210. var finishStateId = _appendixService.GetFinishState().Id;
  211. var appendices = _appendixService.GetAllAppendices()
  212. .Where(a => a.OfferingDate.HasValue &&
  213. (DateTime.Now - a.OfferingDate).Value.Days >= ageDays &&
  214. a.StateId != stateSetId && a.StateId != finishStateId &&
  215. stateConditionIds.Contains(a.StateId.Value) && a.NegotiationDate == null)
  216. .ToList();
  217. var currentCalendarWeek = GetCalendarWeek(DateTime.Now);
  218. appendices = appendices
  219. .Where(a => (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) % interval == 0) ||
  220. (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) < 0))
  221. .OrderBy(a => a.Site == null
  222. ? null
  223. : a.Site.CustomNumber.TryGetInt())
  224. .ThenBy(a => a.CustomNumber.TryGetInt())
  225. .ToList();
  226. if (appendices.Any())
  227. {
  228. var mailBody = GenerateNegotiationDateMailBody(appendices);
  229. foreach (var appendix in appendices)
  230. {
  231. appendix.StateId = stateSetId;
  232. _appendixService.UpdateAppendix(appendix);
  233. }
  234. SendNotification(mailNotification, "Autom. Übersicht nicht verhandelte Nachträge", mailBody);
  235. }
  236. }
  237. /// <summary>
  238. /// Sets the corresponding status for appendices which negotiation date is older than N weeks and notifies
  239. /// the correspondig recipients when the protocol does not exist
  240. /// </summary>
  241. /// <param name="mailNotification">The notification which shall be generated.</param>
  242. private void ProcessNegotiationProtocolNotification(MailNotification mailNotification)
  243. {
  244. var ageDays = _configurationService.TryGetConfigItemValue<int>(
  245. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.AgeDays", 14);
  246. var interval = _configurationService.TryGetConfigItemValue<int>(
  247. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.Interval", 2);
  248. interval = interval == 0
  249. ? 1
  250. : interval;
  251. var finishStateId = _appendixService.GetFinishState().Id;
  252. var appendices = _appendixService.GetAllAppendices()
  253. .Where(a => a.NegotiationDate.HasValue &&
  254. (DateTime.Now - a.NegotiationDate).Value.Days >= ageDays &&
  255. !a.ProtocolExists && a.StateId != finishStateId)
  256. .ToList();
  257. var currentCalendarWeek = GetCalendarWeek(DateTime.Now);
  258. appendices = appendices
  259. .Where(a => (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) % interval == 0) ||
  260. (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) < 0))
  261. .OrderBy(a => a.Site == null
  262. ? null
  263. : a.Site.CustomNumber.TryGetInt())
  264. .ThenBy(a => a.CustomNumber.TryGetInt())
  265. .ToList();
  266. if (appendices.Any())
  267. {
  268. var mailBody = GenerateNegotiationProtocolMailBody(appendices);
  269. SendNotification(mailNotification, "Autom. Übersicht verhandelte Nachträge o. Protokoll", mailBody);
  270. }
  271. }
  272. /// <summary>
  273. /// Sets the corresponding status for appendices which negotiation date is older than N weeks and notifies
  274. /// the correspondig recipients when the order number is still missing
  275. /// </summary>
  276. /// <param name="mailNotification">The notification which shall be generated.</param>
  277. private void ProcessNegotiationOrderNotification(MailNotification mailNotification)
  278. {
  279. var ageDays = _configurationService.TryGetConfigItemValue<int>(
  280. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder.AgeDays", 14);
  281. var interval = _configurationService.TryGetConfigItemValue<int>(
  282. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder.Interval", 2);
  283. interval = interval == 0
  284. ? 1
  285. : interval;
  286. var finishStateId = _appendixService.GetFinishState().Id;
  287. var appendices = _appendixService.GetAllAppendices()
  288. .Where(a => a.NegotiationDate.HasValue &&
  289. (DateTime.Now - a.NegotiationDate).Value.Days >= ageDays &&
  290. String.IsNullOrEmpty(a.OrderNumber) && a.StateId != finishStateId)
  291. .ToList();
  292. var currentCalendarWeek = GetCalendarWeek(DateTime.Now);
  293. appendices = appendices
  294. .Where(a => (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) % interval == 0) ||
  295. (currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value) < 0))
  296. .OrderBy(a => a.Site == null
  297. ? null
  298. : a.Site.CustomNumber.TryGetInt())
  299. .ThenBy(a => a.CustomNumber.TryGetInt())
  300. .ToList();
  301. if (appendices.Any())
  302. {
  303. var mailBody = GenerateNegotiationOrderMailBody(appendices);
  304. SendNotification(mailNotification, "Autom. Übersicht verhandelte Nachträge o. Bestellnummer", mailBody);
  305. }
  306. }
  307. #endregion
  308. #region Mail body generation
  309. /// <summary>
  310. /// Generates a mail body with a list of all appendices with a offering date later than N weeks
  311. /// </summary>
  312. /// <param name="appendices">Appendices matching that criteria.</param>
  313. public string GenerateNegotiationDateMailBody(IEnumerable<Appendix> appendices)
  314. {
  315. var template =
  316. "<html>" +
  317. " <body>" +
  318. " <h3>Übersicht \"Nicht verhandelte Nachträge\"</h3>" +
  319. " <p>Folgende Nachträge haben ein Einreichdatum älter als 8 Wochen, jedoch noch kein Verhandlungstermin" +
  320. " gesetzt:</p>" +
  321. " <ul>" +
  322. " {0}" +
  323. " </ul>" +
  324. " </body>" +
  325. "</html>";
  326. if (!appendices.Any()) return String.Format(template, String.Empty);
  327. var appendicesList = String.Empty;
  328. foreach (var appendix in appendices)
  329. {
  330. appendicesList += String.Format(
  331. "<li>Baustelle <b>\"{0}\"</b> - Nachtrag <b>\"{1}\"</b> - Einreichdatum: <b>{2:dd.MM.yyyy}</b></i>",
  332. appendix.Site == null
  333. ? String.Empty
  334. : appendix.Site.CustomNumber,
  335. appendix.CustomNumber,
  336. appendix.OfferingDate);
  337. }
  338. return String.Format(template, appendicesList);
  339. }
  340. /// <summary>
  341. /// Generates a mail body with a list of all appendices with a negotiation date later than N weeks and not existing protocol
  342. /// </summary>
  343. /// <param name="appendices">Appendices matching that criteria.</param>
  344. public string GenerateNegotiationProtocolMailBody(IEnumerable<Appendix> appendices)
  345. {
  346. var template =
  347. "<html>" +
  348. " <body>" +
  349. " <h3>Übersicht \"Verhandelte Nachträge ohne Protokoll\"</h3>" +
  350. " <p>Folgende Nachträge haben ein Verhandlungstermin älter als zwei Wochen, jedoch noch kein Protokoll:" +
  351. " <ul>" +
  352. " {0}" +
  353. " </ul>" +
  354. " </body>" +
  355. "</html>";
  356. if (!appendices.Any()) return String.Format(template, String.Empty);
  357. var appendicesList = String.Empty;
  358. foreach (var appendix in appendices)
  359. {
  360. appendicesList += String.Format(
  361. "<li>Baustelle <b>\"{0}\"</b> - Nachtrag <b>\"{1}\"</b> - Verhandlungsdatum: <b>{2:dd.MM.yyyy}</b></i>",
  362. appendix.Site == null
  363. ? String.Empty
  364. : appendix.Site.CustomNumber,
  365. appendix.CustomNumber,
  366. appendix.NegotiationDate);
  367. }
  368. return String.Format(template, appendicesList);
  369. }
  370. /// <summary>
  371. /// Generates a mail body with a list of all appendices with a negotiation date later than N weeks and not existing order number
  372. /// </summary>
  373. /// <param name="appendices">Appendices matching that criteria.</param>
  374. public string GenerateNegotiationOrderMailBody(IEnumerable<Appendix> appendices)
  375. {
  376. var template =
  377. "<html>" +
  378. " <body>" +
  379. " <h3>Übersicht \"Verhandelte Nachträge ohne Bestellnummer\"</h3>" +
  380. " <p>Folgende Nachträge haben ein Verhandlungstermin älter als zwei Wochen, jedoch noch keine Bestellnummer:" +
  381. " <ul>" +
  382. " {0}" +
  383. " </ul>" +
  384. " </body>" +
  385. "</html>";
  386. if (!appendices.Any()) return String.Format(template, String.Empty);
  387. var appendicesList = String.Empty;
  388. foreach (var appendix in appendices)
  389. {
  390. appendicesList += String.Format(
  391. "<li> Baustelle <b>\"{1}\"</b> - Nachtrag <b>\"{0}\"</b> - Verhandlungsdatum: <b>{2:dd.MM.yyyy}</b></i>",
  392. appendix.Site == null
  393. ? String.Empty
  394. : appendix.Site.CustomNumber,
  395. appendix.CustomNumber,
  396. appendix.NegotiationDate);
  397. }
  398. return String.Format(template, appendicesList);
  399. }
  400. #endregion
  401. #region Mail sending
  402. /// <summary>
  403. /// Sends a generated mail body to the specified recipients in the mail notification
  404. /// </summary>
  405. /// <param name="mailNotification">The mail notification.</param>
  406. /// <param name="subject">The mail subject.</param>
  407. /// <param name="body">The mail body.</param>
  408. public void SendNotification(MailNotification mailNotification, string subject, string body)
  409. {
  410. if (mailNotification == null) return;
  411. var mailServerConfig = _configurationService.GetCurrentConfiguration().MailServerElement;
  412. var smptClient = new SmtpClient(mailServerConfig.SmtpServer, mailServerConfig.Port)
  413. {
  414. EnableSsl = mailServerConfig.UseSsl,
  415. Credentials = new NetworkCredential(
  416. mailServerConfig.Username,
  417. mailServerConfig.Password,
  418. mailServerConfig.Domain)
  419. };
  420. var recipients =
  421. mailNotification.Users
  422. .Select(u => u.MailAddress);
  423. var mailMessage = new MailMessage
  424. {
  425. IsBodyHtml = true,
  426. Subject = subject,
  427. Body = body,
  428. From = new MailAddress("Nachtragsbenachrichtigung@schweerbau.de")
  429. };
  430. foreach (var recipient in recipients)
  431. mailMessage.To.Add(recipient);
  432. smptClient.Send(mailMessage);
  433. }
  434. #endregion
  435. #region Helper
  436. /// <summary>
  437. /// Determines the calendar week of a specific datetime
  438. /// </summary>
  439. /// <param name="date">The datetime which calendarweek should be calculated.</param>
  440. public static int GetCalendarWeek(DateTime date)
  441. {
  442. var currentCulture = CultureInfo.CurrentCulture;
  443. var calendar = currentCulture.Calendar;
  444. var calendarWeek = calendar.GetWeekOfYear(
  445. date,
  446. currentCulture.DateTimeFormat.CalendarWeekRule,
  447. currentCulture.DateTimeFormat.FirstDayOfWeek);
  448. if (calendarWeek > 52)
  449. {
  450. date = date.AddDays(7);
  451. var testCalendarWeek = calendar.GetWeekOfYear(date,
  452. currentCulture.DateTimeFormat.CalendarWeekRule,
  453. currentCulture.DateTimeFormat.FirstDayOfWeek);
  454. if (testCalendarWeek == 2)
  455. calendarWeek = 1;
  456. }
  457. return calendarWeek;
  458. }
  459. #endregion
  460. }
  461. }