MainWindow.xaml.cs 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Drawing.Drawing2D;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Net.Http;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Controls;
  17. using System.Windows.Forms;
  18. using System.Windows.Input;
  19. using System.Windows.Interop;
  20. using System.Windows.Media;
  21. using System.Windows.Threading;
  22. using AvalonDock.Layout;
  23. using Comal.Classes;
  24. using Comal.Stores;
  25. using Comal.TaskScheduler.Shared;
  26. using H.Pipes;
  27. using InABox.Clients;
  28. using InABox.Configuration;
  29. using InABox.Core;
  30. using InABox.Database;
  31. using InABox.Database.SQLite;
  32. using InABox.DynamicGrid;
  33. using InABox.Mail;
  34. using InABox.Rpc;
  35. using InABox.Scripting;
  36. using InABox.Wpf;
  37. using InABox.WPF;
  38. using NAudio.Wave;
  39. using PRS.Shared;
  40. using InABox.WPF.Themes;
  41. using PRSDesktop.Configuration;
  42. using PRSDesktop.Forms;
  43. using PRSServer;
  44. using SharpAvi.Codecs;
  45. using SharpAvi.Output;
  46. using Syncfusion.Windows.Shared;
  47. using Syncfusion.Windows.Tools.Controls;
  48. using Application = System.Windows.Application;
  49. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  50. using Color = System.Windows.Media.Color;
  51. using ColorConverter = System.Windows.Media.ColorConverter;
  52. using Control = System.Windows.Controls.Control;
  53. using Image = System.Drawing.Image;
  54. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  55. using MessageBox = System.Windows.MessageBox;
  56. using Pen = System.Drawing.Pen;
  57. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  58. using SortDirection = InABox.Core.SortDirection;
  59. using InABox.Wpf.Reports;
  60. using Comal.Classes.SecurityDescriptors;
  61. using System.Threading;
  62. using H.Formatters;
  63. using PRSDesktop.Forms.Issues;
  64. using Brushes = System.Windows.Media.Brushes;
  65. using System.Windows.Media.Imaging;
  66. namespace PRSDesktop;
  67. public enum PanelType
  68. {
  69. InPlace,
  70. NewWindow
  71. }
  72. public class SimpleCommand : ICommand
  73. {
  74. public Action OnExecute { get; private set; }
  75. public bool CanExecute(object? parameter) => true;
  76. public event EventHandler? CanExecuteChanged
  77. {
  78. add => CommandManager.RequerySuggested += value;
  79. remove => CommandManager.RequerySuggested -= value;
  80. }
  81. public void Execute(object? parameter)
  82. {
  83. OnExecute?.Invoke();
  84. }
  85. public SimpleCommand(Action onExecute)
  86. {
  87. OnExecute = onExecute;
  88. }
  89. }
  90. /// <summary>
  91. /// Interaction logic for Main.xaml
  92. /// </summary>
  93. public partial class MainWindow : IPanelHostControl
  94. {
  95. //private const int WM_LBUTTONDOWN = 0x201;
  96. private static PipeServer<string>? _client;
  97. private IRpcClientTransport? _transport;
  98. private WaveIn? _audio;
  99. private bool _audioMuted;
  100. private MemoryStream? _audioStream;
  101. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  102. private DesktopConsole? _console;
  103. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  104. private DispatcherTimer? _recorder;
  105. private Process? _recordingnotes;
  106. private int _screenheight = 720;
  107. private int _screenleft;
  108. private int _screentop;
  109. private int _screenwidth = 1280;
  110. private readonly Dictionary<Guid, SecondaryWindow> SecondaryWindows = new();
  111. private CoreTable? _timesheets;
  112. private DailyActivityHistory? ActivityHistory;
  113. private readonly List<Control> CurrentModules = new();
  114. private Fluent.RibbonTabItem? CurrentTab;
  115. private Fluent.Button? CurrentButton;
  116. private readonly int FRAMES_PER_SECOND = 10;
  117. private DatabaseType DatabaseType;
  118. private readonly Dictionary<int, int> messages = new();
  119. private readonly DispatcherTimer NotificationsWatchDog;
  120. private DateTime pausestarted = DateTime.MinValue;
  121. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  122. // We use a Guid for the StationID rather than an IP or Mac address
  123. // because we want true single-instance restriction. Using either of
  124. // the above allows for two instances on the once machine, and thus
  125. // double-counting in the Heartbeat() function
  126. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  127. private TimeSpan totalpauses = new(0);
  128. private readonly int VIDEO_HEIGHT = 1080;
  129. private readonly int VIDEO_WIDTH = 1920;
  130. private PanelHost PanelHost;
  131. public MainWindow()
  132. {
  133. PanelHost = new PanelHost(this);
  134. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  135. NotificationsWatchDog.Tick += Notifications_Tick;
  136. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  137. ClientFactory.PushHandlers.AddHandler<Notification>(ReceiveNotification);
  138. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  139. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  140. ClientFactory.OnLog += (type, userid, message, parameters) => Logger.Send(LogType.Information, ClientFactory.UserID, message, parameters);
  141. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  142. HotKeyManager.Initialize();
  143. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  144. //HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  145. //HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  146. //HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  147. Logger.Send(LogType.Information, "", "Connecting to server");
  148. var settings = App.DatabaseSettings;
  149. bool dbConnected;
  150. DatabaseType = settings.DatabaseType;
  151. switch (DatabaseType)
  152. {
  153. case DatabaseType.Standalone:
  154. ClientFactory.SetClientType(typeof(LocalClient<>), Platform.Wpf, CoreUtils.GetVersion());
  155. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  156. DbFactory.Logo = App.DatabaseSettings.Logo;
  157. dbConnected = true;
  158. break;
  159. case DatabaseType.Networked:
  160. if (App.DatabaseSettings.Protocol == SerializerProtocol.RPC)
  161. {
  162. _transport = new RpcClientSocketTransport(App.DatabaseSettings.URLs);
  163. _transport.OnClose += TransportConnectionLost;
  164. _transport.OnException += Transport_OnException;
  165. _transport.OnOpen += Transport_OnOpen; ;
  166. dbConnected = _transport.Connect();
  167. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  168. _transport);
  169. }
  170. else
  171. {
  172. var url = RestClient<User>.Ping(App.DatabaseSettings.URLs, out DatabaseInfo info);
  173. ClientFactory.SetClientType(typeof(RestClient<>), Platform.Wpf, CoreUtils.GetVersion(), url, true);
  174. dbConnected = true;
  175. }
  176. break;
  177. case DatabaseType.Local:
  178. //new RPC stuff (temporary disabled - for enabling when RPC is ready)
  179. var pipename = DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, true);
  180. _transport = new RpcClientPipeTransport(pipename);
  181. _transport.OnClose += TransportConnectionLost;
  182. dbConnected = _transport.Connect();
  183. ClientFactory.SetClientType(typeof(RpcClient<>), Platform.Wpf, CoreUtils.GetVersion(), _transport );
  184. //ClientFactory.SetClientType(typeof(IPCClient<>), Platform.Wpf, CoreUtils.GetVersion(),
  185. // DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName, false));
  186. //dbConnected = true;
  187. break;
  188. default:
  189. throw new Exception($"Invalid database type {DatabaseType}");
  190. }
  191. InitializeComponent();
  192. if (!dbConnected)
  193. {
  194. switch (DoConnectionFailed())
  195. {
  196. case ConnectionFailedResult.Quit:
  197. Close();
  198. return;
  199. case ConnectionFailedResult.Restart:
  200. App.ShouldRestart = true;
  201. Close();
  202. return;
  203. case ConnectionFailedResult.Ok:
  204. // Do nothing
  205. break;
  206. }
  207. }
  208. ThemeManager.BaseColor = Colors.CornflowerBlue;
  209. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  210. try
  211. {
  212. var dbInfo = new Client<User>().Info();
  213. ClientFactory.DatabaseID = dbInfo.DatabaseID;
  214. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  215. if (dbInfo.Logo?.Any() == true)
  216. using (var ms = new MemoryStream(dbInfo.Logo))
  217. {
  218. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  219. }
  220. }
  221. catch
  222. {
  223. }
  224. //VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  225. //AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  226. //SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  227. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  228. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  229. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  230. Logger.Send(LogType.Information, "", "Checking for updates");
  231. if (SupportUtils.CheckForUpdates())
  232. {
  233. Logger.Send(LogType.Information, "", "Update found, closing application.");
  234. Close();
  235. return;
  236. }
  237. Exception? startupException = null;
  238. ValidationStatus? loginStatus = null;
  239. Progress.ShowModal("Loading PRS", progress =>
  240. {
  241. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  242. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  243. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  244. ImportFactory.Register(typeof(CustomImporter<>), "Custom", "All Files (*.*)|*.*");
  245. FormUtils.Register();
  246. DigitalFormDocumentFactory.Init(
  247. new WpfDigitalFormDocumentHandler(
  248. b => Dispatcher.BeginInvoke(() =>
  249. {
  250. BackgroundUploadStatus.Visibility = b
  251. ? Visibility.Visible
  252. : Visibility.Hidden;
  253. }
  254. ),
  255. () => _transport?.IsConnected() ?? false
  256. )
  257. );
  258. DigitalFormDocumentFactory.Run();
  259. Logger.Send(LogType.Information, "", "Registering Classes");
  260. progress.Report("Registering Classes");
  261. var tasks = new List<Task>
  262. {
  263. Task.Run(() =>
  264. {
  265. CoreUtils.RegisterClasses(typeof(TaskGrid).Assembly);
  266. CoreUtils.RegisterClasses();
  267. ComalUtils.RegisterClasses();
  268. StoreUtils.RegisterClasses();
  269. PRSSharedUtils.RegisterClasses();
  270. WPFUtils.RegisterClasses();
  271. ReportUtils.RegisterClasses();
  272. ConfigurationUtils.RegisterClasses();
  273. }),
  274. Task.Run(() =>
  275. {
  276. ScriptDocument.DefaultAssemblies.AddRange(
  277. Assembly.Load("RoslynPad.Roslyn.Windows"),
  278. Assembly.Load("RoslynPad.Editor.Windows"),
  279. typeof(Control).Assembly,
  280. typeof(MessageBox).Assembly,
  281. typeof(SolidColorBrush).Assembly
  282. );
  283. ScriptDocument.Initialize();
  284. }),
  285. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  286. };
  287. Task.WaitAll(tasks.ToArray());
  288. Logger.Send(LogType.Information, "", "Configuring Application");
  289. progress.Report("Configuring Application");
  290. RegisterModules(progress);
  291. if (DatabaseType == DatabaseType.Standalone)
  292. {
  293. progress.Report("Starting local database...");
  294. try
  295. {
  296. StartLocalDatabase(progress);
  297. }
  298. catch (Exception err)
  299. {
  300. startupException = new Exception(
  301. string.Format(
  302. "Unable to open database ({0})\n\n{1}\n\n{2}",
  303. App.DatabaseSettings.FileName,
  304. err.Message,
  305. err.StackTrace
  306. )
  307. );
  308. }
  309. }
  310. });
  311. if (startupException is null && App.DatabaseSettings.Autologin)
  312. {
  313. try
  314. {
  315. Logger.Send(LogType.Information, "", "Logging in");
  316. Dispatcher.Invoke(() =>
  317. {
  318. loginStatus = TryAutoLogin();
  319. });
  320. if(loginStatus == ValidationStatus.VALID)
  321. {
  322. // Do the AfterLogin() here so that we aren't opening and closing progress windows again and again.
  323. Progress.ShowModal("Loading PRS", progress =>
  324. {
  325. AfterLogin(progress);
  326. });
  327. }
  328. }
  329. catch(Exception e)
  330. {
  331. startupException = e;
  332. }
  333. }
  334. if (startupException != null)
  335. {
  336. MessageWindow.ShowError("Error during startup.", startupException);
  337. }
  338. // If the login status is valid, then we've already loaded everything, so we don't here.
  339. if(loginStatus != ValidationStatus.VALID)
  340. {
  341. Logger.Send(LogType.Information, "", "Logging in");
  342. if (DoLogin() == ValidationStatus.VALID)
  343. {
  344. AfterLogin(null);
  345. }
  346. else
  347. {
  348. ConfigureMainScreen(null);
  349. }
  350. }
  351. ProfileName.Content = App.Profile;
  352. URL.Content = GetDatabaseConnectionDescription();
  353. if (loginStatus == ValidationStatus.VALID && DatabaseType == DatabaseType.Standalone)
  354. {
  355. Progress.ShowModal("Starting Scheduler", progress =>
  356. {
  357. scheduler.Start();
  358. });
  359. }
  360. }
  361. #region Connection Management
  362. private string GetDatabaseConnectionDescription()
  363. {
  364. return DatabaseType switch
  365. {
  366. #if RPC
  367. DatabaseType.Networked => (ClientFactory.Parameters?.FirstOrDefault() as RpcClientSocketTransport)?.Host,
  368. #else
  369. DatabaseType.Networked => ClientFactory.Parameters?.FirstOrDefault() as string,
  370. #endif
  371. DatabaseType.Standalone => App.DatabaseSettings?.FileName,
  372. DatabaseType.Local => App.DatabaseSettings?.LocalServerName,
  373. _ => ""
  374. } ?? "";
  375. }
  376. /// <summary>
  377. /// Reconnect to the server.
  378. /// </summary>
  379. /// <returns><see langword="true"/> if connection was successful.</returns>
  380. private bool Reconnect()
  381. {
  382. if (_transport != null)
  383. {
  384. return _transport.Connect();
  385. }
  386. Logger.Send(LogType.Error, ClientFactory.UserID, "Trying to reconnect without a transport set.");
  387. return true; // Returning true so we don't get stuck in infinite loops in exceptional circumstances.
  388. }
  389. private enum ConnectionFailedResult
  390. {
  391. Quit,
  392. Restart,
  393. Ok
  394. }
  395. /// <summary>
  396. /// To be called when initial connection to the server has failed; asks the user if they want to retry,
  397. /// change the database settings, or simply quit PRS.
  398. /// </summary>
  399. /// <returns>The action to take next.</returns>
  400. /// <exception cref="Exception"></exception>
  401. private ConnectionFailedResult DoConnectionFailed()
  402. {
  403. bool connected = false;
  404. while (!connected)
  405. {
  406. var connectionFailedWindow = new ConnectionFailed();
  407. connectionFailedWindow.ShowDialog();
  408. var reconnect = false;
  409. switch (connectionFailedWindow.Result)
  410. {
  411. case ConnectionFailedWindowResult.OpenDatabaseConfiguration:
  412. var result = ShowDatabaseConfiguration();
  413. switch (result)
  414. {
  415. case DatabaseConfigurationResult.RestartRequired:
  416. var shouldRestart = MessageBox.Show(
  417. "A restart is required to apply these changes. Do you wish to restart now?",
  418. "Restart?",
  419. MessageBoxButton.YesNo);
  420. if (shouldRestart == MessageBoxResult.Yes)
  421. {
  422. return ConnectionFailedResult.Restart;
  423. }
  424. else
  425. {
  426. reconnect = true;
  427. }
  428. break;
  429. case DatabaseConfigurationResult.RestartNotRequired:
  430. reconnect = true;
  431. break;
  432. case DatabaseConfigurationResult.Cancel:
  433. reconnect = true;
  434. break;
  435. default:
  436. throw new Exception($"Invalid enum result {result}");
  437. }
  438. break;
  439. case ConnectionFailedWindowResult.RetryConnection:
  440. reconnect = true;
  441. break;
  442. case ConnectionFailedWindowResult.Quit:
  443. return ConnectionFailedResult.Quit;
  444. default:
  445. throw new Exception($"Invalid enum result {connectionFailedWindow.Result}");
  446. }
  447. if (!reconnect)
  448. {
  449. return ConnectionFailedResult.Quit;
  450. }
  451. connected = Reconnect();
  452. }
  453. return ConnectionFailedResult.Ok;
  454. }
  455. private void Transport_OnOpen(IRpcTransport transport, RpcTransportOpenArgs e)
  456. {
  457. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection opened");
  458. }
  459. private void Transport_OnException(IRpcTransport transport, RpcTransportExceptionArgs e)
  460. {
  461. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error in connection: {CoreUtils.FormatException(e.Exception)}");
  462. }
  463. private void TransportConnectionLost(IRpcTransport transport, RpcTransportCloseArgs e)
  464. {
  465. Logger.Send(LogType.Information, ClientFactory.UserID, "Connection lost");
  466. if (transport is IRpcClientTransport client)
  467. {
  468. Dispatcher.Invoke(() =>
  469. {
  470. var reconnection = new ReconnectionWindow();
  471. var cancellationTokenSource = new CancellationTokenSource();
  472. reconnection.OnCancelled = () => cancellationTokenSource.Cancel();
  473. var ct = cancellationTokenSource.Token;
  474. var work = () =>
  475. {
  476. try
  477. {
  478. DateTime lost = DateTime.Now;
  479. while (!client.IsConnected() && !ct.IsCancellationRequested)
  480. {
  481. try
  482. {
  483. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnecting - ({DateTime.Now - lost:hh\\:mm})");
  484. if (client.Connect(ct))
  485. {
  486. break;
  487. }
  488. }
  489. catch (System.Exception e1)
  490. {
  491. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e1.Message}");
  492. // TODO: Remove this suppression
  493. if (e1.Message.StartsWith("The socket is connected, you needn't connect again!"))
  494. {
  495. break;
  496. }
  497. }
  498. }
  499. if (client.IsConnected())
  500. {
  501. Logger.Send(LogType.Information, ClientFactory.UserID, "Reconnected");
  502. ClientFactory.Validate(ClientFactory.SessionID);
  503. Logger.Send(LogType.Information, ClientFactory.UserID, "Validated");
  504. return true;
  505. }
  506. }
  507. catch (Exception e)
  508. {
  509. Logger.Send(LogType.Error, ClientFactory.UserID, $"Reconnect Failed: {e.Message}");
  510. }
  511. return false;
  512. };
  513. var task = Task.Run(() =>
  514. {
  515. var result = work();
  516. Dispatcher.Invoke(() =>
  517. {
  518. reconnection.Close();
  519. });
  520. return result;
  521. }, ct);
  522. reconnection.ShowDialog();
  523. if (!task.Result)
  524. {
  525. Close();
  526. }
  527. });
  528. }
  529. }
  530. #endregion
  531. private bool _loggingOut = false;
  532. private void ClientFactory_OnRequestError(RequestException e)
  533. {
  534. if (e.Status == StatusCode.Unauthenticated)
  535. {
  536. switch (e.Method)
  537. {
  538. case RequestMethod.Query:
  539. case RequestMethod.Save:
  540. case RequestMethod.Delete:
  541. case RequestMethod.MultiQuery:
  542. case RequestMethod.MultiSave:
  543. case RequestMethod.MultiDelete:
  544. if (!_loggingOut)
  545. {
  546. Dispatcher.InvokeAsync(() =>
  547. {
  548. _loggingOut = true;
  549. try
  550. {
  551. Logout(null, true);
  552. }
  553. finally
  554. {
  555. _loggingOut = false;
  556. }
  557. });
  558. }
  559. break;
  560. default:
  561. break;
  562. }
  563. }
  564. }
  565. private void ApplyColorScheme()
  566. {
  567. Color baseColor;
  568. try
  569. {
  570. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  571. }
  572. catch
  573. {
  574. baseColor = Colors.CornflowerBlue;
  575. }
  576. ThemeManager.BaseColor = baseColor;
  577. DynamicGridUtils.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  578. DynamicGridUtils.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  579. DynamicGridUtils.FilterBackground = ThemeManager.FilterBackgroundBrush;
  580. DynamicGridUtils.FilterForeground = ThemeManager.FilterForegroundBrush;
  581. //_ribbon.Background = new SolidColorBrush(Colors.White);
  582. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  583. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  584. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  585. UpdateRibbonColors();
  586. PanelHost.Refresh();
  587. }
  588. #region Configuration
  589. /*
  590. protected override void OnSourceInitialized(EventArgs e)
  591. {
  592. base.OnSourceInitialized(e);
  593. var source = PresentationSource.FromVisual(this) as HwndSource;
  594. source?.AddHook(WndProc);
  595. }
  596. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  597. {
  598. var message = (App.Message)msg;
  599. switch (message)
  600. {
  601. case App.Message.Maximise:
  602. WindowState = WindowState.Maximized;
  603. break;
  604. }
  605. return IntPtr.Zero;
  606. }*/
  607. private void ConfigureMainScreen(IProgress<string>? progress)
  608. {
  609. var bMaps = Security.CanView<Equipment>()
  610. || Security.CanView<Job>()
  611. || Security.CanView<TimeSheet>()
  612. || Security.CanView<GPSTracker>();
  613. var sections = new[]
  614. {
  615. new ProgressSection("Configuring Main Screen", SetupMainScreen),
  616. new ProgressSection("Configuring Projects", () => SetupProjectsTab(bMaps)),
  617. new ProgressSection("Configuring Manufacturing", () => SetupManufacturingTab(bMaps)),
  618. new ProgressSection("Configuring Logistics", () => SetupLogisticsTab(bMaps)),
  619. new ProgressSection("Configuring Products", () => SetupProductsTab(bMaps)),
  620. new ProgressSection("Configuring Human Resources", () => SetupHumanResourcesTab(bMaps)),
  621. new ProgressSection("Configuring Accounts", () => SetupAccountsTab(bMaps)),
  622. new ProgressSection("Configuring Equipment", () => SetupEquipmentTab(bMaps)),
  623. new ProgressSection("Configuring DigitalForms", () => SetupDigitalFormsTab(bMaps)),
  624. new ProgressSection("Configuring Dashboards", () => SetupDashboardsTab(bMaps)),
  625. new ProgressSection("Configuring System Modules", SetupSystemModules)
  626. };
  627. if(progress is not null)
  628. {
  629. Dispatcher.Invoke(SetupScreen);
  630. foreach(var section in sections)
  631. {
  632. progress.Report(section.Message);
  633. Dispatcher.Invoke(section.Action);
  634. }
  635. }
  636. else
  637. {
  638. SetupScreen();
  639. Progress.ShowModal(sections);
  640. }
  641. }
  642. private void SetupScreen()
  643. {
  644. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  645. if (button != null)
  646. button.Visibility = Visibility.Collapsed;
  647. if (ClientFactory.UserGuid == Guid.Empty)
  648. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  649. else
  650. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  651. }
  652. private void SetupMainScreen()
  653. {
  654. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  655. // Notifications Area
  656. SetFrameworkItemVisibility(SendNotification, Security.CanView<Notification>());
  657. SetFrameworkItemVisibility(Notifications, Security.CanView<Notification>());
  658. SetFrameworkItemVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  659. UserID.Content = ClientFactory.UserID;
  660. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  661. {
  662. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  663. if (timeUntilExpiration.Days < 14)
  664. {
  665. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  666. PasswordExpiryNotice.Visibility = Visibility.Visible;
  667. }
  668. else
  669. {
  670. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  671. }
  672. }
  673. }
  674. private void SetupSystemModules()
  675. {
  676. SetFrameworkItemVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  677. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  678. SetFrameworkItemVisibility(SecurityDefaultsButton,
  679. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  680. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  681. BackstageSeparator1a.Visibility = Visibility.Visible;
  682. SystemLogsButton.Visibility = Visibility.Visible;
  683. SetFrameworkItemVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  684. SetFrameworkItemVisibility(EventList, Security.IsAllowed<CanManageEvents>());
  685. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList, EventList);
  686. //SetModuleVisibility<>(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  687. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  688. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  689. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  690. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  691. SetupDock<CanViewJobDock>(JobDock, Jobs);
  692. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  693. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  694. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  695. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  696. SetupDock<CanViewProblemsDock>(ProblemsDock, Problems);
  697. SetupDock<CanViewRequisitionsDock>(RequisitionsDock, Requisitions);
  698. _ribbon.InvalidateArrange();
  699. }
  700. private void SetupDashboardsTab(bool bMaps)
  701. {
  702. if (!Security.IsAllowed<ViewDesktopDashboardsTab>())
  703. return;
  704. SetModuleVisibility<UtilityDashboard>(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  705. SetModuleVisibility<NotificationPanel>(DashboardMessagesButton, Security.CanView<Notification>());
  706. SetModuleVisibility<TaskPanel>(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  707. SetModuleVisibility<AttendancePanel>(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  708. SetModuleVisibility<MapsPanel>(DashboardsMapButton, bMaps);
  709. SetModuleVisibility<DailyReport>(DashboardsDailyReportButton,
  710. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  711. SetModuleVisibility<FactoryProductivityDashboard>(FactoryProductivityButton,
  712. ClientFactory.IsSupported<ManufacturingHistory>()
  713. && Security.IsAllowed<CanViewFactoryKPIs>()
  714. && Security.IsAllowed<ViewDesktopFactoryKPIsDashboard>());
  715. SetModuleVisibility<ManufacturingTemplateAnalysis>(TemplateAnalysisButton,
  716. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  717. && Security.IsAllowed<CanViewTemplateAnalysis>()
  718. && Security.IsAllowed<ViewDesktopTemplateAnalysisDashboard>());
  719. SetModuleVisibility<FactoryFloorAnalysis>(FactoryAnalysisButton,
  720. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>()
  721. && Security.IsAllowed<CanViewFactoryAnalysis>()
  722. && Security.IsAllowed<ViewDesktopFactoryAnalysisDashboard>());
  723. SetModuleVisibility<DatabaseActivityDashboard>(DatabaseActivityButton,
  724. ClientFactory.IsSupported<UserTracking>()
  725. && Security.IsAllowed<CanViewDatabaseActivity>()
  726. && Security.IsAllowed<ViewDesktopDatabaseActivityDashboard>());
  727. SetModuleVisibility<UserActivity>(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>()
  728. && Security.IsAllowed<CanViewUserActivity>()
  729. && Security.IsAllowed<ViewDesktopUserActivityDashboard>());
  730. SetModuleVisibility<WidgetDashboard>(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>() && Security.IsAllowed<ViewDesktopQuickStatusDashboard>());
  731. SetVisibleIfEither(DashboardsTaskSeparator,
  732. new FrameworkElement[]
  733. {
  734. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  735. DashboardsMapButton,
  736. DashboardsDailyReportButton
  737. },
  738. new FrameworkElement[]
  739. {
  740. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton
  741. });
  742. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  743. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  744. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QuickStatusButton);
  745. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  746. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  747. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  748. DatabaseActivityButton,
  749. UserActivityButton, QuickStatusButton);
  750. }
  751. private void SetupDigitalFormsTab(bool bMaps)
  752. {
  753. if (!Security.IsAllowed<ViewDesktopDigitalFormsTab>())
  754. return;
  755. SetModuleVisibility<UtilityDashboard>(DigitalFormsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  756. SetModuleVisibility<NotificationPanel>(DigitalFormsMessagesButton, Security.CanView<Notification>());
  757. SetModuleVisibility<TaskPanel>(DigitalFormsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  758. SetModuleVisibility<AttendancePanel>(DigitalFormsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  759. SetModuleVisibility<MapsPanel>(DigitalFormsMapButton, bMaps);
  760. SetModuleVisibility<DailyReport>(DigitalFormsDailyReportButton,
  761. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  762. SetModuleVisibility<DigitalFormsLibrary>(DigitalFormsFormsLibraryButton, ClientFactory.IsSupported<DigitalForm>()
  763. && Security.CanView<DigitalForm>()
  764. && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  765. SetModuleVisibility<CompletedFormsPanel>(DigitalFormsCompletedFormsButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>() && Security.IsAllowed<ViewDesktopDigitalFormsDashboard>());
  766. SetVisibleIfEither(DigitalFormsTaskSeparator,
  767. new FrameworkElement[]
  768. {
  769. DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton, DigitalFormsAttendanceButton, DigitalFormsMapButton,
  770. DigitalFormsDailyReportButton
  771. }, new FrameworkElement[] { DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton });
  772. SetVisibleIfAny(DigitalFormsActions, DigitalFormsDashboardButton, DigitalFormsMessagesButton, DigitalFormsTaskButton,
  773. DigitalFormsAttendanceButton, DigitalFormsDailyReportButton, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  774. SetTabVisibleIfAny(DigitalFormsTab, DigitalFormsFormsLibraryButton, DigitalFormsCompletedFormsButton);
  775. }
  776. private void SetupEquipmentTab(bool bMaps)
  777. {
  778. if (!Security.IsAllowed<ViewDesktopEquipmentTab>())
  779. return;
  780. SetModuleVisibility<UtilityDashboard>(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  781. SetModuleVisibility<NotificationPanel>(EquipmentMessagesButton, Security.CanView<Notification>());
  782. SetModuleVisibility<TaskPanel>(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  783. SetModuleVisibility<AttendancePanel>(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  784. SetModuleVisibility<MapsPanel>(EquipmentMapButton, bMaps);
  785. SetModuleVisibility<DailyReport>(EquipmentDailyReportButton,
  786. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  787. SetModuleVisibility<EquipmentPanel>(EquipmentButton, ClientFactory.IsSupported<Equipment>()
  788. && Security.CanView<Equipment>()
  789. && Security.IsAllowed<ViewDesktopEquipmentListScreen>());
  790. SetModuleVisibility<EquipmentMaintenancePanel>(EquipmentMaintenanceButton,
  791. ClientFactory.IsSupported<Equipment>()
  792. && Security.CanView<Equipment>()
  793. && Security.IsAllowed<ViewDesktopEquipmentMaintenanceScreen>() );
  794. SetModuleVisibility<EquipmentPlannerPanel>(EquipmentPlannerButton,
  795. ClientFactory.IsSupported<Equipment>()
  796. && Security.CanView<Equipment>()
  797. && ClientFactory.IsSupported<Assignment>()
  798. && Security.CanView<Assignment>()
  799. && Security.IsAllowed<ViewDesktopEquipmentPlannerScreen>());
  800. SetVisibleIfEither(EquipmentTaskSeparator,
  801. new FrameworkElement[]
  802. {
  803. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  804. EquipmentDailyReportButton
  805. }, new FrameworkElement[] { EquipmentButton, EquipmentPlannerButton });
  806. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  807. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton, EquipmentPlannerButton);
  808. SetModuleVisibility<GPSTrackers>(TrackersMasterList, Security.CanView<GPSTracker>() && Security.IsAllowed<ViewDesktopGPSTrackersScreen>());
  809. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  810. }
  811. private void SetupAccountsTab(bool bMaps)
  812. {
  813. if (!Security.IsAllowed<ViewDesktopAccountsTab>())
  814. return;
  815. SetModuleVisibility<UtilityDashboard>(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  816. SetModuleVisibility<NotificationPanel>(AccountsMessagesButton, Security.CanView<Notification>());
  817. SetModuleVisibility<TaskPanel>(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  818. SetModuleVisibility<AttendancePanel>(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  819. SetModuleVisibility<MapsPanel>(AccountsMapButton, bMaps);
  820. SetModuleVisibility<DailyReport>(AccountsDailyReportButton,
  821. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  822. SetModuleVisibility<CustomerPanel>(CustomerList, ClientFactory.IsSupported<Customer>()
  823. && Security.CanView<Customer>()
  824. && Security.IsAllowed<ViewDesktopCustomersScreen>());
  825. SetModuleVisibility<InvoicePanel>(InvoiceList, ClientFactory.IsSupported<Invoice>()
  826. && Security.CanView<Invoice>()
  827. && Security.IsAllowed<ViewDesktopInvoicesScreen>());
  828. SetModuleVisibility<CustomerReceipts>(ReceiptList, ClientFactory.IsSupported<Receipt>()
  829. && Security.CanView<Receipt>()
  830. && Security.IsAllowed<ViewDesktopReceiptsScreen>());
  831. SetModuleVisibility<SupplierPanel>(SupplierList, ClientFactory.IsSupported<Supplier>()
  832. && Security.CanView<Supplier>()
  833. && Security.IsAllowed<ViewDesktopSuppliersScreen>());
  834. SetModuleVisibility<DataEntryPanel>(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  835. SetModuleVisibility<SupplierPurchaseOrderPanel>(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>()
  836. && Security.CanView<PurchaseOrder>()
  837. && Security.IsAllowed<ViewDesktopPurchaseOrdersScreen>());
  838. SetModuleVisibility<SupplierBillPanel>(BillsList, ClientFactory.IsSupported<Bill>()
  839. && Security.CanView<Bill>()
  840. && Security.IsAllowed<ViewDesktopBillsScreen>());
  841. SetModuleVisibility<SupplierPayments>(PaymentsList, ClientFactory.IsSupported<Payment>()
  842. && Security.CanView<Payment>()
  843. && Security.IsAllowed<ViewDesktopPaymentsScreen>());
  844. SetVisibleIfEither(AccountsTaskSeparator1,
  845. new FrameworkElement[]
  846. {
  847. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  848. AccountsDailyReportButton
  849. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  850. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  851. new FrameworkElement[] { SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList });
  852. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  853. AccountsAttendanceButton,
  854. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  855. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, AccountsDataButton, PurchasesList, BillsList, PaymentsList);
  856. }
  857. private void SetupHumanResourcesTab(bool bMaps)
  858. {
  859. if (!Security.IsAllowed<ViewDesktopHumanResourcesTab>())
  860. return;
  861. SetModuleVisibility<UtilityDashboard>(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  862. SetModuleVisibility<NotificationPanel>(HumanResourcesMessagesButton, Security.CanView<Notification>());
  863. SetModuleVisibility<TaskPanel>(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  864. SetModuleVisibility<AttendancePanel>(HumanResourcesAttendanceButton,
  865. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  866. SetModuleVisibility<MapsPanel>(HumanResourcesMapButton, bMaps);
  867. SetModuleVisibility<DailyReport>(HumanResourcesDailyReportButton,
  868. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  869. SetModuleVisibility<CalendarPanel>(CalendarButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopCalendarScreen>());
  870. SetModuleVisibility<EmployeeResourcePlannerPanel>(EmployeePlannerButton, Security.CanView<Assignment>() && Security.IsAllowed<ViewDesktopEmployeePlannerScreen>());
  871. SetModuleVisibility<TimesheetPanel>(TimesheetsButton, Security.CanView<TimeSheet>() && Security.IsAllowed<ViewDesktopStaffTimeSheetsScreen>());
  872. SetModuleVisibility<LeaveRequestPanel>(LeaveRequestsButton, Security.CanView<LeaveRequest>() && Security.IsAllowed<ViewDesktopLeaveRequestsScreen>());
  873. SetModuleVisibility<OrgChartPanel>(OrgChartButton,
  874. ClientFactory.IsSupported<Employee>()
  875. &&
  876. Security.IsAllowed<ViewDesktopOrgChartScreen>()
  877. );
  878. SetModuleVisibility<MeetingPanel>(MeetingsButton, Security.IsAllowed<ViewDesktopMeetingsScreen>());
  879. SetVisibleIfEither(HumanResourcesTaskSeparator,
  880. new FrameworkElement[]
  881. {
  882. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  883. HumanResourcesMapButton, HumanResourcesDailyReportButton
  884. }, new FrameworkElement[] { CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  885. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  886. HumanResourcesAttendanceButton,
  887. HumanResourcesDailyReportButton, CalendarButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  888. SetModuleVisibility<UserPanel>(UsersButton, Security.CanView<User>() && Security.IsAllowed<ViewDesktopUserAccountsScreen>());
  889. SetModuleVisibility<EmployeePanel>(EmployeesButton, Security.CanView<Employee>() && Security.IsAllowed<ViewDesktopEmployeeListScreen>());
  890. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  891. new FrameworkElement[] { CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  892. new FrameworkElement[] { UsersButton, EmployeesButton });
  893. SetTabVisibleIfAny(HumanResourcesTab, CalendarButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  894. }
  895. private void SetupProductsTab(bool bMaps)
  896. {
  897. if (!Security.IsAllowed<ViewDesktopProductManagementTab>())
  898. return;
  899. SetModuleVisibility<UtilityDashboard>(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  900. SetModuleVisibility<NotificationPanel>(ProductsMessagesButton, Security.CanView<Notification>());
  901. SetModuleVisibility<TaskPanel>(ProductsTaskButton, Security.CanView<Kanban>());
  902. SetModuleVisibility<AttendancePanel>(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  903. SetModuleVisibility<MapsPanel>(ProductsMapButton, bMaps);
  904. SetModuleVisibility<DailyReport>(ProductsDailyReportButton,
  905. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  906. SetModuleVisibility<ProductsPanel>(ProductsMasterList, Security.CanView<Product>() && Security.IsAllowed<ViewDesktopProductListScreen>());
  907. SetModuleVisibility<StockLocationPanel>(StockLocationList, Security.CanView<StockLocation>() && Security.IsAllowed<ViewDesktopStockLocationsScreen>());
  908. SetModuleVisibility<StockMovementPanel>(StockMovementList, Security.CanView<StockMovement>() && Security.IsAllowed<ViewDesktopStockMovementsScreen>());
  909. SetModuleVisibility<StockForecastPanel>(StockForecastButton, Security.CanView<Product>()
  910. && Security.CanView<JobMaterial>()
  911. && Security.IsAllowed<ViewDesktopStockForecastScreen>());
  912. SetModuleVisibility<ReservationManagementPanel>(ReservationManagementButton, Security.IsAllowed<ViewDesktopReservationManagementScreen>());
  913. SetVisibleIfEither(ProductsTaskSeparator,
  914. new FrameworkElement[]
  915. {
  916. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  917. ProductsDailyReportButton
  918. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton });
  919. SetVisibleIfAny(ProductActions, ProductsMasterList, StockLocationList, StockMovementList, StockForecastButton);
  920. SetTabVisibleIfAny(ProductTab, ProductActions);
  921. }
  922. private void SetupLogisticsTab(bool bMaps)
  923. {
  924. if (!Security.IsAllowed<ViewDesktopLogisticsTab>())
  925. return;
  926. SetModuleVisibility<UtilityDashboard>(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  927. SetModuleVisibility<NotificationPanel>(LogisticsMessagesButton, Security.CanView<Notification>());
  928. SetModuleVisibility<TaskPanel>(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  929. SetModuleVisibility<AttendancePanel>(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  930. SetModuleVisibility<MapsPanel>(LogisticsMapButton, bMaps);
  931. SetModuleVisibility<DailyReport>(LogisticsDailyReportButton,
  932. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  933. SetModuleVisibility<ReadyToGoPanel>(ReadyToGoItemsButton,
  934. ClientFactory.IsSupported<DeliveryItem>()
  935. && Security.IsAllowed<CanViewLogisticsReadyToGo>()
  936. && Security.IsAllowed<ViewDesktopReadyToGoScreen>());
  937. SetModuleVisibility<DispatchPanel>(DispatchButton, Security.CanView<Shipment>()
  938. && Security.CanView<DeliveryItem>()
  939. && Security.IsAllowed<ViewDesktopRackListScreen>());
  940. SetModuleVisibility<RequisitionPanel>(RequisitionsButton, Security.CanView<Requisition>() && Security.IsAllowed<ViewDesktopSiteRequisitionsScreen>());
  941. SetModuleVisibility<DeliveryPanel>(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>() && Security.IsAllowed<ViewDesktopDeliveriesScren>());
  942. SetModuleVisibility<DeliveredOnSitePanel>(DeliveredItemsButton,
  943. ClientFactory.IsSupported<DeliveryItem>()
  944. && Security.IsAllowed<CanViewDeliveredOnSite>()
  945. && Security.IsAllowed<ViewDesktopDeliveredOnSiteScreen>());
  946. SetModuleVisibility<ConsignmentsPanel>(ConsignmentButton, Security.CanView<Consignment>() && Security.IsAllowed<ViewDesktopIncomingConsignmentsScreen>());
  947. SetVisibleIfEither(LogisticsTaskSeparator1,
  948. new FrameworkElement[]
  949. {
  950. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  951. LogisticsDailyReportButton
  952. },
  953. new FrameworkElement[]
  954. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  955. SetVisibleIfEither(LogisticsTaskSeparator2,
  956. new FrameworkElement[]
  957. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  958. new FrameworkElement[] { ConsignmentButton });
  959. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  960. DeliveredItemsButton,
  961. ConsignmentButton);
  962. }
  963. private void SetupManufacturingTab(bool bMaps)
  964. {
  965. if (!Security.IsAllowed<ViewDesktopManufacturingTab>())
  966. return;
  967. SetModuleVisibility<UtilityDashboard>(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  968. SetModuleVisibility<NotificationPanel>(ManufacturingMessagesButton, Security.CanView<Notification>());
  969. SetModuleVisibility<TaskPanel>(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  970. SetModuleVisibility<AttendancePanel>(ManufacturingAttendanceButton,
  971. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  972. SetModuleVisibility<MapsPanel>(ManufacturingMapButton, bMaps);
  973. SetModuleVisibility<DailyReport>(ManufacturingDailyReportButton,
  974. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  975. SetVisibleIfAny(ManufacturingTaskSeparator,
  976. new FrameworkElement[]
  977. {
  978. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  979. ManufacturingMapButton, ManufacturingDailyReportButton
  980. });
  981. SetModuleVisibility<StagingPanel>(DesignManagementButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  982. SetFrameworkItemVisibility(ManufacturingDesignSeparator, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopDesignManagementScreen>());
  983. SetModuleVisibility<ManufacturingPanel>(FactoryStatusButton,
  984. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>()
  985. && Security.IsAllowed<CanViewFactoryStatus>()
  986. && Security.IsAllowed<ViewDesktopManufacturingStatusScreen>());
  987. SetModuleVisibility<ManufacturingAllocationPanel>(FactoryAllocationButton,
  988. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>()
  989. && Security.IsAllowed<CanViewFactoryAllocation>()
  990. && Security.IsAllowed<ViewDesktopFactoryAllocationScreen>());
  991. //SetModuleVisibility<>(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  992. SetModuleVisibility<FactoryPanel>(FactoryFloorButton,
  993. ClientFactory.IsSupported<ManufacturingPacket>()
  994. && Security.IsAllowed<CanViewFactoryFloor>()
  995. && Security.IsAllowed<ViewDesktopFactoryFloorScreen>());
  996. //SetModuleVisibility<>(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  997. SetVisibleIfAny(ManufacturingActionSeparator,
  998. new FrameworkElement[]
  999. {
  1000. FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton
  1001. });
  1002. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  1003. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  1004. FactoryFloorButton);
  1005. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  1006. }
  1007. private void SetupProjectsTab(bool bMaps)
  1008. {
  1009. if (!Security.IsAllowed<ViewDesktopProjectsTab>())
  1010. return;
  1011. SetModuleVisibility<UtilityDashboard>(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  1012. SetModuleVisibility<NotificationPanel>(ProjectMessagesButton, Security.CanView<Notification>());
  1013. SetModuleVisibility<TaskPanel>(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  1014. SetModuleVisibility<AttendancePanel>(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  1015. SetModuleVisibility<MapsPanel>(ProjectsMapButton, bMaps);
  1016. SetModuleVisibility<DailyReport>(ProjectDailyReportButton,
  1017. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  1018. SetModuleVisibility<ProjectsPanel>(ProjectsButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectsScreen>());
  1019. //SetModuleVisibility<>(ServiceButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopServiceScreen>());
  1020. SetModuleVisibility<JobResourcePlannerPanel>(ProjectPlannerButton, Security.CanView<Job>() && Security.IsAllowed<ViewDesktopProjectPlannerScreen>());
  1021. SetVisibleIfEither(ProjectTaskSeparator,
  1022. new FrameworkElement[]
  1023. {
  1024. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  1025. ProjectDailyReportButton
  1026. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ProjectPlannerButton });
  1027. SetModuleVisibility<QuotePanel>(QuotesButton, Security.CanView<Quote>() && Security.IsAllowed<ViewDesktopQuotesScreen>());
  1028. SetModuleVisibility<KitPanel>(KitsMasterList, Security.CanView<Kit>() && Security.IsAllowed<ViewDesktopProductKitsScreen>());
  1029. SetModuleVisibility<CostSheetPanel>(CostSheetsMasterList, Security.CanView<CostSheet>() && Security.IsAllowed<ViewDesktopCostSheetsScreen>());
  1030. SetVisibleIfAny(ProjectsSetup, KitsMasterList, CostSheetsMasterList);
  1031. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  1032. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  1033. SetTabVisibleIfAny(ProjectsTab, QuotesButton, ProjectsButton, ProjectPlannerButton, CostSheetsMasterList, KitsMasterList);
  1034. }
  1035. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  1036. where TSecurityDescriptor : ISecurityDescriptor, new()
  1037. {
  1038. if (Security.IsAllowed<TSecurityDescriptor>())
  1039. {
  1040. if (!DockGroup.Children.Any(x => x == layout))
  1041. {
  1042. DockGroup.Children.Add(layout);
  1043. }
  1044. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  1045. dock.Setup();
  1046. }
  1047. else
  1048. {
  1049. DockGroup.RemoveChild(layout);
  1050. }
  1051. }
  1052. private void LoadApplicationState()
  1053. {
  1054. if (ClientFactory.UserGuid != Guid.Empty)
  1055. {
  1056. _ribbon.IsCollapsed = false;
  1057. if (OutstandingDailyReports(false))
  1058. {
  1059. MessageWindow.ShowMessage("There are outstanding Daily Reports that must be filled out before continuing!"
  1060. + "\n\nAccess to PRS is restricted until this is corrected.",
  1061. "Outstanding Reports");
  1062. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  1063. if(dailyReportPanel is not null)
  1064. {
  1065. dailyReportPanel.OnTimeSheetConfirmed += e =>
  1066. {
  1067. if (!OutstandingDailyReports(true))
  1068. {
  1069. ConfigureMainScreen(null);
  1070. LoadApplicationState();
  1071. }
  1072. };
  1073. }
  1074. return;
  1075. }
  1076. using (new WaitCursor())
  1077. {
  1078. _ribbon.IsCollapsed = false;
  1079. LoadInitialWindow();
  1080. }
  1081. }
  1082. }
  1083. private void LoadInitialWindow()
  1084. {
  1085. var app = new LocalConfiguration<AppSettings>().Load();
  1086. var module = app.Settings.ContainsKey("CurrentPanel")
  1087. ? !string.IsNullOrWhiteSpace(app.Settings["CurrentPanel"])
  1088. ? app.Settings["CurrentPanel"].Split([" / "], StringSplitOptions.None)
  1089. : [ "Human Resources", "Task List"]
  1090. : [ "Human Resources", "Task List"];
  1091. try
  1092. {
  1093. var bFound = false;
  1094. if (module.Length == 2)
  1095. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1096. {
  1097. if (String.Equals(tab.Header, module.First()))
  1098. {
  1099. _ribbon.SelectedTabItem = tab;
  1100. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1101. {
  1102. foreach (var item in bar.Items)
  1103. {
  1104. var button = item as Fluent.Button;
  1105. if (button != null && String.Equals(button.Header, module.Last()))
  1106. {
  1107. bFound = true;
  1108. if (button.Command is SimpleCommand command)
  1109. command.Execute(null);
  1110. //button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1111. break;
  1112. }
  1113. }
  1114. if (bFound)
  1115. break;
  1116. }
  1117. }
  1118. if (bFound)
  1119. break;
  1120. }
  1121. }
  1122. catch (Exception e)
  1123. {
  1124. MessageWindow.ShowError($"Unable to load {app.Settings["CurrentPanel"]}", e);
  1125. }
  1126. }
  1127. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1128. {
  1129. _ribbon.SelectedTabItem = CurrentTab;
  1130. }
  1131. private void LoadSecondaryWindows()
  1132. {
  1133. if (ClientFactory.UserGuid != Guid.Empty)
  1134. {
  1135. var windows = App.DatabaseSettings.SecondaryWindows;
  1136. foreach (var key in windows.Keys.ToArray())
  1137. {
  1138. SecondaryWindows[key] = new SecondaryWindow(
  1139. key,
  1140. windows[key].Item1,
  1141. windows[key].Item2,
  1142. windows[key].Item3,
  1143. windows[key].Item4,
  1144. windows[key].Item5,
  1145. windows[key].Item6
  1146. );
  1147. SecondaryWindows[key].Closed += (o, e) => { SecondaryWindows.Remove(key); };
  1148. SecondaryWindows[key].Show();
  1149. }
  1150. }
  1151. else
  1152. {
  1153. foreach (var key in SecondaryWindows.Keys.ToArray())
  1154. {
  1155. App.IsClosing = true;
  1156. SecondaryWindows[key].Close();
  1157. App.IsClosing = false;
  1158. }
  1159. }
  1160. }
  1161. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1162. {
  1163. if (sender == null)
  1164. throw new Exception("No Tab Found!");
  1165. if (sender is Fluent.RibbonTabItem)
  1166. return (Fluent.RibbonTabItem)sender;
  1167. return GetTabItem(sender.Parent as FrameworkElement);
  1168. }
  1169. private IEnumerable<IBasePanel> Panels
  1170. {
  1171. get
  1172. {
  1173. if(PanelHost.CurrentPanel is not null)
  1174. {
  1175. yield return PanelHost.CurrentPanel;
  1176. }
  1177. foreach(var window in SecondaryWindows.Values)
  1178. {
  1179. yield return window.Panel;
  1180. }
  1181. }
  1182. }
  1183. #region LoadWindow / LoadSecondaryWindow
  1184. private T? LoadWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1185. {
  1186. return LoadWindow<T>(sender, new CancelEventArgs());
  1187. }
  1188. public IBasePanel? LoadWindow(Type t, Fluent.Button sender, CancelEventArgs cancel)
  1189. {
  1190. using (new WaitCursor())
  1191. {
  1192. UnloadWindow(cancel);
  1193. if (cancel.Cancel)
  1194. {
  1195. return null;
  1196. }
  1197. CurrentTab = GetTabItem(sender);
  1198. CurrentButton = sender;
  1199. //CurrentButton.IsSelected = true;
  1200. UpdateRibbonColors();
  1201. var moduleName = sender.Header?.ToString() ?? "";
  1202. var panel = PanelHost.LoadPanel(t, moduleName);
  1203. ContentControl.Content = panel;
  1204. Title =
  1205. $"{moduleName} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1206. PanelHost.Refresh();
  1207. if (panel is NotificationPanel)
  1208. {
  1209. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1210. NotificationsWatchDog.IsEnabled = false;
  1211. Notifications.Visibility = Visibility.Collapsed;
  1212. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1213. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1214. }
  1215. else
  1216. {
  1217. ReloadNotifications();
  1218. }
  1219. if (sender != null)
  1220. {
  1221. var settings = new LocalConfiguration<AppSettings>().Load();
  1222. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1223. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1224. {
  1225. settings.Settings["CurrentPanel"] = module;
  1226. try
  1227. {
  1228. new LocalConfiguration<AppSettings>().Save(settings);
  1229. }
  1230. catch (Exception e)
  1231. {
  1232. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1233. }
  1234. }
  1235. }
  1236. return panel;
  1237. }
  1238. }
  1239. private T? LoadWindow<T>(Fluent.Button sender, CancelEventArgs cancel) where T : class, IBasePanel, new()
  1240. {
  1241. return LoadWindow(typeof(T), sender, cancel) as T;
  1242. }
  1243. private void LoadSecondaryWindow(Type t, Fluent.Button sender)
  1244. {
  1245. var id = Guid.NewGuid();
  1246. var window = new Tuple<string, string, double, double, double, double>(
  1247. t.EntityName(),
  1248. sender.Header?.ToString() ?? "",
  1249. Left + 100,
  1250. Top + 100,
  1251. Width - 200,
  1252. Height - 200
  1253. );
  1254. App.DatabaseSettings.SecondaryWindows[id] = window;
  1255. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1256. SecondaryWindows[id] = new SecondaryWindow(
  1257. id,
  1258. window.Item1,
  1259. window.Item2,
  1260. window.Item3,
  1261. window.Item4,
  1262. window.Item5,
  1263. window.Item6
  1264. );
  1265. SecondaryWindows[id].Show();
  1266. }
  1267. private void LoadSecondaryWindow<T>(Fluent.Button sender) where T : class, IBasePanel, new()
  1268. => LoadSecondaryWindow(typeof(T), sender);
  1269. // private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1270. // {
  1271. // var panel = PanelHost.CurrentPanel;
  1272. // if (panel is null) return;
  1273. //
  1274. // var id = Guid.NewGuid();
  1275. // var window = new Tuple<string, string, double, double, double, double>(
  1276. // panel.GetType().EntityName(),
  1277. // PanelHost.CurrentModuleName,
  1278. // Left + 100,
  1279. // Top + 100,
  1280. // Width - 200,
  1281. // Height - 200
  1282. // );
  1283. // App.DatabaseSettings.SecondaryWindows[id] = window;
  1284. // new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1285. // SecondaryWindows[id] = new SecondaryWindow(
  1286. // id,
  1287. // window.Item1,
  1288. // window.Item2,
  1289. // window.Item3,
  1290. // window.Item4,
  1291. // window.Item5,
  1292. // window.Item6
  1293. // );
  1294. // SecondaryWindows[id].Show();
  1295. // }
  1296. #endregion
  1297. private void UpdateRibbonColors()
  1298. {
  1299. foreach (var tab in _ribbon.Tabs)
  1300. {
  1301. bool bFound = false;
  1302. foreach (var grp in tab.Groups)
  1303. {
  1304. foreach (var btn in grp.Items)
  1305. {
  1306. if (btn is Fluent.Button fluentbutton)
  1307. {
  1308. bFound = bFound || (btn == CurrentButton);
  1309. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1310. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1311. }
  1312. }
  1313. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1314. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1315. }
  1316. }
  1317. }
  1318. private static void StartLocalDatabase(IProgress<string> progress)
  1319. {
  1320. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1321. if (!Directory.Exists(dirName) && dirName != null)
  1322. Directory.CreateDirectory(dirName);
  1323. var FileName = App.DatabaseSettings.FileName;
  1324. var Exists = File.Exists(FileName);
  1325. progress.Report("Configuring Stores");
  1326. DbFactory.Stores = CoreUtils.TypeList(
  1327. new[]
  1328. {
  1329. typeof(Store<>).Assembly,
  1330. typeof(EquipmentStore).Assembly
  1331. },
  1332. myType =>
  1333. myType.IsClass
  1334. && !myType.IsAbstract
  1335. && !myType.IsGenericType
  1336. && myType.GetInterfaces().Contains(typeof(IStore))
  1337. ).ToArray();
  1338. DbFactory.DefaultStore = typeof(BaseStore<>);
  1339. DbFactory.ProviderFactory = new SQLiteProviderFactory(App.DatabaseSettings.FileName);
  1340. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1341. DbFactory.Logo = App.DatabaseSettings.Logo;
  1342. progress.Report("Starting Local Database");
  1343. DbFactory.Start();
  1344. ClientFactory.DatabaseID = DbFactory.ID;
  1345. progress.Report("Checking Database");
  1346. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  1347. if (!users.Any())
  1348. {
  1349. var user = new User { UserID = "ADMIN", Password = "admin" };
  1350. DbFactory.NewProvider(Logger.Main).Save(user);
  1351. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1352. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1353. employee.UserLink.ID = user.ID;
  1354. DbFactory.NewProvider(Logger.Main).Save(employee);
  1355. }
  1356. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1357. Job.JobNumberPrefix = App.DatabaseSettings.JobPrefix;
  1358. PurchaseOrder.PONumberPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1359. }
  1360. #endregion
  1361. #region Login Management
  1362. private ValidationStatus? TryAutoLogin()
  1363. {
  1364. ValidationStatus? result = null;
  1365. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1366. {
  1367. try
  1368. {
  1369. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1370. }
  1371. catch (Exception e)
  1372. {
  1373. MessageWindow.ShowError("Error connecting to server.\nPlease check the server URL and port number.", e);
  1374. result = null;
  1375. }
  1376. if (result == ValidationStatus.INVALID)
  1377. {
  1378. MessageWindow.ShowMessage("Unable to Login with User ID: " + App.DatabaseSettings.UserID, "Login failed");
  1379. }
  1380. }
  1381. return result;
  1382. }
  1383. private ValidationStatus? DoLogin()
  1384. {
  1385. ValidationStatus? result = null;
  1386. if (result != ValidationStatus.VALID)
  1387. {
  1388. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationStatus.INVALID);
  1389. if (login.ShowDialog() == true)
  1390. {
  1391. result = ValidationStatus.VALID;
  1392. }
  1393. }
  1394. return result ?? ValidationStatus.INVALID;
  1395. }
  1396. /// <summary>
  1397. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1398. /// </summary>
  1399. /// <param name="progress">If not <see langword="null"/>, then rather than opening a new progress window, just uses that.</param>
  1400. private void AfterLogin(IProgress<string>? progress)
  1401. {
  1402. Logger.Send(LogType.Information, "", "Checking Support Ticket Status");
  1403. CheckSupportTicketStatus();
  1404. Logger.Send(LogType.Information, "", "Loading employee");
  1405. LoadCurrentEmployee();
  1406. if (CheckTimesheetBypass(true))
  1407. {
  1408. UpdateCurrentLogin();
  1409. }
  1410. else
  1411. {
  1412. Dispatcher.Invoke(() =>
  1413. {
  1414. MessageWindow.ShowMessage("You must clock on before logging in to PRS!", "Not clocked in.");
  1415. });
  1416. ClientFactory.InvalidateUser();
  1417. App.EmployeeID = Guid.Empty;
  1418. App.EmployeeName = "";
  1419. App.EmployeeCode = "";
  1420. App.EmployeeEmail = "";
  1421. }
  1422. Logger.Send(LogType.Information, "", "Setting colours");
  1423. if(progress is null)
  1424. {
  1425. ApplyColorScheme();
  1426. }
  1427. else
  1428. {
  1429. Dispatcher.Invoke(ApplyColorScheme);
  1430. }
  1431. Logger.Send(LogType.Information, "", "Configuring main window");
  1432. ConfigureMainScreen(progress);
  1433. Logger.Send(LogType.Information, "", "Loading current window");
  1434. if(progress is null)
  1435. {
  1436. LoadApplicationState();
  1437. }
  1438. else
  1439. {
  1440. Dispatcher.Invoke(LoadApplicationState);
  1441. }
  1442. Logger.Send(LogType.Information, "", "Loading secondary window");
  1443. if(progress is null)
  1444. {
  1445. LoadSecondaryWindows();
  1446. }
  1447. else
  1448. {
  1449. Dispatcher.Invoke(LoadSecondaryWindows);
  1450. }
  1451. //if (_ribbon.Menu.IsVisible)
  1452. //{
  1453. // _ribbon.;
  1454. //}
  1455. }
  1456. /// <summary>
  1457. /// Creates a new <see cref="Login"/> if one does not already exist. Otherwise, updates the <see cref="Login"/> entry in the database with new Station ID.
  1458. /// </summary>
  1459. private void UpdateCurrentLogin()
  1460. {
  1461. if (CoreUtils.GetVersion().Equals("???"))
  1462. return;
  1463. // Register this station with the Server
  1464. // Later on, the heartbeat will check to make sure
  1465. // that the StationID hasn't changed. If it has,
  1466. // then we've logged in somewhere else and we'll
  1467. // drop out of this station
  1468. var curr = new Client<Login>().Query(
  1469. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1470. null
  1471. ).Rows.FirstOrDefault();
  1472. if (curr != null)
  1473. {
  1474. var c = curr.ToObject<Login>();
  1475. c.StationID = station.StationID;
  1476. station = c;
  1477. }
  1478. else
  1479. {
  1480. station.User.ID = ClientFactory.UserGuid;
  1481. station.TimeStamp = DateTime.Now;
  1482. }
  1483. new Client<Login>().Save(station, "", (o, e) => { });
  1484. }
  1485. private void LoadCurrentEmployee()
  1486. {
  1487. var me = new Client<Employee>().Query(
  1488. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1489. Columns.None<Employee>().Add(x => x.ID).Add(x => x.Email).Add(x => x.Name)
  1490. );
  1491. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1492. App.EmployeeName = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Name) ?? "";
  1493. App.EmployeeCode = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Code) ?? "";
  1494. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1495. }
  1496. private void ExecuteLogout()
  1497. {
  1498. new Client<Login>().Delete(station, "");
  1499. station.ID = Guid.Empty;
  1500. App.EmployeeID = Guid.Empty;
  1501. App.EmployeeName = "";
  1502. App.EmployeeEmail = "";
  1503. }
  1504. /// <summary>
  1505. /// Logs the user out and unloads windows
  1506. /// </summary>
  1507. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1508. private bool Logout(string? message = null, bool force = false)
  1509. {
  1510. // I really don't like all these try-catch blocks; unfortunately, if we are trying to log out and invalidate due to an unauthenticated user,
  1511. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1512. try
  1513. {
  1514. FinalizeAutoTimesheet();
  1515. }
  1516. catch
  1517. {
  1518. if (!force) throw;
  1519. }
  1520. // Try to unload the window;
  1521. try
  1522. {
  1523. UnloadWindow(null);
  1524. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1525. scheduler.Stop();
  1526. }
  1527. catch
  1528. {
  1529. if (!force) throw;
  1530. }
  1531. // Next, try to set things to being empty
  1532. try
  1533. {
  1534. if (!CoreUtils.GetVersion().Equals("???"))
  1535. if (station.ID != Guid.Empty)
  1536. {
  1537. ExecuteLogout();
  1538. }
  1539. ClearTrackingKanban();
  1540. }
  1541. catch
  1542. {
  1543. if (!force) throw;
  1544. }
  1545. ClientFactory.InvalidateUser();
  1546. ConfigureMainScreen(null);
  1547. LoadSecondaryWindows();
  1548. if (message != null)
  1549. {
  1550. MessageWindow.ShowMessage(message, "Logged out");
  1551. }
  1552. if (DoLogin() == ValidationStatus.VALID)
  1553. {
  1554. AfterLogin(null);
  1555. }
  1556. return true;
  1557. }
  1558. #endregion
  1559. #region Timesheets
  1560. private void RefreshTimeSheets()
  1561. {
  1562. if (App.EmployeeID == Guid.Empty)
  1563. return;
  1564. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1565. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1566. _timesheets = new Client<TimeSheet>().Query(
  1567. filter,
  1568. Columns.None<TimeSheet>().Add(
  1569. x => x.ID,
  1570. x => x.Date,
  1571. x => x.Finish
  1572. )
  1573. );
  1574. }
  1575. private CoreTable GetTimesheet()
  1576. {
  1577. return new Client<TimeSheet>().Query(
  1578. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1579. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1580. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1581. );
  1582. }
  1583. private bool CheckTimesheetBypass(bool message)
  1584. {
  1585. if (!ClientFactory.IsSupported<TimeSheet>())
  1586. return true;
  1587. var isClockedOn = IsClockedOn();
  1588. if (!Security.IsAllowed<CanBypassTimeBench>())
  1589. {
  1590. if (!isClockedOn)
  1591. {
  1592. return false;
  1593. }
  1594. return true;
  1595. }
  1596. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1597. if (!isClockedOn)
  1598. {
  1599. var ts = new TimeSheet();
  1600. ts.Date = DateTime.Today;
  1601. ts.Start = DateTime.Now.TimeOfDay;
  1602. ts.EmployeeLink.ID = App.EmployeeID;
  1603. ts.Notes = "Automatic Login from PRS Desktop";
  1604. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1605. }
  1606. return true;
  1607. }
  1608. private bool IsClockedOn()
  1609. {
  1610. RefreshTimeSheets();
  1611. if (_timesheets == null)
  1612. return false;
  1613. return _timesheets.Rows.Any(r =>
  1614. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1615. }
  1616. private void FinalizeAutoTimesheet()
  1617. {
  1618. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1619. {
  1620. var check = new Client<TimeSheet>().Query(
  1621. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  1622. .IsEqualTo(TimeSpan.Zero)
  1623. );
  1624. if (check.Rows.Any())
  1625. {
  1626. var ts = check.Rows.First().ToObject<TimeSheet>();
  1627. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  1628. {
  1629. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  1630. }
  1631. else
  1632. {
  1633. ts.Finish = DateTime.Now.TimeOfDay;
  1634. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  1635. }
  1636. }
  1637. }
  1638. }
  1639. #endregion
  1640. private string CurrentPanelSlug()
  1641. {
  1642. var app = new LocalConfiguration<AppSettings>().Load();
  1643. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1644. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1645. }
  1646. private bool ShowHelp()
  1647. {
  1648. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1649. return true;
  1650. }
  1651. private void Wiki_Click(object sender, RoutedEventArgs e)
  1652. {
  1653. ShowHelp();
  1654. }
  1655. private void Window_Loaded(object sender, RoutedEventArgs e)
  1656. {
  1657. }
  1658. private void UnloadWindow(CancelEventArgs? cancel)
  1659. {
  1660. PanelHost.UnloadPanel(cancel);
  1661. if (cancel?.Cancel == true)
  1662. {
  1663. return;
  1664. }
  1665. Title =
  1666. $" - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1667. if (CurrentTab is not null)
  1668. {
  1669. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1670. if (border != null)
  1671. {
  1672. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1673. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1674. }
  1675. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1676. if (ReportsBar is not null)
  1677. {
  1678. ReportsBar.Items.Clear();
  1679. ReportsBar.Visibility = Visibility.Collapsed;
  1680. ReportsBar.IsLauncherVisible = false;
  1681. }
  1682. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1683. if (ActionBar is not null)
  1684. {
  1685. ActionBar.IsLauncherVisible = false;
  1686. foreach (var module in CurrentModules)
  1687. ActionBar.Items.Remove(module);
  1688. }
  1689. }
  1690. CurrentTab = null;
  1691. CurrentButton = null;
  1692. ContentControl.Content = null;
  1693. }
  1694. private void RibbonWindow_Activated(object sender, EventArgs e)
  1695. {
  1696. }
  1697. private void RegisterModules(IProgress<string> progress)
  1698. {
  1699. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1700. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1701. foreach (var item in bar.Items)
  1702. Dispatcher.Invoke(() =>
  1703. {
  1704. var button = item as RibbonButton;
  1705. if (button != null && button.Label != "Refresh")
  1706. if (bar.Header.Equals("Actions"))
  1707. Modules.Register(button.Label);
  1708. });
  1709. }
  1710. #region Visibility
  1711. private void SetFrameworkItemVisibility(FrameworkElement button, bool visible)
  1712. {
  1713. var vResult = true;
  1714. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1715. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1716. if (button is Fluent.Button rb)
  1717. {
  1718. CustomModules.Register(rb.Header?.ToString() ?? "");
  1719. rb.IsEnabled = !OutstandingDailyReports(false);
  1720. }
  1721. }
  1722. private void SetModuleVisibility<T>(Fluent.Button button, bool visible) where T : class, IBasePanel, new()
  1723. {
  1724. SetFrameworkItemVisibility(button,visible);
  1725. button.MinWidth = 60;
  1726. if (button.Command == null)
  1727. {
  1728. button.Command = new SimpleCommand(() => LoadWindow<T>(button));
  1729. var menu = new ContextMenu();
  1730. menu.Items.Add(new MenuItem()
  1731. {
  1732. Header = "Open in New Window",
  1733. Icon = new System.Windows.Controls.Image() { Source = PRSDesktop.Resources.target.AsBitmapImage() },
  1734. Command = new SimpleCommand(() => LoadSecondaryWindow<T>(button))
  1735. });
  1736. button.ContextMenu = menu;
  1737. }
  1738. }
  1739. private static void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1740. {
  1741. var bLeft = false;
  1742. foreach (var button in left)
  1743. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1744. var bRight = false;
  1745. foreach (var button in right)
  1746. bRight = bRight || button.Visibility == Visibility.Visible;
  1747. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1748. }
  1749. private static void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1750. {
  1751. var bVisible = false;
  1752. foreach (var button in buttons)
  1753. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1754. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1755. }
  1756. private static void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1757. {
  1758. var bVisible = false;
  1759. foreach (var button in buttons)
  1760. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1761. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1762. }
  1763. #endregion
  1764. private static Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1765. {
  1766. foreach (var group in tab.Groups)
  1767. {
  1768. if (group != null)
  1769. if (predicate.Invoke(group))
  1770. return group;
  1771. }
  1772. return null;
  1773. }
  1774. #region Button Event Handlers
  1775. #region Accounts
  1776. #endregion
  1777. #region Dashboards
  1778. #endregion
  1779. private void Console_Click(object sender, RoutedEventArgs a)
  1780. {
  1781. if (_console is null)
  1782. {
  1783. _console = new DesktopConsole("Console");
  1784. _console.Closing += (o, args) => _console = null;
  1785. }
  1786. _console.Show();
  1787. }
  1788. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1789. {
  1790. PanelHost.Refresh();
  1791. }
  1792. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  1793. //{
  1794. // if (NotificationsList.SelectedIndex < 0)
  1795. // return;
  1796. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  1797. // var selected = editors[NotificationsList.SelectedIndex];
  1798. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  1799. //}
  1800. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  1801. //{
  1802. // Notification notification = (sender as Label).Tag as Notification;
  1803. // NotificationDetails details = new NotificationDetails(notification);
  1804. // details.ShowDialog();
  1805. // ReloadNotifications();
  1806. //}
  1807. private void Library_Click(object sender, RoutedEventArgs e)
  1808. {
  1809. Process.Start(
  1810. new ProcessStartInfo
  1811. {
  1812. FileName = App.DatabaseSettings.LibraryLocation,
  1813. UseShellExecute = true,
  1814. Verb = "open"
  1815. }
  1816. );
  1817. }
  1818. private void SendNotificationClick(object sender, RoutedEventArgs e)
  1819. {
  1820. var form = new NotificationForm { Description = "" };
  1821. if (form.ShowDialog() == true)
  1822. ReloadNotifications();
  1823. }
  1824. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  1825. {
  1826. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  1827. if (info == null)
  1828. info = new CompanyInformation();
  1829. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  1830. }
  1831. private void Setup_Click(object sender, RoutedEventArgs e)
  1832. {
  1833. var tab = _ribbon.SelectedTabItem;
  1834. if (tab is null)
  1835. return;
  1836. var menu = new ContextMenu();
  1837. PanelHost.InitialiseSetupMenu(menu);
  1838. menu.IsOpen = true;
  1839. }
  1840. private void Issues_Click(object sender, RoutedEventArgs e)
  1841. {
  1842. try
  1843. {
  1844. IssuesWindow.Execute();
  1845. CheckSupportTicketStatus();
  1846. }
  1847. catch(Exception err)
  1848. {
  1849. MessageWindow.ShowError("Could not load issues.", err);
  1850. }
  1851. }
  1852. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  1853. where TEntityForm : EntityForm<TEntity, TEntityLink, TEntityForm>, new()
  1854. where TEntity : Entity, new()
  1855. where TEntityLink : EntityLink<TEntity>, new()
  1856. {
  1857. var entityForm = new TEntityForm();
  1858. entityForm.Form.CopyFrom(form);
  1859. entityForm.Description = form.Description;
  1860. entityForm.FormStarted = DateTime.Now;
  1861. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  1862. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  1863. {
  1864. dataModel.Update(null);
  1865. }
  1866. }
  1867. private void Forms_Click(object sender, RoutedEventArgs e)
  1868. {
  1869. var select = new MultiSelectDialog<DigitalForm>(
  1870. Filter<DigitalForm>.And(
  1871. LookupFactory.DefineChildFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  1872. new Filter<DigitalForm>(x => x.ID).InQuery(
  1873. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  1874. x => x.Form.ID)),
  1875. LookupFactory.DefineChildColumns<KanbanForm, DigitalForm>()
  1876. .Add(x => x.Description),
  1877. false);
  1878. if (select.ShowDialog() == true)
  1879. {
  1880. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  1881. if (digitalForm is not null)
  1882. {
  1883. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  1884. }
  1885. };
  1886. }
  1887. #endregion
  1888. private bool OutstandingDailyReports(bool refresh)
  1889. {
  1890. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  1891. return false;
  1892. if (refresh)
  1893. RefreshTimeSheets();
  1894. if (_timesheets == null)
  1895. return false;
  1896. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  1897. }
  1898. private void ShutDownTransport()
  1899. {
  1900. if (_transport != null)
  1901. {
  1902. _transport.OnClose -= TransportConnectionLost;
  1903. if (_transport.IsConnected())
  1904. _transport.Disconnect();
  1905. _transport = null;
  1906. }
  1907. }
  1908. private void Window_Unloaded(object sender, RoutedEventArgs e)
  1909. {
  1910. ShutDownTransport();
  1911. }
  1912. private void RibbonWindow_Closed(object sender, EventArgs e)
  1913. {
  1914. ShutDownTransport();
  1915. //DisconnectRecorderNotes();
  1916. Application.Current.Shutdown();
  1917. }
  1918. //private bool _closingFromSystemMenu = false;
  1919. private void Window_Closing(object sender, CancelEventArgs e)
  1920. {
  1921. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  1922. {
  1923. WindowState = WindowState.Minimized;
  1924. e.Cancel = true;
  1925. return;
  1926. }*/
  1927. PanelHost.UnloadPanel(e);
  1928. if (!e.Cancel)
  1929. {
  1930. ISubPanelHost.Global.ShutdownSubPanels(e);
  1931. }
  1932. if (e.Cancel)
  1933. {
  1934. return;
  1935. }
  1936. App.IsClosing = true;
  1937. FinalizeAutoTimesheet();
  1938. if (!CoreUtils.GetVersion().Equals("???"))
  1939. scheduler.Stop();
  1940. CurrentTab = null;
  1941. UpdateRibbonColors();
  1942. if (!CoreUtils.GetVersion().Equals("???"))
  1943. if (station.ID != Guid.Empty)
  1944. ExecuteLogout();
  1945. ShutDownTransport();
  1946. }
  1947. #region Notifications + Heartbeat
  1948. private void ReceiveNotification(Notification notification)
  1949. {
  1950. if (Security.CanView<Notification>())
  1951. {
  1952. Notifications.AddNotification(notification);
  1953. }
  1954. foreach(var panel in Panels.OfType<NotificationPanel>())
  1955. {
  1956. panel.AddNotification(notification);
  1957. }
  1958. }
  1959. private void Notifications_Tick(object? sender, EventArgs e)
  1960. {
  1961. if (ClientFactory.UserGuid != Guid.Empty)
  1962. {
  1963. try
  1964. {
  1965. ReloadNotifications();
  1966. }
  1967. catch (Exception err)
  1968. {
  1969. Logger.Send(LogType.Error, ClientFactory.UserID,
  1970. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  1971. }
  1972. Heartbeat();
  1973. try
  1974. {
  1975. CheckIsLoggedOn();
  1976. }
  1977. catch (Exception err2)
  1978. {
  1979. Logger.Send(LogType.Error, ClientFactory.UserID,
  1980. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  1981. }
  1982. }
  1983. //else
  1984. //{
  1985. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  1986. //}
  1987. }
  1988. private void CheckIsLoggedOn()
  1989. {
  1990. if (CoreUtils.GetVersion().Equals("???"))
  1991. return;
  1992. var bLogout = false;
  1993. if (!Security.IsAllowed<CanBypassTimeBench>())
  1994. if (!IsClockedOn())
  1995. {
  1996. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  1997. bLogout = true;
  1998. Dispatcher.Invoke(() => { Logout(); });
  1999. }
  2000. if (!bLogout)
  2001. new Client<Login>().Query(
  2002. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2003. Columns.None<Login>().Add(x => x.StationID),
  2004. null,
  2005. CoreRange.All,
  2006. (o, e) =>
  2007. {
  2008. if (e is RemoteException remote)
  2009. {
  2010. if (remote.Status == StatusCode.Unauthenticated)
  2011. {
  2012. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2013. Dispatcher.Invoke(() =>
  2014. {
  2015. Logout("You have been logged out due to inactivity");
  2016. });
  2017. }
  2018. else
  2019. {
  2020. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2021. }
  2022. }
  2023. else if (e is not null)
  2024. {
  2025. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2026. }
  2027. else if (o is not null)
  2028. {
  2029. var row = o.Rows.FirstOrDefault();
  2030. if (row == null)
  2031. {
  2032. station.ID = Guid.Empty;
  2033. new Client<Login>().Save(station, "", (o1, e1) => { });
  2034. }
  2035. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2036. {
  2037. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2038. bLogout = true;
  2039. Dispatcher.Invoke(() => { Logout(); });
  2040. }
  2041. }
  2042. }
  2043. );
  2044. }
  2045. private void Heartbeat()
  2046. {
  2047. //Task.Run(() =>
  2048. //{
  2049. try
  2050. {
  2051. CheckSupportTicketStatus();
  2052. bool IsClockedOn = this.IsClockedOn();
  2053. if (IsClockedOn)
  2054. {
  2055. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2056. {
  2057. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2058. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2059. }
  2060. if (Security.IsAllowed<MonitorApplicationWindows>())
  2061. {
  2062. if (ActivityHistory == null)
  2063. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2064. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2065. var title = OpenWindowGetter.GetActiveWindowTitle();
  2066. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2067. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2068. }
  2069. }
  2070. PanelHost.Heartbeat();
  2071. foreach(var window in SecondaryWindows.Values)
  2072. {
  2073. window.Heartbeat();
  2074. }
  2075. }
  2076. catch (Exception err)
  2077. {
  2078. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2079. }
  2080. //});
  2081. }
  2082. private void CheckSupportTicketStatus()
  2083. {
  2084. Dispatcher.BeginInvoke(() =>
  2085. {
  2086. IssuesButton.Background = IssuesWindow.Check()
  2087. ? new SolidColorBrush(Colors.Red) { Opacity = 0.5 }
  2088. : Brushes.Transparent;
  2089. });
  2090. }
  2091. private void Notifications_Changed(object sender)
  2092. {
  2093. if (Notifications.IsActive)
  2094. {
  2095. Notifications.Visibility = Visibility.Visible;
  2096. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2097. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2098. ? new GridLength(300, GridUnitType.Pixel)
  2099. : DockingGrid.ColumnDefinitions[2].Width;
  2100. }
  2101. else
  2102. {
  2103. Notifications.Visibility = Visibility.Collapsed;
  2104. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2105. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2106. }
  2107. }
  2108. private void ReloadNotifications()
  2109. {
  2110. if (Security.CanView<Notification>())
  2111. Notifications.Refresh();
  2112. if (!NotificationsWatchDog.IsEnabled)
  2113. {
  2114. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2115. NotificationsWatchDog.IsEnabled = true;
  2116. }
  2117. }
  2118. #endregion
  2119. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2120. {
  2121. PanelHost.IncrementTrackingModuleClick();
  2122. }
  2123. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2124. {
  2125. PanelHost.IncrementTrackingModuleKey();
  2126. }
  2127. public static void ActivateWindow(Window window)
  2128. {
  2129. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2130. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2131. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2132. if (threadId1 != threadId2)
  2133. {
  2134. AttachThreadInput(threadId1, threadId2, true);
  2135. SetForegroundWindow(hwnd);
  2136. AttachThreadInput(threadId1, threadId2, false);
  2137. }
  2138. else
  2139. {
  2140. SetForegroundWindow(hwnd);
  2141. }
  2142. }
  2143. private static IntPtr GetForegroundWindow()
  2144. {
  2145. var active = GetActiveWindow();
  2146. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2147. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2148. return hwnd;
  2149. }
  2150. [DllImport("user32.dll", SetLastError = true)]
  2151. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2152. [DllImport("user32.dll")]
  2153. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2154. [DllImport("user32.dll")]
  2155. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2156. [DllImport("user32.dll")]
  2157. private static extern IntPtr GetActiveWindow();
  2158. #region Modules + Reports
  2159. public void ClearActions()
  2160. {
  2161. foreach (var module in CurrentModules)
  2162. {
  2163. if (module.Parent is Fluent.RibbonGroupBox bar)
  2164. bar.Items.Remove(module);
  2165. }
  2166. CurrentModules.Clear();
  2167. }
  2168. public void ClearReports()
  2169. {
  2170. if (CurrentTab is not null)
  2171. {
  2172. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2173. if (ReportsBar is not null)
  2174. {
  2175. ReportsBar.Visibility = Visibility.Collapsed;
  2176. ReportsBar.Items.Clear();
  2177. }
  2178. }
  2179. }
  2180. public void CreateReport(PanelAction action)
  2181. {
  2182. if (CurrentTab is null)
  2183. return;
  2184. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2185. if (ReportsBar is not null)
  2186. {
  2187. var button = new Fluent.Button
  2188. {
  2189. Header = action.Caption,
  2190. LargeIcon = action.Image?.AsBitmapImage(),
  2191. MinWidth = 60
  2192. };
  2193. if (action.Menu is not null)
  2194. {
  2195. button.ContextMenu = action.Menu;
  2196. }
  2197. button.Click += (o, e) =>
  2198. {
  2199. action.Execute();
  2200. };
  2201. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2202. ReportsBar.Items.Add(button);
  2203. }
  2204. }
  2205. private NullConverter<Visibility>? _vis = null;
  2206. public void CreatePanelAction(PanelAction action)
  2207. {
  2208. if (CurrentTab is null)
  2209. return;
  2210. if (_vis == null)
  2211. {
  2212. _vis = new();
  2213. _vis.Converting += (o, e) =>
  2214. {
  2215. };
  2216. }
  2217. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2218. if (Actions is not null)
  2219. {
  2220. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2221. {
  2222. var sep = new RibbonSeparator();
  2223. CurrentModules.Add(sep);
  2224. Actions.Items.Add(sep);
  2225. }
  2226. if (action.OnPopulate != null)
  2227. {
  2228. Fluent.DropDownButton button;
  2229. if (action.OnExecute != null)
  2230. {
  2231. button = new Fluent.SplitButton();
  2232. ((Fluent.SplitButton)button).Click += (o, e) => action.Execute();
  2233. }
  2234. else
  2235. button = new Fluent.DropDownButton();
  2236. button.MinWidth = 60;
  2237. button.DataContext = action;
  2238. button.DropDownOpened += (sender, args) => { button.ItemsSource = CreateMenuItems(action); };
  2239. button.Bind<PanelAction, String>(Fluent.DropDownButton.HeaderProperty, x => x.Caption, null);
  2240. button.Bind<PanelAction, Bitmap?>(Fluent.DropDownButton.LargeIconProperty, x => x.Image,
  2241. new BitmapToBitmapImageConverter());
  2242. button.Bind<PanelAction, ContextMenu?>(ContextMenuProperty, x => x.Menu);
  2243. button.Bind<PanelAction, bool>(IsEnabledProperty, x => x.IsEnabled);
  2244. button.Bind<PanelAction, Visibility>(Fluent.DropDownButton.VisibilityProperty, x => x.Visibility, _vis);
  2245. Actions.Items.Add(button);
  2246. CurrentModules.Add(button);
  2247. }
  2248. else
  2249. {
  2250. var button = new Fluent.Button()
  2251. {
  2252. MinWidth = 60,
  2253. DataContext = action
  2254. };
  2255. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x => x.Caption, null);
  2256. button.Bind<PanelAction, Bitmap?>(Fluent.Button.LargeIconProperty, x => x.Image,
  2257. new BitmapToBitmapImageConverter());
  2258. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x => x.Menu);
  2259. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2260. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility, _vis);
  2261. button.Click += (o, e) => action.Execute();
  2262. Actions.Items.Add(button);
  2263. CurrentModules.Add(button);
  2264. }
  2265. }
  2266. }
  2267. private static ObservableCollection<MenuItem> CreateMenuItems(PanelAction action)
  2268. {
  2269. var items = new ObservableCollection<MenuItem>();
  2270. var entries = action.Populate();
  2271. if (entries != null)
  2272. {
  2273. foreach (var entry in entries)
  2274. {
  2275. var item = new Fluent.MenuItem()
  2276. {
  2277. Header = entry.Caption,
  2278. DataContext = entry.Data,
  2279. Icon = entry.Image?.AsBitmapImage()
  2280. };
  2281. item.Click += (o, eventArgs) => entry.Execute();
  2282. items.Add(item);
  2283. }
  2284. }
  2285. return items;
  2286. }
  2287. #endregion
  2288. #region Tracking Kanban
  2289. private class TrackingKanbanFilterItemComponent : DynamicGridFilterComponent<Kanban>
  2290. {
  2291. public TrackingKanbanFilterItemComponent() : base(
  2292. new GlobalConfiguration<CoreFilterDefinitions>(nameof(Kanban)),
  2293. new UserConfiguration<CoreFilterDefinitions>(nameof(Kanban)))
  2294. {
  2295. ButtonText = "Filter";
  2296. }
  2297. public string Text { get; private set; } = "Filter";
  2298. public Bitmap? Image { get; private set; }
  2299. protected override void UpdateButtonText(Bitmap image, string text)
  2300. {
  2301. Text = text;
  2302. Image = image;
  2303. }
  2304. }
  2305. private TrackingKanbanFilterItemComponent? _trackingKanbanFilterComponent;
  2306. private TrackingKanbanFilterItemComponent TrackingKanbanFilterComponent
  2307. {
  2308. get
  2309. {
  2310. if(_trackingKanbanFilterComponent is null)
  2311. {
  2312. _trackingKanbanFilterComponent = new();
  2313. _trackingKanbanFilterComponent.OnFiltersSelected += _trackingKanbanFilterComponent_OnFiltersSelected;
  2314. }
  2315. return _trackingKanbanFilterComponent;
  2316. }
  2317. }
  2318. private ContextMenu? _trackingKanbanMenu;
  2319. private MenuItem? _trackingKanbanFilterMenu;
  2320. private void _trackingKanbanFilterComponent_OnFiltersSelected(DynamicGridSelectedFilterSettings filters)
  2321. {
  2322. if (_trackingKanbanMenu is null) return;
  2323. if (!filters.MultipleFilters)
  2324. {
  2325. _trackingKanbanMenu.IsOpen = false;
  2326. }
  2327. if(_trackingKanbanFilterMenu is not null)
  2328. {
  2329. _trackingKanbanFilterMenu.Header = TrackingKanbanFilterComponent.Text;
  2330. _trackingKanbanFilterMenu.Icon = new System.Windows.Controls.Image() { Source = TrackingKanbanFilterComponent.Image?.AsBitmapImage(24, 24) };
  2331. }
  2332. }
  2333. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2334. {
  2335. var menu = new ContextMenu();
  2336. var others = new MenuItem() { Header = "Other Tasks" };
  2337. var waiting = new MenuItem() { Header = "Waiting Tasks" };
  2338. using (new WaitCursor())
  2339. {
  2340. var filter =
  2341. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2342. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2343. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue);
  2344. var kanbanFilter = TrackingKanbanFilterComponent.GetFilter();
  2345. if(kanbanFilter is not null)
  2346. {
  2347. filter = filter.And(x => x.Kanban.ID).InQuery(kanbanFilter, x => x.ID);
  2348. }
  2349. var kanbans = Client.Query(
  2350. filter,
  2351. Columns.None<KanbanSubscriber>()
  2352. .Add(x => x.Kanban.ID)
  2353. .Add(x => x.Kanban.Number)
  2354. .Add(x => x.Kanban.Title)
  2355. .Add(x => x.Kanban.Status)
  2356. .Add(x => x.Assignee),
  2357. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending));
  2358. foreach (var subscriber in kanbans.ToObjects<KanbanSubscriber>())
  2359. {
  2360. CreateTaskMenu(subscriber.Assignee ? (subscriber.Kanban.Status != KanbanStatus.Waiting ? menu : waiting) : others,
  2361. $"{subscriber.Kanban.Number} {subscriber.Kanban.Title}",
  2362. subscriber.Kanban.ID);
  2363. }
  2364. menu.AddSeparatorIfNeeded();
  2365. if(others.Items.Count > 0)
  2366. {
  2367. menu.Items.Add(others);
  2368. }
  2369. if(waiting.Items.Count > 0)
  2370. {
  2371. menu.Items.Add(waiting);
  2372. }
  2373. menu.AddSeparatorIfNeeded();
  2374. CreateTaskMenu(menu, "(No Task Selected)", Guid.Empty);
  2375. if(_kanbantrackingassignment is not null && _kanbantrackingassignment.Task.ID != Guid.Empty)
  2376. {
  2377. menu.AddItem("View Task", null, _kanbantrackingassignment.Task.ID, ViewTrackingKanban_Click);
  2378. }
  2379. menu.AddSeparatorIfNeeded();
  2380. var filterItem = menu.AddItem(TrackingKanbanFilterComponent.Text, TrackingKanbanFilterComponent.Image, null);
  2381. TrackingKanbanFilterComponent.PopulateMenu(filterItem);
  2382. _trackingKanbanFilterMenu = filterItem;
  2383. }
  2384. menu.IsOpen = true;
  2385. _trackingKanbanMenu = menu;
  2386. }
  2387. private void ViewTrackingKanban_Click(Guid guid)
  2388. {
  2389. var item = Client.Query(
  2390. new Filter<Kanban>(x => x.ID).IsEqualTo(guid),
  2391. DynamicGridUtils.LoadEditorColumns<Kanban>())
  2392. .ToObjects<Kanban>().FirstOrDefault();
  2393. if (item is null) return;
  2394. var grid = DynamicGridUtils.CreateDynamicGrid<Kanban>(typeof(DynamicGrid<>));
  2395. grid.EditItemsNonModal(ISubPanelHost.Global, [item], (items, saved) => { });
  2396. }
  2397. private Assignment? _kanbantrackingassignment = null;
  2398. private CoreFilterDefinitions? _kanbanTrackingFilter = null;
  2399. private void SetTrackingKanban(Guid kanbanID, string header)
  2400. {
  2401. SelectedTaskName.Content = header;
  2402. var createNewAssignment = false;
  2403. if (_kanbantrackingassignment is not null)
  2404. {
  2405. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2406. {
  2407. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2408. Client.Save(_kanbantrackingassignment, "");
  2409. }
  2410. // Update Existing Kanban
  2411. if (kanbanID == Guid.Empty)
  2412. _kanbantrackingassignment = null;
  2413. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2414. {
  2415. createNewAssignment = true;
  2416. }
  2417. }
  2418. else if (kanbanID != Guid.Empty)
  2419. {
  2420. createNewAssignment = true;
  2421. }
  2422. if (createNewAssignment)
  2423. {
  2424. _kanbantrackingassignment = new Assignment();
  2425. _kanbantrackingassignment.Task.ID = kanbanID;
  2426. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2427. _kanbantrackingassignment.Title = header;
  2428. _kanbantrackingassignment.Date = DateTime.Today;
  2429. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2430. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2431. Client.Save(_kanbantrackingassignment, "");
  2432. }
  2433. }
  2434. private void ClearTrackingKanban()
  2435. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2436. private void CreateTaskMenu(ItemsControl menu, string title, Guid id)
  2437. {
  2438. menu.AddCheckMenuItem(title, (title, id), TrackingKanbanMenuItem_Click, isChecked: _kanbantrackingassignment?.Task.ID == id);
  2439. }
  2440. private void TrackingKanbanMenuItem_Click((string title, Guid id) tuple, bool isChecked)
  2441. {
  2442. if (isChecked)
  2443. {
  2444. SetTrackingKanban(tuple.id, tuple.title);
  2445. }
  2446. }
  2447. #endregion
  2448. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2449. {
  2450. if (sender is not Border border || !border.IsVisible)
  2451. return;
  2452. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2453. if (dock is null)
  2454. return;
  2455. dock.Refresh();
  2456. }
  2457. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2458. {
  2459. if (sender is not LayoutAnchorable layout)
  2460. return;
  2461. var content = layout.Content as DependencyObject;
  2462. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2463. if (dock is null)
  2464. return;
  2465. if (layout.IsActive && layout.IsVisible)
  2466. dock.Refresh();
  2467. }
  2468. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2469. {
  2470. e.Handled = true;
  2471. }
  2472. #region Backstage Functions
  2473. private enum DatabaseConfigurationResult
  2474. {
  2475. RestartRequired,
  2476. RestartNotRequired,
  2477. Cancel
  2478. }
  2479. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2480. {
  2481. DatabaseConfigurationResult result;
  2482. var config = new DataBaseConfiguration();
  2483. if (config.ShowDialog() == true)
  2484. {
  2485. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2486. if (newsettings.RestartRequired(App.DatabaseSettings))
  2487. {
  2488. result = DatabaseConfigurationResult.RestartRequired;
  2489. }
  2490. else
  2491. {
  2492. result = DatabaseConfigurationResult.RestartNotRequired;
  2493. }
  2494. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2495. {
  2496. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2497. ApplyColorScheme();
  2498. }
  2499. }
  2500. else
  2501. {
  2502. result = DatabaseConfigurationResult.Cancel;
  2503. }
  2504. return result;
  2505. }
  2506. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2507. {
  2508. switch (ShowDatabaseConfiguration())
  2509. {
  2510. case DatabaseConfigurationResult.RestartRequired:
  2511. MessageBox.Show("Please restart the application to apply these changes!");
  2512. break;
  2513. }
  2514. }
  2515. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2516. {
  2517. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2518. if (info == null)
  2519. info = new CompanyInformation();
  2520. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2521. }
  2522. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2523. {
  2524. var window = new GlobalTokenWindow();
  2525. window.ShowDialog();
  2526. Security.Reset();
  2527. }
  2528. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2529. {
  2530. var logfile = CoreUtils.GetLogFile();
  2531. if (File.Exists(logfile))
  2532. {
  2533. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2534. startInfo.Verb = "open";
  2535. startInfo.UseShellExecute = true;
  2536. Process.Start(startInfo);
  2537. }
  2538. else
  2539. {
  2540. MessageBox.Show(logfile + " does not exist!");
  2541. }
  2542. }
  2543. private void CheckForUpdates_OnClick(object sender, RoutedEventArgs e)
  2544. {
  2545. if (SupportUtils.CheckForUpdates())
  2546. {
  2547. Close();
  2548. }
  2549. else
  2550. {
  2551. if (MessageWindow.ShowYesNo(
  2552. "You appear to be using the latest version already!\n\nRun the installer anyway?", "Update"))
  2553. {
  2554. if (SupportUtils.DownloadAndRunInstaller())
  2555. {
  2556. Close();
  2557. }
  2558. }
  2559. }
  2560. }
  2561. private void OpenSupportSession_OnClick(object sender, RoutedEventArgs e)
  2562. {
  2563. SupportUtils.OpenSupportSession();
  2564. }
  2565. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2566. {
  2567. var list = new MasterList(typeof(DocumentType));
  2568. list.ShowDialog();
  2569. }
  2570. private void EventList_Click(object sender, RoutedEventArgs e)
  2571. {
  2572. var list = new MasterList(typeof(Event));
  2573. list.ShowDialog();
  2574. }
  2575. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2576. {
  2577. var employee = new Client<Employee>().Query(
  2578. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2579. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2580. var item = new MyDetailsConfiguration(employee);
  2581. item.User = ClientFactory.UserGuid;
  2582. var buttons = new DynamicEditorButtons();
  2583. buttons.Add("Change Password", null, item, (sender, item) =>
  2584. {
  2585. var details = (item as MyDetailsConfiguration)!;
  2586. var changePassword = new ChangePassword(details.User);
  2587. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2588. {
  2589. var newUser = new User();
  2590. newUser.SetID(details.User);
  2591. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2592. new Client<User>().Save(newUser, "Changed Password");
  2593. MessageBox.Show("Password changed!");
  2594. }
  2595. });
  2596. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  2597. if (employee == null)
  2598. {
  2599. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  2600. {
  2601. editor.Editable = Editable.Disabled;
  2602. };
  2603. }
  2604. editor.Items = new BaseObject[] { item };
  2605. if (editor.ShowDialog() == true)
  2606. {
  2607. if (employee != null)
  2608. {
  2609. item.SaveTo(employee);
  2610. new Client<Employee>().Save(employee, "Edited by user");
  2611. }
  2612. }
  2613. }
  2614. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  2615. {
  2616. Logout();
  2617. }
  2618. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  2619. {
  2620. if (DoLogin() == ValidationStatus.VALID)
  2621. AfterLogin(null);
  2622. }
  2623. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  2624. {
  2625. //_closingFromSystemMenu = true;
  2626. Close();
  2627. }
  2628. #endregion
  2629. }