EmailInterfaceForm.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using System;
  2. using System.Linq;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using com.sun.org.apache.xpath.@internal;
  8. using Comal.Classes;
  9. using InABox.Clients;
  10. using InABox.Core;
  11. using InABox.DynamicGrid;
  12. using InABox.Mail;
  13. using InABox.Wpf;
  14. using InABox.WPF;
  15. namespace PRSDesktop
  16. {
  17. public enum EmailRootFolder
  18. {
  19. Inbox,
  20. Sent
  21. }
  22. public class EmailInterface : BaseObject
  23. {
  24. [EnumLookupEditor(typeof(EmailRootFolder), Editable = Editable.Disabled)]
  25. public EmailRootFolder Folder { get; set; }
  26. [TextBoxEditor(Editable = Editable.Disabled)]
  27. public string ID { get; set; }
  28. [DateTimeEditor(Editable = Editable.Disabled)]
  29. public DateTime Date { get; set; }
  30. [TextBoxEditor(Editable = Editable.Disabled)]
  31. public string Subject { get; set; }
  32. public CustomerLink Customer { get; set; }
  33. public JobLink Job { get; set; }
  34. public TimeSpan Time { get; set; }
  35. }
  36. public class EmailInterfaceGrid : DynamicGrid<EmailInterface>
  37. {
  38. public static readonly DependencyProperty RootFolderProperty =
  39. DependencyProperty.Register(nameof(RootFolder), typeof(EmailRootFolder), typeof(EmailInterfaceGrid));
  40. public static readonly DependencyProperty
  41. FolderProperty = DependencyProperty.Register(nameof(Folder), typeof(string), typeof(EmailInterfaceGrid));
  42. public static readonly DependencyProperty CountProperty = DependencyProperty.Register(nameof(Count), typeof(int), typeof(EmailInterfaceGrid));
  43. private static readonly ICoreMailer mailer = ClientFactory.CreateMailer();
  44. public EmailInterfaceGrid()
  45. {
  46. Folder = "";
  47. FromDate = DateTime.MinValue;
  48. ToDate = DateTime.MaxValue;
  49. if (Mailer != null)
  50. try
  51. {
  52. Mailer.Connect();
  53. }
  54. catch (Exception)
  55. {
  56. MessageBox.Show("Unable to connect to email system!\nPlease configure this in User Settings");
  57. }
  58. else
  59. MessageBox.Show("Please configure Email Settings before continuing.");
  60. }
  61. protected override void Init()
  62. {
  63. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.delete.AsBitmapImage(), EmailActionIgnore)
  64. { Position = DynamicActionColumnPosition.Start });
  65. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.minus.AsBitmapImage(), EmailLessTimeClick));
  66. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.plus.AsBitmapImage(), EmailMoreTimeClick));
  67. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.tick.AsBitmapImage(), EmailActionClick));
  68. }
  69. protected override void DoReconfigure(DynamicGridOptions options)
  70. {
  71. options.RecordCount = true;
  72. options.DirectEdit = true;
  73. }
  74. public EmailRootFolder RootFolder
  75. {
  76. get => (EmailRootFolder)GetValue(RootFolderProperty);
  77. set => SetValue(RootFolderProperty, value);
  78. }
  79. public string Folder
  80. {
  81. get => (string)GetValue(FolderProperty);
  82. set => SetValue(FolderProperty, value);
  83. }
  84. public int Count
  85. {
  86. get => (int)GetValue(CountProperty);
  87. set => SetValue(CountProperty, value);
  88. }
  89. public Guid EmployeeID { get; set; }
  90. public Guid ActivityID { get; set; }
  91. public DateTime FromDate { get; set; }
  92. public DateTime ToDate { get; set; }
  93. public ICoreMailer Mailer => mailer;
  94. //Dictionary<String, Guid> validemails = new Dictionary<String, Guid>();
  95. protected override DynamicGridColumns LoadColumns()
  96. {
  97. var result = new DynamicGridColumns();
  98. result.Add<EmailInterface, DateTime>(x => x.Date, 120, "Date", "dd MMM yy HH:mm", Alignment.MiddleCenter);
  99. result.Add<EmailInterface, EmailRootFolder>(x => x.Folder, 60, "Folder", "", Alignment.MiddleCenter);
  100. result.Add<EmailInterface, string>(x => x.ID, 60, "ID", "", Alignment.MiddleCenter);
  101. result.Add<EmailInterface, Guid>(x => x.Customer.ID, 200, "Customer", "", Alignment.MiddleLeft);
  102. result.Add<EmailInterface, string>(x => x.Subject, 0, "Subject", "", Alignment.MiddleLeft);
  103. result.Add<EmailInterface, Guid>(x => x.Job.ID, 200, "Job", "", Alignment.MiddleLeft);
  104. result.Add<EmailInterface, TimeSpan>(x => x.Time, 100, "Time", "", Alignment.MiddleCenter);
  105. //var cols = new Columns<EmailInterface>().Default(ColumnType.IncludeLinked);
  106. return result;
  107. }
  108. public override void DeleteItems(params CoreRow[] rows)
  109. {
  110. }
  111. public override EmailInterface LoadItem(CoreRow row)
  112. {
  113. return row.ToObject<EmailInterface>();
  114. }
  115. protected override void Reload(
  116. Filters<EmailInterface> criteria, Columns<EmailInterface> columns, ref SortOrder<EmailInterface>? sort,
  117. CancellationToken token, Action<CoreTable?, Exception?> action)
  118. {
  119. var result = new CoreTable();
  120. result.LoadColumns(typeof(EmailInterface));
  121. if (Mailer != null && Mailer.IsConnected)
  122. {
  123. var folder = Mailer.FindFolder(RootFolder.Equals(EmailRootFolder.Inbox) ? Mailer.Inbox : Mailer.SentItems, Folder);
  124. if (folder != null)
  125. {
  126. var index = Math.Max(folder.Count - Count, 0);
  127. var messages = Mailer.ListMessages(folder, index, index + (Count - 1));
  128. var filtered = messages.Where(x => x.Date.Date >= FromDate && x.Date.Date <= ToDate).ToArray();
  129. foreach (var message in filtered.Reverse())
  130. if (message.Date.Date >= FromDate && message.Date.Date <= ToDate)
  131. {
  132. var email = "";
  133. if (RootFolder.Equals(EmailRootFolder.Inbox))
  134. email = message.From; // validemails.ContainsKey(message.From.ToUpper()) ? message.From.ToUpper() : "";
  135. else
  136. email = message.To.First();
  137. //foreach (var to in message.To)
  138. //{
  139. // if (validemails.ContainsKey(to.ToUpper()))
  140. // {
  141. // email = to.ToUpper();
  142. // break;
  143. // }
  144. //}
  145. var subject = message.Subject ?? "";
  146. if (!string.IsNullOrWhiteSpace(email) && !subject.StartsWith("[PRS:"))
  147. {
  148. var intf = new EmailInterface();
  149. intf.Folder = RootFolder;
  150. intf.ID = message.ID;
  151. intf.Date = message.Date;
  152. intf.Customer.ID = Guid.Empty; // validemails[email];
  153. intf.Subject = subject;
  154. result.LoadRow(intf);
  155. }
  156. }
  157. }
  158. }
  159. action.Invoke(result, null);
  160. }
  161. public override void SaveItem(EmailInterface item)
  162. {
  163. }
  164. private bool EmailMoreTimeClick(CoreRow? arg)
  165. {
  166. if (arg == null)
  167. return false;
  168. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  169. t = t.Floor(new TimeSpan(0, 15, 0)).Add(new TimeSpan(0, 15, 0));
  170. UpdateCell(arg.Index, "Time", t);
  171. return false;
  172. }
  173. private bool EmailLessTimeClick(CoreRow? arg)
  174. {
  175. if (arg == null)
  176. return false;
  177. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  178. t = t.Ceiling(new TimeSpan(0, 15, 0)).Subtract(new TimeSpan(0, 15, 0));
  179. if (t.Ticks < 0L)
  180. t = new TimeSpan(0);
  181. UpdateCell(arg.Index, "Time", t);
  182. return false;
  183. }
  184. private bool EmailActionIgnore(CoreRow? row)
  185. {
  186. if (row == null)
  187. return false;
  188. var id = row.Get<EmailInterface, string>(x => x.ID);
  189. var fld = RootFolder == EmailRootFolder.Sent ? Mailer.SentItems : Mailer.Inbox;
  190. var msg = Mailer.GetMessage(fld, id);
  191. msg.Subject = string.Format("[PRS:Ignore] {0}", msg.Subject);
  192. msg.Save();
  193. return true;
  194. }
  195. private bool EmailActionClick(CoreRow? arg)
  196. {
  197. if (arg == null)
  198. return false;
  199. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  200. if (t.Ticks == 0L)
  201. {
  202. MessageBox.Show("You must select a time");
  203. return false;
  204. }
  205. var bOK = true;
  206. var jobid = Entity.EntityLinkID<EmailInterface, JobLink>(x => x.Job, arg);
  207. var jobname = arg.Get<EmailInterface, string>(x => x.Subject);
  208. var jobnumber = "";
  209. if (jobid == null)
  210. {
  211. if (Security.IsAllowed<CanCreateJobsFromEmails>())
  212. bOK = MessageBox.Show("Create new job?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK;
  213. jobid = Guid.Empty;
  214. }
  215. else
  216. {
  217. var job = new Client<Job>().Query(
  218. new Filter<Job>(x => x.ID).IsEqualTo(jobid),
  219. Columns.None<Job>().Add(x => x.JobNumber, x => x.Name)).Rows
  220. .FirstOrDefault();
  221. jobname = job != null ? job.Get<Job, string>(x => x.Name) : "";
  222. jobnumber = job != null ? job.Get<Job, string>(x => x.JobNumber) : "";
  223. }
  224. if (bOK)
  225. {
  226. var ag = new AssignmentGrid();
  227. ag.OnBeforeSave += (editor, items) =>
  228. {
  229. var ass = items.FirstOrDefault() as Assignment;
  230. if (ass != null)
  231. {
  232. if (!ass.JobLink.IsValid() && Security.IsAllowed<CanCreateJobsFromEmails>())
  233. {
  234. var job = new Job();
  235. job.Name = jobname;
  236. job.Customer.ID = arg.Get<EmailInterface, Guid>(x => x.Customer.ID);
  237. var defstatus = new Client<JobStatus>().Query(new Filter<JobStatus>(x => x.Default).IsEqualTo(true));
  238. if (defstatus.Rows.Any())
  239. job.JobStatus.ID = defstatus.Rows.First().Get<JobStatus, Guid>(x => x.ID);
  240. job.JobType = JobType.Project;
  241. job.SiteLead.ID = EmployeeID;
  242. job.ProjectLead.ID = EmployeeID;
  243. //job.JobStatus = defstatus.ID;
  244. job.Notes = new[] { string.Format("As per email dated {0:dd MMM yy}", arg.Get<EmailInterface, DateTime>(x => x.Date)) };
  245. new Client<Job>().Save(job, "Created from Email Interface");
  246. foreach (var item in items)
  247. {
  248. ass.JobLink.ID = job.ID;
  249. ass.JobLink.JobNumber = job.JobNumber;
  250. }
  251. }
  252. }
  253. };
  254. var Time = arg.Get<EmailInterface, DateTime>(x => x.Date).TimeOfDay;
  255. var Duration = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  256. var ass = new Assignment();
  257. ass.Date = arg.Get<EmailInterface, DateTime>(x => x.Date).Date;
  258. ass.Actual.Start = RootFolder == EmailRootFolder.Inbox ? Time : Time.Subtract(Duration);
  259. ass.Actual.Duration = Duration;
  260. ass.Actual.Finish = ass.Actual.Start.Add(ass.Actual.Duration);
  261. ass.ActivityLink.ID = ActivityID;
  262. var id = arg.Get<EmailInterface, string>(x => x.ID);
  263. var fld = RootFolder == EmailRootFolder.Sent ? Mailer.SentItems : Mailer.Inbox;
  264. var msg = Mailer.GetMessage(fld, id);
  265. ass.Description = msg.Body != null ? CoreUtils.StripHTML(msg.Body) : "";
  266. //ass.Completed = DateTime.Now;
  267. ass.EmployeeLink.ID = EmployeeID;
  268. ass.JobLink.ID = jobid ?? Guid.Empty;
  269. if (ag.EditItems(new[] { ass }))
  270. {
  271. msg.Subject = ass.JobLink.IsValid()
  272. ? string.Format("[PRS:{0}] {1}", ass.JobLink.JobNumber, msg.Subject)
  273. : string.Format("[PRS:No Job] {0}", msg.Subject);
  274. msg.Save();
  275. return true;
  276. }
  277. }
  278. return false;
  279. }
  280. }
  281. /// <summary>
  282. /// Interaction logic for EmailInterfaceForm.xaml
  283. /// </summary>
  284. public partial class EmailInterfaceForm : ThemableWindow
  285. {
  286. public EmailInterfaceForm()
  287. {
  288. InitializeComponent();
  289. Preview.VisibleButtons = RichTextEditorButtons.None;
  290. Emails.OnSelectItem += Emails_OnSelectItem;
  291. var me = new Client<Employee>().Load(new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)).FirstOrDefault();
  292. Emails.EmployeeID = me?.ID ?? Guid.Empty;
  293. Emails.ActivityID = Guid.Empty;
  294. Employee.Content = me != null ? me.Name : "(No Employee Found)";
  295. }
  296. public DateTime FromDate
  297. {
  298. get => Emails.FromDate;
  299. set => Emails.FromDate = value;
  300. }
  301. public DateTime ToDate
  302. {
  303. get => Emails.ToDate;
  304. set => Emails.ToDate = value;
  305. }
  306. private void Emails_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  307. {
  308. var row = e.Rows?.FirstOrDefault();
  309. if (!Emails.Mailer.IsConnected || row == null)
  310. return;
  311. var fld = Folder.SelectedIndex == 1 ? Emails.Mailer.SentItems : Emails.Mailer.Inbox;
  312. var mailer = Emails.Mailer;
  313. Task.Run(() =>
  314. {
  315. var id = row.Get<EmailInterface, string>(x => x.ID);
  316. var msg = mailer.GetMessage(fld, id);
  317. var text = CoreUtils.StripHTML(msg.Body);
  318. Dispatcher.BeginInvoke(new Action(() => { Preview.Text = text; }));
  319. });
  320. }
  321. private void Window_Loaded(object sender, RoutedEventArgs e)
  322. {
  323. Emails.Refresh(true, true);
  324. }
  325. private void Folder_SelectionChanged(object sender, SelectionChangedEventArgs e)
  326. {
  327. if (Emails == null || !Emails.IsLoaded)
  328. return;
  329. Emails.RootFolder = Folder.SelectedIndex == 1 ? EmailRootFolder.Sent : EmailRootFolder.Inbox;
  330. Emails.Refresh(false, true);
  331. }
  332. private void Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
  333. {
  334. if (Emails == null || !Emails.IsLoaded)
  335. return;
  336. var value = ((ComboBoxItem)Items.SelectedValue).Content.ToString() ?? "";
  337. var count = value.Equals("All Items") ? int.MaxValue : int.Parse(value);
  338. Emails.Count = count;
  339. Emails.Refresh(false, true);
  340. }
  341. }
  342. }