EmailInterfaceForm.xaml.cs 14 KB

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