MainWindow.xaml.cs 117 KB

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