AppendixNotificationPlugin.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. foreach (var appendix in appendices)
  219. {
  220. var h = (currentCalendarWeek - GetCalendarWeek(appendix.OfferingDate.Value)) % interval;
  221. }
  222. appendices = appendices
  223. .Where(a => ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) % interval == 0) ||
  224. ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) < 0))
  225. .OrderBy(a => a.Site == null
  226. ? null
  227. : a.Site.CustomNumber.TryGetInt())
  228. .ThenBy(a => a.CustomNumber.TryGetInt())
  229. .ToList();
  230. if (appendices.Any())
  231. {
  232. var mailBody = GenerateNegotiationDateMailBody(appendices);
  233. foreach (var appendix in appendices)
  234. {
  235. appendix.StateId = stateSetId;
  236. _appendixService.UpdateAppendix(appendix);
  237. }
  238. SendNotification(mailNotification, "Autom. Übersicht nicht verhandelte Nachträge", mailBody);
  239. }
  240. }
  241. /// <summary>
  242. /// Sets the corresponding status for appendices which negotiation date is older than N weeks and notifies
  243. /// the correspondig recipients when the protocol does not exist
  244. /// </summary>
  245. /// <param name="mailNotification">The notification which shall be generated.</param>
  246. private void ProcessNegotiationProtocolNotification(MailNotification mailNotification)
  247. {
  248. var ageDays = _configurationService.TryGetConfigItemValue<int>(
  249. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.AgeDays", 14);
  250. var interval = _configurationService.TryGetConfigItemValue<int>(
  251. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationProtocol.Interval", 2);
  252. interval = interval == 0
  253. ? 1
  254. : interval;
  255. var finishStateId = _appendixService.GetFinishState().Id;
  256. var appendices = _appendixService.GetAllAppendices()
  257. .Where(a => a.NegotiationDate.HasValue &&
  258. (DateTime.Now - a.NegotiationDate).Value.Days >= ageDays &&
  259. !a.ProtocolExists && a.StateId != finishStateId)
  260. .ToList();
  261. var currentCalendarWeek = GetCalendarWeek(DateTime.Now);
  262. appendices = appendices
  263. .Where(a => ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) % interval == 0) ||
  264. ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) < 0))
  265. .OrderBy(a => a.Site == null
  266. ? null
  267. : a.Site.CustomNumber.TryGetInt())
  268. .ThenBy(a => a.CustomNumber.TryGetInt())
  269. .ToList();
  270. if (appendices.Any())
  271. {
  272. var mailBody = GenerateNegotiationProtocolMailBody(appendices);
  273. SendNotification(mailNotification, "Autom. Übersicht verhandelte Nachträge o. Protokoll", mailBody);
  274. }
  275. }
  276. /// <summary>
  277. /// Sets the corresponding status for appendices which negotiation date is older than N weeks and notifies
  278. /// the correspondig recipients when the order number is still missing
  279. /// </summary>
  280. /// <param name="mailNotification">The notification which shall be generated.</param>
  281. private void ProcessNegotiationOrderNotification(MailNotification mailNotification)
  282. {
  283. var ageDays = _configurationService.TryGetConfigItemValue<int>(
  284. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder.AgeDays", 14);
  285. var interval = _configurationService.TryGetConfigItemValue<int>(
  286. "GreenTree.Nachtragsmanagement.AppendixNotificationPlugin.ProcessNegotiationOrder.Interval", 2);
  287. interval = interval == 0
  288. ? 1
  289. : interval;
  290. var finishStateId = _appendixService.GetFinishState().Id;
  291. var appendices = _appendixService.GetAllAppendices()
  292. .Where(a => a.NegotiationDate.HasValue &&
  293. (DateTime.Now - a.NegotiationDate).Value.Days >= ageDays &&
  294. String.IsNullOrEmpty(a.OrderNumber) && a.StateId != finishStateId)
  295. .ToList();
  296. var currentCalendarWeek = GetCalendarWeek(DateTime.Now);
  297. appendices = appendices
  298. .Where(a => ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) % interval == 0) ||
  299. ((currentCalendarWeek - GetCalendarWeek(a.OfferingDate.Value)) < 0))
  300. .OrderBy(a => a.Site == null
  301. ? null
  302. : a.Site.CustomNumber.TryGetInt())
  303. .ThenBy(a => a.CustomNumber.TryGetInt())
  304. .ToList();
  305. if (appendices.Any())
  306. {
  307. var mailBody = GenerateNegotiationOrderMailBody(appendices);
  308. SendNotification(mailNotification, "Autom. Übersicht verhandelte Nachträge o. Bestellnummer", mailBody);
  309. }
  310. }
  311. #endregion
  312. #region Mail body generation
  313. /// <summary>
  314. /// Generates a mail body with a list of all appendices with a offering date later than N weeks
  315. /// </summary>
  316. /// <param name="appendices">Appendices matching that criteria.</param>
  317. public string GenerateNegotiationDateMailBody(IEnumerable<Appendix> appendices)
  318. {
  319. var template =
  320. "<html>" +
  321. " <body>" +
  322. " <h3>Übersicht \"Nicht verhandelte Nachträge\"</h3>" +
  323. " <p>Folgende Nachträge haben ein Einreichdatum älter als 8 Wochen, jedoch noch kein Verhandlungstermin" +
  324. " gesetzt:</p>" +
  325. " <ul>" +
  326. " {0}" +
  327. " </ul>" +
  328. " </body>" +
  329. "</html>";
  330. if (!appendices.Any()) return String.Format(template, String.Empty);
  331. var appendicesList = String.Empty;
  332. foreach (var appendix in appendices)
  333. {
  334. appendicesList += String.Format(
  335. "<li>Baustelle <b>\"{0}\"</b> - Nachtrag <b>\"{1}\"</b> - Einreichdatum: <b>{2:dd.MM.yyyy}</b></i>",
  336. appendix.Site == null
  337. ? String.Empty
  338. : appendix.Site.CustomNumber,
  339. appendix.CustomNumber,
  340. appendix.OfferingDate);
  341. }
  342. return String.Format(template, appendicesList);
  343. }
  344. /// <summary>
  345. /// Generates a mail body with a list of all appendices with a negotiation date later than N weeks and not existing protocol
  346. /// </summary>
  347. /// <param name="appendices">Appendices matching that criteria.</param>
  348. public string GenerateNegotiationProtocolMailBody(IEnumerable<Appendix> appendices)
  349. {
  350. var template =
  351. "<html>" +
  352. " <body>" +
  353. " <h3>Übersicht \"Verhandelte Nachträge ohne Protokoll\"</h3>" +
  354. " <p>Folgende Nachträge haben ein Verhandlungstermin älter als zwei Wochen, jedoch noch kein Protokoll:" +
  355. " <ul>" +
  356. " {0}" +
  357. " </ul>" +
  358. " </body>" +
  359. "</html>";
  360. if (!appendices.Any()) return String.Format(template, String.Empty);
  361. var appendicesList = String.Empty;
  362. foreach (var appendix in appendices)
  363. {
  364. appendicesList += String.Format(
  365. "<li>Baustelle <b>\"{0}\"</b> - Nachtrag <b>\"{1}\"</b> - Verhandlungsdatum: <b>{2:dd.MM.yyyy}</b></i>",
  366. appendix.Site == null
  367. ? String.Empty
  368. : appendix.Site.CustomNumber,
  369. appendix.CustomNumber,
  370. appendix.NegotiationDate);
  371. }
  372. return String.Format(template, appendicesList);
  373. }
  374. /// <summary>
  375. /// Generates a mail body with a list of all appendices with a negotiation date later than N weeks and not existing order number
  376. /// </summary>
  377. /// <param name="appendices">Appendices matching that criteria.</param>
  378. public string GenerateNegotiationOrderMailBody(IEnumerable<Appendix> appendices)
  379. {
  380. var template =
  381. "<html>" +
  382. " <body>" +
  383. " <h3>Übersicht \"Verhandelte Nachträge ohne Bestellnummer\"</h3>" +
  384. " <p>Folgende Nachträge haben ein Verhandlungstermin älter als zwei Wochen, jedoch noch keine Bestellnummer:" +
  385. " <ul>" +
  386. " {0}" +
  387. " </ul>" +
  388. " </body>" +
  389. "</html>";
  390. if (!appendices.Any()) return String.Format(template, String.Empty);
  391. var appendicesList = String.Empty;
  392. foreach (var appendix in appendices)
  393. {
  394. appendicesList += String.Format(
  395. "<li>Baustelle <b>\"{0}\"</b> - Nachtrag <b>\"{1}\"</b> - Verhandlungsdatum: <b>{2:dd.MM.yyyy}</b></i>",
  396. appendix.Site == null
  397. ? String.Empty
  398. : appendix.Site.CustomNumber,
  399. appendix.CustomNumber,
  400. appendix.NegotiationDate);
  401. }
  402. return String.Format(template, appendicesList);
  403. }
  404. #endregion
  405. #region Mail sending
  406. /// <summary>
  407. /// Sends a generated mail body to the specified recipients in the mail notification
  408. /// </summary>
  409. /// <param name="mailNotification">The mail notification.</param>
  410. /// <param name="subject">The mail subject.</param>
  411. /// <param name="body">The mail body.</param>
  412. public void SendNotification(MailNotification mailNotification, string subject, string body)
  413. {
  414. if (mailNotification == null) return;
  415. var mailServerConfig = _configurationService.GetCurrentConfiguration().MailServerElement;
  416. var smptClient = new SmtpClient(mailServerConfig.SmtpServer, mailServerConfig.Port)
  417. {
  418. EnableSsl = mailServerConfig.UseSsl,
  419. Credentials = new NetworkCredential(
  420. mailServerConfig.Username,
  421. mailServerConfig.Password,
  422. mailServerConfig.Domain)
  423. };
  424. var recipients =
  425. mailNotification.Users
  426. .Select(u => u.MailAddress);
  427. var mailMessage = new MailMessage
  428. {
  429. IsBodyHtml = true,
  430. Subject = subject,
  431. Body = body,
  432. From = new MailAddress("Nachtragsbenachrichtigung@schweerbau.de")
  433. };
  434. foreach (var recipient in recipients)
  435. mailMessage.To.Add(recipient);
  436. smptClient.Send(mailMessage);
  437. }
  438. #endregion
  439. #region Helper
  440. /// <summary>
  441. /// Determines the calendar week of a specific datetime
  442. /// </summary>
  443. /// <param name="date">The datetime which calendarweek should be calculated.</param>
  444. public static int GetCalendarWeek(DateTime date)
  445. {
  446. var currentCulture = CultureInfo.CurrentCulture;
  447. var calendar = currentCulture.Calendar;
  448. var calendarWeek = calendar.GetWeekOfYear(
  449. date,
  450. currentCulture.DateTimeFormat.CalendarWeekRule,
  451. currentCulture.DateTimeFormat.FirstDayOfWeek);
  452. if (calendarWeek > 52)
  453. {
  454. date = date.AddDays(7);
  455. var testCalendarWeek = calendar.GetWeekOfYear(date,
  456. currentCulture.DateTimeFormat.CalendarWeekRule,
  457. currentCulture.DateTimeFormat.FirstDayOfWeek);
  458. if (testCalendarWeek == 2)
  459. calendarWeek = 1;
  460. }
  461. return calendarWeek;
  462. }
  463. #endregion
  464. }
  465. }