MainWindow.xaml.cs 114 KB

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