EmailInterfaceForm.xaml.cs 15 KB

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