JobResourcePlanner.xaml.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using Comal.Classes;
  13. using InABox.Clients;
  14. using InABox.Configuration;
  15. using InABox.Core;
  16. using InABox.DynamicGrid;
  17. using InABox.WPF;
  18. using NPOI.SS.Formula.Functions;
  19. using PRSDesktop.WidgetGroups;
  20. using Syncfusion.UI.Xaml.Grid;
  21. using Syncfusion.Windows.Tools.Controls;
  22. using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
  23. namespace PRSDesktop
  24. {
  25. public class JobResourcePlannerProperties : IUserConfigurationSettings, IDashboardProperties
  26. {
  27. public JobSelectorSettings JobSettings { get; set; }
  28. public JobSelectorData JobSelection { get; set; }
  29. public Guid ActivityType { get; set; }
  30. public int MonthsToView { get; set; }
  31. public TeamSelectorSettings TeamSettings { get; set; }
  32. public TeamSelectorData TeamSelection { get; set; }
  33. public double SplitterPosition { get; set; }
  34. public double HoursPerDay { get; set; }
  35. public double EmployeeSplitterPosition { get; set; }
  36. public bool IncludeUnApprovedLeave { get; set; }
  37. public JobResourcePlannerProperties()
  38. {
  39. JobSettings = new JobSelectorSettings();
  40. JobSelection = new JobSelectorData();
  41. TeamSettings = new TeamSelectorSettings();
  42. TeamSelection = new TeamSelectorData();
  43. MonthsToView = 1;
  44. SplitterPosition = 0F;
  45. EmployeeSplitterPosition = 0F;
  46. HoursPerDay = 8.5;
  47. ActivityType = Guid.Empty;
  48. IncludeUnApprovedLeave = false;
  49. }
  50. }
  51. public partial class JobResourcePlanner : UserControl
  52. {
  53. private enum Suppress
  54. {
  55. This
  56. }
  57. private ActivityModel[] _activities = new ActivityModel[] { };
  58. private LeaveRequestModel[] _leaverequests = new LeaveRequestModel[] { };
  59. private StandardLeaveModel[] _standardleaves = new StandardLeaveModel[] { };
  60. private JobModel[] _jobs = new JobModel[] { };
  61. private EmployeeResourceModel[] _emps = new EmployeeResourceModel[] { };
  62. private List<AssignmentModel> _assignments = new List<AssignmentModel>();
  63. public JobResourcePlannerProperties Properties { get; set; }
  64. public event LoadSettings<JobResourcePlannerProperties>? LoadSettings;
  65. public event SaveSettings<JobResourcePlannerProperties>? SaveSettings;
  66. private void DoLoadSettings()
  67. {
  68. Properties = LoadSettings?.Invoke(this);
  69. }
  70. private void DoSaveSettings()
  71. {
  72. SaveSettings?.Invoke(this, Properties);
  73. }
  74. public JobResourcePlanner()
  75. {
  76. using (new EventSuppressor(Suppress.This))
  77. InitializeComponent();
  78. }
  79. public void Setup()
  80. {
  81. using (new EventSuppressor(Suppress.This))
  82. {
  83. DoLoadSettings();
  84. JobSelector.Setup();
  85. JobSelector.Settings = Properties.JobSettings;
  86. JobSelector.Selection = Properties.JobSelection;
  87. _jobs = JobSelector.GetJobData<JobModel>(r => new JobModel(r));
  88. TeamSelector.Setup();
  89. TeamSelector.Settings = Properties.TeamSettings;
  90. TeamSelector.Selection = Properties.TeamSelection;
  91. _emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>(r => new EmployeeResourceModel(r));
  92. ViewWindow.ItemsSource = new Dictionary<int, String>()
  93. {
  94. { 1, "1 Month" },
  95. { 3, "3 Months" },
  96. { 6, "6 Months" },
  97. { 12, "12 months" }
  98. };
  99. ViewWindow.SelectedValue = Properties.MonthsToView;
  100. if (Properties.SplitterPosition != 0F)
  101. TeamSelectorRow.Height = new GridLength(Properties.SplitterPosition, GridUnitType.Pixel);
  102. if (Properties.EmployeeSplitterPosition != 0F)
  103. AvailableEmployeesRow.Height = new GridLength(Properties.SplitterPosition, GridUnitType.Pixel);
  104. HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
  105. LeaveType.SelectedIndex = Properties.IncludeUnApprovedLeave ? 1 : 0;
  106. AvailableEmployees.Refresh(true, false);
  107. AssignedEmployees.Refresh(true, false);
  108. MultiQuery query = new MultiQuery();
  109. query.Add<StandardLeave>(
  110. LookupFactory.DefineFilter<StandardLeave>(),
  111. StandardLeaveModel.Columns
  112. );
  113. query.Add<LeaveRequest>(
  114. new Filter<LeaveRequest>(x => x.Status).IsNotEqualTo(LeaveRequestStatus.Rejected),
  115. LeaveRequestModel.Columns
  116. );
  117. query.Add<Activity>(
  118. LookupFactory.DefineFilter<Activity>(),
  119. new Columns<Activity>(x => x.ID).Add(x => x.Code).Add(x => x.Description),
  120. new SortOrder<Activity>(x => x.Code)
  121. );
  122. query.Query();
  123. _standardleaves = query.Get<StandardLeave>().Rows.Select(r=>new StandardLeaveModel(r)).ToArray();
  124. _leaverequests = query.Get<LeaveRequest>().Rows.Select(r => new LeaveRequestModel(r)).ToArray();
  125. _activities = query.Get<Activity>().Rows.Select(r => new ActivityModel(r)).ToArray();
  126. ActivityType.ItemsSource = _activities;
  127. ActivityType.SelectedValue = Properties.ActivityType;
  128. }
  129. }
  130. public void Shutdown()
  131. {
  132. }
  133. private bool GetStandardLeaveTimes(DateTime date, out TimeSpan start, out TimeSpan finish)
  134. {
  135. bool result = false;
  136. start = TimeSpan.Zero;
  137. finish = TimeSpan.FromDays(1);
  138. var requests = _standardleaves.Where(x =>
  139. (x.From <= date)
  140. && (x.To.Add(x.ToTime) > date)
  141. );
  142. if (requests.Any())
  143. {
  144. result = true;
  145. start = TimeSpan.FromDays(1);
  146. finish = TimeSpan.Zero;
  147. foreach (var leave in requests)
  148. {
  149. var curstart = leave.From == date ? leave.FromTime : TimeSpan.Zero;
  150. start = start > curstart ? curstart : start;
  151. var curfinish = leave.To == date ? leave.ToTime : TimeSpan.FromDays(1);
  152. finish = finish < curfinish ? curfinish : finish;
  153. }
  154. }
  155. return result;
  156. }
  157. private void AdjustStandardLeave(DateTime date, ref TimeSpan time)
  158. {
  159. TimeSpan result = TimeSpan.Zero;
  160. var leaves = _standardleaves.Where(x =>
  161. (x.From <= date)
  162. && (x.To.Add(x.ToTime) > date)
  163. );
  164. foreach (var leave in leaves)
  165. {
  166. result += (leave.To == date ? leave.ToTime : TimeSpan.FromDays(1)) -
  167. (leave.From == date ? leave.FromTime : TimeSpan.Zero);
  168. }
  169. time = time >= result ? time - result : TimeSpan.Zero;
  170. }
  171. private bool GetLeaveRequestTimes(DateTime date, EmployeeResourceModel emp, out TimeSpan start, out TimeSpan finish)
  172. {
  173. bool result = false;
  174. start = TimeSpan.Zero;
  175. finish = TimeSpan.FromDays(1);
  176. var requests = _leaverequests.Where(x =>
  177. (x.From <= date)
  178. && (x.To.Add(x.ToTime) > date)
  179. && (x.EmployeeID == emp.ID)
  180. && (Properties.IncludeUnApprovedLeave ? true : x.Status == LeaveRequestStatus.Approved)
  181. );
  182. if (requests.Any())
  183. {
  184. result = true;
  185. start = TimeSpan.FromDays(1);
  186. finish = TimeSpan.Zero;
  187. foreach (var leave in requests)
  188. {
  189. var curstart = leave.From == date ? leave.FromTime : TimeSpan.Zero;
  190. start = start > curstart ? curstart : start;
  191. var curfinish = leave.To == date ? leave.ToTime : TimeSpan.FromDays(1);
  192. finish = finish < curfinish ? curfinish : finish;
  193. }
  194. }
  195. return result;
  196. }
  197. private void AdjustLeaveRequests(DateTime date, EmployeeResourceModel emp, ref TimeSpan time)
  198. {
  199. TimeSpan result = TimeSpan.Zero;
  200. var requests = _leaverequests.Where(x =>
  201. (x.From <= date)
  202. && (x.To.Add(x.ToTime) > date)
  203. && (x.EmployeeID == emp.ID)
  204. && (Properties.IncludeUnApprovedLeave ? true : x.Status == LeaveRequestStatus.Approved)
  205. );
  206. foreach (var leave in requests)
  207. {
  208. result += (leave.To == date ? leave.ToTime : TimeSpan.FromDays(1)) -
  209. (leave.From == date ? leave.FromTime : TimeSpan.Zero);
  210. }
  211. time = time >= result ? time - result : TimeSpan.Zero;
  212. }
  213. public void Refresh()
  214. {
  215. using (new WaitCursor())
  216. {
  217. var jobids = _jobs.Select(x => x.ID).ToArray();
  218. var empids = _emps.Select(x => x.ID).ToArray();
  219. var actids = _activities.Select(x => x.ID).ToArray();
  220. DateTime todate = DateTime.Today.AddMonths(Properties.MonthsToView);
  221. MultiQuery query = new MultiQuery();
  222. query.Add<Assignment>(
  223. new Filter<Assignment>(x=>x.EmployeeLink.ID).InList(empids)
  224. .And(x=>x.Date).IsGreaterThanOrEqualTo(DateTime.Today)
  225. .And(x=>x.Date).IsLessThanOrEqualTo(DateTime.Today.AddMonths(Properties.MonthsToView)),
  226. AssignmentModel.Columns
  227. );
  228. query.Query();
  229. _assignments = query.Get<Assignment>().Rows.Select(r => new AssignmentModel(r)).ToList();
  230. var data = new DataTable();
  231. data.Columns.Add("Date", typeof(DateTime));
  232. data.PrimaryKey = new System.Data.DataColumn[] { data.Columns[0] };
  233. data.Columns.Add("Total", typeof(object));
  234. data.Columns.Add("Available", typeof(object));
  235. foreach (var job in _jobs)
  236. data.Columns.Add(job.ID.ToString(), typeof(object));
  237. DateTime date = DateTime.Today;
  238. while (date <= DateTime.Today.AddMonths(Properties.MonthsToView))
  239. {
  240. double avail = 0.0F;
  241. foreach (var emp in _emps)
  242. {
  243. var roster = RosterUtils.GetRoster(emp.Roster, emp.Start, date);
  244. var hours = roster.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue)
  245. .Aggregate<RosterBlock, TimeSpan>(TimeSpan.Zero, (value, block) => value + block.Duration);
  246. AdjustStandardLeave(date, ref hours);
  247. AdjustLeaveRequests(date, emp, ref hours);
  248. avail += hours.TotalHours;
  249. }
  250. double total = avail;
  251. var values = new List<object> { date };
  252. var anyjobstoday = _assignments.Where(x => (x.Date.Date == date.Date));
  253. avail -= anyjobstoday.Aggregate<AssignmentModel, double>(0F, (value, model) => value + model.BookedDuration.TotalHours);
  254. foreach (var job in _jobs)
  255. {
  256. var thisjobtoday = _assignments.Where(x => (x.Date.Date == date.Date) && (x.JobID == job.ID));
  257. if (thisjobtoday.Any())
  258. {
  259. var assigned = thisjobtoday.Aggregate<AssignmentModel, double>(0F,
  260. (value, model) => value + model.BookedDuration.TotalHours);
  261. values.Add(assigned / Properties.HoursPerDay);
  262. }
  263. else
  264. values.Add(null);
  265. }
  266. values.Insert(1,avail / Properties.HoursPerDay);
  267. values.Insert(1,total / Properties.HoursPerDay);
  268. data.Rows.Add(values.ToArray());
  269. date = date.AddDays(1);
  270. }
  271. dataGrid.ItemsSource = data;
  272. }
  273. }
  274. private abstract class LeaveConverter : IMultiValueConverter
  275. {
  276. protected System.Windows.Media.Color GetColor(object[] value)
  277. {
  278. if ((value[0] != DBNull.Value) && (value[0] != DependencyProperty.UnsetValue))
  279. return Colors.DarkSeaGreen;
  280. if (value[1] is GridCell cell)
  281. {
  282. if (cell.DataContext is DataRowView rowview)
  283. {
  284. var total = rowview.Row["Total"];
  285. if ((total == DBNull.Value) || ((double)total == 0.0F))
  286. return Colors.LightGray;
  287. var avail = rowview.Row["Available"];
  288. if ((avail == DBNull.Value) || ((double)avail == 0.0F))
  289. return Colors.LightSalmon;
  290. return Colors.LightYellow;
  291. }
  292. }
  293. return Colors.WhiteSmoke;
  294. }
  295. public abstract object Convert(object[] value, Type targetType, object parameter, CultureInfo culture);
  296. public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
  297. {
  298. throw new NotImplementedException();
  299. }
  300. }
  301. private class LeaveBackgroundConverter : LeaveConverter
  302. {
  303. public override object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
  304. {
  305. return new SolidColorBrush(base.GetColor(value)) { Opacity = 0.8 };
  306. }
  307. }
  308. private class LeaveForegroundConverter : LeaveConverter
  309. {
  310. public override object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
  311. {
  312. return new SolidColorBrush(ImageUtils.GetForegroundColor(base.GetColor(value)));
  313. }
  314. }
  315. private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e)
  316. {
  317. MultiBinding CreateBinding<TConverter>(String path) where TConverter : IMultiValueConverter, new()
  318. {
  319. var binding = new MultiBinding();
  320. binding.Bindings.Add(new Binding(path));
  321. binding.Bindings.Add(new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.Self) });
  322. binding.Converter = new TConverter();
  323. return binding;
  324. }
  325. var value = (e.Column.ValueBinding as Binding)!;
  326. if (value.Path.Path.Equals("Date"))
  327. {
  328. e.Column.Width = 80;
  329. e.Column.HeaderStyle = Resources["DateHeaderStyle"] as Style;
  330. e.Column.AllowFocus = false;
  331. }
  332. else if (value.Path.Path.Equals("Total"))
  333. {
  334. e.Cancel = true;
  335. }
  336. else if (value.Path.Path.Equals("Available"))
  337. {
  338. e.Column = new GridNumericColumn() { NumberDecimalDigits = 2, MappingName = e.Column.MappingName};
  339. e.Column.Width = 50;
  340. e.Column.HeaderStyle = e.Column.HeaderStyle = Resources["ContentHeaderStyle"] as Style;
  341. e.Column.AllowFocus = false;
  342. e.Column.HeaderText = "Available";
  343. }
  344. else
  345. {
  346. e.Column = new GridNumericColumn() { NumberDecimalDigits = 2, MappingName = e.Column.MappingName};
  347. e.Column.Width = 40;
  348. e.Column.HeaderStyle = Resources["ContentHeaderStyle"] as Style;
  349. var jobid = Guid.Parse(value.Path.Path);
  350. e.Column.HeaderText = _jobs.FirstOrDefault(x=>x.ID == jobid)?.Name ?? jobid.ToString();
  351. e.Column.DisplayBinding = new Binding { Path = new PropertyPath(e.Column.MappingName) };
  352. e.Column.AllowFocus = true;
  353. var style = new Style(typeof(GridCell));
  354. style.Setters.Add(new Setter(BackgroundProperty, CreateBinding<LeaveBackgroundConverter>(value.Path.Path)));
  355. style.Setters.Add(new Setter(ForegroundProperty, CreateBinding<LeaveForegroundConverter>(value.Path.Path)));
  356. e.Column.CellStyle = style;
  357. }
  358. e.Column.TextAlignment = TextAlignment.Center;
  359. e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
  360. e.Column.ColumnSizer = GridLengthUnitType.None;
  361. e.Column.ShowHeaderToolTip = false;
  362. e.Column.ShowToolTip = false;
  363. }
  364. private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
  365. {
  366. var emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>(r => new EmployeeResourceModel(r));
  367. }
  368. private void DataGrid_OnSelectionChanging(object? sender, GridSelectionChangingEventArgs e)
  369. {
  370. }
  371. private bool bResettingSelection = false;
  372. private void DataGrid_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
  373. {
  374. bResettingSelection = true;
  375. dataGrid.SelectionController.ClearSelections(false);
  376. }
  377. private void DataGrid_OnCurrentCellActivating(object? sender, CurrentCellActivatingEventArgs e)
  378. {
  379. if (bResettingSelection)
  380. {
  381. bResettingSelection = false;
  382. return;
  383. }
  384. var thiscol = dataGrid.Columns[e.CurrentRowColumnIndex.ColumnIndex];
  385. var selected = dataGrid.SelectionController.SelectedCells;
  386. if (selected.Any(x => x.Column != thiscol))
  387. e.Cancel = true;
  388. else
  389. e.Cancel = false;
  390. }
  391. private void DataGrid_OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
  392. {
  393. }
  394. private bool ExtractSelection(out Guid jobid, out DateTime[] dates)
  395. {
  396. var selected = dataGrid.SelectionController.SelectedCells;
  397. var colname = selected.Select(x => x.Column.MappingName).Distinct().FirstOrDefault();
  398. if (Guid.TryParse(colname, out Guid job))
  399. {
  400. jobid = job;
  401. dates = selected.Select(x => ((DataRowView)x.RowData).Row["Date"]).Cast<DateTime>().ToArray();
  402. return true;
  403. }
  404. else
  405. {
  406. jobid = Guid.Empty;
  407. dates = new DateTime[] { };
  408. return false;
  409. }
  410. }
  411. private void DataGrid_OnMouseUp(object sender, MouseButtonEventArgs e)
  412. {
  413. if (ExtractSelection(out Guid jobid, out DateTime[] dates))
  414. {
  415. LoadAssignedEmployees(jobid, dates);
  416. LoadAvailableEmployees(dates);
  417. }
  418. }
  419. private JobPlannerEmployee GetEmployee(Guid id, List<JobPlannerEmployee> list)
  420. {
  421. var result = list.FirstOrDefault(x => x.ID == id);
  422. if (result == null)
  423. {
  424. result = new JobPlannerEmployee()
  425. {
  426. ID = id,
  427. Name = _emps.FirstOrDefault(x=>x.ID == id)?.Name ?? id.ToString(),
  428. Time = TimeSpan.Zero
  429. };
  430. list.Add(result);
  431. }
  432. return result;
  433. }
  434. private void LoadAvailableEmployees(DateTime[] dates)
  435. {
  436. List<JobPlannerEmployee> availableemployees = new List<JobPlannerEmployee>();
  437. foreach (var emp in _emps)
  438. {
  439. foreach (var date in dates)
  440. {
  441. var roster = RosterUtils.GetRoster(emp.Roster, emp.Start, date);
  442. var blocks = roster?.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue) ?? new RosterBlock[] { };
  443. var rostered = blocks.Aggregate(TimeSpan.Zero, (time, block) => time += block.Duration);
  444. AdjustStandardLeave(date, ref rostered);
  445. AdjustLeaveRequests(date, emp, ref rostered);
  446. var assignments = _assignments.Where(x => (x.Date == date) && (x.EmployeeID == emp.ID));
  447. var assigned = assignments.Aggregate(TimeSpan.Zero, (time, assign) => time += assign.BookedDuration);
  448. if (rostered > assigned)
  449. GetEmployee(emp.ID, availableemployees).Time += rostered.Subtract(assigned);
  450. AvailableEmployees.Items = availableemployees.OrderBy(x=>x.Name).ToList();
  451. AvailableEmployees.Refresh(false, true);
  452. }
  453. }
  454. }
  455. private void LoadAssignedEmployees(Guid jobid, DateTime[] dates)
  456. {
  457. List<JobPlannerEmployee> assignedemployees = new List<JobPlannerEmployee>();
  458. foreach (var assignment in _assignments.Where(x => dates.Contains(x.Date) && (x.JobID == jobid)))
  459. GetEmployee(assignment.EmployeeID,assignedemployees).Time += assignment.BookedDuration;
  460. AssignedEmployees.Items = assignedemployees.OrderBy(x=>x.Name).ToList();;
  461. AssignedEmployees.Refresh(false, true);
  462. }
  463. private void JobSelector_OnSettingsChanged(object sender, JobSelectorSettingsChangedArgs args)
  464. {
  465. if (EventSuppressor.IsSet(Suppress.This))
  466. return;
  467. Properties.JobSettings = args.Settings;
  468. DoSaveSettings();
  469. }
  470. private void JobSelector_OnSelectionChanged(object sender, JobSelectorSelectionChangedArgs args)
  471. {
  472. if (EventSuppressor.IsSet(Suppress.This))
  473. return;
  474. Properties.JobSelection = args.Selection;
  475. _jobs = JobSelector.GetJobData<JobModel>(x => new JobModel(x));
  476. DoSaveSettings();
  477. Refresh();
  478. }
  479. private void TeamSelector_OnSettingsChanged(object sender, TeamSelectorSettingsChangedArgs args)
  480. {
  481. if (EventSuppressor.IsSet(Suppress.This))
  482. return;
  483. Properties.TeamSettings = args.Settings;
  484. DoSaveSettings();
  485. }
  486. private void TeamSelector_OnSelectionChanged(object sender, TeamSelectorSelectionChangedArgs args)
  487. {
  488. if (EventSuppressor.IsSet(Suppress.This))
  489. return;
  490. Properties.TeamSelection = args.Selection;
  491. _emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>(x => new EmployeeResourceModel(x));
  492. DoSaveSettings();
  493. Refresh();
  494. }
  495. private void JobSelector_OnSizeChanged(object sender, SizeChangedEventArgs e)
  496. {
  497. if (EventSuppressor.IsSet(Suppress.This))
  498. return;
  499. Properties.SplitterPosition = TeamSelectorRow.Height.Value;
  500. DoSaveSettings();
  501. }
  502. private void ViewWindow_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  503. {
  504. if (EventSuppressor.IsSet(Suppress.This))
  505. return;
  506. Properties.MonthsToView = (int)ViewWindow.SelectedValue;
  507. DoSaveSettings();
  508. Refresh();
  509. }
  510. private void HoursSelector_Down_Click(object sender, RoutedEventArgs e)
  511. {
  512. Properties.HoursPerDay = Math.Max(0.25F, Properties.HoursPerDay - 0.25);
  513. HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
  514. DoSaveSettings();
  515. Refresh();
  516. }
  517. private void HoursSelector_Up_Click(object sender, RoutedEventArgs e)
  518. {
  519. Properties.HoursPerDay = Math.Min(24F, Properties.HoursPerDay + 0.25);
  520. HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
  521. DoSaveSettings();
  522. Refresh();
  523. }
  524. private void ActivityType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  525. {
  526. if (EventSuppressor.IsSet(Suppress.This))
  527. return;
  528. Properties.ActivityType = (Guid)(ActivityType.SelectedValue ?? Guid.Empty);
  529. DoSaveSettings();
  530. }
  531. private void AvailableEmployees_OnSizeChanged(object sender, SizeChangedEventArgs e)
  532. {
  533. if (EventSuppressor.IsSet(Suppress.This))
  534. return;
  535. Properties.EmployeeSplitterPosition = AvailableEmployeesRow.Height.Value;
  536. DoSaveSettings();
  537. }
  538. private void AvailableEmployees_OnOnAction(object sender, JobPlannerEmployee[] availables)
  539. {
  540. List<TimeSpan> edges = new List<TimeSpan>();
  541. void CheckEdges(params TimeSpan[] times)
  542. {
  543. foreach (var time in times)
  544. {
  545. if (!edges.Contains(time))
  546. edges.Add(time);
  547. }
  548. }
  549. bool IsRostered(RosterBlock[] blocks, TimeSpan start, TimeSpan finish)
  550. {
  551. foreach (var block in blocks)
  552. {
  553. if ((block.Start <= start) && (block.Finish >= finish))
  554. return true;
  555. }
  556. return false;
  557. }
  558. bool IsStandardLeave(DateTime date, TimeSpan start, TimeSpan finish)
  559. {
  560. return _standardleaves.Any(x =>
  561. (x.From.Add(x.FromTime) <= date.Add(start))
  562. && (x.To.Add(x.ToTime) >= date.Add(finish))
  563. );
  564. }
  565. bool IsLeaveRequest(DateTime date, EmployeeResourceModel emp, TimeSpan start, TimeSpan finish)
  566. {
  567. return _leaverequests.Any(x =>
  568. (x.EmployeeID == emp.ID)
  569. && (x.From.Add(x.FromTime) <= date.Add(start))
  570. && (x.To.Add(x.ToTime) >= date.Add(finish))
  571. );
  572. }
  573. bool IsAssigned(AssignmentModel[] assignments, TimeSpan start, TimeSpan finish)
  574. {
  575. foreach (var assignment in assignments)
  576. {
  577. if ((assignment.BookedStart <= start) && (assignment.BookedFinish >= finish))
  578. return true;
  579. }
  580. return false;
  581. }
  582. if (ExtractSelection(out Guid jobid, out DateTime[] dates))
  583. {
  584. if (dataGrid.ItemsSource is DataTable table)
  585. {
  586. List<Assignment> updates = new List<Assignment>();
  587. foreach (var available in availables)
  588. {
  589. foreach (var date in dates)
  590. {
  591. var emp = _emps.FirstOrDefault(x => x.ID == available.ID);
  592. if (emp != null)
  593. {
  594. var roster = RosterUtils.GetRoster(emp.Roster, emp.Start, date);
  595. var blocks = roster?.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue) ?? new RosterBlock[] { };
  596. foreach (var block in blocks)
  597. CheckEdges(block.Start, block.Finish);
  598. if (GetStandardLeaveTimes(date, out TimeSpan stdleavestart, out TimeSpan stdleavefinish))
  599. CheckEdges(stdleavestart, stdleavefinish);
  600. if (GetLeaveRequestTimes(date, emp, out TimeSpan leaverequeststart, out TimeSpan leaverequestfinish))
  601. CheckEdges(leaverequeststart, leaverequestfinish);
  602. var assignments = _assignments.Where(x => (x.Date == date) && (x.EmployeeID == emp.ID)).ToArray();
  603. foreach (var assignment in assignments)
  604. CheckEdges(assignment.BookedStart, assignment.BookedFinish);
  605. edges.Sort();
  606. double adjustment = 0.0F;
  607. for (int i = 0; i < edges.Count - 1; i++)
  608. {
  609. var start = edges[i];
  610. var finish = edges[i + 1];
  611. if (IsRostered(blocks, start, finish)
  612. && (!IsStandardLeave(date,start,finish))
  613. && (!IsLeaveRequest(date,emp,start,finish))
  614. && !IsAssigned(assignments, start, finish))
  615. {
  616. Assignment assignment = new Assignment();
  617. assignment.ActivityLink.ID = Properties.ActivityType;
  618. assignment.EmployeeLink.ID = emp.ID;
  619. assignment.Date = date;
  620. assignment.JobLink.ID = jobid;
  621. assignment.Booked.Start = start;
  622. assignment.Booked.Finish = finish;
  623. assignment.Booked.Duration = finish - start;
  624. updates.Add(assignment);
  625. adjustment += assignment.Booked.Duration.TotalHours;
  626. }
  627. }
  628. System.Data.DataRow row = table.Rows.Find(date);
  629. row.BeginEdit();
  630. double jobvalue = (row[jobid.ToString()] == DBNull.Value)
  631. ? adjustment / Properties.HoursPerDay
  632. : (double)row[jobid.ToString()] + (adjustment / Properties.HoursPerDay);
  633. row[jobid.ToString()] = jobvalue <= 0F ? null : jobvalue;
  634. row["Available"] = Math.Max(0F, (double)row["Available"] - (adjustment / Properties.HoursPerDay));
  635. row.EndEdit();
  636. }
  637. }
  638. var entry = AvailableEmployees.Items.FirstOrDefault(x => x.ID == available.ID);
  639. if (entry != null)
  640. {
  641. AvailableEmployees.Items.Remove(entry);
  642. GetEmployee(entry.ID, AssignedEmployees.Items).Time += entry.Time;
  643. }
  644. }
  645. if (updates.Any())
  646. {
  647. using (new WaitCursor())
  648. {
  649. new Client<Assignment>().Save(updates, "Assigned by Job Planner");
  650. CoreTable temp = new CoreTable();
  651. temp.LoadColumns(typeof(Assignment));
  652. temp.LoadRows(updates);
  653. _assignments.AddRange(temp.Rows.Select(r => new AssignmentModel(r)));
  654. AssignedEmployees.Items = AssignedEmployees.Items.OrderBy(x => x.Name).ToList();
  655. AssignedEmployees.Refresh(false, true);
  656. AvailableEmployees.Refresh(false, true);
  657. }
  658. }
  659. }
  660. }
  661. }
  662. private void AssignedEmployees_OnOnAction(object sender, JobPlannerEmployee[] employees)
  663. {
  664. if (ExtractSelection(out Guid jobid, out DateTime[] dates))
  665. {
  666. if (dataGrid.ItemsSource is DataTable table)
  667. {
  668. foreach (var date in dates)
  669. {
  670. var emptimes = _assignments.Where(x =>
  671. (x.JobID == jobid)
  672. && (x.Date == date)
  673. && employees.Any(e => e.ID == x.EmployeeID)
  674. ).ToArray();
  675. var emptime = emptimes.Aggregate(TimeSpan.Zero, (time, ass) => time += ass.BookedDuration);
  676. System.Data.DataRow row = table.Rows.Find(date);
  677. row.BeginEdit();
  678. double value = (row[jobid.ToString()] == DBNull.Value)
  679. ? 0.0F
  680. : (double)row[jobid.ToString()] - (emptime.TotalHours / Properties.HoursPerDay);
  681. row[jobid.ToString()] = value <= 0F ? null : value;
  682. row["Available"] = (double)row["Available"] + (emptime.TotalHours/Properties.HoursPerDay);
  683. row.EndEdit();
  684. }
  685. }
  686. var assignments = _assignments.Where(x =>
  687. (x.JobID == jobid)
  688. && dates.Contains(x.Date)
  689. && employees.Any(e => e.ID == x.EmployeeID)
  690. ).ToArray();
  691. if (assignments.Any())
  692. {
  693. using (new WaitCursor())
  694. {
  695. var deletes = assignments.Select(x => new Assignment() { ID = x.ID }).ToArray();
  696. new Client<Assignment>().Delete(deletes, "Deleted from Job Planner");
  697. var removes = AssignedEmployees.Items.Where(x => employees.Any(e => e.ID == x.ID)).ToArray();
  698. foreach (var remove in removes)
  699. {
  700. AssignedEmployees.Items.Remove(remove);
  701. GetEmployee(remove.ID, AssignedEmployees.Items).Time += remove.Time;
  702. }
  703. AssignedEmployees.Refresh(false, true);
  704. AvailableEmployees.Items = AvailableEmployees.Items.OrderBy(x => x.Name).ToList();
  705. AvailableEmployees.Refresh(false, true);
  706. foreach (var assignment in assignments)
  707. _assignments.Remove(assignment);
  708. }
  709. }
  710. }
  711. }
  712. private void LeaveType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  713. {
  714. if (EventSuppressor.IsSet(Suppress.This))
  715. return;
  716. Properties.IncludeUnApprovedLeave = LeaveType.SelectedIndex > 0;
  717. DoSaveSettings();
  718. Refresh();
  719. }
  720. }
  721. }