MainWindow.xaml.cs 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  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. ISubPanelHost.Global.ShutdownSubPanels(e);
  2072. }
  2073. if (e.Cancel)
  2074. {
  2075. return;
  2076. }
  2077. App.IsClosing = true;
  2078. FinalizeAutoTimesheet();
  2079. if (!CoreUtils.GetVersion().Equals("???"))
  2080. scheduler.Stop();
  2081. CurrentTab = null;
  2082. UpdateRibbonColors();
  2083. if (!CoreUtils.GetVersion().Equals("???"))
  2084. if (station.ID != Guid.Empty)
  2085. ExecuteLogout();
  2086. ShutDownTransport();
  2087. }
  2088. #region Notifications + Heartbeat
  2089. private void ReceiveNotification(Notification notification)
  2090. {
  2091. if (Security.CanView<Notification>())
  2092. {
  2093. Notifications.AddNotification(notification);
  2094. }
  2095. foreach(var panel in Panels.OfType<NotificationPanel>())
  2096. {
  2097. panel.AddNotification(notification);
  2098. }
  2099. }
  2100. private void Notifications_Tick(object? sender, EventArgs e)
  2101. {
  2102. if (ClientFactory.UserGuid != Guid.Empty)
  2103. {
  2104. try
  2105. {
  2106. ReloadNotifications();
  2107. }
  2108. catch (Exception err)
  2109. {
  2110. Logger.Send(LogType.Error, ClientFactory.UserID,
  2111. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2112. }
  2113. Heartbeat();
  2114. try
  2115. {
  2116. CheckIsLoggedOn();
  2117. }
  2118. catch (Exception err2)
  2119. {
  2120. Logger.Send(LogType.Error, ClientFactory.UserID,
  2121. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2122. }
  2123. }
  2124. //else
  2125. //{
  2126. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2127. //}
  2128. }
  2129. private void CheckIsLoggedOn()
  2130. {
  2131. if (CoreUtils.GetVersion().Equals("???"))
  2132. return;
  2133. var bLogout = false;
  2134. if (!Security.IsAllowed<CanBypassTimeBench>())
  2135. if (!IsClockedOn())
  2136. {
  2137. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2138. bLogout = true;
  2139. Dispatcher.Invoke(() => { Logout(); });
  2140. }
  2141. if (!bLogout)
  2142. new Client<Login>().Query(
  2143. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2144. Columns.None<Login>().Add(x => x.StationID),
  2145. null,
  2146. CoreRange.All,
  2147. (o, e) =>
  2148. {
  2149. if (e is RemoteException remote)
  2150. {
  2151. if (remote.Status == StatusCode.Unauthenticated)
  2152. {
  2153. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2154. Dispatcher.Invoke(() =>
  2155. {
  2156. Logout("You have been logged out due to inactivity");
  2157. });
  2158. }
  2159. else
  2160. {
  2161. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(remote)}");
  2162. }
  2163. }
  2164. else if (e is not null)
  2165. {
  2166. Logger.Send(LogType.Information, ClientFactory.UserID, $"Error in CheckIsLoggedOn(): {CoreUtils.FormatException(e)}");
  2167. }
  2168. else if (o is not null)
  2169. {
  2170. var row = o.Rows.FirstOrDefault();
  2171. if (row == null)
  2172. {
  2173. station.ID = Guid.Empty;
  2174. new Client<Login>().Save(station, "", (o1, e1) => { });
  2175. }
  2176. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2177. {
  2178. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2179. bLogout = true;
  2180. Dispatcher.Invoke(() => { Logout(); });
  2181. }
  2182. }
  2183. }
  2184. );
  2185. }
  2186. private void Heartbeat()
  2187. {
  2188. //Task.Run(() =>
  2189. //{
  2190. try
  2191. {
  2192. bool IsClockedOn = this.IsClockedOn();
  2193. if (IsClockedOn)
  2194. {
  2195. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2196. {
  2197. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2198. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2199. }
  2200. if (Security.IsAllowed<MonitorApplicationWindows>())
  2201. {
  2202. if (ActivityHistory == null)
  2203. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2204. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2205. var title = OpenWindowGetter.GetActiveWindowTitle();
  2206. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2207. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2208. }
  2209. }
  2210. PanelHost.Heartbeat();
  2211. foreach(var window in SecondaryWindows.Values)
  2212. {
  2213. window.Heartbeat();
  2214. }
  2215. }
  2216. catch (Exception err)
  2217. {
  2218. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2219. }
  2220. //});
  2221. }
  2222. private void Notifications_Changed(object sender)
  2223. {
  2224. if (Notifications.IsActive)
  2225. {
  2226. Notifications.Visibility = Visibility.Visible;
  2227. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2228. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2229. ? new GridLength(300, GridUnitType.Pixel)
  2230. : DockingGrid.ColumnDefinitions[2].Width;
  2231. }
  2232. else
  2233. {
  2234. Notifications.Visibility = Visibility.Collapsed;
  2235. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2236. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2237. }
  2238. }
  2239. private void ReloadNotifications()
  2240. {
  2241. if (Security.CanView<Notification>())
  2242. Notifications.Refresh();
  2243. if (!NotificationsWatchDog.IsEnabled)
  2244. {
  2245. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2246. NotificationsWatchDog.IsEnabled = true;
  2247. }
  2248. }
  2249. #endregion
  2250. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2251. {
  2252. PanelHost.IncrementTrackingModuleClick();
  2253. }
  2254. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2255. {
  2256. PanelHost.IncrementTrackingModuleKey();
  2257. }
  2258. #region Recording
  2259. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2260. //{
  2261. // switch (msg)
  2262. // {
  2263. // case 0x100:
  2264. // if (_subject != null)
  2265. // {
  2266. // _recorder.Stop();
  2267. // pausestarted = DateTime.Now;
  2268. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2269. // }
  2270. // break;
  2271. // default:
  2272. // messages.TryGetValue(msg, out int value);
  2273. // messages[msg] = value + 1;
  2274. // break;
  2275. // }
  2276. // return IntPtr.Zero;
  2277. //}
  2278. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2279. {
  2280. ToggleRecording();
  2281. }
  2282. private bool ToggleRecording()
  2283. {
  2284. if (!Security.IsAllowed<CanRecordScreen>())
  2285. return true;
  2286. if (_recorder is null)
  2287. {
  2288. var windowInteropHelper = new WindowInteropHelper(this);
  2289. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2290. _screenleft = screen.WorkingArea.Left;
  2291. _screentop = screen.WorkingArea.Top;
  2292. _screenwidth = screen.WorkingArea.Width;
  2293. _screenheight = screen.WorkingArea.Height;
  2294. //VIDEO_WIDTH = _screenwidth;
  2295. //VIDEO_HEIGHT = _screenheight;
  2296. //SetupJPEGEncoder();
  2297. messages.Clear();
  2298. _bitmaps.Clear();
  2299. ConnectToRecordNotes();
  2300. StartAudio();
  2301. _recorder = new DispatcherTimer();
  2302. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2303. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2304. _recorder.Start();
  2305. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2306. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2307. RecordingNotesButton.Visibility = Visibility.Visible;
  2308. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2309. AudioRecordingButton.Visibility = Visibility.Visible;
  2310. }
  2311. else
  2312. {
  2313. using (new WaitCursor())
  2314. {
  2315. StopRecording();
  2316. _recorder.Stop();
  2317. _recorder = null;
  2318. DisconnectRecorderNotes();
  2319. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2320. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2321. RecordingNotesButton.Visibility = Visibility.Hidden;
  2322. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2323. AudioRecordingButton.Visibility = Visibility.Hidden;
  2324. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2325. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2326. ProcessScreenShots(filename);
  2327. }
  2328. }
  2329. return true;
  2330. }
  2331. private void StopRecording()
  2332. {
  2333. try
  2334. {
  2335. _audio?.StopRecording();
  2336. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2337. }
  2338. catch (Exception e)
  2339. {
  2340. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2341. }
  2342. }
  2343. private void StartAudio()
  2344. {
  2345. _audioMuted = true;
  2346. _audioStream = new MemoryStream();
  2347. _audio = new WaveIn
  2348. {
  2349. DeviceNumber = 0,
  2350. WaveFormat = new WaveFormat(44100, 16, 2)
  2351. };
  2352. _audio.DataAvailable += (o, e) =>
  2353. {
  2354. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2355. _audioStream.Write(buf, 0, e.BytesRecorded);
  2356. };
  2357. try
  2358. {
  2359. _audio.StartRecording();
  2360. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2361. }
  2362. catch (Exception e)
  2363. {
  2364. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2365. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2366. }
  2367. }
  2368. private bool ToggleRecordingAudio()
  2369. {
  2370. if (!Security.IsAllowed<CanRecordScreen>())
  2371. return true;
  2372. if (_recorder != null)
  2373. {
  2374. _audioMuted = !_audioMuted;
  2375. AudioRecordingStatus.Source = _audioMuted
  2376. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2377. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2378. }
  2379. return true;
  2380. }
  2381. private void DisconnectRecorderNotes()
  2382. {
  2383. if (_client != null)
  2384. {
  2385. _client.WriteAsync("QUIT");
  2386. _client.StopAsync();
  2387. _client = null;
  2388. }
  2389. }
  2390. private void ConnectToRecordNotes()
  2391. {
  2392. var filename = Debugger.IsAttached
  2393. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2394. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2395. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2396. _recordingnotes = Process.Start(filename);
  2397. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2398. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2399. _client = new PipeServer<string>("PRSScreenRecorder", formatter:new BinaryFormatter()); //, sec);
  2400. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2401. _client.MessageReceived += (o, args) =>
  2402. {
  2403. if (string.Equals(args.Message, "RESUME"))
  2404. Dispatcher.Invoke(() =>
  2405. {
  2406. _audio?.StartRecording();
  2407. totalpauses += DateTime.Now - pausestarted;
  2408. _recorder?.Start();
  2409. Activate();
  2410. Focus();
  2411. });
  2412. };
  2413. _client.StartAsync();
  2414. }
  2415. private bool ShowRecordingNotes()
  2416. {
  2417. if (_recorder != null)
  2418. {
  2419. _audio?.StopRecording();
  2420. _recorder.Stop();
  2421. pausestarted = DateTime.Now;
  2422. _client?.WriteAsync("EDIT");
  2423. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2424. }
  2425. return true;
  2426. }
  2427. private void TakeScreenShot()
  2428. {
  2429. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2430. {
  2431. var cursor = PointToScreen(Mouse.GetPosition(this));
  2432. using (var g = Graphics.FromImage(bmp))
  2433. {
  2434. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2435. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2436. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2437. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2438. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2439. }
  2440. var key = DateTime.Now - totalpauses;
  2441. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2442. {
  2443. var ms = new MemoryStream();
  2444. reduced.Save(ms, ImageFormat.Png);
  2445. ms.Position = 0;
  2446. _bitmaps[key] = ms;
  2447. }
  2448. }
  2449. }
  2450. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2451. {
  2452. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2453. using (var dc = Graphics.FromImage(reduced))
  2454. {
  2455. // Figure out the ratio
  2456. var ratioX = (double)reducedWidth / original.Width;
  2457. var ratioY = (double)reducedHeight / original.Height;
  2458. // use whichever multiplier is smaller
  2459. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2460. // now we can get the new height and width
  2461. var newHeight = Convert.ToInt32(original.Height * ratio);
  2462. var newWidth = Convert.ToInt32(original.Width * ratio);
  2463. // Now calculate the X,Y position of the upper-left corner
  2464. // (one of these will always be zero)
  2465. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2466. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2467. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2468. dc.Clear(System.Drawing.Color.Black); // white padding
  2469. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2470. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2471. GraphicsUnit.Pixel);
  2472. }
  2473. return reduced;
  2474. }
  2475. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2476. {
  2477. // and buffer of appropriate size for storing its bits
  2478. var buffer = new byte[width * height * 4];
  2479. var pixelFormat = PixelFormat.Format32bppRgb;
  2480. // Now copy bits from bitmap to buffer
  2481. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2482. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2483. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2484. bitmap.UnlockBits(bits);
  2485. return buffer;
  2486. }
  2487. private void ProcessScreenShots(string filename)
  2488. {
  2489. if (!_bitmaps.Any() || _audioStream is null)
  2490. return;
  2491. Progress.Show("Saving Video");
  2492. var framRate = 10;
  2493. using (var writer = new AviWriter(filename))
  2494. {
  2495. writer.FramesPerSecond = framRate;
  2496. writer.EmitIndex1 = true;
  2497. _audioStream.Position = 0;
  2498. var audio = writer.AddAudioStream(2);
  2499. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2500. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2501. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2502. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2503. var audioBuffer = new byte[audioBlockSize];
  2504. _audioStream.Position = 0;
  2505. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2506. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2507. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2508. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2509. //stream.Codec = CodecIds.Uncompressed;
  2510. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2511. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2512. var start = keys.First();
  2513. var end = keys.Last();
  2514. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2515. {
  2516. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2517. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2518. var key = keys.LastOrDefault(x => x <= cur);
  2519. if (_bitmaps.ContainsKey(key))
  2520. {
  2521. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2522. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2523. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2524. stream.WriteFrame(true, buf, 0, buf.Length);
  2525. if (_audioStream.Position < _audioStream.Length)
  2526. {
  2527. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2528. audio.WriteBlock(audioBuffer, 0, bytes);
  2529. }
  2530. }
  2531. }
  2532. writer.Close();
  2533. //foreach (var key in _bitmaps.Keys)
  2534. // File.Delete(_bitmaps[key]);
  2535. }
  2536. Progress.SetMessage("Transcoding");
  2537. //var inputFile = new MediaFile { Filename = filename };
  2538. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2539. //using (var engine = new Engine())
  2540. //{
  2541. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2542. // engine.Convert(inputFile, outputFile);
  2543. //}
  2544. Progress.Close();
  2545. var dirName = Path.GetDirectoryName(filename);
  2546. if (dirName is not null)
  2547. {
  2548. var startInfo = new ProcessStartInfo(dirName);
  2549. startInfo.Verb = "open";
  2550. startInfo.UseShellExecute = true;
  2551. Process.Start(startInfo);
  2552. //MessageBox.Show("Recording Saved");
  2553. }
  2554. }
  2555. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2556. {
  2557. ToggleRecording();
  2558. }
  2559. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2560. {
  2561. ToggleRecordingAudio();
  2562. }
  2563. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2564. {
  2565. ShowRecordingNotes();
  2566. }
  2567. #endregion
  2568. public static void ActivateWindow(Window window)
  2569. {
  2570. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2571. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2572. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2573. if (threadId1 != threadId2)
  2574. {
  2575. AttachThreadInput(threadId1, threadId2, true);
  2576. SetForegroundWindow(hwnd);
  2577. AttachThreadInput(threadId1, threadId2, false);
  2578. }
  2579. else
  2580. {
  2581. SetForegroundWindow(hwnd);
  2582. }
  2583. }
  2584. private static IntPtr GetForegroundWindow()
  2585. {
  2586. var active = GetActiveWindow();
  2587. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2588. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2589. return hwnd;
  2590. }
  2591. [DllImport("user32.dll", SetLastError = true)]
  2592. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2593. [DllImport("user32.dll")]
  2594. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2595. [DllImport("user32.dll")]
  2596. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2597. [DllImport("user32.dll")]
  2598. private static extern IntPtr GetActiveWindow();
  2599. #region Check For Updates
  2600. private string GetUpdateLocation()
  2601. {
  2602. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2603. {
  2604. string url = "";
  2605. //var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2606. //var port = App.DatabaseSettings.Port;
  2607. var domain = ClientFactory.Parameters?.FirstOrDefault()?.ToString() ?? "";
  2608. domain = domain.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
  2609. if (!String.IsNullOrWhiteSpace(domain))
  2610. {
  2611. try
  2612. {
  2613. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}") };
  2614. client.GetAsync("operations").Wait();
  2615. url = $"https://{domain}";
  2616. }
  2617. catch (Exception)
  2618. {
  2619. url = $"http://{domain}";
  2620. }
  2621. }
  2622. return url;
  2623. }
  2624. else
  2625. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2626. }
  2627. private string GetLatestVersion(string location)
  2628. {
  2629. return Client.Version();
  2630. }
  2631. private string GetReleaseNotes(string location)
  2632. {
  2633. return Client.ReleaseNotes();
  2634. }
  2635. private byte[]? GetInstaller(string location)
  2636. {
  2637. return Client.Installer();
  2638. }
  2639. private void CheckForUpdates()
  2640. {
  2641. Update.CheckForUpdates(
  2642. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2643. }
  2644. #endregion
  2645. #region Modules + Reports
  2646. public void ClearActions()
  2647. {
  2648. foreach (var module in CurrentModules)
  2649. {
  2650. if (module.Parent is Fluent.RibbonGroupBox bar)
  2651. bar.Items.Remove(module);
  2652. }
  2653. CurrentModules.Clear();
  2654. }
  2655. public void ClearReports()
  2656. {
  2657. if (CurrentTab is not null)
  2658. {
  2659. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2660. if (ReportsBar is not null)
  2661. {
  2662. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  2663. ReportsBar.Items.Clear();
  2664. }
  2665. }
  2666. }
  2667. public void CreateReport(PanelAction action)
  2668. {
  2669. if (CurrentTab is null)
  2670. return;
  2671. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  2672. if (ReportsBar is not null)
  2673. {
  2674. var button = new Fluent.Button
  2675. {
  2676. Header = action.Caption,
  2677. LargeIcon = action.Image.AsBitmapImage(),
  2678. MinWidth = 60
  2679. };
  2680. if (action.Menu is not null)
  2681. {
  2682. button.ContextMenu = action.Menu;
  2683. }
  2684. button.Click += (o, e) =>
  2685. {
  2686. action.Execute();
  2687. };
  2688. ReportsBar.Items.Add(button);
  2689. }
  2690. }
  2691. private NullConverter<Visibility>? _vis = null;
  2692. public void CreatePanelAction(PanelAction action)
  2693. {
  2694. if (CurrentTab is null)
  2695. return;
  2696. if (_vis == null)
  2697. {
  2698. _vis = new();
  2699. _vis.Converting += (o, e) =>
  2700. {
  2701. };
  2702. }
  2703. var Actions = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  2704. if (Actions is not null)
  2705. {
  2706. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2707. {
  2708. var sep = new RibbonSeparator();
  2709. CurrentModules.Add(sep);
  2710. Actions.Items.Add(sep);
  2711. }
  2712. if (action.OnPopulate != null)
  2713. {
  2714. Fluent.DropDownButton button = null;
  2715. if (action.OnExecute != null)
  2716. {
  2717. button = new Fluent.SplitButton();
  2718. ((Fluent.SplitButton)button).Click += (o, e) => action.Execute();
  2719. }
  2720. else
  2721. button = new Fluent.DropDownButton();
  2722. button.MinWidth = 60;
  2723. button.DataContext = action;
  2724. button.DropDownOpened += (sender, args) => { button.ItemsSource = CreateMenuItems(action); };
  2725. button.Bind<PanelAction, String>(Fluent.DropDownButton.HeaderProperty, x => x.Caption, null);
  2726. button.Bind<PanelAction, Bitmap?>(Fluent.DropDownButton.LargeIconProperty, x => x.Image,
  2727. new BitmapToBitmapImageConverter());
  2728. button.Bind<PanelAction, ContextMenu?>(ContextMenuProperty, x => x.Menu);
  2729. button.Bind<PanelAction, bool>(IsEnabledProperty, x => x.IsEnabled);
  2730. button.Bind<PanelAction, Visibility>(Fluent.DropDownButton.VisibilityProperty, x => x.Visibility, _vis);
  2731. Actions.Items.Add(button);
  2732. CurrentModules.Add(button);
  2733. }
  2734. else
  2735. {
  2736. var button = new Fluent.Button()
  2737. {
  2738. MinWidth = 60,
  2739. DataContext = action
  2740. };
  2741. button.Bind<PanelAction, String>(Fluent.Button.HeaderProperty, x => x.Caption, null);
  2742. button.Bind<PanelAction, Bitmap?>(Fluent.Button.LargeIconProperty, x => x.Image,
  2743. new BitmapToBitmapImageConverter());
  2744. button.Bind<PanelAction, ContextMenu?>(Fluent.Button.ContextMenuProperty, x => x.Menu);
  2745. button.Bind<PanelAction, bool>(Fluent.Button.IsEnabledProperty, x => x.IsEnabled);
  2746. button.Bind<PanelAction, Visibility>(Fluent.Button.VisibilityProperty, x => x.Visibility, _vis);
  2747. button.Click += (o, e) => action.Execute();
  2748. Actions.Items.Add(button);
  2749. CurrentModules.Add(button);
  2750. }
  2751. }
  2752. }
  2753. private static ObservableCollection<MenuItem> CreateMenuItems(PanelAction action)
  2754. {
  2755. var items = new ObservableCollection<MenuItem>();
  2756. var entries = action.Populate();
  2757. if (entries != null)
  2758. {
  2759. foreach (var entry in entries)
  2760. {
  2761. var item = new Fluent.MenuItem()
  2762. {
  2763. Header = entry.Caption,
  2764. DataContext = entry.Data,
  2765. Icon = entry.Image?.AsBitmapImage()
  2766. };
  2767. item.Click += (o, eventArgs) => entry.Execute();
  2768. items.Add(item);
  2769. }
  2770. }
  2771. return items;
  2772. }
  2773. #endregion
  2774. #region Tracking Kanban
  2775. private void SelectTask_Click(object sender, RoutedEventArgs e)
  2776. {
  2777. ContextMenu menu = new ContextMenu();
  2778. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  2779. using (new WaitCursor())
  2780. {
  2781. var kanbans = new Client<KanbanSubscriber>().Query(
  2782. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  2783. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  2784. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  2785. Columns.None<KanbanSubscriber>().Add(x => x.Kanban.ID)
  2786. .Add(x => x.Kanban.Number)
  2787. .Add(x => x.Kanban.Title)
  2788. .Add(x => x.Assignee),
  2789. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  2790. );
  2791. foreach (var row in kanbans.Rows)
  2792. {
  2793. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  2794. String.Format("{0} {1}",
  2795. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  2796. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  2797. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  2798. );
  2799. }
  2800. menu.Items.Add(new Separator());
  2801. menu.Items.Add(others);
  2802. menu.Items.Add(new Separator());
  2803. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  2804. }
  2805. menu.IsOpen = true;
  2806. }
  2807. private Assignment? _kanbantrackingassignment = null;
  2808. private void SetTrackingKanban(Guid kanbanID, string header)
  2809. {
  2810. SelectedTaskName.Content = header;
  2811. var createNewAssignment = false;
  2812. if (_kanbantrackingassignment is not null)
  2813. {
  2814. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  2815. {
  2816. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2817. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2818. }
  2819. // Update Existing Kanban
  2820. if (kanbanID == Guid.Empty)
  2821. _kanbantrackingassignment = null;
  2822. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  2823. {
  2824. createNewAssignment = true;
  2825. }
  2826. }
  2827. else if (kanbanID != Guid.Empty)
  2828. {
  2829. createNewAssignment = true;
  2830. }
  2831. if (createNewAssignment)
  2832. {
  2833. _kanbantrackingassignment = new Assignment();
  2834. _kanbantrackingassignment.Task.ID = kanbanID;
  2835. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  2836. _kanbantrackingassignment.Title = header;
  2837. _kanbantrackingassignment.Date = DateTime.Today;
  2838. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  2839. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  2840. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2841. }
  2842. }
  2843. private void ClearTrackingKanban()
  2844. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  2845. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  2846. {
  2847. var item = new MenuItem()
  2848. {
  2849. Header = title,
  2850. Tag = id
  2851. };
  2852. item.Click += (o, args) =>
  2853. {
  2854. if (o is not MenuItem menu) return;
  2855. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  2856. };
  2857. items.Add(item);
  2858. }
  2859. #endregion
  2860. private void DockPanelBorder_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  2861. {
  2862. if (sender is not Border border || !border.IsVisible)
  2863. return;
  2864. var dock = border.Child is IDockPanel panel ? panel : border.Child?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2865. if (dock is null)
  2866. return;
  2867. dock.Refresh();
  2868. }
  2869. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  2870. {
  2871. if (sender is not LayoutAnchorable layout)
  2872. return;
  2873. var content = layout.Content as DependencyObject;
  2874. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  2875. if (dock is null)
  2876. return;
  2877. if (layout.IsActive && layout.IsVisible)
  2878. dock.Refresh();
  2879. }
  2880. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  2881. {
  2882. e.Handled = true;
  2883. }
  2884. #region Backstage Functions
  2885. private enum DatabaseConfigurationResult
  2886. {
  2887. RestartRequired,
  2888. RestartNotRequired,
  2889. Cancel
  2890. }
  2891. private DatabaseConfigurationResult ShowDatabaseConfiguration()
  2892. {
  2893. DatabaseConfigurationResult result;
  2894. var config = new DataBaseConfiguration();
  2895. if (config.ShowDialog() == true)
  2896. {
  2897. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  2898. if (newsettings.RestartRequired(App.DatabaseSettings))
  2899. {
  2900. result = DatabaseConfigurationResult.RestartRequired;
  2901. }
  2902. else
  2903. {
  2904. result = DatabaseConfigurationResult.RestartNotRequired;
  2905. }
  2906. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  2907. {
  2908. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  2909. ApplyColorScheme();
  2910. }
  2911. }
  2912. else
  2913. {
  2914. result = DatabaseConfigurationResult.Cancel;
  2915. }
  2916. return result;
  2917. }
  2918. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  2919. {
  2920. switch (ShowDatabaseConfiguration())
  2921. {
  2922. case DatabaseConfigurationResult.RestartRequired:
  2923. MessageBox.Show("Please restart the application to apply these changes!");
  2924. break;
  2925. }
  2926. }
  2927. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  2928. {
  2929. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2930. if (info == null)
  2931. info = new CompanyInformation();
  2932. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2933. }
  2934. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  2935. {
  2936. var window = new GlobalTokenWindow();
  2937. window.ShowDialog();
  2938. Security.Reset();
  2939. }
  2940. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  2941. {
  2942. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  2943. if (File.Exists(logfile))
  2944. {
  2945. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  2946. startInfo.Verb = "open";
  2947. startInfo.UseShellExecute = true;
  2948. Process.Start(startInfo);
  2949. }
  2950. else
  2951. {
  2952. MessageBox.Show(logfile + " does not exist!");
  2953. }
  2954. }
  2955. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  2956. {
  2957. var list = new MasterList(typeof(DocumentType));
  2958. list.ShowDialog();
  2959. }
  2960. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  2961. {
  2962. var employee = new Client<Employee>().Query(
  2963. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  2964. .Rows.FirstOrDefault()?.ToObject<Employee>();
  2965. var item = new MyDetailsConfiguration(employee);
  2966. item.User = ClientFactory.UserGuid;
  2967. var buttons = new DynamicEditorButtons();
  2968. buttons.Add("Change Password", null, item, (sender, item) =>
  2969. {
  2970. var details = (item as MyDetailsConfiguration)!;
  2971. var changePassword = new ChangePassword(details.User);
  2972. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  2973. {
  2974. var newUser = new User();
  2975. newUser.ID = details.User;
  2976. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  2977. new Client<User>().Save(newUser, "Changed Password");
  2978. MessageBox.Show("Password changed!");
  2979. }
  2980. });
  2981. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  2982. if (employee == null)
  2983. {
  2984. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  2985. {
  2986. editor.Editable = Editable.Disabled;
  2987. };
  2988. }
  2989. editor.Items = new BaseObject[] { item };
  2990. if (editor.ShowDialog() == true)
  2991. {
  2992. if (employee != null)
  2993. {
  2994. item.SaveTo(employee);
  2995. new Client<Employee>().Save(employee, "Edited by user");
  2996. }
  2997. }
  2998. }
  2999. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3000. {
  3001. Logout();
  3002. }
  3003. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3004. {
  3005. if (DoLogin() == ValidationStatus.VALID)
  3006. AfterLogin(null);
  3007. }
  3008. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3009. {
  3010. //_closingFromSystemMenu = true;
  3011. Close();
  3012. }
  3013. #endregion
  3014. }