MainWindow.xaml.cs 119 KB

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