MainWindow.xaml.cs 116 KB

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