| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Drawing;
- using System.Globalization;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Input;
- using System.Windows.Media;
- using Comal.Classes;
- using InABox.Clients;
- using InABox.Configuration;
- using InABox.Core;
- using InABox.DynamicGrid;
- using InABox.WPF;
- using NPOI.SS.Formula.Functions;
- using PRSDesktop.WidgetGroups;
- using System.ComponentModel;
- using Syncfusion.UI.Xaml.Grid;
- using Syncfusion.Windows.Tools.Controls;
- using SelectionChangedEventArgs = System.Windows.Controls.SelectionChangedEventArgs;
- using PRS.Shared;
- using Columns = InABox.Core.Columns;
- using InABox.Wpf;
- using MYOB.AccountRight.SDK.Extensions;
- using Syncfusion.Data.Extensions;
- using NPOI.OpenXmlFormats.Spreadsheet;
- using Syncfusion.UI.Xaml.Scheduler;
- using Color = System.Drawing.Color;
- namespace PRSDesktop;
- public enum JobPlannerDisplayMode
- {
- JobColumns,
- DateColumns
- }
- public class JobResourcePlannerProperties : IUserConfigurationSettings, IDashboardProperties
- {
- public JobSelectorSettings JobSettings { get; set; }
- public JobSelectorData JobSelection { get; set; }
-
- public Guid ActivityType { get; set; }
-
- public int MonthsToView { get; set; }
- public TeamSelectorSettings TeamSettings { get; set; }
- public TeamSelectorData TeamSelection { get; set; }
- public double SplitterPosition { get; set; }
- public double HoursPerDay { get; set; }
- public double EmployeeSplitterPosition { get; set; }
- public bool IncludeUnApprovedLeave { get; set; }
- public JobPlannerDisplayMode DisplayMode { get; set; }
-
- public JobResourcePlannerProperties()
- {
- JobSettings = new JobSelectorSettings();
- JobSelection = new JobSelectorData();
- TeamSettings = new TeamSelectorSettings();
- TeamSelection = new TeamSelectorData();
- MonthsToView = 1;
- SplitterPosition = 0F;
- EmployeeSplitterPosition = 0F;
- HoursPerDay = 8.5;
- ActivityType = Guid.Empty;
- IncludeUnApprovedLeave = false;
- DisplayMode = JobPlannerDisplayMode.DateColumns;
- }
- }
- public partial class JobResourcePlanner : UserControl
- {
- private enum Suppress
- {
- This
- }
- private ActivityModel[] _activities = new ActivityModel[] { };
- private LeaveRequestModel[] _leaverequests = new LeaveRequestModel[] { };
- private StandardLeaveModel[] _standardleaves = new StandardLeaveModel[] { };
- private JobModel[] _jobs = new JobModel[] { };
- private EmployeeResourceModel[] _emps = new EmployeeResourceModel[] { };
- private List<AssignmentModel> _assignments = new List<AssignmentModel>();
- private DateTime[] _dates = Array.Empty<DateTime>();
- private double[] _totals = Array.Empty<double>();
- private double[] _available = Array.Empty<double>();
-
- public JobResourcePlannerProperties Properties { get; set; }
- public event LoadSettings<JobResourcePlannerProperties>? LoadSettings;
- public event SaveSettings<JobResourcePlannerProperties>? SaveSettings;
-
- private void DoLoadSettings()
- {
- Properties = LoadSettings?.Invoke(this) ?? new JobResourcePlannerProperties();
- }
-
- private void DoSaveSettings()
- {
- SaveSettings?.Invoke(this, Properties);
- }
- public JobResourcePlanner()
- {
- using (new EventSuppressor(Suppress.This))
- InitializeComponent();
- }
-
- public void Setup()
- {
- using (new EventSuppressor(Suppress.This))
- {
- DoLoadSettings();
-
- JobSelector.Setup();
- JobSelector.Settings = Properties.JobSettings;
- JobSelector.Selection = Properties.JobSelection;
- _jobs = JobSelector.GetJobData<JobModel>(r => new JobModel(r));
- TeamSelector.Setup();
- TeamSelector.Settings = Properties.TeamSettings;
- TeamSelector.Selection = Properties.TeamSelection;
- _emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>((row, rosters) => new EmployeeResourceModel(row, rosters));
-
- ViewWindow.ItemsSource = new Dictionary<int, String>()
- {
- { 1, "1 Month" },
- { 3, "3 Months" },
- { 6, "6 Months" },
- { 12, "12 months" }
- };
- ViewWindow.SelectedValue = Properties.MonthsToView;
-
- if (Properties.SplitterPosition != 0F)
- TeamSelectorRow.Height = new GridLength(Properties.SplitterPosition, GridUnitType.Pixel);
- if (Properties.EmployeeSplitterPosition != 0F)
- AvailableEmployeesRow.Height = new GridLength(Properties.SplitterPosition, GridUnitType.Pixel);
- HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
-
- LeaveType.SelectedIndex = Properties.IncludeUnApprovedLeave ? 1 : 0;
- Orientation.SelectedIndex = Properties.DisplayMode == JobPlannerDisplayMode.JobColumns ? 1 : 0;
- AvailableEmployees.Refresh(true, false);
- AssignedEmployees.Refresh(true, false);
-
- MultiQuery query = new MultiQuery();
-
- query.Add<StandardLeave>(
- LookupFactory.DefineFilter<StandardLeave>(),
- StandardLeaveModel.Columns
- );
-
- query.Add<LeaveRequest>(
- new Filter<LeaveRequest>(x => x.Status).IsNotEqualTo(LeaveRequestStatus.Rejected),
- LeaveRequestModel.Columns
- );
- query.Add<Activity>(
- LookupFactory.DefineFilter<Activity>(),
- Columns.None<Activity>().Add(x => x.ID).Add(x => x.Code).Add(x => x.Description),
- new SortOrder<Activity>(x => x.Code)
- );
- query.Query();
- _standardleaves = query.Get<StandardLeave>().Rows.Select(r=>new StandardLeaveModel(r)).ToArray();
- _leaverequests = query.Get<LeaveRequest>().Rows.Select(r => new LeaveRequestModel(r)).ToArray();
-
- _activities = query.Get<Activity>().Rows.Select(r => new ActivityModel(r)).ToArray();
- ActivityType.ItemsSource = _activities;
- ActivityType.SelectedValue = Properties.ActivityType;
-
- }
- }
- public void Shutdown(CancelEventArgs? cancel)
- {
- }
-
- private bool GetStandardLeaveTimes(DateTime date, out TimeSpan start, out TimeSpan finish)
- {
- bool result = false;
- start = TimeSpan.Zero;
- finish = TimeSpan.FromDays(1);
- var requests = _standardleaves.Where(x =>
- (x.From <= date)
- && (x.To.Add(x.ToTime) > date)
- );
- if (requests.Any())
- {
- result = true;
- start = TimeSpan.FromDays(1);
- finish = TimeSpan.Zero;
- foreach (var leave in requests)
- {
- var curstart = leave.From == date ? leave.FromTime : TimeSpan.Zero;
- start = start > curstart ? curstart : start;
- var curfinish = leave.To == date ? leave.ToTime : TimeSpan.FromDays(1);
- finish = finish < curfinish ? curfinish : finish;
- }
- }
- return result;
- }
-
- private void AdjustStandardLeave(DateTime date, ref TimeSpan time)
- {
- TimeSpan result = TimeSpan.Zero;
- var leaves = _standardleaves.Where(x =>
- (x.From <= date)
- && (x.To.Add(x.ToTime) > date)
- );
- foreach (var leave in leaves)
- {
- result += (leave.To == date ? leave.ToTime : TimeSpan.FromDays(1)) -
- (leave.From == date ? leave.FromTime : TimeSpan.Zero);
- }
- time = time >= result ? time - result : TimeSpan.Zero;
- }
- private bool GetLeaveRequestTimes(DateTime date, EmployeeResourceModel emp, out TimeSpan start, out TimeSpan finish)
- {
- bool result = false;
- start = TimeSpan.Zero;
- finish = TimeSpan.FromDays(1);
- var requests = _leaverequests.Where(x =>
- (x.From <= date)
- && (x.To.Add(x.ToTime) > date)
- && (x.EmployeeID == emp.ID)
- && (Properties.IncludeUnApprovedLeave ? true : x.Status == LeaveRequestStatus.Approved)
- );
- if (requests.Any())
- {
- result = true;
- start = TimeSpan.FromDays(1);
- finish = TimeSpan.Zero;
- foreach (var leave in requests)
- {
- var curstart = leave.From == date ? leave.FromTime : TimeSpan.Zero;
- start = start > curstart ? curstart : start;
- var curfinish = leave.To == date ? leave.ToTime : TimeSpan.FromDays(1);
- finish = finish < curfinish ? curfinish : finish;
- }
- }
- return result;
- }
-
- private void AdjustLeaveRequests(DateTime date, EmployeeResourceModel emp, ref TimeSpan time)
- {
- TimeSpan result = TimeSpan.Zero;
- var requests = _leaverequests.Where(x =>
- (x.From <= date)
- && (x.To.Add(x.ToTime) > date)
- && (x.EmployeeID == emp.ID)
- && (Properties.IncludeUnApprovedLeave ? true : x.Status == LeaveRequestStatus.Approved)
- );
- foreach (var leave in requests)
- {
- result += (leave.To == date ? leave.ToTime : TimeSpan.FromDays(1)) -
- (leave.From == date ? leave.FromTime : TimeSpan.Zero);
- }
- time = time >= result ? time - result : TimeSpan.Zero;
- }
- public void Refresh()
- {
- using (new WaitCursor())
- {
-
- var jobids = _jobs.Select(x => x.ID).ToArray();
- var empids = _emps.Select(x => x.ID).ToArray();
- var actids = _activities.Select(x => x.ID).ToArray();
- DateTime fromDate = DateTime.Today;
- DateTime toDate = DateTime.Today.AddMonths(Properties.MonthsToView);
-
- MultiQuery query = new MultiQuery();
- query.Add<Assignment>(
- new Filter<Assignment>(x=>x.EmployeeLink.ID).InList(empids)
- .And(x=>x.Date).IsGreaterThanOrEqualTo(fromDate)
- .And(x=>x.Date).IsLessThanOrEqualTo(toDate),
- AssignmentModel.Columns
- );
- query.Query();
- _assignments = query.Get<Assignment>().Rows.Select(r => new AssignmentModel(r)).ToList();
- var data = new DataTable();
- var dates = new List<DateTime>();
- for (var curdate = fromDate; curdate <= toDate; curdate = curdate.AddDays(1))
- {
- dates.Add(curdate);
- }
- _dates = dates.ToArray();
- var dataValues = new object?[dates.Count, _jobs.Length];
- var available = new double[dates.Count];
- var totals = new double[dates.Count];
- foreach (var (dateIdx, date) in dates.WithIndex())
- {
- double avail = 0.0F;
- foreach (var emp in _emps)
- {
- var roster = RosterUtils.GetRoster(emp.Roster, emp.RosterStart, date);
- var hours = roster.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue)
- .Aggregate<RosterBlock, TimeSpan>(TimeSpan.Zero, (value, block) => value + block.Duration);
-
- AdjustStandardLeave(date, ref hours);
-
- AdjustLeaveRequests(date, emp, ref hours);
-
- avail += hours.TotalHours;
- }
-
- var total = avail;
-
- var values = new List<object?> { date };
-
- var anyjobstoday = _assignments.Where(x => (x.Date.Date == date.Date));
- avail -= anyjobstoday.Aggregate<AssignmentModel, double>(0F, (value, model) => value + model.BookedDuration.TotalHours);
- foreach (var (jobIdx, job) in _jobs.WithIndex())
- {
- var thisjobtoday = _assignments.Where(x => (x.Date.Date == date.Date) && (x.JobID == job.ID));
- if (thisjobtoday.Any())
- {
- var assigned = thisjobtoday.Aggregate<AssignmentModel, double>(0F,
- (value, model) => value + model.BookedDuration.TotalHours);
- dataValues[dateIdx, jobIdx] = assigned / Properties.HoursPerDay;
- }
- else
- dataValues[dateIdx, jobIdx] = null;
- }
- available[dateIdx] = avail / Properties.HoursPerDay;
- totals[dateIdx] = total / Properties.HoursPerDay;
- }
- _totals = totals;
- _available = available;
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- dataGrid.HeaderRowHeight = 200;
- data.Columns.Add("Date", typeof(DateTime));
-
- data.Columns.Add("Available", typeof(object));
-
- foreach (var job in _jobs)
- data.Columns.Add(job.ID.ToString(), typeof(object));
-
- foreach(var (dateIdx, date) in dates.WithIndex())
- {
- var values = new List<object?>(_jobs.Length + 3) { date };
-
- foreach (var (jobIdx, job) in _jobs.WithIndex())
- {
- values.Add(dataValues[dateIdx, jobIdx]);
- }
- values.Insert(1, available[dateIdx]);
- data.Rows.Add(values.ToArray());
- }
- }
- else if(Properties.DisplayMode == JobPlannerDisplayMode.DateColumns)
- {
- dataGrid.HeaderRowHeight = 30;
- data.Columns.Add("Job", typeof(object));
- var availableRow = new List<object?> { "Available" };
- foreach(var (dateIdx, date) in dates.WithIndex())
- {
- data.Columns.Add(dateIdx.ToString(), typeof(object));
- availableRow.Add(available[dateIdx]);
- }
- data.Rows.Add(availableRow.ToArray());
- foreach (var (jobIdx, job) in _jobs.WithIndex())
- {
- var values = new List<object?>(dates.Count + 1) { job };
- foreach(var (dateIdx, date) in dates.WithIndex())
- {
- values.Add(dataValues[dateIdx, jobIdx]);
- }
- data.Rows.Add(values.ToArray());
- }
- }
- dataGrid.ItemsSource = data;
- }
- }
- private interface ICellWrapper
- {
- DataRowView Row { get; }
-
- string ColumnName { get; }
- }
- public class GridCellInfoWrapper : ICellWrapper
- {
- private GridCellInfo Cell;
- public DataRowView Row => (Cell.RowData as DataRowView)!;
- public string ColumnName => (Cell.Column.ValueBinding as Binding)!.Path.Path;
- public GridCellInfoWrapper(GridCellInfo cell)
- {
- Cell = cell;
- }
- }
- public class GridCellWrapper : ICellWrapper
- {
- private GridCell Cell;
- public DataRowView Row => (Cell.DataContext as DataRowView)!;
- public string ColumnName => (Cell.ColumnBase?.GridColumn.ValueBinding as Binding)?.Path.Path ?? "";
- public GridCellWrapper(GridCell cell)
- {
- Cell = cell;
- }
- }
- private int? GetDateIndex(ICellWrapper cell)
- {
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- if (cell?.Row?.Row?.ItemArray?.First() is DateTime dt)
- return _dates.IndexOf(dt);
- return null;
- }
- else
- {
- if(int.TryParse(cell.ColumnName, out var idx))
- {
- return idx;
- }
- else
- {
- return null;
- }
- }
- }
- private double? GetTotal(ICellWrapper cell)
- {
- var dateIndex = GetDateIndex(cell);
- return dateIndex.HasValue ? _totals[dateIndex.Value] : null;
- }
- private double? GetAvailable(ICellWrapper cell)
- {
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- if (cell?.Row?.Row?.Table?.Columns?.Contains("Available") == true && cell.Row["Available"] is double d)
- return d;
- return null;
- }
- else
- {
- var dateIndex = GetDateIndex(cell);
- return dateIndex.HasValue ? _available[dateIndex.Value] : null;
- }
- }
-
- private abstract class LeaveConverter : IMultiValueConverter
- {
- protected JobResourcePlanner Planner { get; set; }
- public LeaveConverter(JobResourcePlanner planner)
- {
- Planner = planner;
- }
- protected System.Windows.Media.Color GetColor(object[] value)
- {
- if ((value[0] != DBNull.Value) && (value[0] != DependencyProperty.UnsetValue) && (value[0] is not double d || d != 0.0))
- return Colors.DarkSeaGreen;
- if (value[1] is GridCell cell)
- {
- var cellWrp = new GridCellWrapper(cell);
- var total = Planner.GetTotal(cellWrp);
- var available = Planner.GetAvailable(cellWrp);
- if (!total.HasValue || total == 0.0)
- return Colors.LightGray;
- if (!available.HasValue || available == 0.0F)
- return Colors.LightSalmon;
- return Colors.LightYellow;
- }
- return Colors.WhiteSmoke;
- }
- public abstract object Convert(object[] value, Type targetType, object parameter, CultureInfo culture);
- public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
- }
-
- private class LeaveBackgroundConverter : LeaveConverter
- {
- public LeaveBackgroundConverter(JobResourcePlanner planner): base(planner) { }
- public override object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
- {
- return new SolidColorBrush(base.GetColor(value)) { Opacity = 0.8 };
- }
- }
- private class LeaveForegroundConverter : LeaveConverter
- {
- public LeaveForegroundConverter(JobResourcePlanner planner): base(planner) { }
- public override object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
- {
- return new SolidColorBrush(ImageUtils.GetForegroundColor(base.GetColor(value)));
- }
- }
-
- private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e)
- {
- MultiBinding CreateBinding<TConverter>(String path, TConverter converter) where TConverter : IMultiValueConverter
- {
- var binding = new MultiBinding();
- binding.Bindings.Add(new Binding(path));
- binding.Bindings.Add(new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.Self) });
- binding.Converter = converter;
- return binding;
- }
- var value = (e.Column.ValueBinding as Binding)!;
- if (value.Path.Path.Equals("Date"))
- {
- e.Column.Width = 80;
- e.Column.HeaderStyle = Resources["DateHeaderStyle"] as Style;
- e.Column.AllowFocus = false;
- }
- else if (value.Path.Path.Equals("Job"))
- {
- e.Column.Width = 250;
- e.Column.HeaderStyle = Resources["DateHeaderStyle"] as Style;
- e.Column.AllowFocus = false;
- e.Column.TextAlignment = TextAlignment.Left;
- e.Column.DisplayBinding = new Binding
- {
- Path = new PropertyPath(e.Column.MappingName),
- Converter = new FuncConverter<object?, object?>(x => x is JobModel job ? job.Name : x)
- };
- e.Column.HeaderText = "Project Name";
- }
- else if (value.Path.Path.Equals("Available"))
- {
- e.Column = new GridNumericColumn() { NumberDecimalDigits = 2, MappingName = e.Column.MappingName};
- e.Column.Width = 50;
- e.Column.HeaderStyle = e.Column.HeaderStyle = Resources["RotatedHeaderStyle"] as Style;
- e.Column.AllowFocus = false;
- e.Column.HeaderText = "Available";
- }
- else
- {
- e.Column = new GridNumericColumn() { NumberDecimalDigits = 2, MappingName = e.Column.MappingName};
-
-
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- e.Column.Width = 40;
- e.Column.HeaderStyle = Resources["RotatedHeaderStyle"] as Style;
- e.Column.HeaderText = (Guid.TryParse(value.Path.Path, out var id)
- ? _jobs.FirstOrDefault(x => x.ID == id)?.Name ?? value.Path.Path
- : value.Path.Path);
- }
- else
- {
- e.Column.Width = 50;
- e.Column.HeaderStyle = Resources["ContentHeaderStyle"] as Style;
- if(int.TryParse(value.Path.Path, out var idx))
- {
- e.Column.HeaderText = _dates[idx].ToString("dd/MM");
- }
- }
- e.Column.DisplayBinding = new Binding { Path = new PropertyPath(e.Column.MappingName) };
- e.Column.AllowFocus = true;
- var style = new Style(typeof(GridCell));
- style.Setters.Add(new Setter(BackgroundProperty, CreateBinding<LeaveBackgroundConverter>(value.Path.Path, new(this))));
- style.Setters.Add(new Setter(ForegroundProperty, CreateBinding<LeaveForegroundConverter>(value.Path.Path, new(this))));
- e.Column.CellStyle = style;
- e.Column.TextAlignment = TextAlignment.Center;
- e.Column.HorizontalHeaderContentAlignment = HorizontalAlignment.Center;
- }
- e.Column.ColumnSizer = GridLengthUnitType.None;
- e.Column.ShowHeaderToolTip = false;
- e.Column.ShowToolTip = false;
- }
-
- private void DataGrid_ContextMenuOpening(object sender, ContextMenuEventArgs e)
- {
- var emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>((row, rosters) => new EmployeeResourceModel(row, rosters));
- }
-
- private void DataGrid_OnSelectionChanging(object? sender, GridSelectionChangingEventArgs e)
- {
- var selected = dataGrid.SelectionController.SelectedCells;
- var added = e.AddedItems.OfType<GridCellInfo>();
- if (selected.Any() && added.Any())
- {
- if (Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- e.Cancel = added.Any(a => selected.All(s => s.Column != a.Column));
- else
- e.Cancel = selected.Union(added).GroupBy(x => x.Column).Any(g => g.Count() > 1);
- }
- }
-
- private bool bResettingSelection = false;
-
- private void DataGrid_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
- {
- bResettingSelection = true;
- dataGrid.SelectionController.ClearSelections(false);
- }
-
- private void DataGrid_OnCurrentCellActivating(object? sender, CurrentCellActivatingEventArgs e)
- {
- if (bResettingSelection)
- {
- bResettingSelection = false;
- return;
- }
- // if (Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- // {
- // var thiscol = dataGrid.Columns[e.CurrentRowColumnIndex.ColumnIndex];
- // var selected = dataGrid.SelectionController.SelectedCells;
- // if (selected.Any(x => x.Column != thiscol))
- // e.Cancel = true;
- // else
- // e.Cancel = false;
- //
- // }
- // else
- // {
- // var current = e.CurrentRowColumnIndex.RowIndex;
- // var original = dataGrid.SelectionController.SelectedCells;
- // // This is Dumb, but it seems the only way to find if multiple rows have been selected
- // // ie if there are two cells with the same column, we must have multiple rows
- // // Stupid SelectedCell -> RowIndex is alwasy showing up as -1!
- // if (original.GroupBy(x => x.Column).Any(g=>g.Count() > 1))
- // e.Cancel = true;
- // else
- // e.Cancel = false;
- // }
- }
-
- private void DataGrid_OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
- {
- }
- private void GetCellData(ICellWrapper cell, out (Guid jobID, DateTime date) result)
- {
- result = (Guid.Empty, DateTime.MinValue);
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- if (Guid.TryParse(cell.ColumnName, out var emp))
- {
- result.jobID = emp;
- }
- result.date = (DateTime)cell.Row.Row.ItemArray.First()!;
- }
- else
- {
- if(int.TryParse(cell.ColumnName, out var idx))
- {
- result.date = _dates[idx];
- }
- else
- {
- result.date = DateTime.MinValue;
- }
- var jobModel = cell.Row.Row.ItemArray.First() as JobModel;
- result.jobID = jobModel?.ID ?? Guid.Empty;
- }
- }
- private ICellWrapper Wrap(GridCellInfo cell)
- {
- return new GridCellInfoWrapper(cell);
- }
- private ICellWrapper Wrap(GridCell cell)
- {
- return new GridCellWrapper(cell);
- }
- private bool ExtractSelection(out Guid[] jobs, out DateTime[] dates)
- {
- var from = DateTime.MaxValue;
- var to = DateTime.MinValue;
- var jobList = new List<Guid>();
- foreach (var cell in dataGrid.GetSelectedCells())
- {
- GetCellData(Wrap(cell), out var result);
- if (result.jobID == Guid.Empty) continue;
- if (!jobList.Contains(result.jobID))
- jobList.Add(result.jobID);
- if(result.date != DateTime.MinValue)
- {
- if (result.date < from)
- from = result.date;
- if (result.date > to)
- to = result.date;
- }
- }
- if(jobList.Count > 0 && to != DateTime.MinValue && from != DateTime.MaxValue)
- {
- jobs = jobList.ToArray();
- var datesList = new List<DateTime>();
- for(DateTime date = from; date <= to; date = date.AddDays(1))
- {
- datesList.Add(date);
- }
- dates = datesList.ToArray();
- return true;
- }
- else
- {
- jobs = [];
- dates = [];
- return false;
- }
- }
-
- private void DataGrid_OnMouseUp(object sender, MouseButtonEventArgs e)
- {
- if (ExtractSelection(out var jobIDs, out var dates))
- {
- if(jobIDs.Length == 1)
- {
- LoadAssignedEmployees(jobIDs, dates);
- LoadAvailableEmployees(dates);
- }
- else
- {
- AvailableEmployees.Items = [];
- AssignedEmployees.Items = [];
- AvailableEmployees.Refresh(false, true);
- AssignedEmployees.Refresh(false, true);
- }
- }
- }
-
- private JobPlannerEmployee GetEmployee(Guid id, List<JobPlannerEmployee> list)
- {
- var result = list.FirstOrDefault(x => x.ID == id);
- if (result == null)
- {
- result = new JobPlannerEmployee()
- {
- ID = id,
- Name = _emps.FirstOrDefault(x=>x.ID == id)?.Name ?? id.ToString(),
- Time = TimeSpan.Zero
- };
- list.Add(result);
- }
- return result;
- }
- private void LoadAvailableEmployees(DateTime[] dates)
- {
- List<JobPlannerEmployee> availableemployees = new List<JobPlannerEmployee>();
- foreach (var emp in _emps)
- {
- foreach (var date in dates)
- {
- var roster = RosterUtils.GetRoster(emp.Roster, emp.RosterStart, date);
- var blocks = roster?.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue) ?? new RosterBlock[] { };
- var rostered = blocks.Aggregate(TimeSpan.Zero, (time, block) => time += block.Duration);
- AdjustStandardLeave(date, ref rostered);
- AdjustLeaveRequests(date, emp, ref rostered);
- var assignments = _assignments.Where(x => (x.Date == date) && (x.EmployeeID == emp.ID));
- var assigned = assignments.Aggregate(TimeSpan.Zero, (time, assign) => time += assign.BookedDuration);
- if (rostered > assigned)
- GetEmployee(emp.ID, availableemployees).Time += rostered.Subtract(assigned);
- AvailableEmployees.Items = availableemployees.OrderBy(x=>x.Name).ToList();
- AvailableEmployees.Refresh(false, true);
- }
- }
- }
-
- private void LoadAssignedEmployees(Guid[] jobIDs, DateTime[] dates)
- {
- List<JobPlannerEmployee> assignedemployees = new List<JobPlannerEmployee>();
- foreach (var assignment in _assignments.Where(x => dates.Contains(x.Date) && jobIDs.Contains(x.JobID)))
- GetEmployee(assignment.EmployeeID, assignedemployees).Time += assignment.BookedDuration;
- AssignedEmployees.Items = assignedemployees.OrderBy(x=>x.Name).ToList();
- AssignedEmployees.Refresh(false, true);
- }
- private void JobSelector_OnSettingsChanged(object sender, JobSelectorSettingsChangedArgs args)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.JobSettings = args.Settings;
- DoSaveSettings();
- }
- private void JobSelector_OnSelectionChanged(object sender, JobSelectorSelectionChangedArgs args)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.JobSelection = args.Selection;
- _jobs = JobSelector.GetJobData<JobModel>(x => new JobModel(x));
- DoSaveSettings();
- Refresh();
- }
- private void TeamSelector_OnSettingsChanged(object sender, TeamSelectorSettingsChangedArgs args)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.TeamSettings = args.Settings;
- DoSaveSettings();
- }
- private void TeamSelector_OnSelectionChanged(object sender, TeamSelectorSelectionChangedArgs args)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.TeamSelection = args.Selection;
- _emps = TeamSelector.GetEmployeeData<EmployeeResourceModel>((row, rosters) => new EmployeeResourceModel(row, rosters));
- DoSaveSettings();
- Refresh();
- }
- private void JobSelector_OnSizeChanged(object sender, SizeChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.SplitterPosition = TeamSelectorRow.Height.Value;
- DoSaveSettings();
- }
- private void ViewWindow_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.MonthsToView = (int)ViewWindow.SelectedValue;
- DoSaveSettings();
- Refresh();
- }
- private void HoursSelector_Down_Click(object sender, RoutedEventArgs e)
- {
- Properties.HoursPerDay = Math.Max(0.25F, Properties.HoursPerDay - 0.25);
- HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
- DoSaveSettings();
- Refresh();
- }
- private void HoursSelector_Up_Click(object sender, RoutedEventArgs e)
- {
- Properties.HoursPerDay = Math.Min(24F, Properties.HoursPerDay + 0.25);
- HoursSelector.Text = $"{Properties.HoursPerDay:F2}";
- DoSaveSettings();
- Refresh();
- }
-
-
- private void ActivityType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.ActivityType = (Guid)(ActivityType.SelectedValue ?? Guid.Empty);
- DoSaveSettings();
- }
-
- private void AvailableEmployees_OnSizeChanged(object sender, SizeChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.EmployeeSplitterPosition = AvailableEmployeesRow.Height.Value;
- DoSaveSettings();
- }
- private void AvailableEmployees_OnOnAction(object sender, JobPlannerEmployee[] availables)
- {
- List<TimeSpan> edges = new List<TimeSpan>();
- void CheckEdges(params TimeSpan[] times)
- {
- foreach (var time in times)
- {
- if (!edges.Contains(time))
- edges.Add(time);
- }
- }
- bool IsRostered(RosterBlock[] blocks, TimeSpan start, TimeSpan finish)
- {
- foreach (var block in blocks)
- {
- if ((block.Start <= start) && (block.Finish >= finish))
- return true;
- }
- return false;
- }
- bool IsStandardLeave(DateTime date, TimeSpan start, TimeSpan finish)
- {
- return _standardleaves.Any(x =>
- (x.From.Add(x.FromTime) <= date.Add(start))
- && (x.To.Add(x.ToTime) >= date.Add(finish))
- );
- }
-
- bool IsLeaveRequest(DateTime date, EmployeeResourceModel emp, TimeSpan start, TimeSpan finish)
- {
- return _leaverequests.Any(x =>
- (x.EmployeeID == emp.ID)
- && (x.From.Add(x.FromTime) <= date.Add(start))
- && (x.To.Add(x.ToTime) >= date.Add(finish))
- );
- }
- bool IsAssigned(AssignmentModel[] assignments, TimeSpan start, TimeSpan finish)
- {
- foreach (var assignment in assignments)
- {
- if ((assignment.BookedStart <= start) && (assignment.BookedFinish >= finish))
- return true;
- }
- return false;
- }
-
- if (ExtractSelection(out var jobIDs, out var dates))
- {
- if (dataGrid.ItemsSource is DataTable table)
- {
- List<Assignment> updates = new List<Assignment>();
- foreach (var available in availables)
- {
- foreach (var date in dates)
- {
- var dateIdx = _dates.IndexOf(date);
- var emp = _emps.FirstOrDefault(x => x.ID == available.ID);
- if (emp != null)
- {
- var roster = RosterUtils.GetRoster(emp.Roster, emp.RosterStart, date);
- var blocks = roster?.GetBlocks(date, TimeSpan.MinValue, TimeSpan.MaxValue) ?? new RosterBlock[] { };
- foreach (var block in blocks)
- CheckEdges(block.Start, block.Finish);
- if (GetStandardLeaveTimes(date, out TimeSpan stdleavestart, out TimeSpan stdleavefinish))
- CheckEdges(stdleavestart, stdleavefinish);
- if (GetLeaveRequestTimes(date, emp, out TimeSpan leaverequeststart, out TimeSpan leaverequestfinish))
- CheckEdges(leaverequeststart, leaverequestfinish);
-
- var assignments = _assignments.Where(x => (x.Date == date) && (x.EmployeeID == emp.ID)).ToArray();
- foreach (var assignment in assignments)
- CheckEdges(assignment.BookedStart, assignment.BookedFinish);
- edges.Sort();
- var adjustment = new double[jobIDs.Length];
- for (int i = 0; i < edges.Count - 1; i++)
- {
- var start = edges[i];
- var finish = edges[i + 1];
- if (IsRostered(blocks, start, finish)
- && (!IsStandardLeave(date,start,finish))
- && (!IsLeaveRequest(date,emp,start,finish))
- && !IsAssigned(assignments, start, finish))
- {
- foreach(var (idx, jobid) in jobIDs.WithIndex())
- {
- Assignment assignment = new Assignment();
- assignment.ActivityLink.ID = Properties.ActivityType;
- assignment.EmployeeLink.ID = emp.ID;
- assignment.Date = date;
- assignment.JobLink.ID = jobid;
- assignment.Booked.Start = start;
- assignment.Booked.Finish = finish;
- assignment.Booked.Duration = finish - start;
- updates.Add(assignment);
- adjustment[idx] += assignment.Booked.Duration.TotalHours;
- }
- }
- }
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- System.Data.DataRow row = table.Rows[dateIdx];
- row.BeginEdit();
- foreach(var (idx, jobid) in jobIDs.WithIndex())
- {
- var adj = adjustment[idx];
- _available[dateIdx] = Math.Max(0F, _available[dateIdx] - (adj / Properties.HoursPerDay));
- row["Available"] = _available[dateIdx];
- double jobvalue = (row[jobid.ToString()] == DBNull.Value)
- ? adj / Properties.HoursPerDay
- : (double)row[jobid.ToString()] + (adj / Properties.HoursPerDay);
- row[jobid.ToString()] = jobvalue <= 0F ? null : jobvalue;
- }
- row.EndEdit();
- }
- else
- {
- var availableRow = table.Rows[0];
- availableRow.BeginEdit();
- foreach(var (idx, jobid) in jobIDs.WithIndex())
- {
- var job = _jobs.WithIndex().First(x => x.Value.ID == jobid);
- var row = table.Rows[job.Key + 1];
- var adj = adjustment[idx];
- _available[dateIdx] = Math.Max(0F, _available[dateIdx] - (adj / Properties.HoursPerDay));
- availableRow[dateIdx.ToString()] = _available[dateIdx];
- row.BeginEdit();
- double jobvalue = (row[dateIdx.ToString()] == DBNull.Value)
- ? adj / Properties.HoursPerDay
- : (double)row[dateIdx.ToString()] + (adj / Properties.HoursPerDay);
- row[dateIdx.ToString()] = jobvalue <= 0F ? null : jobvalue;
- row.EndEdit();
- }
- availableRow.EndEdit();
- foreach(var row in table.Rows.Cast<System.Data.DataRow>())
- {
- row.BeginEdit();
- row[dateIdx.ToString()] = row[dateIdx.ToString()];
- row.EndEdit();
- }
- }
- }
- }
- var entry = AvailableEmployees.Items.FirstOrDefault(x => x.ID == available.ID);
- if (entry != null)
- {
- AvailableEmployees.Items.Remove(entry);
- GetEmployee(entry.ID, AssignedEmployees.Items).Time += entry.Time;
- }
- }
- if (updates.Any())
- {
- using (new WaitCursor())
- {
- new Client<Assignment>().Save(updates, "Assigned by Job Planner");
-
- CoreTable temp = new CoreTable();
- temp.LoadColumns(typeof(Assignment));
- temp.LoadRows(updates);
- _assignments.AddRange(temp.Rows.Select(r => new AssignmentModel(r)));
-
- AssignedEmployees.Refresh(false, true);
- AvailableEmployees.Refresh(false, true);
- }
- }
- }
- }
- }
- private void AssignedEmployees_OnOnAction(object sender, JobPlannerEmployee[] employees)
- {
- if (ExtractSelection(out var jobIDs, out var dates))
- {
- if (dataGrid.ItemsSource is DataTable table)
- {
- foreach (var date in dates)
- {
- var dateIdx = _dates.IndexOf(date);
- var emptimes = _assignments.Where(x =>
- jobIDs.Contains(x.JobID)
- && (x.Date == date)
- && employees.Any(e => e.ID == x.EmployeeID)
- ).ToArray();
- var emptime = emptimes.Aggregate(TimeSpan.Zero, (time, ass) => time += ass.BookedDuration);
- if(Properties.DisplayMode == JobPlannerDisplayMode.JobColumns)
- {
- System.Data.DataRow row = table.Rows[dateIdx];
- row.BeginEdit();
- foreach(var jobid in jobIDs)
- {
- _available[dateIdx] = _available[dateIdx] + (emptime.TotalHours / Properties.HoursPerDay);
- row["Available"] = _available[dateIdx];
- double value = (row[jobid.ToString()] == DBNull.Value)
- ? 0.0F
- : (double)row[jobid.ToString()] - (emptime.TotalHours / Properties.HoursPerDay);
- row[jobid.ToString()] = value <= 0F ? null : value;
- }
- row.EndEdit();
- }
- else
- {
- var availableRow = table.Rows[0];
- availableRow.BeginEdit();
- foreach(var jobid in jobIDs)
- {
- var jobIdx = _jobs.WithIndex().First(x => x.Value.ID == jobid).Key;
- _available[dateIdx] = _available[dateIdx] + (emptime.TotalHours/Properties.HoursPerDay);
- availableRow[dateIdx.ToString()] = _available[dateIdx];
- var row = table.Rows[jobIdx + 1];
- row.BeginEdit();
- double value = (row[dateIdx.ToString()] == DBNull.Value)
- ? 0.0F
- : (double)row[dateIdx.ToString()] - (emptime.TotalHours / Properties.HoursPerDay);
- row[dateIdx.ToString()] = value <= 0F ? null : value;
- row.EndEdit();
- }
- availableRow.EndEdit();
- foreach(var row in table.Rows.Cast<System.Data.DataRow>())
- {
- row.BeginEdit();
- row[dateIdx.ToString()] = row[dateIdx.ToString()];
- row.EndEdit();
- }
- }
- }
- }
-
- var assignments = _assignments.Where(x =>
- jobIDs.Contains(x.JobID)
- && dates.Contains(x.Date)
- && employees.Any(e => e.ID == x.EmployeeID)
- ).ToArray();
- if (assignments.Any())
- {
- using (new WaitCursor())
- {
- var deletes = assignments.Select(x => new Assignment() { ID = x.ID }).ToArray();
- new Client<Assignment>().Delete(deletes, "Deleted from Job Planner");
-
- var removes = AssignedEmployees.Items.Where(x => employees.Any(e => e.ID == x.ID)).ToArray();
- foreach (var remove in removes)
- {
- GetEmployee(remove.ID, AvailableEmployees.Items).Time += remove.Time;
- AssignedEmployees.Items.Remove(remove);
- }
-
- foreach (var assignment in assignments)
- _assignments.Remove(assignment);
-
- AssignedEmployees.Refresh(false, true);
- AvailableEmployees.Refresh(false, true);
-
- }
- }
-
- }
- }
- private void LeaveType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.IncludeUnApprovedLeave = LeaveType.SelectedIndex > 0;
- DoSaveSettings();
- Refresh();
- }
-
-
- private void Orientation_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (EventSuppressor.IsSet(Suppress.This))
- return;
- Properties.DisplayMode = Orientation.SelectedIndex <= 0
- ? JobPlannerDisplayMode.DateColumns
- : JobPlannerDisplayMode.JobColumns;
- DoSaveSettings();
- Refresh();
- }
- private void AvailableEmployees_OnAfterRefresh(object sender, AfterRefreshEventArgs args)
- {
- AvailableEmployees.Items = AvailableEmployees.Items.OrderBy(x => x.Name).ToList();
- }
- private void AssignedEmployees_OnAfterRefresh(object sender, AfterRefreshEventArgs args)
- {
- AssignedEmployees.Items = AssignedEmployees.Items.OrderBy(x => x.Name).ToList();
- }
- private void Data_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- Settings.Visibility = Data.SelectedTab == JobView
- ? Visibility.Visible
- : Visibility.Collapsed;
- }
- ScheduleAppointmentCollection appointments = new();
-
- private void Schedule_OnQueryAppointments(object? sender, QueryAppointmentsEventArgs e)
- {
- appointments.Clear();
- var cols = Columns.Required<JobStage>()
- .Add(x => x.ID)
- .Add(x => x.StartDate)
- .Add(x => x.EndDate)
- .Add(x=>x.Name)
- .Add(x => x.Job.ID)
- .Add(x => x.Job.JobNumber)
- .Add(x => x.Job.Name)
- .Add(x => x.Type.ID)
- .Add(x => x.Type.Color)
- .Add(x => x.Type.Description)
- .Add(x => x.Type.Color)
- .Add(x=>x.Calendar.ID)
- .Add(x=>x.Calendar.Name)
- .Add(x=>x.Calendar.Monday)
- .Add(x=>x.Calendar.Tuesday)
- .Add(x=>x.Calendar.Wednesday)
- .Add(x=>x.Calendar.Thursday)
- .Add(x=>x.Calendar.Friday)
- .Add(x=>x.Calendar.Saturday)
- .Add(x=>x.Calendar.Sunday)
- .Add(x => x.Apprentices)
- .Add(x=>x.ApprenticeHours)
- .Add(x=>x.Supervisors)
- .Add(x=>x.SupervisionHours)
- .Add(x=>x.Tradespersons)
- .Add(x=>x.TradesHours);
-
- var stages = Client.Query<JobStage>(
- new Filter<JobStage>(x => x.StartDate).IsLessThanOrEqualTo(e.VisibleDateRange.ActualEndDate)
- .And(x => x.EndDate).IsGreaterThanOrEqualTo(e.VisibleDateRange.ActualStartDate),
- cols
- ).ToObjects<JobStage>()
- .ToArray();
-
- foreach (var stage in stages)
- CreateAppointment(stage);
- Schedule.ItemsSource = appointments;
- }
- private void CreateAppointment(JobStage stage)
- {
- var model = new StageModel(stage);
- appointments.Add(model);
- }
-
- private class StageModel : ScheduleAppointment
- {
- public StageModel(JobStage stage)
- {
- Stage = stage;
- }
-
- private JobStage _stage;
- public JobStage Stage
- {
- get => _stage;
- set
- {
- _stage = value;
- Reload();
- }
- }
- public void Reload()
- {
- var color = !string.IsNullOrWhiteSpace(_stage.Type.Color)
- ? (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(_stage.Type.Color)
- : Colors.Transparent;
-
- StartTime = _stage.StartDate;
- EndTime = _stage.EndDate;
- IsAllDay = true;
- AppointmentBackground = new SolidColorBrush(color);
- Foreground = new SolidColorBrush(color.GetForegroundColor());
- Subject = $"{_stage.Job.JobNumber}: {_stage.Job.Name}";
- }
- }
-
- private void Schedule_AppointmentEditorOpening(object? sender, AppointmentEditorOpeningEventArgs e)
- {
-
- }
- void CreateMenu<T>(ItemsControl menu, CalendarMenuName name, string header, Action<T?>? action, T data)
- {
- var item = new MenuItem();
- item.Name = name.ToString();
- item.Header = header;
- if (action != null)
- item.Click += (o,args) => action(data);
- menu.Items.Add(item);
- }
- private StageModel? _copiedModel;
-
-
- private void CreateJobStage(JobStageType type)
- {
- if (Schedule.SelectedDate is null)
- return;
-
- var stage = new JobStage
- {
- StartDate = Schedule.SelectedDate.Value,
- EndDate = Schedule.SelectedDate.Value,
- Name = type.Description
- };
- stage.Type.CopyFrom(type);
- if (new JobStagesGrid().EditItems([stage]))
- {
- CreateAppointment(stage);
- _copiedModel = null;
- }
- if (!types?.Any(x => x.ID == stage.Type.ID) == false)
- types = null;
- }
- private void EditJobStage(StageModel? stage)
- {
- if (stage is null)
- return;
- if (new JobStagesGrid().EditItems([stage.Stage]))
- {
- stage.Reload();
- _copiedModel = null;
- }
- }
-
- private void DeleteJobStage(StageModel? stage)
- {
- if (stage is null)
- return;
- //Schedule.ItemsSource = null;
- appointments.Remove(stage);
- new Client<JobStage>().Delete(stage.Stage,"Deleted from Project Planner");
- _copiedModel = null;
- }
- private void CopyJobStage(StageModel? stage)
- {
- _copiedModel = stage;
- }
-
- private void PasteJobStage(StageModel? stage)
- {
- if (stage is null || Schedule.SelectedDate is null)
- return;
- var newstage = stage.Stage.Clone();
- newstage.ID = Guid.Empty;
- newstage.OriginalValues?.TryRemove("ID", out _);
-
- var span = newstage.EndDate - newstage.StartDate;
- newstage.StartDate = Schedule.SelectedDate.Value;
- newstage.EndDate = newstage.StartDate + span;
-
- new Client<JobStage>().Save(newstage,"Created from Project Planner");
- CreateAppointment(newstage);
- _copiedModel = null;
- }
-
- private List<JobStageType>? types;
- private void Schedule_OnSchedulerContextMenuOpening(object? sender, SchedulerContextMenuOpeningEventArgs e)
- {
- e.ContextMenu.Items.Clear();
- if ((e.MenuType == SchedulerContextMenuType.Appointment) && (e.MenuInfo.Appointment is StageModel model))
- {
- CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Edit Booking", EditJobStage, model);
- CreateMenu(e.ContextMenu, CalendarMenuName.Copy, "Copy Booking", CopyJobStage, model);
- e.ContextMenu.Items.Add(new Separator());
- CreateMenu(e.ContextMenu, CalendarMenuName.Edit, "Delete Booking", DeleteJobStage, model);
- }
- else if (e.MenuType == SchedulerContextMenuType.MonthCell)
- {
- types ??= new Client<JobStageType>().Query(null, Columns.All<JobStageType>()).ToList<JobStageType>();
- if (types.Any())
- {
- var header = new MenuItem() { Header = "Create Booking..." };
- foreach (var type in types)
- CreateMenu(header, CalendarMenuName.CreateNew, type.Description, CreateJobStage, type);
- e.ContextMenu.Items.Add(header);
- }
- else
- CreateMenu(e.ContextMenu, CalendarMenuName.CreateNew, "Create Booking", CreateJobStage, new JobStageType());
-
- if (_copiedModel != null)
- {
- e.ContextMenu.Items.Add(new Separator());
- CreateMenu(e.ContextMenu, CalendarMenuName.Paste, "Paste Booking", PasteJobStage, _copiedModel);
- }
- }
- }
- private void Schedule_OnAppointmentDropping(object? sender, AppointmentDroppingEventArgs e)
- {
- if (e.Appointment is StageModel model)
- {
- var duration = model.Stage.EndDate - model.Stage.StartDate;
- model.Stage.StartDate = e.DropTime;
- model.Stage.EndDate = e.DropTime + duration;
- model.Reload();
- new Client<JobStage>().Save(model.Stage,"Reallocated By Project Planner", (o,e) => { });
- }
- }
- }
|