123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408 |
- using System;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using com.sun.org.apache.xpath.@internal;
- using Comal.Classes;
- using InABox.Clients;
- using InABox.Core;
- using InABox.DynamicGrid;
- using InABox.Mail;
- using InABox.Wpf;
- using InABox.WPF;
- namespace PRSDesktop;
- public enum EmailRootFolder
- {
- Inbox,
- Sent
- }
- public class EmailInterface : BaseObject
- {
- [EnumLookupEditor(typeof(EmailRootFolder), Editable = Editable.Disabled)]
- public EmailRootFolder Folder { get; set; }
- [TextBoxEditor(Editable = Editable.Disabled)]
- public string ID { get; set; }
- [DateTimeEditor(Editable = Editable.Disabled)]
- public DateTime Date { get; set; }
- [TextBoxEditor(Editable = Editable.Disabled)]
- public string Subject { get; set; }
- public CustomerLink Customer => InitializeField(ref _customer, nameof(Customer));
- private CustomerLink? _customer;
- public JobLink Job => InitializeField(ref _job, nameof(Job));
- private JobLink? _job;
- public TimeSpan Time { get; set; }
- }
- public class EmailInterfaceGrid : DynamicGrid<EmailInterface>
- {
- public static readonly DependencyProperty RootFolderProperty =
- DependencyProperty.Register(nameof(RootFolder), typeof(EmailRootFolder), typeof(EmailInterfaceGrid));
- public static readonly DependencyProperty
- FolderProperty = DependencyProperty.Register(nameof(Folder), typeof(string), typeof(EmailInterfaceGrid));
- public static readonly DependencyProperty CountProperty = DependencyProperty.Register(nameof(Count), typeof(int), typeof(EmailInterfaceGrid));
- private static readonly ICoreMailer mailer = ClientFactory.CreateMailer();
- public EmailInterfaceGrid()
- {
- Folder = "";
- FromDate = DateTime.MinValue;
- ToDate = DateTime.MaxValue;
- if (Mailer != null)
- try
- {
- Mailer.Connect();
- }
- catch (Exception)
- {
- MessageBox.Show("Unable to connect to email system!\nPlease configure this in User Settings");
- }
- else
- MessageBox.Show("Please configure Email Settings before continuing.");
- }
- protected override void Init()
- {
- base.Init();
- ActionColumns.Add(new DynamicImageColumn(InABox.Wpf.Resources.delete.AsBitmapImage(), EmailActionIgnore)
- { Position = DynamicActionColumnPosition.Start });
- ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.minus.AsBitmapImage(), EmailLessTimeClick));
- ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.plus.AsBitmapImage(), EmailMoreTimeClick));
- ActionColumns.Add(new DynamicImageColumn(PRSDesktop.Resources.tick.AsBitmapImage(), EmailActionClick));
- }
- protected override void DoReconfigure(DynamicGridOptions options)
- {
- base.DoReconfigure(options);
- options.RecordCount = true;
- options.DirectEdit = true;
- }
- public EmailRootFolder RootFolder
- {
- get => (EmailRootFolder)GetValue(RootFolderProperty);
- set => SetValue(RootFolderProperty, value);
- }
- public string Folder
- {
- get => (string)GetValue(FolderProperty);
- set => SetValue(FolderProperty, value);
- }
- public int Count
- {
- get => (int)GetValue(CountProperty);
- set => SetValue(CountProperty, value);
- }
- public Guid EmployeeID { get; set; }
- public Guid ActivityID { get; set; }
- public DateTime FromDate { get; set; }
- public DateTime ToDate { get; set; }
- public ICoreMailer Mailer => mailer;
- //Dictionary<String, Guid> validemails = new Dictionary<String, Guid>();
- protected override DynamicGridColumns LoadColumns()
- {
- var result = new DynamicGridColumns();
- result.Add<EmailInterface>(x => x.Date, 120, "Date", "dd MMM yy HH:mm", Alignment.MiddleCenter);
- result.Add<EmailInterface>(x => x.Folder, 60, "Folder", "", Alignment.MiddleCenter);
- result.Add<EmailInterface>(x => x.ID, 60, "ID", "", Alignment.MiddleCenter);
- result.Add<EmailInterface>(x => x.Customer.ID, 200, "Customer", "", Alignment.MiddleLeft);
- result.Add<EmailInterface>(x => x.Subject, 0, "Subject", "", Alignment.MiddleLeft);
- result.Add<EmailInterface>(x => x.Job.ID, 200, "Job", "", Alignment.MiddleLeft);
- result.Add<EmailInterface>(x => x.Time, 100, "Time", "", Alignment.MiddleCenter);
- //var cols = new Columns<EmailInterface>().Default(ColumnType.IncludeLinked);
- return result;
- }
- public override void DeleteItems(params CoreRow[] rows)
- {
- }
- public override EmailInterface LoadItem(CoreRow row)
- {
- return row.ToObject<EmailInterface>();
- }
- protected override void Reload(
- Filters<EmailInterface> criteria, Columns<EmailInterface> columns, ref SortOrder<EmailInterface>? sort,
- CancellationToken token, Action<CoreTable?, Exception?> action)
- {
- var result = new CoreTable();
- result.LoadColumns(typeof(EmailInterface));
- if (Mailer != null && Mailer.IsConnected)
- {
- var folder = Mailer.FindFolder(RootFolder.Equals(EmailRootFolder.Inbox) ? Mailer.Inbox : Mailer.SentItems, Folder);
- if (folder != null)
- {
- var index = Math.Max(folder.Count - Count, 0);
- var messages = Mailer.ListMessages(folder, index, index + (Count - 1));
- var filtered = messages.Where(x => x.Date.Date >= FromDate && x.Date.Date <= ToDate).ToArray();
- foreach (var message in filtered.Reverse())
- if (message.Date.Date >= FromDate && message.Date.Date <= ToDate)
- {
- var email = "";
- if (RootFolder.Equals(EmailRootFolder.Inbox))
- email = message.From; // validemails.ContainsKey(message.From.ToUpper()) ? message.From.ToUpper() : "";
- else
- email = message.To.First();
- //foreach (var to in message.To)
- //{
- // if (validemails.ContainsKey(to.ToUpper()))
- // {
- // email = to.ToUpper();
- // break;
- // }
- //}
- var subject = message.Subject ?? "";
- if (!string.IsNullOrWhiteSpace(email) && !subject.StartsWith("[PRS:"))
- {
- var intf = new EmailInterface();
- intf.Folder = RootFolder;
- intf.ID = message.ID;
- intf.Date = message.Date;
- intf.Customer.ID = Guid.Empty; // validemails[email];
- intf.Subject = subject;
- result.LoadRow(intf);
- }
- }
- }
- }
- action.Invoke(result, null);
- }
- public override void SaveItem(EmailInterface item)
- {
- }
- private bool EmailMoreTimeClick(CoreRow? arg)
- {
- if (arg == null)
- return false;
- var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
- t = t.Floor(new TimeSpan(0, 15, 0)).Add(new TimeSpan(0, 15, 0));
- UpdateCell(arg.Index, "Time", t);
- return false;
- }
- private bool EmailLessTimeClick(CoreRow? arg)
- {
- if (arg == null)
- return false;
- var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
- t = t.Ceiling(new TimeSpan(0, 15, 0)).Subtract(new TimeSpan(0, 15, 0));
- if (t.Ticks < 0L)
- t = new TimeSpan(0);
- UpdateCell(arg.Index, "Time", t);
- return false;
- }
- private bool EmailActionIgnore(CoreRow? row)
- {
- if (row == null)
- return false;
- var id = row.Get<EmailInterface, string>(x => x.ID);
- var fld = RootFolder == EmailRootFolder.Sent ? Mailer.SentItems : Mailer.Inbox;
- var msg = Mailer.GetMessage(fld, id);
- msg.Subject = string.Format("[PRS:Ignore] {0}", msg.Subject);
- msg.Save();
- return true;
- }
- private bool EmailActionClick(CoreRow? arg)
- {
- if (arg == null)
- return false;
- var t = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
- if (t.Ticks == 0L)
- {
- MessageBox.Show("You must select a time");
- return false;
- }
- var bOK = true;
- var jobid = Entity.EntityLinkID<EmailInterface, JobLink>(x => x.Job, arg);
- var jobname = arg.Get<EmailInterface, string>(x => x.Subject);
- var jobnumber = "";
- if (jobid == null)
- {
- if (Security.IsAllowed<CanCreateJobsFromEmails>())
- bOK = MessageBox.Show("Create new job?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK;
- jobid = Guid.Empty;
- }
- else
- {
- var job = new Client<Job>().Query(
- new Filter<Job>(x => x.ID).IsEqualTo(jobid),
- Columns.None<Job>().Add(x => x.JobNumber, x => x.Name)).Rows
- .FirstOrDefault();
- jobname = job != null ? job.Get<Job, string>(x => x.Name) : "";
- jobnumber = job != null ? job.Get<Job, string>(x => x.JobNumber) : "";
- }
- if (bOK)
- {
- var ag = new AssignmentGrid();
- ag.OnBeforeSave += (editor, items) =>
- {
- var ass = items.FirstOrDefault() as Assignment;
- if (ass != null)
- {
- if (!ass.JobLink.IsValid() && Security.IsAllowed<CanCreateJobsFromEmails>())
- {
- var job = new Job();
- job.Name = jobname;
- job.Customer.ID = arg.Get<EmailInterface, Guid>(x => x.Customer.ID);
-
- job.JobType = JobType.Project;
- job.SiteLead.ID = EmployeeID;
- job.ProjectLead.ID = EmployeeID;
- //job.JobStatus = defstatus.ID;
- job.Notes = new[] { string.Format("As per email dated {0:dd MMM yy}", arg.Get<EmailInterface, DateTime>(x => x.Date)) };
- new Client<Job>().Save(job, "Created from Email Interface");
- foreach (var item in items)
- {
- ass.JobLink.ID = job.ID;
- ass.JobLink.JobNumber = job.JobNumber;
- }
- }
- }
- };
- var Time = arg.Get<EmailInterface, DateTime>(x => x.Date).TimeOfDay;
- var Duration = arg.Get<EmailInterface, TimeSpan>(x => x.Time);
- var ass = new Assignment();
- ass.Date = arg.Get<EmailInterface, DateTime>(x => x.Date).Date;
- ass.Actual.Start = RootFolder == EmailRootFolder.Inbox ? Time : Time.Subtract(Duration);
- ass.Actual.Duration = Duration;
- ass.Actual.Finish = ass.Actual.Start.Add(ass.Actual.Duration);
- ass.ActivityLink.ID = ActivityID;
- var id = arg.Get<EmailInterface, string>(x => x.ID);
- var fld = RootFolder == EmailRootFolder.Sent ? Mailer.SentItems : Mailer.Inbox;
- var msg = Mailer.GetMessage(fld, id);
- ass.Description = msg.Body != null ? CoreUtils.StripHTML(msg.Body) : "";
- //ass.Completed = DateTime.Now;
- ass.EmployeeLink.ID = EmployeeID;
- ass.JobLink.ID = jobid ?? Guid.Empty;
- if (ag.EditItems(new[] { ass }))
- {
- msg.Subject = ass.JobLink.IsValid()
- ? string.Format("[PRS:{0}] {1}", ass.JobLink.JobNumber, msg.Subject)
- : string.Format("[PRS:No Job] {0}", msg.Subject);
- msg.Save();
- return true;
- }
- }
- return false;
- }
- }
- /// <summary>
- /// Interaction logic for EmailInterfaceForm.xaml
- /// </summary>
- public partial class EmailInterfaceForm : ThemableWindow
- {
- public EmailInterfaceForm()
- {
- InitializeComponent();
- Preview.VisibleButtons = RichTextEditorButtons.None;
- Emails.OnSelectItem += Emails_OnSelectItem;
- var me = new Client<Employee>().Load(new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)).FirstOrDefault();
- Emails.EmployeeID = me?.ID ?? Guid.Empty;
- Emails.ActivityID = Guid.Empty;
- Employee.Content = me != null ? me.Name : "(No Employee Found)";
- }
- public DateTime FromDate
- {
- get => Emails.FromDate;
- set => Emails.FromDate = value;
- }
- public DateTime ToDate
- {
- get => Emails.ToDate;
- set => Emails.ToDate = value;
- }
- private void Emails_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
- {
- var row = e.Rows?.FirstOrDefault();
- if (!Emails.Mailer.IsConnected || row == null)
- return;
- var fld = Folder.SelectedIndex == 1 ? Emails.Mailer.SentItems : Emails.Mailer.Inbox;
- var mailer = Emails.Mailer;
- Task.Run(() =>
- {
- var id = row.Get<EmailInterface, string>(x => x.ID);
- var msg = mailer.GetMessage(fld, id);
- var text = CoreUtils.StripHTML(msg.Body);
- Dispatcher.BeginInvoke(new Action(() => { Preview.Text = text; }));
- });
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- Emails.Refresh(true, true);
- }
- private void Folder_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (Emails == null || !Emails.IsLoaded)
- return;
- Emails.RootFolder = Folder.SelectedIndex == 1 ? EmailRootFolder.Sent : EmailRootFolder.Inbox;
- Emails.Refresh(false, true);
- }
- private void Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (Emails == null || !Emails.IsLoaded)
- return;
- var value = ((ComboBoxItem)Items.SelectedValue).Content.ToString() ?? "";
- var count = value.Equals("All Items") ? int.MaxValue : int.Parse(value);
- Emails.Count = count;
- Emails.Refresh(false, true);
- }
- }
|