EmailInterfaceForm.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using com.sun.org.apache.xpath.@internal;
  9. using Comal.Classes;
  10. using InABox.Clients;
  11. using InABox.Core;
  12. using InABox.DynamicGrid;
  13. using InABox.Mail;
  14. using InABox.Wpf;
  15. using InABox.WPF;
  16. namespace PRSDesktop;
  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 => InitializeField(ref _customer, nameof(Customer));
  33. private CustomerLink? _customer;
  34. public JobLink Job => InitializeField(ref _job, nameof(Job));
  35. private JobLink? _job;
  36. public TimeSpan Time { get; set; }
  37. }
  38. public class EmailInterfaceGrid : DynamicGrid<EmailInterface>
  39. {
  40. public static readonly DependencyProperty RootFolderProperty =
  41. DependencyProperty.Register(nameof(RootFolder), typeof(EmailRootFolder), typeof(EmailInterfaceGrid));
  42. public static readonly DependencyProperty
  43. FolderProperty = DependencyProperty.Register(nameof(Folder), typeof(string), typeof(EmailInterfaceGrid));
  44. public static readonly DependencyProperty CountProperty = DependencyProperty.Register(nameof(Count), typeof(int), typeof(EmailInterfaceGrid));
  45. private static readonly ICoreMailer mailer = ClientFactory.CreateMailer();
  46. public EmailInterfaceGrid()
  47. {
  48. Folder = "";
  49. FromDate = DateTime.MinValue;
  50. ToDate = DateTime.MaxValue;
  51. if (Mailer != null)
  52. try
  53. {
  54. Mailer.Connect();
  55. }
  56. catch (Exception)
  57. {
  58. MessageBox.Show("Unable to connect to email system!\nPlease configure this in User Settings");
  59. }
  60. else
  61. MessageBox.Show("Please configure Email Settings before continuing.");
  62. }
  63. protected override void Init()
  64. {
  65. base.Init();
  66. ActionColumns.Add(new DynamicImageColumn(InABox.Wpf.Resources.delete.AsBitmapImage(), EmailActionIgnore)
  67. { Position = DynamicActionColumnPosition.Start });
  68. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.minus.AsBitmapImage(), EmailLessTimeClick));
  69. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.plus.AsBitmapImage(), EmailMoreTimeClick));
  70. ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.tick.AsBitmapImage(), EmailActionClick));
  71. }
  72. protected override void DoReconfigure(DynamicGridOptions options)
  73. {
  74. base.DoReconfigure(options);
  75. options.RecordCount = true;
  76. options.DirectEdit = true;
  77. }
  78. public EmailRootFolder RootFolder
  79. {
  80. get => (EmailRootFolder)GetValue(RootFolderProperty);
  81. set => SetValue(RootFolderProperty, value);
  82. }
  83. public string Folder
  84. {
  85. get => (string)GetValue(FolderProperty);
  86. set => SetValue(FolderProperty, value);
  87. }
  88. public int Count
  89. {
  90. get => (int)GetValue(CountProperty);
  91. set => SetValue(CountProperty, value);
  92. }
  93. public Guid EmployeeID { get; set; }
  94. public Guid ActivityID { get; set; }
  95. public DateTime FromDate { get; set; }
  96. public DateTime ToDate { get; set; }
  97. public ICoreMailer Mailer => mailer;
  98. //Dictionary<String, Guid> validemails = new Dictionary<String, Guid>();
  99. protected override DynamicGridColumns LoadColumns()
  100. {
  101. var result = new DynamicGridColumns();
  102. result.Add<EmailInterface>(x => x.Date, 120, "Date", "dd MMM yy HH:mm", Alignment.MiddleCenter);
  103. result.Add<EmailInterface>(x => x.Folder, 60, "Folder", "", Alignment.MiddleCenter);
  104. result.Add<EmailInterface>(x => x.ID, 60, "ID", "", Alignment.MiddleCenter);
  105. result.Add<EmailInterface>(x => x.Customer.ID, 200, "Customer", "", Alignment.MiddleLeft);
  106. result.Add<EmailInterface>(x => x.Subject, 0, "Subject", "", Alignment.MiddleLeft);
  107. result.Add<EmailInterface>(x => x.Job.ID, 200, "Job", "", Alignment.MiddleLeft);
  108. result.Add<EmailInterface>(x => x.Time, 100, "Time", "", Alignment.MiddleCenter);
  109. //var cols = new Columns<EmailInterface>().Default(ColumnType.IncludeLinked);
  110. return result;
  111. }
  112. public override void DeleteItems(params CoreRow[] rows)
  113. {
  114. }
  115. public override EmailInterface LoadItem(CoreRow row)
  116. {
  117. return row.ToObject<EmailInterface>();
  118. }
  119. protected override void Reload(
  120. Filters<EmailInterface> criteria, Columns<EmailInterface> columns, ref SortOrder<EmailInterface>? sort,
  121. CancellationToken token, Action<CoreTable?, Exception?> action)
  122. {
  123. var result = new CoreTable();
  124. result.LoadColumns(typeof(EmailInterface));
  125. if (Mailer != null && Mailer.IsConnected)
  126. {
  127. var folder = Mailer.FindFolder(RootFolder.Equals(EmailRootFolder.Inbox) ? Mailer.Inbox : Mailer.SentItems, Folder);
  128. if (folder != null)
  129. {
  130. var index = Math.Max(folder.Count - Count, 0);
  131. var messages = Mailer.ListMessages(folder, index, index + (Count - 1));
  132. var filtered = messages.Where(x => x.Date.Date >= FromDate && x.Date.Date <= ToDate).ToArray();
  133. foreach (var message in (filtered as IEnumerable<ICoreMailSummary>).Reverse())
  134. if (message.Date.Date >= FromDate && message.Date.Date <= ToDate)
  135. {
  136. var email = "";
  137. if (RootFolder.Equals(EmailRootFolder.Inbox))
  138. email = message.From; // validemails.ContainsKey(message.From.ToUpper()) ? message.From.ToUpper() : "";
  139. else
  140. email = message.To.First();
  141. //foreach (var to in message.To)
  142. //{
  143. // if (validemails.ContainsKey(to.ToUpper()))
  144. // {
  145. // email = to.ToUpper();
  146. // break;
  147. // }
  148. //}
  149. var subject = message.Subject ?? "";
  150. if (!string.IsNullOrWhiteSpace(email) && !subject.StartsWith("[PRS:"))
  151. {
  152. var intf = new EmailInterface();
  153. intf.Folder = RootFolder;
  154. intf.ID = message.ID;
  155. intf.Date = message.Date;
  156. intf.Customer.ID = Guid.Empty; // validemails[email];
  157. intf.Subject = subject;
  158. result.LoadRow(intf);
  159. }
  160. }
  161. }
  162. }
  163. action.Invoke(result, null);
  164. }
  165. public override void SaveItem(EmailInterface item)
  166. {
  167. }
  168. private bool EmailMoreTimeClick(CoreRow? arg)
  169. {
  170. if (arg == null)
  171. return false;
  172. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  173. t = t.Floor(new TimeSpan(0, 15, 0)).Add(new TimeSpan(0, 15, 0));
  174. UpdateCell(arg.Index, "Time", t);
  175. return false;
  176. }
  177. private bool EmailLessTimeClick(CoreRow? arg)
  178. {
  179. if (arg == null)
  180. return false;
  181. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  182. t = t.Ceiling(new TimeSpan(0, 15, 0)).Subtract(new TimeSpan(0, 15, 0));
  183. if (t.Ticks < 0L)
  184. t = new TimeSpan(0);
  185. UpdateCell(arg.Index, "Time", t);
  186. return false;
  187. }
  188. private bool EmailActionIgnore(CoreRow? row)
  189. {
  190. if (row == null)
  191. return false;
  192. var id = row.Get<EmailInterface, string>(x => x.ID);
  193. var fld = RootFolder == EmailRootFolder.Sent ? Mailer.SentItems : Mailer.Inbox;
  194. var msg = Mailer.GetMessage(fld, id);
  195. msg.Subject = string.Format("[PRS:Ignore] {0}", msg.Subject);
  196. msg.Save();
  197. return true;
  198. }
  199. private bool EmailActionClick(CoreRow? arg)
  200. {
  201. if (arg == null)
  202. return false;
  203. var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
  204. if (t.Ticks == 0L)
  205. {
  206. MessageBox.Show("You must select a time");
  207. return false;
  208. }
  209. var bOK = true;
  210. var jobid = Entity.EntityLinkID<EmailInterface, JobLink>(x => x.Job, arg);
  211. var jobname = arg.Get<EmailInterface, string>(x => x.Subject);
  212. var jobnumber = "";
  213. if (jobid == null)
  214. {
  215. if (Security.IsAllowed<CanCreateJobsFromEmails>())
  216. bOK = MessageBox.Show("Create new job?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK;
  217. jobid = Guid.Empty;
  218. }
  219. else
  220. {
  221. var job = new Client<Job>().Query(
  222. Filter<Job>.Where(x => x.ID).IsEqualTo(jobid),
  223. Columns.None<Job>().Add(x => x.JobNumber, x => x.Name)).Rows
  224. .FirstOrDefault();
  225. jobname = job != null ? job.Get<Job, string>(x => x.Name) : "";
  226. jobnumber = job != null ? job.Get<Job, string>(x => x.JobNumber) : "";
  227. }
  228. if (bOK)
  229. {
  230. var ag = new AssignmentGrid();
  231. ag.OnBeforeSave += (editor, items) =>
  232. {
  233. var ass = items.FirstOrDefault() as Assignment;
  234. if (ass != null)
  235. {
  236. if (!ass.Job.IsValid() && Security.IsAllowed<CanCreateJobsFromEmails>())
  237. {
  238. var job = new Job();
  239. job.Name = jobname;
  240. job.Customer.ID = arg.Get<EmailInterface, Guid>(x => x.Customer.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.Job.ID = job.ID;
  250. ass.Job.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.Activity.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.Employee.ID = EmployeeID;
  269. ass.Job.ID = jobid ?? Guid.Empty;
  270. if (ag.EditItems(new[] { ass }))
  271. {
  272. msg.Subject = ass.Job.IsValid()
  273. ? string.Format("[PRS:{0}] {1}", ass.Job.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(Filter<Employee>.Where(x => x.User.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. }