EmailInterfaceForm.xaml.cs 16 KB

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