MainWindow.xaml.cs 114 KB

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