MainWindow.xaml.cs 130 KB

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