MainWindow.xaml.cs 114 KB

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