MainWindow.xaml.cs 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Net.Mail;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. using System.Windows;
  17. using System.Windows.Controls;
  18. using System.Windows.Controls.Primitives;
  19. using System.Windows.Forms;
  20. using System.Windows.Input;
  21. using System.Windows.Interop;
  22. using System.Windows.Media;
  23. using System.Windows.Threading;
  24. using AvalonDock.Layout;
  25. using Comal.Classes;
  26. using Comal.Stores;
  27. using Comal.TaskScheduler.Shared;
  28. using H.Pipes;
  29. using InABox.Client.IPC;
  30. using InABox.Clients;
  31. using InABox.Configuration;
  32. using InABox.Core;
  33. using InABox.Database;
  34. using InABox.Database.SQLite;
  35. using InABox.DeviceIdentifier;
  36. using InABox.DynamicGrid;
  37. using InABox.Mail;
  38. using InABox.Reports;
  39. using InABox.Core.Reports;
  40. using InABox.Scripting;
  41. using InABox.WPF;
  42. using NAudio.Wave;
  43. using PRS.Shared;
  44. using InABox.WPF.Themes;
  45. using NPOI.SS.Formula.Functions;
  46. using PRSDesktop.Configuration;
  47. using PRSDesktop.Forms;
  48. using PRSServer;
  49. using SharpAvi.Codecs;
  50. using SharpAvi.Output;
  51. using Syncfusion.UI.Xaml.Maps;
  52. using Syncfusion.Windows.Shared;
  53. using Syncfusion.Windows.Tools;
  54. using Syncfusion.Windows.Tools.Controls;
  55. using Activity = Comal.Classes.Activity;
  56. using Application = System.Windows.Application;
  57. using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
  58. using Color = System.Windows.Media.Color;
  59. using ColorConverter = System.Windows.Media.ColorConverter;
  60. using Control = System.Windows.Controls.Control;
  61. using Image = System.Drawing.Image;
  62. using KeyEventArgs = System.Windows.Input.KeyEventArgs;
  63. using MessageBox = System.Windows.MessageBox;
  64. using Pen = System.Drawing.Pen;
  65. using PixelFormat = System.Drawing.Imaging.PixelFormat;
  66. using Role = Comal.Classes.Role;
  67. using SortDirection = InABox.Core.SortDirection;
  68. using ValidationResult = InABox.Clients.ValidationResult;
  69. using System.Diagnostics.CodeAnalysis;
  70. using System.Runtime.InteropServices;
  71. using FastReport.Export.Email;
  72. using InABox.Wpf;
  73. using javax.xml.crypto;
  74. using PRSDesktop.Components.Spreadsheet;
  75. using InABox.Wpf.Reports;
  76. namespace PRSDesktop
  77. {
  78. /// <summary>
  79. /// Interaction logic for Main.xaml
  80. /// </summary>
  81. public partial class MainWindow : IPanelHost
  82. {
  83. //private const int WM_LBUTTONDOWN = 0x201;
  84. private static PipeServer<string>? _client;
  85. private WaveIn? _audio;
  86. private bool _audioMuted;
  87. private MemoryStream? _audioStream;
  88. private readonly Dictionary<DateTime, Stream> _bitmaps = new();
  89. private Console? _console;
  90. private Dictionary<DateTime, Tuple<Rectangle, string>> _notes = new();
  91. //Dictionary<Type, IBasePanel> Panels = new Dictionary<Type, IBasePanel>();
  92. private DispatcherTimer? _recorder;
  93. private Process? _recordingnotes;
  94. private int _screenheight = 720;
  95. private int _screenleft;
  96. private int _screentop;
  97. private int _screenwidth = 1280;
  98. private readonly Dictionary<Guid, SecondaryWindow> _secondarywindows = new();
  99. private CoreTable? _timesheets;
  100. private DailyActivityHistory? ActivityHistory;
  101. private readonly List<Control> CurrentModules = new();
  102. private IBasePanel? CurrentPanel;
  103. private int CurrentPanel_Clicks;
  104. private int CurrentPanel_Keys;
  105. private string CurrentPanel_Label = "";
  106. private DateTime CurrentPanel_Ticks = DateTime.MinValue;
  107. private Fluent.RibbonTabItem? CurrentTab;
  108. private Fluent.Button? CurrentButton;
  109. private readonly int FRAMES_PER_SECOND = 10;
  110. private DatabaseType DatabaseType;
  111. private readonly Dictionary<int, int> messages = new();
  112. private readonly DispatcherTimer NotificationsWatchDog;
  113. private DateTime pausestarted = DateTime.MinValue;
  114. private readonly Scheduler scheduler = new() { Interval = new TimeSpan(0, 5, 0) };
  115. // We use a Guid for the StationID rather than an IP or Mac address
  116. // because we want true single-instance restriction. Using either of
  117. // the above allows for two instances on the once machine, and thus
  118. // double-counting in the Heartbeat() function
  119. private Login station = new() { StationID = Guid.NewGuid().ToString() };
  120. private TimeSpan totalpauses = new(0);
  121. private readonly int VIDEO_HEIGHT = 1080;
  122. private readonly int VIDEO_WIDTH = 1920;
  123. public MainWindow()
  124. {
  125. NotificationsWatchDog = new DispatcherTimer { IsEnabled = false };
  126. NotificationsWatchDog.Tick += Notifications_Tick;
  127. NotificationsWatchDog.Interval = new TimeSpan(0, 2, 0);
  128. ClientFactory.Notifications.AddHandler<Notification>(ReceiveNotification);
  129. ClientFactory.RegisterMailer(EmailType.IMAP, typeof(IMAPMailer));
  130. ClientFactory.RegisterMailer(EmailType.Exchange, typeof(ExchangeMailer));
  131. ClientFactory.OnLog += (_, message) => { Logger.Send(LogType.Information, ClientFactory.UserID, message); };
  132. ClientFactory.OnRequestError += ClientFactory_OnRequestError;
  133. HotKeyManager.Initialize();
  134. HotKeyManager.RegisterHotKey(Key.F1, ShowHelp);
  135. HotKeyManager.RegisterHotKey(Key.F5, ToggleRecording);
  136. HotKeyManager.RegisterHotKey(Key.F6, ShowRecordingNotes);
  137. HotKeyManager.RegisterHotKey(Key.F4, ToggleRecordingAudio);
  138. DatabaseType = App.DatabaseSettings.DatabaseType;
  139. switch (DatabaseType)
  140. {
  141. case DatabaseType.Standalone:
  142. ClientFactory.SetClientType(typeof(LocalClient<>), "Wpf", CoreUtils.GetVersion(), "");
  143. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  144. DbFactory.Logo = App.DatabaseSettings.Logo;
  145. break;
  146. case DatabaseType.Networked:
  147. ClientFactory.SetClientType(typeof(JsonClient<>), "Wpf", CoreUtils.GetVersion(),
  148. App.DatabaseSettings.URL, App.DatabaseSettings.Port, true);
  149. break;
  150. case DatabaseType.Local:
  151. ClientFactory.SetClientType(typeof(PipeIPCClient<>), "Wpf", CoreUtils.GetVersion(),
  152. DatabaseServerProperties.GetPipeName(App.DatabaseSettings.LocalServerName));
  153. break;
  154. }
  155. ThemeManager.BaseColor = Colors.CornflowerBlue;
  156. Progress.DisplayImage = PRSDesktop.Resources.splash_small.AsBitmapImage();
  157. try
  158. {
  159. var dbInfo = new Client<User>().Info();
  160. ThemeManager.BaseColor = (Color)ColorConverter.ConvertFromString(dbInfo.ColorScheme);
  161. if (dbInfo.Logo?.Any() == true)
  162. using (var ms = new MemoryStream(dbInfo.Logo))
  163. {
  164. Progress.DisplayImage = new Bitmap(ms).AsBitmapImage();
  165. }
  166. }
  167. catch
  168. {
  169. }
  170. InitializeComponent();
  171. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  172. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  173. SecondaryWindowStatus.Source = PRSDesktop.Resources.target.AsGrayScale().AsBitmapImage();
  174. ConsoleStatus.Source = PRSDesktop.Resources.view.AsGrayScale().AsBitmapImage();
  175. SelectTask.Source = PRSDesktop.Resources.uparrow.Invert().AsBitmapImage();
  176. Title = $"{(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  177. CheckForUpdates();
  178. Exception? startupException = null;
  179. Exception? loginException = null;
  180. ValidationResult? loginStatus = null;
  181. Progress.ShowModal("Loading PRS", progress =>
  182. {
  183. DynamicGridUtils.PreviewReport = (t, m) => { ReportUtils.PreviewReport(t, m, false, Security.IsAllowed<CanDesignReports>()); };
  184. DynamicGridUtils.PrintMenu = (e, s, m, p) => { ReportUtils.PrintMenu(e, s, m, Security.IsAllowed<CanDesignReports>(), p); };
  185. ImportFactory.Register(typeof(ExcelImporter<>), "Excel File", "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm");
  186. FormUtils.Register();
  187. Logger.Send(LogType.Information, "", "Registering Classes");
  188. progress.Report("Registering Classes");
  189. var tasks = new List<Task>
  190. {
  191. Task.Run(() => CoreUtils.RegisterClasses(typeof(KanbanGrid).Assembly)),
  192. Task.Run(() => CoreUtils.RegisterClasses()),
  193. Task.Run(() => ComalUtils.RegisterClasses()),
  194. Task.Run(() => ReportUtils.RegisterClasses()),
  195. Task.Run(() => ConfigurationUtils.RegisterClasses()),
  196. Task.Run(() => DynamicGridUtils.RegisterClasses()),
  197. Task.Run(() =>
  198. {
  199. ScriptDocument.DefaultAssemblies.AddRange(
  200. Assembly.Load("RoslynPad.Roslyn.Windows"),
  201. Assembly.Load("RoslynPad.Editor.Windows"),
  202. typeof(Control).Assembly,
  203. typeof(MessageBox).Assembly,
  204. typeof(SolidColorBrush).Assembly
  205. );
  206. ScriptDocument.Initialize();
  207. }),
  208. Task.Run(() => DatabaseUpdateScripts.RegisterScripts())
  209. };
  210. Task.WaitAll(tasks.ToArray());
  211. progress.Report("Configuring Application");
  212. RegisterModules(progress);
  213. if (DatabaseType == DatabaseType.Standalone)
  214. {
  215. progress.Report("Starting local database...");
  216. try
  217. {
  218. StartLocalDatabase(progress);
  219. }
  220. catch (Exception err)
  221. {
  222. startupException = new Exception(
  223. string.Format(
  224. "Unable to open database ({0})\n\n{1}\n\n{2}",
  225. App.DatabaseSettings.FileName,
  226. err.Message,
  227. err.StackTrace
  228. )
  229. );
  230. }
  231. }
  232. /*if (startupException == null && App.DatabaseSettings.Autologin)
  233. {
  234. progress.Report("Logging in...");
  235. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  236. {
  237. ValidationResult? result;
  238. try
  239. {
  240. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  241. }
  242. catch(Exception e)
  243. {
  244. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  245. loginException = new Exception("Error connecting to server.\nPlease check the server URL and port number.");
  246. result = null;
  247. }
  248. loginStatus = result;
  249. if (result == ValidationResult.INVALID)
  250. {
  251. loginException = new Exception("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  252. }
  253. }
  254. if(loginStatus == ValidationResult.VALID)
  255. {
  256. LoadCurrentEmployee();
  257. if(!CheckTimesheetBypass(false))
  258. {
  259. loginException = new Exception("You must clock on before logging in to PRS!");
  260. loginStatus = null;
  261. }
  262. }
  263. }*/
  264. });
  265. if (startupException != null)
  266. MessageBox.Show(startupException.Message);
  267. else if (loginException != null)
  268. MessageBox.Show(loginException.Message);
  269. if (DoLogin(App.DatabaseSettings.Autologin) == ValidationResult.VALID)
  270. {
  271. AfterLogin();
  272. }
  273. ProfileName.Content = App.Profile;
  274. URL.Content = DatabaseType switch
  275. {
  276. DatabaseType.Networked => URLCache.IsHTTPS ? App.DatabaseSettings.URL : $"{App.DatabaseSettings.URL} - Not Secure",
  277. DatabaseType.Standalone => App.DatabaseSettings.FileName,
  278. DatabaseType.Local => App.DatabaseSettings.LocalServerName,
  279. _ => ""
  280. };
  281. Progress.ShowModal("Starting Up", progress =>
  282. {
  283. if (loginStatus == ValidationResult.VALID && DatabaseType == DatabaseType.Standalone)
  284. {
  285. progress.Report("Starting Scheduler");
  286. scheduler.Start();
  287. }
  288. });
  289. }
  290. private bool _loggingOut = false;
  291. private void ClientFactory_OnRequestError(RequestException e)
  292. {
  293. if (e.Status == StatusCode.Unauthenticated)
  294. {
  295. switch (e.Method)
  296. {
  297. case RequestMethod.Query:
  298. case RequestMethod.Save:
  299. case RequestMethod.Delete:
  300. case RequestMethod.MultiQuery:
  301. case RequestMethod.MultiSave:
  302. case RequestMethod.MultiDelete:
  303. if (!_loggingOut)
  304. {
  305. Dispatcher.InvokeAsync(() =>
  306. {
  307. _loggingOut = true;
  308. try
  309. {
  310. Logout(null, true);
  311. }
  312. finally
  313. {
  314. _loggingOut = false;
  315. }
  316. });
  317. }
  318. break;
  319. default:
  320. break;
  321. }
  322. }
  323. }
  324. private void ApplyColorScheme()
  325. {
  326. Color baseColor;
  327. try
  328. {
  329. baseColor = (Color)ColorConverter.ConvertFromString(App.DatabaseSettings.ColorScheme);
  330. }
  331. catch
  332. {
  333. baseColor = Colors.CornflowerBlue;
  334. }
  335. ThemeManager.BaseColor = baseColor;
  336. BaseDynamicGrid.SelectionBackground = ThemeManager.SelectionBackgroundBrush;
  337. BaseDynamicGrid.SelectionForeground = ThemeManager.SelectionForegroundBrush;
  338. BaseDynamicGrid.FilterBackground = ThemeManager.FilterBackgroundBrush;
  339. //_ribbon.Background = new SolidColorBrush(Colors.White);
  340. //_ribbon.BackStageColor = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  341. ////_ribbon.BackStage.Background = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Background);
  342. ////_ribbon.BackStage.Foreground = ThemeConverter.GetBrush(ElementType.Ribbon, BrushType.Foreground);
  343. UpdateRibbonColors();
  344. CurrentPanel?.Refresh();
  345. }
  346. #region Configuration
  347. /*
  348. protected override void OnSourceInitialized(EventArgs e)
  349. {
  350. base.OnSourceInitialized(e);
  351. var source = PresentationSource.FromVisual(this) as HwndSource;
  352. source?.AddHook(WndProc);
  353. }
  354. private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  355. {
  356. var message = (App.Message)msg;
  357. switch (message)
  358. {
  359. case App.Message.Maximise:
  360. WindowState = WindowState.Maximized;
  361. break;
  362. }
  363. return IntPtr.Zero;
  364. }*/
  365. private interface ISetupActionItem
  366. {
  367. }
  368. private class SetupActionItem : ISetupActionItem
  369. {
  370. public string Name { get; set; }
  371. public Action Action { get; set; }
  372. public Bitmap? Image { get; set; }
  373. public Type? SecurityToken { get; set; }
  374. public Func<bool>? CanView { get; set; }
  375. public SetupActionItem(string name, Action action, Bitmap? image)
  376. {
  377. Name = name;
  378. Action = action;
  379. Image = image;
  380. }
  381. public bool IsVisible() => (SecurityToken == null || Security.IsAllowed(SecurityToken)) && (CanView == null || CanView());
  382. public SetupActionItem SetSecurityToken<T>() where T : ISecurityDescriptor, new()
  383. {
  384. SecurityToken = typeof(T);
  385. return this;
  386. }
  387. public SetupActionItem SetCanView<T>() where T : Entity
  388. {
  389. return SetSecurityToken<AutoSecurityDescriptor<T, CanView<T>>>();
  390. }
  391. }
  392. private class SetupSeparator : ISetupActionItem { }
  393. private Dictionary<Fluent.RibbonTabItem, List<ISetupActionItem>> SetupActions = new();
  394. private List<ISetupActionItem> GetSetupActionList(Fluent.RibbonTabItem tab)
  395. {
  396. if (!SetupActions.TryGetValue(tab, out var list))
  397. {
  398. list = new();
  399. SetupActions[tab] = list;
  400. }
  401. return list;
  402. }
  403. private SetupActionItem AddSetupAction(List<ISetupActionItem> list, string header, Action action, Bitmap? image)
  404. {
  405. var item = new SetupActionItem(header, action, image);
  406. list.Add(item);
  407. return item;
  408. }
  409. private SetupActionItem AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image)
  410. => AddSetupAction(GetSetupActionList(tab), header, action, image);
  411. private SetupActionItem? AddSetupAction(Fluent.RibbonTabItem tab, string header, Action action, Bitmap? image, bool canView)
  412. {
  413. if (!canView)
  414. return null;
  415. return AddSetupAction(tab, header, action, image);
  416. }
  417. private SetupSeparator AddSetupSeparator(List<ISetupActionItem> list)
  418. {
  419. var separator = new SetupSeparator();
  420. list.Add(separator);
  421. return separator;
  422. }
  423. private SetupSeparator AddSetupSeparator(Fluent.RibbonTabItem tab)
  424. => AddSetupSeparator(GetSetupActionList(tab));
  425. private void AddSetupModulesAndReports(Fluent.RibbonTabItem tab)
  426. {
  427. AddSetupSeparator(tab);
  428. AddSetupAction(tab, "Custom Modules", ManageModules, PRSDesktop.Resources.script).SetSecurityToken<CanCustomiseModules>();
  429. AddSetupAction(tab, "Reports", ManageReports, PRSDesktop.Resources.printer).SetSecurityToken<CanDesignReports>();
  430. AddSetupAction(tab, "Email Templates", ManageEmailTemplates, PRSDesktop.Resources.email).SetSecurityToken<CanDesignReports>();
  431. }
  432. private void ConfigureMainScreen()
  433. {
  434. var button = _ribbon.FindVisualChildren<Fluent.DropDownButton>().FirstOrDefault();
  435. if (button != null)
  436. button.Visibility = Visibility.Collapsed;
  437. if (ClientFactory.UserGuid == Guid.Empty)
  438. _ribbonRow.Height = new GridLength(30, GridUnitType.Pixel);
  439. else
  440. _ribbonRow.Height = new GridLength(1, GridUnitType.Auto);
  441. var bMaps = Security.CanView<Equipment>()
  442. || Security.CanView<Job>()
  443. || Security.CanView<TimeSheet>()
  444. || Security.CanView<GPSTracker>();
  445. Progress.ShowModal(
  446. new ProgressSection(
  447. "Configuring Main Screen",
  448. () =>
  449. {
  450. ReportUtils.ExportDefinitions.Clear();
  451. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  452. //DockManager.SidePanelSize = OutstandingDailyReports(false) ? 0.00F : 30.00F;
  453. // Notifications Area
  454. SetVisibility(SendNotification, Security.CanView<Notification>());
  455. SetVisibility(Notifications, Security.CanView<Notification>());
  456. SetVisibility(TaskTracking, Security.IsAllowed<CanTrackTasksInDailyReport>());
  457. UserID.Content = ClientFactory.UserID;
  458. if (ClientFactory.PasswordExpiration != DateTime.MinValue)
  459. {
  460. var timeUntilExpiration = ClientFactory.PasswordExpiration - DateTime.Now;
  461. if (timeUntilExpiration.Days < 14)
  462. {
  463. PasswordExpiryNotice.Content = $"Password will expire in {timeUntilExpiration.Days} days!";
  464. PasswordExpiryNotice.Visibility = Visibility.Visible;
  465. }
  466. else
  467. {
  468. PasswordExpiryNotice.Visibility = Visibility.Collapsed;
  469. }
  470. }
  471. }
  472. ),
  473. new ProgressSection(
  474. "Configuring Quotes",
  475. () =>
  476. {
  477. //// Quotes Menu Bar
  478. SetVisibility(QuotesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  479. SetVisibility(QuotesMessagesButton, Security.CanView<Notification>());
  480. SetVisibility(QuotesTaskButton, Security.IsAllowed<CanViewTasks>());
  481. SetVisibility(QuotesAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  482. SetVisibility(QuotesMapButton, bMaps);
  483. SetVisibility(QuotesDailyReportButton,
  484. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  485. SetVisibility(QuotesButton, Security.CanView<Quote>());
  486. SetVisibleIfEither(QuotesTaskSeparator,
  487. new FrameworkElement[]
  488. {
  489. QuotesDashboardButton, QuotesMessagesButton, QuotesTaskButton, QuotesAttendanceButton, QuotesMapButton,
  490. QuotesDailyReportButton
  491. }, new FrameworkElement[] { QuotesButton });
  492. SetVisibility(KitsMasterList, Security.CanView<Kit>());
  493. SetVisibility(CostSheetsMasterList, Security.CanView<CostSheet>());
  494. SetVisibleIfEither(QuotesActionSeparator, new FrameworkElement[] { QuotesButton },
  495. new FrameworkElement[] { KitsMasterList, CostSheetsMasterList });
  496. SetVisibleIfAny(QuotesActions, QuotesButton, KitsMasterList, CostSheetsMasterList);
  497. AddSetupAction(QuotesTab, "Status Codes", QuoteStatusButton_Click, PRSDesktop.Resources.quotestatus,
  498. ClientFactory.IsSupported<Quote>() && Security.IsAllowed<CanModifyQuoteStatuses>());
  499. AddSetupAction(QuotesTab, "Design Sections", QuoteDesignSectionButton_Click, PRSDesktop.Resources.design,
  500. Security.CanView<QuoteDesignSection>());
  501. AddSetupSeparator(QuotesTab);
  502. AddSetupAction(QuotesTab, "Kit Conditions", KitConditionList_Click, PRSDesktop.Resources.kitcondition,
  503. Security.CanView<KitCondition>());
  504. AddSetupAction(QuotesTab, "Kit Formulae", KitFormulaeList_Click, PRSDesktop.Resources.kitformula,
  505. Security.CanView<KitFormula>());
  506. AddSetupAction(QuotesTab, "Cost Sheet Types", CostSheetTypeList_Click, PRSDesktop.Resources.costsheettype,
  507. Security.CanView<CostSheetType>());
  508. AddSetupAction(QuotesTab, "Cost Sheet Brands", CostSheetBrandList_Click, PRSDesktop.Resources.costsheetbrand,
  509. Security.CanView<CostSheetBrand>());
  510. AddSetupAction(QuotesTab, "Cost Sheet Sections", CostSheetSectionList_Click, PRSDesktop.Resources.costsheetsection,
  511. Security.CanView<CostSheetSection>());
  512. AddSetupSeparator(QuotesTab);
  513. AddSetupAction(QuotesTab, "Symbols", QuoteDiagramSymbols_Checked, PRSDesktop.Resources.pencil,
  514. Security.CanView<QuoteDiagramSymbol>());
  515. AddSetupAction(QuotesTab, "Symbol Types", QuoteDiagramSymbolTypes_Checked, PRSDesktop.Resources.attachment,
  516. Security.CanView<QuoteDiagramSymbol>());
  517. AddSetupAction(QuotesTab, "Dimension Types", QuoteTakeOffUnits_Click, PRSDesktop.Resources.box,
  518. Security.CanView<QuoteTakeOffUnit>());
  519. AddSetupSeparator(QuotesTab);
  520. AddSetupAction(QuotesTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Quote>(), PRSDesktop.Resources.box,
  521. Security.CanView<QuoteSpreadsheet>());
  522. AddSetupModulesAndReports(QuotesTab);
  523. SetTabVisibleIfAny(QuotesTab, QuotesActions);
  524. }
  525. ),
  526. new ProgressSection(
  527. "Configuring Projects",
  528. () =>
  529. {
  530. SetVisibility(ProjectsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  531. SetVisibility(ProjectMessagesButton, Security.CanView<Notification>());
  532. SetVisibility(ProjectTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  533. SetVisibility(ProjectAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  534. SetVisibility(ProjectsMapButton, bMaps);
  535. SetVisibility(ProjectDailyReportButton,
  536. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  537. SetVisibility(ProjectsButton, Security.CanView<Job>());
  538. SetVisibility(ServiceButton, false);
  539. SetVisibility(ProjectPlannerButton, Security.CanView<Job>());
  540. SetVisibleIfEither(ProjectTaskSeparator,
  541. new FrameworkElement[]
  542. {
  543. ProjectsDashboardButton, ProjectMessagesButton, ProjectTaskButton, ProjectAttendanceButton, ProjectsMapButton,
  544. ProjectDailyReportButton
  545. }, new FrameworkElement[] { QuotesButton, ProjectsButton, ServiceButton, ProjectPlannerButton });
  546. AddSetupAction(ProjectsTab, "Job Statuses", JobStatusButton_Click, PRSDesktop.Resources.view,
  547. Security.CanView<JobStatus>());
  548. AddSetupAction(ProjectsTab, "Document MileStones", JobDocumentMileStoneButton_OnClick, PRSDesktop.Resources.revision,
  549. true);
  550. //AddSetupAction(ProjectsTab, "Document Tags", JobDocumentTagButton_OnClick, PRSDesktop.Resources.checklist,
  551. // true);
  552. AddSetupAction(ProjectsTab, "Financial Statuses", FinancialStatusButton_Click, PRSDesktop.Resources.view,
  553. Security.CanView<JobFinancial>());
  554. AddSetupAction(ProjectsTab, "Drawing Templates", DrawingTemplatesButton_Click, PRSDesktop.Resources.doc_misc,
  555. true);
  556. AddSetupSeparator(ProjectsTab);
  557. AddSetupAction(ProjectsTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Job>(), PRSDesktop.Resources.box,
  558. Security.CanView<JobSpreadsheet>());
  559. AddSetupModulesAndReports(ProjectsTab);
  560. //ProjectsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  561. //ProjectReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  562. SetTabVisibleIfAny(ProjectsTab, ProjectsButton, ServiceButton, ProjectPlannerButton);
  563. }
  564. ),
  565. new ProgressSection(
  566. "Configuring Manufacturing",
  567. () =>
  568. {
  569. SetVisibility(ManufacturingDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  570. SetVisibility(ManufacturingMessagesButton, Security.CanView<Notification>());
  571. SetVisibility(ManufacturingTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  572. SetVisibility(ManufacturingAttendanceButton,
  573. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  574. SetVisibility(ManufacturingMapButton, bMaps);
  575. SetVisibility(ManufacturingDailyReportButton,
  576. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  577. SetVisibility(FactoryStatusButton,
  578. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryStatus>());
  579. SetVisibility(FactoryAllocationButton,
  580. ClientFactory.IsSupported<ManufacturingFactory, ManufacturingPacket, ManufacturingPacketStage>() &&
  581. Security.IsAllowed<CanViewFactoryAllocation>());
  582. //SetVisibility(FactoryScheduleButton, ClientFactory.IsSupported<Booking>() && ClientFactory.IsEnabled<>());
  583. SetVisibility(FactoryFloorButton,
  584. ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryFloor>());
  585. //SetVisibility(FactoryReadyButton, ClientFactory.IsSupported<ManufacturingPacket>() && Security.IsAllowed<CanViewFactoryReadyToGo>());
  586. SetVisibleIfEither(ManufacturingTaskSeparator,
  587. new FrameworkElement[]
  588. {
  589. ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton, ManufacturingAttendanceButton,
  590. ManufacturingMapButton, ManufacturingDailyReportButton
  591. }, new FrameworkElement[] { FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton /* , FactoryReadyButton */ });
  592. SetVisibleIfAny(ManufacturingActions, ManufacturingDashboardButton, ManufacturingMessagesButton, ManufacturingTaskButton,
  593. ManufacturingAttendanceButton, ManufacturingDailyReportButton, FactoryStatusButton, FactoryAllocationButton,
  594. FactoryFloorButton);
  595. AddSetupAction(ManufacturingTab, "Factory Settings", FactorySetup_Click, PRSDesktop.Resources.factorysetup,
  596. ClientFactory.IsSupported<ManufacturingFactory>() && Security.IsAllowed<CanViewFactorySettings>());
  597. AddSetupAction(ManufacturingTab, "Manufacturing Templates", TemplateSetup_Click, PRSDesktop.Resources.template,
  598. Security.CanView<ManufacturingTemplate>());
  599. AddSetupAction(ManufacturingTab, "Manufacturing Trolleys", TrolleySetup_Click, PRSDesktop.Resources.trolley,
  600. Security.CanView<ManufacturingTrolley>());
  601. AddSetupAction(ManufacturingTab, "Lost Time Types", LostTimeSetup_Click, PRSDesktop.Resources.smiley,
  602. Security.CanView<ManufacturingLostTime>());
  603. //ManufacturingActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  604. //ManufacturingReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  605. AddSetupModulesAndReports(ManufacturingTab);
  606. SetTabVisibleIfAny(ManufacturingTab, FactoryStatusButton, FactoryAllocationButton, FactoryFloorButton);
  607. }
  608. ),
  609. new ProgressSection(
  610. "Configuring Logistics",
  611. () =>
  612. {
  613. SetVisibility(LogisticsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  614. SetVisibility(LogisticsMessagesButton, Security.CanView<Notification>());
  615. SetVisibility(LogisticsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  616. SetVisibility(LogisticsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  617. SetVisibility(LogisticsMapButton, bMaps);
  618. SetVisibility(LogisticsDailyReportButton,
  619. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  620. SetVisibility(ReadyToGoItemsButton,
  621. ClientFactory.IsSupported<DeliveryItem>() && Security.IsAllowed<CanViewLogisticsReadyToGo>());
  622. SetVisibility(DispatchButton, Security.CanView<Shipment>() && Security.CanView<DeliveryItem>());
  623. SetVisibility(RequisitionsButton, Security.CanView<Requisition>());
  624. SetVisibility(DeliveriesButton, Security.IsAllowed<CanViewDeliveriesModule>());
  625. SetVisibility(DeliveredItemsButton,
  626. ClientFactory.IsSupported<DeliveryItem>() && Security.IsAllowed<CanViewDeliveredOnSite>());
  627. SetVisibility(ConsignmentButton, Security.CanView<Consignment>());
  628. SetVisibleIfEither(LogisticsTaskSeparator1,
  629. new FrameworkElement[]
  630. {
  631. LogisticsDashboardButton, LogisticsMessagesButton, LogisticsTaskButton, LogisticsAttendanceButton, LogisticsMapButton,
  632. LogisticsDailyReportButton
  633. },
  634. new FrameworkElement[]
  635. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton });
  636. SetVisibleIfEither(LogisticsTaskSeparator2,
  637. new FrameworkElement[]
  638. { ReadyToGoItemsButton, DispatchButton, RequisitionsButton, DeliveriesButton, DeliveredItemsButton },
  639. new FrameworkElement[] { ConsignmentButton });
  640. AddSetupAction(LogisticsTab, "Delivery Types", DeliveryTypesButton_Click, PRSDesktop.Resources.truck,
  641. Security.CanView<ConsignmentType>());
  642. AddSetupAction(LogisticsTab, "Consignment Types", ConsignmentTypesButton_Click, PRSDesktop.Resources.service,
  643. Security.CanView<DeliveryType>());
  644. //LogisticsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  645. //LogisticsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  646. AddSetupModulesAndReports(LogisticsTab);
  647. SetTabVisibleIfAny(LogisticsTab, DispatchButton, RequisitionsButton, DeliveriesButton, ReadyToGoItemsButton,
  648. DeliveredItemsButton,
  649. ConsignmentButton);
  650. }
  651. ),
  652. new ProgressSection(
  653. "Configuring Products",
  654. () =>
  655. {
  656. SetVisibility(ProductsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  657. SetVisibility(ProductsMessagesButton, Security.CanView<Notification>());
  658. SetVisibility(ProductsTaskButton, Security.CanView<Kanban>());
  659. SetVisibility(ProductsAttendanceButton, Security.IsAllowed<CanViewInOutBoard>());
  660. SetVisibility(ProductsMapButton, bMaps);
  661. SetVisibility(ProductsDailyReportButton,
  662. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  663. SetVisibility(ProductsMasterList, Security.CanView<Product>());
  664. SetVisibility(StockLocationList, Security.CanView<StockLocation>());
  665. SetVisibility(StockMovementList, Security.CanView<StockMovement>());
  666. SetVisibility(StockSummaryButton, Security.CanView<JobMaterial>());
  667. SetVisibleIfEither(ProductsTaskSeparator,
  668. new FrameworkElement[]
  669. {
  670. ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton, ProductsMapButton,
  671. ProductsDailyReportButton
  672. }, new FrameworkElement[] { ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton });
  673. SetVisibleIfAny(ProductActions, ProductsDashboardButton, ProductsMessagesButton, ProductsTaskButton, ProductsAttendanceButton,
  674. ProductsDailyReportButton, ProductsMasterList, StockLocationList, StockMovementList, StockSummaryButton);
  675. AddSetupAction(ProductTab, "Product Dimensions", ProductDimensionUnitsList_Click, PRSDesktop.Resources.unitofmeasure,
  676. Security.CanView<ProductDimensionUnit>());
  677. AddSetupAction(ProductTab, "Product Groups", ProductGroupsList_Click, PRSDesktop.Resources.productgroup,
  678. Security.CanView<ProductGroup>());
  679. AddSetupAction(ProductTab, "Product Styles", ProductStylesList_Click, PRSDesktop.Resources.palette,
  680. Security.CanView<ProductStyle>());
  681. AddSetupAction(ProductTab, "Stock Areas", StockAreasList_Click, PRSDesktop.Resources.rack,
  682. Security.CanView<StockArea>());
  683. AddSetupAction(ProductTab, "Stock Warehouses", StockWarehouseList_Click, PRSDesktop.Resources.factorysetup,
  684. Security.CanView<StockWarehouse>());
  685. AddSetupSeparator(ProductTab);
  686. AddSetupAction(ProductTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Product>(), PRSDesktop.Resources.box,
  687. Security.CanView<ProductSpreadsheet>());
  688. AddSetupModulesAndReports(ProductTab);
  689. SetTabVisibleIfAny(ProductTab, ProductActions);
  690. }
  691. ),
  692. new ProgressSection(
  693. "Configuring Human Resources",
  694. () =>
  695. {
  696. SetVisibility(HumanResourcesDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  697. SetVisibility(HumanResourcesMessagesButton, Security.CanView<Notification>());
  698. SetVisibility(HumanResourcesTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  699. SetVisibility(HumanResourcesAttendanceButton,
  700. ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  701. SetVisibility(HumanResourcesMapButton, bMaps);
  702. SetVisibility(HumanResourcesDailyReportButton,
  703. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  704. SetVisibility(AssignmentsButton, Security.CanView<Assignment>());
  705. SetVisibility(EmployeePlannerButton, Security.CanView<Assignment>());
  706. SetVisibility(TimesheetsButton, Security.CanView<TimeSheet>());
  707. SetVisibility(LeaveRequestsButton, Security.CanView<LeaveRequest>());
  708. SetVisibility(OrgChartButton,
  709. ClientFactory.IsSupported<Employee>()
  710. && (
  711. Security.IsAllowed<CanViewOrgChartByEmployee>()
  712. || Security.IsAllowed<CanViewOrgChartByPosition>()
  713. || Security.IsAllowed<CanViewOrgChartByRole>()
  714. )
  715. );
  716. SetVisibleIfEither(HumanResourcesTaskSeparator,
  717. new FrameworkElement[]
  718. {
  719. HumanResourcesDashboardButton, HumanResourcesMessagesButton, HumanResourcesTaskButton, HumanResourcesAttendanceButton,
  720. HumanResourcesMapButton, HumanResourcesDailyReportButton
  721. }, new FrameworkElement[] { AssignmentsButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton });
  722. SetVisibleIfAny(HumanResourcesActions, HumanResourcesDashboardButton, HumanResourcesTaskButton,
  723. HumanResourcesAttendanceButton,
  724. HumanResourcesDailyReportButton, AssignmentsButton, EmployeePlannerButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton);
  725. SetVisibility(UsersButton, Security.CanView<User>());
  726. SetVisibility(EmployeesButton, Security.CanView<Employee>());
  727. AddSetupAction(HumanResourcesTab, "Security Groups", SecurityGroupsButton_Click, PRSDesktop.Resources.securitygroup,
  728. Security.CanView<SecurityGroup>());
  729. AddSetupSeparator(HumanResourcesTab);
  730. AddSetupAction(HumanResourcesTab, "Employee Groups", GroupsSetup_Click, PRSDesktop.Resources.employees,
  731. Security.CanView<EmployeeGroup>());
  732. AddSetupAction(HumanResourcesTab, "Positions", PositionsSetup_Click, PRSDesktop.Resources.position,
  733. Security.CanView<EmployeePosition>());
  734. AddSetupAction(HumanResourcesTab, "Roles", RolesSetup_Click, PRSDesktop.Resources.employeerole,
  735. Security.CanView<EmployeeRole>());
  736. AddSetupAction(HumanResourcesTab, "Teams", EmployeeTeamsButton_Click, PRSDesktop.Resources.team,
  737. Security.CanView<EmployeeTeam>());
  738. AddSetupAction(HumanResourcesTab, "Activities", ActivityMenu_Click, PRSDesktop.Resources.quality,
  739. Security.CanView<Activity>());
  740. AddSetupAction(HumanResourcesTab, "Qualifications", QualificationMenu_Click, PRSDesktop.Resources.certificate,
  741. Security.CanView<Qualification>());
  742. AddSetupAction(HumanResourcesTab, "Rosters", RosterMenu_Click, PRSDesktop.Resources.assignments,
  743. Security.CanView<EmployeeRoster>());
  744. AddSetupSeparator(HumanResourcesTab);
  745. // AddSetupAction(HumanResourcesTab, "Rosters", RostersButton_Click, PRSDesktop.Resources.attendance,
  746. // Security.CanView<Roster>());
  747. AddSetupAction(HumanResourcesTab, "Overtime Rules", OvertimeRulesButton_Click, PRSDesktop.Resources.overtime,
  748. Security.CanView<OvertimeRule>());
  749. AddSetupAction(HumanResourcesTab, "Standard Leave", StandardLeaveButton_Click, PRSDesktop.Resources.fireworks,
  750. Security.CanView<StandardLeave>());
  751. SetVisibleIfEither(HumanResourcesSetupSeparator1,
  752. new FrameworkElement[] { AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton },
  753. new FrameworkElement[] { UsersButton, EmployeesButton });
  754. //HumanResourcesActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  755. //HumanResourcesReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  756. AddSetupSeparator(HumanResourcesTab);
  757. AddSetupAction(HumanResourcesTab, "Spreadsheet Templates", () => ViewSpreadsheetTemplates<Employee>(), PRSDesktop.Resources.box,
  758. Security.CanView<EmployeeSpreadsheet>());
  759. AddSetupModulesAndReports(HumanResourcesTab);
  760. SetTabVisibleIfAny(HumanResourcesTab, AssignmentsButton, TimesheetsButton, LeaveRequestsButton, OrgChartButton, UsersButton, EmployeesButton);
  761. }
  762. ),
  763. new ProgressSection(
  764. "Configuring Accounts",
  765. () =>
  766. {
  767. SetVisibility(AccountsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  768. SetVisibility(AccountsMessagesButton, Security.CanView<Notification>());
  769. SetVisibility(AccountsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  770. SetVisibility(AccountsDataButton, Security.IsAllowed<CanViewDataEntryPanel>());
  771. SetVisibility(AccountsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  772. SetVisibility(AccountsMapButton, bMaps);
  773. SetVisibility(AccountsDailyReportButton,
  774. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  775. SetVisibility(CustomerList, ClientFactory.IsSupported<Customer>() && Security.CanView<Customer>());
  776. SetVisibility(InvoiceList, ClientFactory.IsSupported<Invoice>() && Security.CanView<Invoice>());
  777. SetVisibility(ReceiptList, ClientFactory.IsSupported<Receipt>() && Security.CanView<Receipt>());
  778. SetVisibility(SupplierList, ClientFactory.IsSupported<Supplier>() && Security.CanView<Supplier>());
  779. SetVisibility(PurchasesList, ClientFactory.IsSupported<PurchaseOrder>() && Security.CanView<PurchaseOrder>());
  780. SetVisibility(BillsList, ClientFactory.IsSupported<Bill>() && Security.CanView<Bill>());
  781. SetVisibility(PaymentsList, ClientFactory.IsSupported<Payment>() && Security.CanView<Payment>());
  782. SetVisibleIfEither(AccountsTaskSeparator1,
  783. new FrameworkElement[]
  784. {
  785. AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton, AccountsAttendanceButton, AccountsMapButton,
  786. AccountsDailyReportButton
  787. }, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList });
  788. SetVisibleIfEither(AccountsTaskSeparator2, new FrameworkElement[] { CustomerList, InvoiceList, ReceiptList },
  789. new FrameworkElement[] { SupplierList, PurchasesList, BillsList, PaymentsList });
  790. SetVisibleIfAny(AccountsActions, AccountsDashboardButton, AccountsMessagesButton, AccountsTaskButton,
  791. AccountsAttendanceButton,
  792. AccountsDailyReportButton, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  793. AddSetupAction(AccountsTab, "Contact Types", ContactTypeList_Click, PRSDesktop.Resources.contacttype,
  794. ClientFactory.IsSupported<Contact>() && Security.CanView<ContactType>());
  795. AddSetupAction(AccountsTab, "Tax Codes", TaxCodeList_Click, PRSDesktop.Resources.taxcode,
  796. ClientFactory.IsSupported<GLCode>() && Security.CanView<TaxCode>());
  797. AddSetupAction(AccountsTab, "Receipt Types", ReceiptTypeList_Click, PRSDesktop.Resources.receipt,
  798. ClientFactory.IsSupported<GLCode>() && Security.CanView<ReceiptType>());
  799. AddSetupAction(AccountsTab, "Payment Types", PaymentTypeList_Click, PRSDesktop.Resources.payment,
  800. ClientFactory.IsSupported<GLCode>() && Security.CanView<PaymentType>());
  801. AddSetupAction(AccountsTab, "Cost Centres", CostCentresList_Click, PRSDesktop.Resources.costcentre,
  802. ClientFactory.IsSupported<CostCentre>() && Security.CanView<CostCentre>());
  803. AddSetupAction(AccountsTab, "GL Codes", GLCodesList_Click, PRSDesktop.Resources.glcode,
  804. ClientFactory.IsSupported<GLCode>() && Security.CanView<GLCode>());
  805. AddSetupAction(AccountsTab, "Purchase Order Categories", PurchaseOrderCategoriesButton_Click, PRSDesktop.Resources.service,
  806. ClientFactory.IsSupported<PurchaseOrderCategory>() && Security.CanView<PurchaseOrderCategory>());
  807. //AccountsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  808. //AccountsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  809. AddSetupSeparator(AccountsTab);
  810. AddSetupAction(AccountsTab, "Customer Spreadsheet Templates", () => ViewSpreadsheetTemplates<Customer>(), PRSDesktop.Resources.box,
  811. Security.CanView<CustomerSpreadsheet>());
  812. AddSetupAction(AccountsTab, "Supplier Spreadsheet Templates", () => ViewSpreadsheetTemplates<Supplier>(), PRSDesktop.Resources.box,
  813. Security.CanView<SupplierSpreadsheet>());
  814. AddSetupModulesAndReports(AccountsTab);
  815. SetTabVisibleIfAny(AccountsTab, CustomerList, InvoiceList, ReceiptList, SupplierList, PurchasesList, BillsList, PaymentsList);
  816. }
  817. ),
  818. new ProgressSection(
  819. "Configuring Equipment",
  820. () =>
  821. {
  822. SetVisibility(EquipmentDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  823. SetVisibility(EquipmentMessagesButton, Security.CanView<Notification>());
  824. SetVisibility(EquipmentTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  825. SetVisibility(EquipmentAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  826. SetVisibility(EquipmentMapButton, bMaps);
  827. SetVisibility(EquipmentDailyReportButton,
  828. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  829. SetVisibility(EquipmentButton, ClientFactory.IsSupported<Equipment>() && Security.CanView<Equipment>());
  830. SetVisibleIfEither(EquipmentTaskSeparator,
  831. new FrameworkElement[]
  832. {
  833. EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton, EquipmentAttendanceButton, EquipmentMapButton,
  834. EquipmentDailyReportButton
  835. }, new FrameworkElement[] { EquipmentButton });
  836. SetVisibleIfAny(EquipmentActions, EquipmentDashboardButton, EquipmentMessagesButton, EquipmentTaskButton,
  837. EquipmentAttendanceButton, EquipmentDailyReportButton, EquipmentButton);
  838. SetVisibility(TrackersMasterList, Security.CanView<GPSTracker>());
  839. AddSetupAction(EquipmentTab, "Tracker Types", TrackerTypes_Click, PRSDesktop.Resources.milestone,
  840. Security.CanView<GPSTrackerType>());
  841. AddSetupAction(EquipmentTab, "Stickers", Stickers_Click, PRSDesktop.Resources.barcode,
  842. Security.CanView<WebSticker>());
  843. AddSetupAction(EquipmentTab, "Digital Keys", DigitalKeys_Click, PRSDesktop.Resources.key,
  844. Security.CanView<DigitalKey>());
  845. AddSetupAction(EquipmentTab, "Equipment Groups", EquipmentGroupList_Click, PRSDesktop.Resources.specifications,
  846. Security.CanView<EquipmentGroup>());
  847. //EquipmentActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  848. //EquipmentReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  849. AddSetupModulesAndReports(EquipmentTab);
  850. SetTabVisibleIfAny(EquipmentTab, EquipmentButton, TrackersMasterList);
  851. }
  852. ),
  853. new ProgressSection(
  854. "Configuring Dashboards",
  855. () =>
  856. {
  857. SetVisibility(DashboardsDashboardButton, Security.IsAllowed<CanViewUserDefinedDashboards>());
  858. SetVisibility(DashboardMessagesButton, Security.CanView<Notification>());
  859. SetVisibility(DashboardsTaskButton, ClientFactory.IsSupported<Kanban>() && Security.IsAllowed<CanViewTasks>());
  860. SetVisibility(DashboardsAttendanceButton, ClientFactory.IsSupported<TimeSheet>() && Security.IsAllowed<CanViewInOutBoard>());
  861. SetVisibility(DashboardsMapButton, bMaps);
  862. SetVisibility(DashboardsDailyReportButton,
  863. ClientFactory.IsSupported<TimeSheet, Assignment>() && Security.IsAllowed<CanViewDailyReports>());
  864. SetVisibility(FactoryProductivityButton,
  865. ClientFactory.IsSupported<ManufacturingHistory>() && Security.IsAllowed<CanViewFactoryKPIs>());
  866. SetVisibility(TemplateAnalysisButton,
  867. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>() &&
  868. Security.IsAllowed<CanViewTemplateAnalysis>());
  869. SetVisibility(FactoryAnalysisButton,
  870. ClientFactory.IsSupported<ManufacturingTemplate, ManufacturingHistory>() && Security.IsAllowed<CanViewFactoryAnalysis>());
  871. SetVisibility(DatabaseActivityButton,
  872. ClientFactory.IsSupported<UserTracking>() && Security.IsAllowed<CanViewDatabaseActivity>());
  873. SetVisibility(UserActivityButton, ClientFactory.IsSupported<ModuleTracking>() && Security.IsAllowed<CanViewUserActivity>());
  874. SetVisibility(QAAnalysisButton, Security.IsAllowed<CanViewDigitalFormsDashbaord>());
  875. SetVisibility(QuickStatusButton, Security.IsAllowed<CanViewQuickStatus>());
  876. SetVisibleIfEither(DashboardsTaskSeparator,
  877. new FrameworkElement[]
  878. {
  879. DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton, DashboardsAttendanceButton,
  880. DashboardsMapButton,
  881. DashboardsDailyReportButton
  882. },
  883. new FrameworkElement[]
  884. {
  885. FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton,
  886. QAAnalysisButton, QuickStatusButton
  887. });
  888. SetVisibleIfAny(DashboardsActions, DashboardsDashboardButton, DashboardMessagesButton, DashboardsTaskButton,
  889. DashboardsAttendanceButton, DashboardsDailyReportButton, FactoryProductivityButton, TemplateAnalysisButton,
  890. FactoryAnalysisButton, DatabaseActivityButton, UserActivityButton, QAAnalysisButton, QuickStatusButton);
  891. //DashboardsActions.IsLauncherButtonVisible = Security.IsAllowed<CanCustomiseModules>();
  892. //DashboardsReports.IsLauncherButtonVisible = Security.IsAllowed<CanDesignReports>();
  893. AddSetupModulesAndReports(DashboardsTab);
  894. SetVisibleIfAny(DashboardsTab, FactoryProductivityButton, TemplateAnalysisButton, FactoryAnalysisButton,
  895. DatabaseActivityButton,
  896. UserActivityButton, QAAnalysisButton, QuickStatusButton);
  897. }
  898. ),
  899. new ProgressSection(
  900. "Configuring System Modules",
  901. () =>
  902. {
  903. SetVisibility(CompanyInformation, Security.CanView<CompanyInformation>());
  904. SetVisibleIfAny(BackstageSeparator0, CompanyInformation);
  905. SetVisibility(SecurityDefaultsButton,
  906. ClientFactory.IsSupported<GlobalSecurityToken>() && Security.IsAllowed<CanCustomiseSecurityDefaults>());
  907. SetVisibleIfAny(BackstageSeparator1, SecurityDefaultsButton);
  908. BackstageSeparator1a.Visibility = Visibility.Visible;
  909. SystemLogsButton.Visibility = Visibility.Visible;
  910. SetVisibility(DocumentTypeList, ClientFactory.IsSupported<DocumentType>() && Security.IsAllowed<CanViewDocumentTypes>());
  911. SetVisibility(DocumentList, ClientFactory.IsSupported<Document>() && Security.IsAllowed<CanViewDocumentList>());
  912. SetVisibility(QAFormSetupButton,
  913. ClientFactory.IsSupported<DigitalForm>() && Security.IsAllowed<CanAdministerDigitalFormsLibrary>());
  914. SetVisibleIfAny(BackstageSeparator2, DocumentTypeList, DocumentList, QAFormSetupButton);
  915. SetVisibility(VideoRecordingButton, Security.IsAllowed<CanRecordScreen>());
  916. LogoutButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  917. LoginButton.Visibility = ClientFactory.UserGuid != Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  918. EditDetailsButton.Visibility = ClientFactory.UserGuid == Guid.Empty ? Visibility.Collapsed : Visibility.Visible;
  919. SetupDock<CanViewContactsDock>(ContactDock, Contacts);
  920. SetupDock<CanViewJobDock>(JobDock, Jobs);
  921. SetupDock<CanViewConsignmentDock>(ConsignmentDock, Consignments);
  922. SetupDock<CanViewDeliveryDock>(DeliveryDock, Deliveries);
  923. SetupDock<CanViewProductDock>(ProductLookupDock, ProductLookup);
  924. SetupDock<CanViewDigitalFormsDock>(DigitalFormsDock, DigitalForms);
  925. SetupDock<CanViewDataEntryPanel>(ScansDock, Scans);
  926. _ribbon.InvalidateArrange();
  927. }
  928. )
  929. );
  930. }
  931. private void ViewSpreadsheetTemplates<TEntity>() where TEntity : Entity
  932. {
  933. SpreadsheetTemplateGrid grid = new SpreadsheetTemplateGrid();
  934. grid.AppliesTo = typeof(TEntity);
  935. grid.Refresh(true, true);
  936. DynamicContentDialog dlg = new DynamicContentDialog(grid,false);
  937. dlg.Title = $"{typeof(TEntity).EntityName().Split(".").Last()} Spreadsheet Templates";
  938. dlg.ShowDialog();
  939. }
  940. private IEnumerable<ReportExportDefinition> AddTemplateDefinitions()
  941. {
  942. if (CurrentPanel == null)
  943. return new List<ReportExportDefinition>() { new ReportExportDefinition("Email Report", PRSDesktop.Resources.email, ReportExportType.PDF,
  944. EmailUtils.DoEmailReport)};
  945. else
  946. return EmailUtils.CreateTemplateDefinitions(CurrentPanel.DataModel(Selection.None));
  947. }
  948. private void SetupDock<TSecurityDescriptor>(LayoutAnchorable layout, IDockPanel dock)
  949. where TSecurityDescriptor : ISecurityDescriptor, new()
  950. {
  951. if (Security.IsAllowed<TSecurityDescriptor>())
  952. {
  953. if (!DockGroup.Children.Any(x => x == layout))
  954. {
  955. DockGroup.Children.Add(layout);
  956. }
  957. if (layout.IsVisible && (ClientFactory.UserGuid != Guid.Empty))
  958. dock.Setup();
  959. }
  960. else
  961. {
  962. DockGroup.RemoveChild(layout);
  963. }
  964. }
  965. private void LoadApplicationState()
  966. {
  967. if (ClientFactory.UserGuid != Guid.Empty)
  968. {
  969. _ribbon.IsCollapsed = false;
  970. if (OutstandingDailyReports(false))
  971. {
  972. MessageBox.Show("There are outstanding Daily Reports that must be filled out before continuing!" +
  973. "\n\nAccess to PRS is restricted until this is corrected.",
  974. "Outstanding Reports"
  975. );
  976. var dailyReportPanel = LoadWindow<DailyReport>(ProjectDailyReportButton);
  977. dailyReportPanel.OnTimeSheetConfirmed += e =>
  978. {
  979. if (!OutstandingDailyReports(true))
  980. {
  981. ConfigureMainScreen();
  982. LoadApplicationState();
  983. }
  984. };
  985. return;
  986. }
  987. using (new WaitCursor())
  988. {
  989. _ribbon.IsCollapsed = false;
  990. LoadInitialWindow();
  991. }
  992. }
  993. }
  994. private void LoadInitialWindow()
  995. {
  996. var app = new LocalConfiguration<AppSettings>().Load();
  997. if (app.Settings.ContainsKey("CurrentPanel"))
  998. {
  999. try
  1000. {
  1001. var bFound = false;
  1002. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1003. if (module.Length == 2)
  1004. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1005. {
  1006. if (String.Equals(tab.Header, module.First()))
  1007. {
  1008. _ribbon.SelectedTabItem = tab;
  1009. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1010. {
  1011. foreach (var item in bar.Items)
  1012. {
  1013. var button = item as Fluent.Button;
  1014. if (button != null && String.Equals(button.Header, module.Last()))
  1015. {
  1016. bFound = true;
  1017. button.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
  1018. break;
  1019. }
  1020. }
  1021. if (bFound)
  1022. break;
  1023. }
  1024. }
  1025. if (bFound)
  1026. break;
  1027. }
  1028. }
  1029. catch (Exception e)
  1030. {
  1031. MessageBox.Show(string.Format("Unable to Load {0}!\n\n{1}\n{2}", app.Settings["CurrentPanel"], e.Message, e.StackTrace));
  1032. }
  1033. }
  1034. }
  1035. private void _ribbon_OnLoaded(object sender, RoutedEventArgs e)
  1036. {
  1037. _ribbon.SelectedTabItem = CurrentTab;
  1038. }
  1039. private void LoadSecondaryWindows()
  1040. {
  1041. if (ClientFactory.UserGuid != Guid.Empty)
  1042. {
  1043. var windows = App.DatabaseSettings.SecondaryWindows;
  1044. foreach (var key in windows.Keys.ToArray())
  1045. {
  1046. _secondarywindows[key] = new SecondaryWindow(
  1047. key,
  1048. windows[key].Item1,
  1049. windows[key].Item2,
  1050. windows[key].Item3,
  1051. windows[key].Item4,
  1052. windows[key].Item5,
  1053. windows[key].Item6
  1054. );
  1055. _secondarywindows[key].Closed += (o, e) => { _secondarywindows.Remove(key); };
  1056. _secondarywindows[key].Show();
  1057. }
  1058. }
  1059. else
  1060. {
  1061. foreach (var key in _secondarywindows.Keys.ToArray())
  1062. {
  1063. App.IsClosing = true;
  1064. _secondarywindows[key].Close();
  1065. App.IsClosing = false;
  1066. }
  1067. }
  1068. }
  1069. private Fluent.RibbonTabItem GetTabItem(FrameworkElement? sender)
  1070. {
  1071. if (sender == null)
  1072. throw new Exception("No Tab Found!");
  1073. if (sender is Fluent.RibbonTabItem)
  1074. return (Fluent.RibbonTabItem)sender;
  1075. return GetTabItem(sender.Parent as FrameworkElement);
  1076. }
  1077. private T LoadWindow<T>(Fluent.Button sender) where T : IBasePanel, new()
  1078. {
  1079. using (new WaitCursor())
  1080. {
  1081. UnloadWindow();
  1082. CurrentTab = GetTabItem(sender);
  1083. CurrentButton = sender;
  1084. //CurrentButton.IsSelected = true;
  1085. UpdateRibbonColors();
  1086. var panel = new T();
  1087. CurrentPanel = panel;
  1088. ReportUtils.ExportDefinitions.Clear();
  1089. ReportUtils.ExportDefinitions.AddRange(AddTemplateDefinitions());
  1090. InitializePanelProperties(panel);
  1091. CurrentPanel.IsReady = false;
  1092. CurrentPanel.Setup();
  1093. CurrentPanel.IsReady = true;
  1094. CurrentPanel.OnUpdateDataModel += (s, m) =>
  1095. {
  1096. ReloadModules(s, m);
  1097. ReloadReports(s, m);
  1098. };
  1099. CurrentPanel_Label = sender.Header?.ToString() ?? "";
  1100. CurrentPanel_Ticks = DateTime.Now;
  1101. ContentControl.Content = CurrentPanel;
  1102. Title =
  1103. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1104. if (sender != null)
  1105. {
  1106. var model = CurrentPanel.DataModel(Selection.None);
  1107. var section = CurrentPanel.SectionName;
  1108. ReloadModules(section, model);
  1109. ReloadReports(section, model);
  1110. }
  1111. CurrentPanel.Refresh();
  1112. if (CurrentPanel is NotificationPanel)
  1113. {
  1114. Logger.Send(LogType.Information, ClientFactory.UserID, "Disabling Heartbeat");
  1115. NotificationsWatchDog.IsEnabled = false;
  1116. Notifications.Visibility = Visibility.Collapsed;
  1117. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  1118. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  1119. }
  1120. else
  1121. {
  1122. ReloadNotifications();
  1123. }
  1124. if (sender != null)
  1125. {
  1126. var settings = new LocalConfiguration<AppSettings>().Load();
  1127. var module = string.Format("{0} / {1}", CurrentTab?.Header, sender.Header);
  1128. if (!settings.Settings.ContainsKey("CurrentPanel") || module != settings.Settings["CurrentPanel"])
  1129. {
  1130. settings.Settings["CurrentPanel"] = module;
  1131. try
  1132. {
  1133. new LocalConfiguration<AppSettings>().Save(settings);
  1134. }
  1135. catch (Exception e)
  1136. {
  1137. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1138. }
  1139. }
  1140. }
  1141. //stopwatch.Stop();
  1142. //Logger.Send(LogType.Information, ClientFactory.UserID, String.Format("Loading {0} to took {1} ms", sender != null ? sender.Label : module, stopwatch.ElapsedMilliseconds));
  1143. return panel;
  1144. }
  1145. }
  1146. private void UpdateRibbonColors()
  1147. {
  1148. foreach (var tab in _ribbon.Tabs)
  1149. {
  1150. bool bFound = false;
  1151. foreach (var grp in tab.Groups)
  1152. {
  1153. foreach (var btn in grp.Items)
  1154. {
  1155. if (btn is Fluent.Button fluentbutton)
  1156. {
  1157. bFound = bFound || (btn == CurrentButton);
  1158. fluentbutton.Background = (btn == CurrentButton) ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1159. fluentbutton.Foreground = (btn == CurrentButton) ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1160. }
  1161. }
  1162. tab.Background = bFound ? ThemeManager.SelectedTabItemBackgroundBrush : new SolidColorBrush(Colors.White);
  1163. tab.Foreground = bFound ? ThemeManager.SelectedTabItemForegroundBrush : new SolidColorBrush(Colors.Black);
  1164. }
  1165. }
  1166. }
  1167. private static void StartLocalDatabase(IProgress<string> progress)
  1168. {
  1169. var dirName = Path.GetDirectoryName(App.DatabaseSettings.FileName);
  1170. if (!Directory.Exists(dirName) && dirName != null)
  1171. Directory.CreateDirectory(dirName);
  1172. var FileName = App.DatabaseSettings.FileName;
  1173. var Exists = File.Exists(FileName);
  1174. progress.Report("Configuring Stores");
  1175. DbFactory.Stores = CoreUtils.TypeList(
  1176. new[]
  1177. {
  1178. typeof(DocumentStore).Assembly,
  1179. typeof(EquipmentStore).Assembly
  1180. },
  1181. myType =>
  1182. myType.IsClass
  1183. && !myType.IsAbstract
  1184. && !myType.IsGenericType
  1185. && myType.GetInterfaces().Contains(typeof(IStore))
  1186. ).ToArray();
  1187. DbFactory.Provider = new SQLiteProvider(App.DatabaseSettings.FileName);
  1188. DbFactory.ColorScheme = App.DatabaseSettings.ColorScheme;
  1189. DbFactory.Logo = App.DatabaseSettings.Logo;
  1190. progress.Report("Starting Local Database");
  1191. var deviceid = DeviceID.Value(App.DatabaseSettings.Port.ToString(), null); //, (m) => Logger.Send(LogType.Information, "", m));
  1192. DbFactory.Start(deviceid);
  1193. progress.Report("Checking Database");
  1194. var users = DbFactory.Provider.Load<User>();
  1195. if (!users.Any())
  1196. {
  1197. var user = new User { UserID = "ADMIN", Password = "admin" };
  1198. DbFactory.Provider.Save(user);
  1199. var employee = DbFactory.Provider.Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN")).FirstOrDefault();
  1200. employee ??= new Employee { Code = "ADMIN", Name = "Administrator Account" };
  1201. employee.UserLink.ID = user.ID;
  1202. DbFactory.Provider.Save(employee);
  1203. }
  1204. StoreUtils.GoogleAPIKey = App.DatabaseSettings.GoogleAPIKey;
  1205. JobStore.AutoIncrementPrefix = App.DatabaseSettings.JobPrefix;
  1206. PurchaseOrderStore.AutoIncrementPrefix = App.DatabaseSettings.PurchaseOrderPrefix;
  1207. }
  1208. #endregion
  1209. #region Login Management
  1210. private ValidationResult? DoLogin(bool autoLogin)
  1211. {
  1212. ValidationResult? result = null;
  1213. if (autoLogin)
  1214. {
  1215. if (App.DatabaseSettings.LoginType == LoginType.UserID)
  1216. {
  1217. try
  1218. {
  1219. result = ClientFactory.Validate(App.DatabaseSettings.UserID, App.DatabaseSettings.Password);
  1220. }
  1221. catch (Exception e)
  1222. {
  1223. Logger.Send(LogType.Error, ClientFactory.UserID, $"Error connecting to server: {CoreUtils.FormatException(e)}");
  1224. MessageBox.Show("Error connecting to server.\nPlease check the server URL and port number.");
  1225. result = null;
  1226. }
  1227. if (result == ValidationResult.INVALID)
  1228. {
  1229. MessageBox.Show("Unable to Login with User ID: " + App.DatabaseSettings.UserID);
  1230. }
  1231. }
  1232. }
  1233. if (result != ValidationResult.VALID)
  1234. {
  1235. var login = new PinLogin(CoreUtils.GetVersion(), result ?? ValidationResult.INVALID);
  1236. if (login.ShowDialog() == true)
  1237. {
  1238. result = ValidationResult.VALID;
  1239. }
  1240. }
  1241. return result ?? ValidationResult.INVALID;
  1242. }
  1243. /// <summary>
  1244. /// To be called after <see cref="DoLogin(bool)"/> and if a valid login session exists. Configures the main screen and loads the windows.
  1245. /// </summary>
  1246. private void AfterLogin()
  1247. {
  1248. LoadCurrentEmployee();
  1249. if (CheckTimesheetBypass(true))
  1250. {
  1251. UpdateCurrentLogin();
  1252. }
  1253. else
  1254. {
  1255. MessageBox.Show("You must clock on before logging in to PRS!");
  1256. ClientFactory.InvalidateUser();
  1257. App.EmployeeID = Guid.Empty;
  1258. }
  1259. ApplyColorScheme();
  1260. ConfigureMainScreen();
  1261. LoadApplicationState();
  1262. LoadSecondaryWindows();
  1263. //if (_ribbon.Menu.IsVisible)
  1264. //{
  1265. // _ribbon.;
  1266. //}
  1267. }
  1268. /// <summary>
  1269. /// 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.
  1270. /// </summary>
  1271. private void UpdateCurrentLogin()
  1272. {
  1273. if (CoreUtils.GetVersion().Equals("???"))
  1274. return;
  1275. // Register this station with the Server
  1276. // Later on, the heartbeat will check to make sure
  1277. // that the StationID hasn't changed. If it has,
  1278. // then we've logged in somewhere else and we'll
  1279. // drop out of this station
  1280. var curr = new Client<Login>().Query(
  1281. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  1282. null
  1283. ).Rows.FirstOrDefault();
  1284. if (curr != null)
  1285. {
  1286. var c = curr.ToObject<Login>();
  1287. c.StationID = station.StationID;
  1288. station = c;
  1289. }
  1290. else
  1291. {
  1292. station.User.ID = ClientFactory.UserGuid;
  1293. station.TimeStamp = DateTime.Now;
  1294. }
  1295. new Client<Login>().Save(station, "", (o, e) => { });
  1296. }
  1297. private void LoadCurrentEmployee()
  1298. {
  1299. var me = new Client<Employee>().Query(
  1300. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid),
  1301. new Columns<Employee>(x => x.ID).Add(x => x.Email)
  1302. );
  1303. App.EmployeeID = me.Rows.FirstOrDefault()?.Get<Employee, Guid>(x => x.ID) ?? Guid.Empty;
  1304. App.EmployeeEmail = me.Rows.FirstOrDefault()?.Get<Employee, String>(x => x.Email) ?? "";
  1305. }
  1306. private void ExecuteLogout()
  1307. {
  1308. new Client<Login>().Delete(station, "");
  1309. station.ID = Guid.Empty;
  1310. App.EmployeeID = Guid.Empty;
  1311. }
  1312. /// <summary>
  1313. /// Logs the user out and unloads windows
  1314. /// </summary>
  1315. /// <param name="message">A message to display as the reason for logging out, or <c>null</c> for no message.</param>
  1316. private bool Logout(string? message = null, bool force = false)
  1317. {
  1318. // 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,
  1319. // all the queries that get called here will throw exceptions and thus break our system, failing to log out.
  1320. try
  1321. {
  1322. FinalizeAutoTimesheet();
  1323. }
  1324. catch
  1325. {
  1326. if (!force) throw;
  1327. }
  1328. // Try to unload the window;
  1329. try
  1330. {
  1331. UnloadWindow();
  1332. if (DatabaseType == DatabaseType.Standalone && !CoreUtils.GetVersion().Equals("???"))
  1333. scheduler.Stop();
  1334. }
  1335. catch
  1336. {
  1337. if (!force) throw;
  1338. }
  1339. // Next, try to set things to being empty
  1340. try
  1341. {
  1342. if (!CoreUtils.GetVersion().Equals("???"))
  1343. if (station.ID != Guid.Empty)
  1344. {
  1345. ExecuteLogout();
  1346. }
  1347. ClearTrackingKanban();
  1348. }
  1349. catch
  1350. {
  1351. if (!force) throw;
  1352. }
  1353. ClientFactory.InvalidateUser();
  1354. ConfigureMainScreen();
  1355. LoadSecondaryWindows();
  1356. if (message != null)
  1357. {
  1358. MessageBox.Show(message);
  1359. }
  1360. if (DoLogin(false) == ValidationResult.VALID)
  1361. {
  1362. AfterLogin();
  1363. }
  1364. return true;
  1365. }
  1366. #endregion
  1367. #region Timesheets
  1368. private void RefreshTimeSheets()
  1369. {
  1370. if (App.EmployeeID == Guid.Empty)
  1371. return;
  1372. var filter = new Filter<TimeSheet>(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID);
  1373. filter = filter.And(new Filter<TimeSheet>(x => x.Confirmed).IsEqualTo(DateTime.MinValue).Or(x => x.Date).IsEqualTo(DateTime.Today));
  1374. _timesheets = new Client<TimeSheet>().Query(
  1375. filter,
  1376. new Columns<TimeSheet>(
  1377. x => x.ID,
  1378. x => x.Date,
  1379. x => x.Finish
  1380. )
  1381. );
  1382. }
  1383. private CoreTable GetTimesheet()
  1384. {
  1385. return new Client<TimeSheet>().Query(
  1386. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today)
  1387. .And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID)
  1388. .And(x => x.Finish).IsEqualTo(TimeSpan.Zero)
  1389. );
  1390. }
  1391. private bool CheckTimesheetBypass(bool message)
  1392. {
  1393. if (!ClientFactory.IsSupported<TimeSheet>())
  1394. return true;
  1395. var isClockedOn = IsClockedOn();
  1396. if (!Security.IsAllowed<CanBypassTimeBench>())
  1397. {
  1398. if (!isClockedOn)
  1399. {
  1400. if (message)
  1401. MessageBox.Show("You must clock on before opening this screen");
  1402. return false;
  1403. }
  1404. return true;
  1405. }
  1406. if (Security.IsAllowed<AutoGenerateTimesheet>())
  1407. if (!isClockedOn)
  1408. {
  1409. var ts = new TimeSheet();
  1410. ts.Date = DateTime.Today;
  1411. ts.Start = DateTime.Now.TimeOfDay;
  1412. ts.EmployeeLink.ID = App.EmployeeID;
  1413. ts.Notes = "Automatic Login from PRS Desktop";
  1414. new Client<TimeSheet>().Save(ts, "AutoLogon because Timebench Bypass is enabled", (o, e) => { });
  1415. }
  1416. return true;
  1417. }
  1418. private bool IsClockedOn()
  1419. {
  1420. RefreshTimeSheets();
  1421. if (_timesheets == null)
  1422. return false;
  1423. return _timesheets.Rows.Any(r =>
  1424. r.Get<TimeSheet, DateTime>(c => c.Date).Date == DateTime.Today && r.Get<TimeSheet, TimeSpan>(c => c.Finish) == new TimeSpan());
  1425. }
  1426. #endregion
  1427. private string CurrentPanelSlug()
  1428. {
  1429. var app = new LocalConfiguration<AppSettings>().Load();
  1430. var module = app.Settings["CurrentPanel"].Split(new[] { " / " }, StringSplitOptions.None);
  1431. return module.LastOrDefault()?.Replace(" ", "_").Replace("/", "") ?? "";
  1432. }
  1433. private bool ShowHelp()
  1434. {
  1435. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + CurrentPanelSlug()) { UseShellExecute = true });
  1436. return true;
  1437. }
  1438. private void Wiki_Click(object sender, RoutedEventArgs e)
  1439. {
  1440. ShowHelp();
  1441. }
  1442. private void Window_Loaded(object sender, RoutedEventArgs e)
  1443. {
  1444. }
  1445. private void UnloadWindow()
  1446. {
  1447. if (CurrentPanel != null)
  1448. {
  1449. Heartbeat(DateTime.Now - CurrentPanel_Ticks, true);
  1450. try
  1451. {
  1452. CurrentPanel.Shutdown();
  1453. }
  1454. catch (Exception e)
  1455. {
  1456. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Error in UnloadWindow(): {0}\n{1}", e.Message, e.StackTrace));
  1457. }
  1458. CurrentPanel_Ticks = DateTime.MinValue;
  1459. CurrentPanel_Label = "";
  1460. CurrentPanel_Clicks = 0;
  1461. CurrentPanel_Keys = 0;
  1462. Title =
  1463. $"{CurrentPanel_Label} - {(String.Equals(App.Profile?.ToUpper(), "DEFAULT") ? "PRS Desktop" : App.Profile)} (Release {CoreUtils.GetVersion()})";
  1464. if (CurrentTab != null)
  1465. {
  1466. var border = VisualUtils.EnumChildrenOfType(CurrentTab, typeof(Border)).LastOrDefault();
  1467. if (border != null)
  1468. {
  1469. ((Border)border).Background = new SolidColorBrush(Colors.Transparent);
  1470. ((Border)border).BorderBrush = new SolidColorBrush(Colors.Transparent);
  1471. }
  1472. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  1473. if (ReportsBar is not null)
  1474. {
  1475. ReportsBar.Items.Clear();
  1476. ReportsBar.Visibility = Visibility.Collapsed;
  1477. ReportsBar.IsLauncherVisible = false;
  1478. }
  1479. var ActionBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"));
  1480. if (ActionBar is not null)
  1481. {
  1482. ActionBar.IsLauncherVisible = false;
  1483. foreach (var module in CurrentModules)
  1484. ActionBar.Items.Remove(module);
  1485. }
  1486. }
  1487. }
  1488. CurrentTab = null;
  1489. CurrentButton = null;
  1490. CurrentPanel = null;
  1491. ContentControl.Content = null;
  1492. }
  1493. private void SecondaryWindow_Click(object sender, RoutedEventArgs e)
  1494. {
  1495. if (CurrentPanel == null)
  1496. return;
  1497. var id = Guid.NewGuid();
  1498. var window = new Tuple<string, string, double, double, double, double>(
  1499. CurrentPanel.GetType().EntityName(),
  1500. CurrentPanel_Label,
  1501. Left + 100,
  1502. Top + 100,
  1503. Width - 200,
  1504. Height - 200
  1505. );
  1506. App.DatabaseSettings.SecondaryWindows[id] = window;
  1507. new LocalConfiguration<DatabaseSettings>(App.Profile).Save(App.DatabaseSettings);
  1508. _secondarywindows[id] = new SecondaryWindow(
  1509. id,
  1510. window.Item1,
  1511. window.Item2,
  1512. window.Item3,
  1513. window.Item4,
  1514. window.Item5,
  1515. window.Item6
  1516. );
  1517. _secondarywindows[id].Show();
  1518. }
  1519. private void RibbonWindow_Activated(object sender, EventArgs e)
  1520. {
  1521. }
  1522. private void RegisterModules(IProgress<string> progress)
  1523. {
  1524. foreach (Fluent.RibbonTabItem tab in _ribbon.Tabs)
  1525. foreach (Fluent.RibbonGroupBox bar in tab.Groups)
  1526. foreach (var item in bar.Items)
  1527. Dispatcher.Invoke(() =>
  1528. {
  1529. var button = item as RibbonButton;
  1530. if (button != null && button.Label != "Refresh")
  1531. if (bar.Header.Equals("Actions"))
  1532. Modules.Register(button.Label);
  1533. });
  1534. //foreach (var item in _ribbon.BackStage.Items)
  1535. //{
  1536. // BackStageCommandButton button = item as BackStageCommandButton;
  1537. // if ((button != null) && (button.Header != "Log Out") && (button.Header != "Exit"))
  1538. // SecurityFactory.Register("System", button.Header, String.Format("System: Configure {0}", button.Header));
  1539. //}
  1540. }
  1541. private void SetVisibility(FrameworkElement button, bool visible)
  1542. {
  1543. var vResult = true;
  1544. var eResult = ClientFactory.UserGuid != Guid.Empty && visible;
  1545. button.Visibility = vResult && eResult ? Visibility.Visible : Visibility.Collapsed;
  1546. if (button is RibbonButton rb)
  1547. {
  1548. CustomModules.Register(rb.Label);
  1549. rb.IsEnabled = !OutstandingDailyReports(false);
  1550. }
  1551. }
  1552. private void SetVisibleIfEither(FrameworkElement separator, FrameworkElement[] left, FrameworkElement[] right)
  1553. {
  1554. var bLeft = false;
  1555. foreach (var button in left)
  1556. bLeft = bLeft || button.Visibility == Visibility.Visible;
  1557. var bRight = false;
  1558. foreach (var button in right)
  1559. bRight = bRight || button.Visibility == Visibility.Visible;
  1560. separator.Visibility = bLeft && bRight ? Visibility.Visible : Visibility.Collapsed;
  1561. }
  1562. private void SetVisibleIfAny(FrameworkElement separator, params FrameworkElement[] buttons)
  1563. {
  1564. var bVisible = false;
  1565. foreach (var button in buttons)
  1566. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1567. separator.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1568. }
  1569. private void SetTabVisibleIfAny(Fluent.RibbonTabItem tab, params FrameworkElement[] buttons)
  1570. {
  1571. var bVisible = false;
  1572. foreach (var button in buttons)
  1573. bVisible = bVisible || button.Visibility == Visibility.Visible;
  1574. bVisible = bVisible || (SetupActions.GetValueOrDefault(tab)?.Count(x => x is SetupActionItem) ?? 0) > 0;
  1575. tab.Visibility = bVisible ? Visibility.Visible : Visibility.Collapsed;
  1576. }
  1577. private Fluent.RibbonGroupBox? FindRibbonBar(Fluent.RibbonTabItem tab, Func<Fluent.RibbonGroupBox, bool> predicate)
  1578. {
  1579. foreach (var group in tab.Groups)
  1580. {
  1581. if (group != null)
  1582. if (predicate.Invoke(group))
  1583. return group;
  1584. }
  1585. return null;
  1586. }
  1587. //private Style tabselected = null;
  1588. //private Style tabunselected = null;
  1589. //private Style Getstyle(bool selected)
  1590. //{
  1591. // if (tabunselected == null)
  1592. // {
  1593. // tabunselected = new Style(typeof(TabButton));
  1594. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(Colors.Transparent));
  1595. // tabunselected.Setters.Add(st1);
  1596. // }
  1597. // if (tabselected == null)
  1598. // {
  1599. // tabselected = new Style(typeof(TabButton));
  1600. // Setter st1 = new Setter(TabButton.BackgroundProperty, new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x9E, 0xDA, 0x11)));
  1601. // tabselected.Setters.Add(st1);
  1602. // }
  1603. // return selected ? tabselected : tabunselected;
  1604. //}
  1605. #region Button Event Handlers
  1606. private void DataEntry_Click(object sender, RoutedEventArgs e)
  1607. {
  1608. LoadWindow<DataEntryPanel>((Fluent.Button)sender);
  1609. }
  1610. private void Console_Click(object sender, RoutedEventArgs a)
  1611. {
  1612. if (_console is null)
  1613. {
  1614. _console = new Console();
  1615. _console.Closing += (o, args) => _console = null;
  1616. }
  1617. _console.Show();
  1618. }
  1619. private void Quotes_Checked(object sender, RoutedEventArgs e)
  1620. {
  1621. LoadWindow<QuotePanel>((Fluent.Button)sender);
  1622. }
  1623. private void Jobs_Checked(object sender, RoutedEventArgs e)
  1624. {
  1625. LoadWindow<JobPanel>((Fluent.Button)sender);
  1626. }
  1627. private void ProjectPlanner_Checked(object sender, RoutedEventArgs e)
  1628. {
  1629. LoadWindow<JobResourcePlannerPanel>((Fluent.Button)sender);
  1630. }
  1631. private void Service_Checked(object sender, RoutedEventArgs e)
  1632. {
  1633. MessageBox.Show("Not Implemented");
  1634. //LoadWindow<JobPanel>((RibbonButton)sender);
  1635. }
  1636. private void Tasks_Checked(object sender, RoutedEventArgs e)
  1637. {
  1638. //LoadWindow<KanbanPanel>((RibbonButton)sender);
  1639. LoadWindow<TaskPanel>((Fluent.Button)sender);
  1640. }
  1641. private void ManufacturingMenu_Checked(object sender, RoutedEventArgs e)
  1642. {
  1643. LoadWindow<ManufacturingPanel>((Fluent.Button)sender);
  1644. }
  1645. // private void Schedule_Checked(object sender, RoutedEventArgs e)
  1646. // {
  1647. // LoadWindow<SchedulePanel>((RibbonButton)sender);
  1648. // }
  1649. private void FactoryFloorButton_Click(object sender, RoutedEventArgs e)
  1650. {
  1651. LoadWindow<FactoryPanel>((Fluent.Button)sender);
  1652. }
  1653. private void DispatchMenu_Checked(object sender, RoutedEventArgs e)
  1654. {
  1655. LoadWindow<DispatchPanel>((Fluent.Button)sender);
  1656. }
  1657. private void ReadyToGoMenu_Checked(object sender, RoutedEventArgs e)
  1658. {
  1659. LoadWindow<ReadyToGoPanel>((Fluent.Button)sender);
  1660. }
  1661. private void Equipment_Checked(object sender, RoutedEventArgs e)
  1662. {
  1663. LoadWindow<EquipmentPanel>((Fluent.Button)sender);
  1664. }
  1665. private void Requisitions_Checked(object sender, RoutedEventArgs e)
  1666. {
  1667. LoadWindow<RequisitionPanel>((Fluent.Button)sender);
  1668. }
  1669. //private void Purchases_Checked(object sender, RoutedEventArgs e)
  1670. //{
  1671. // LoadWindow(PurchasesMenu, new PurchasesPanel());
  1672. //}
  1673. private void Timesheets_Checked(object sender, RoutedEventArgs e)
  1674. {
  1675. LoadWindow<TimesheetPanel>((Fluent.Button)sender);
  1676. }
  1677. private void Attendance_Checked(object sender, RoutedEventArgs e)
  1678. {
  1679. LoadWindow<AttendancePanel>((Fluent.Button)sender);
  1680. }
  1681. private void Maps_Checked(object sender, RoutedEventArgs e)
  1682. {
  1683. LoadWindow<MapsPanel>((Fluent.Button)sender);
  1684. }
  1685. private void FactorySetup_Click()
  1686. {
  1687. var list = new MasterList(typeof(ManufacturingFactory));
  1688. list.ShowDialog();
  1689. }
  1690. private void TemplateSetup_Click()
  1691. {
  1692. var list = new MasterList(typeof(ManufacturingTemplate), "Factory.Name", null, true);
  1693. list.ShowDialog();
  1694. }
  1695. private void RefreshMenu_Click(object sender, RoutedEventArgs e)
  1696. {
  1697. if (CurrentPanel != null)
  1698. CurrentPanel.Refresh();
  1699. }
  1700. private void MenuItem_Click(object sender, RoutedEventArgs e)
  1701. {
  1702. }
  1703. private void QuoteStatusButton_Click()
  1704. {
  1705. var list = new MasterList(typeof(QuoteStatus));
  1706. list.ShowDialog();
  1707. }
  1708. private void QuoteDesignSectionButton_Click()
  1709. {
  1710. var list = new MasterList(typeof(QuoteDesignSection));
  1711. list.ShowDialog();
  1712. }
  1713. private void JobStatusButton_Click()
  1714. {
  1715. var list = new MasterList(typeof(JobStatus));
  1716. list.ShowDialog();
  1717. }
  1718. private void FinancialStatusButton_Click()
  1719. {
  1720. var list = new MasterList(typeof(JobFinancialStatus));
  1721. list.ShowDialog();
  1722. }
  1723. private void DrawingTemplatesButton_Click()
  1724. {
  1725. var list = new MasterList(typeof(DrawingTemplate));
  1726. list.ShowDialog();
  1727. }
  1728. private void RolesSetup_Click()
  1729. {
  1730. var list = new MasterList(typeof(Role));
  1731. list.ShowDialog();
  1732. }
  1733. private void GroupsSetup_Click()
  1734. {
  1735. var list = new MasterList(typeof(EmployeeGroup));
  1736. list.ShowDialog();
  1737. }
  1738. private void PositionsSetup_Click()
  1739. {
  1740. var list = new MasterList(typeof(EmployeePosition));
  1741. list.ShowDialog();
  1742. }
  1743. private void UserSetup_Click(object sender, RoutedEventArgs e)
  1744. {
  1745. LoadWindow<UserPanel>((Fluent.Button)sender);
  1746. //MasterList list = new MasterList(typeof(User));
  1747. //list.ShowDialog();
  1748. }
  1749. private void Employees_Click(object sender, RoutedEventArgs e)
  1750. {
  1751. LoadWindow<EmployeePanel>((Fluent.Button)sender);
  1752. //MasterList list = new MasterList(typeof(Employee));
  1753. //list.ShowDialog();
  1754. }
  1755. private void Customers_Click(object sender, RoutedEventArgs e)
  1756. {
  1757. var list = new MasterList(typeof(Customer));
  1758. list.ShowDialog();
  1759. }
  1760. private void Stickers_Click()
  1761. {
  1762. var list = new MasterList(typeof(WebSticker));
  1763. list.ShowDialog();
  1764. }
  1765. private void Trackers_Click(object sender, RoutedEventArgs e)
  1766. {
  1767. LoadWindow<GPSTrackers>((Fluent.Button)sender);
  1768. //MasterList list = new MasterList(typeof(GPSTracker));
  1769. //list.ShowDialog();
  1770. }
  1771. private void TrackerTypes_Click()
  1772. {
  1773. var list = new MasterList(typeof(GPSTrackerType));
  1774. list.ShowDialog();
  1775. }
  1776. private void DigitalKeys_Click()
  1777. {
  1778. var list = new MasterList(typeof(DigitalKey));
  1779. list.ShowDialog();
  1780. }
  1781. private void SupplierMenu_Click(object sender, RoutedEventArgs e)
  1782. {
  1783. var list = new MasterList(typeof(Supplier));
  1784. list.ShowDialog();
  1785. }
  1786. private void DeliveredOnSiteMenu_Checked(object sender, RoutedEventArgs e)
  1787. {
  1788. LoadWindow<DeliveredOnSitePanel>((Fluent.Button)sender);
  1789. }
  1790. private void DatabaseScripts_Click(object sender, RoutedEventArgs e)
  1791. {
  1792. var list = new MasterList(typeof(Script), "Section", null, true);
  1793. list.ShowDialog();
  1794. }
  1795. private void WebTemplates_Click(object sender, RoutedEventArgs e)
  1796. {
  1797. MasterList list = new MasterList(typeof(WebTemplate), null, null, true);
  1798. list.ShowDialog();
  1799. }
  1800. private void ActivityMenu_Click()
  1801. {
  1802. var list = new MasterList(typeof(Activity));
  1803. list.ShowDialog();
  1804. }
  1805. private void QualificationMenu_Click()
  1806. {
  1807. var list = new MasterList(typeof(Qualification));
  1808. list.ShowDialog();
  1809. }
  1810. private void RosterMenu_Click()
  1811. {
  1812. var list = new MasterList(typeof(EmployeeRoster));
  1813. list.ShowDialog();
  1814. }
  1815. private void Reports_LauncherClick(object sender, RoutedEventArgs e)
  1816. {
  1817. }
  1818. private void Products_Checked(object sender, RoutedEventArgs e)
  1819. {
  1820. LoadWindow<ProductsPanel>((Fluent.Button)sender);
  1821. }
  1822. private void StockLocations_Checked(object sender, RoutedEventArgs e)
  1823. {
  1824. LoadWindow<StockLocationPanel>((Fluent.Button)sender);
  1825. }
  1826. private void StockMovements_Checked(object sender, RoutedEventArgs e)
  1827. {
  1828. LoadWindow<StockMovementPanel>((Fluent.Button)sender);
  1829. }
  1830. private void StockSummaryButton_Clicked(object sender, RoutedEventArgs e)
  1831. {
  1832. LoadWindow<StockSummaryPanel>((Fluent.Button)sender);
  1833. }
  1834. private void KitsMasterList_Click(object sender, RoutedEventArgs e)
  1835. {
  1836. LoadWindow<KitPanel>((Fluent.Button)sender);
  1837. }
  1838. private void CostSheetsMasterList_Click(object sender, RoutedEventArgs e)
  1839. {
  1840. LoadWindow<CostSheetPanel>((Fluent.Button)sender);
  1841. }
  1842. private void LeaveRequestsButton_Click(object sender, RoutedEventArgs e)
  1843. {
  1844. LoadWindow<LeaveRequestPanel>((Fluent.Button)sender);
  1845. }
  1846. private void OrgChartButton_Click(object sender, RoutedEventArgs e)
  1847. {
  1848. LoadWindow<OrgChartPanel>((Fluent.Button)sender);
  1849. }
  1850. private void EquipmentGroupList_Click()
  1851. {
  1852. var list = new MasterList(typeof(EquipmentGroup));
  1853. list.ShowDialog();
  1854. }
  1855. private void KitConditionList_Click()
  1856. {
  1857. var list = new MasterList(typeof(KitCondition));
  1858. list.ShowDialog();
  1859. }
  1860. //private void KitGroupList_Click(object sender, RoutedEventArgs e)
  1861. //{
  1862. // MasterList list = new MasterList(typeof(KitGroup));
  1863. // list.ShowDialog();
  1864. //}
  1865. private void KitFormulaeList_Click()
  1866. {
  1867. var list = new MasterList(typeof(KitFormula));
  1868. list.ShowDialog();
  1869. }
  1870. private void CustomFields_Click(object sender, RoutedEventArgs e)
  1871. {
  1872. var list = new MasterList(typeof(CustomProperty), "Class", null, true);
  1873. list.ShowDialog();
  1874. }
  1875. private void CostSheetTypeList_Click()
  1876. {
  1877. var list = new MasterList(typeof(CostSheetType));
  1878. list.ShowDialog();
  1879. }
  1880. private void CostSheetBrandList_Click()
  1881. {
  1882. var list = new MasterList(typeof(CostSheetBrand));
  1883. list.ShowDialog();
  1884. }
  1885. private void CostSheetSectionList_Click()
  1886. {
  1887. var list = new MasterList(typeof(CostSheetSection));
  1888. list.ShowDialog();
  1889. }
  1890. private void ProductDimensionUnitsList_Click()
  1891. {
  1892. var list = new MasterList(typeof(ProductDimensionUnit));
  1893. list.ShowDialog();
  1894. }
  1895. private void SupplierList_Click(object sender, RoutedEventArgs e)
  1896. {
  1897. LoadWindow<SupplierPanel>((Fluent.Button)sender);
  1898. }
  1899. private void CustomerList_Click(object sender, RoutedEventArgs e)
  1900. {
  1901. LoadWindow<CustomerPanel>((Fluent.Button)sender);
  1902. }
  1903. private void ProductGroupsList_Click()
  1904. {
  1905. var list = new MasterList(typeof(ProductGroup));
  1906. list.ShowDialog();
  1907. }
  1908. private void ProductStylesList_Click()
  1909. {
  1910. var list = new MasterList(typeof(ProductStyle));
  1911. list.ShowDialog();
  1912. }
  1913. private void StockAreasList_Click()
  1914. {
  1915. var list = new MasterList(typeof(StockArea));
  1916. list.ShowDialog();
  1917. }
  1918. private void CostCentresList_Click()
  1919. {
  1920. var list = new MasterList(typeof(CostCentre));
  1921. list.ShowDialog();
  1922. }
  1923. private void GLCodesList_Click()
  1924. {
  1925. var list = new MasterList(typeof(GLCode));
  1926. list.ShowDialog();
  1927. }
  1928. private void CalendarButton_Click(object sender, RoutedEventArgs e)
  1929. {
  1930. LoadWindow<CalendarPanel>((Fluent.Button)sender);
  1931. }
  1932. private void EmployeePlannerButton_Click(object sender, RoutedEventArgs e)
  1933. {
  1934. LoadWindow<EmployeeResourcePlannerPanel>((Fluent.Button)sender);
  1935. }
  1936. private void InvoiceList_Click(object sender, RoutedEventArgs e)
  1937. {
  1938. LoadWindow<InvoicePanel>((Fluent.Button)sender);
  1939. }
  1940. private void ReceiptList_Click(object sender, RoutedEventArgs e)
  1941. {
  1942. LoadWindow<CustomerReceipts>((Fluent.Button)sender);
  1943. }
  1944. private void PaymentsList_Click(object sender, RoutedEventArgs e)
  1945. {
  1946. LoadWindow<SupplierPayments>((Fluent.Button)sender);
  1947. }
  1948. private void BillsList_Click(object sender, RoutedEventArgs e)
  1949. {
  1950. LoadWindow<SupplierBillPanel>((Fluent.Button)sender);
  1951. }
  1952. private void PurchasesList_Click(object sender, RoutedEventArgs e)
  1953. {
  1954. LoadWindow<SupplierPurchaseOrderPanel>((Fluent.Button)sender);
  1955. }
  1956. private void ReceiptTypeList_Click()
  1957. {
  1958. var list = new MasterList(typeof(ReceiptType));
  1959. list.ShowDialog();
  1960. }
  1961. private void PaymentTypeList_Click()
  1962. {
  1963. var list = new MasterList(typeof(PaymentType));
  1964. list.ShowDialog();
  1965. }
  1966. private void TaxCodeList_Click()
  1967. {
  1968. var list = new MasterList(typeof(TaxCode));
  1969. list.ShowDialog();
  1970. }
  1971. private void ContactTypeList_Click()
  1972. {
  1973. var list = new MasterList(typeof(ContactType));
  1974. list.ShowDialog();
  1975. }
  1976. private void EmployeeTeamsButton_Click()
  1977. {
  1978. var list = new MasterList(typeof(Team));
  1979. list.ShowDialog();
  1980. }
  1981. // private void RostersButton_Click()
  1982. // {
  1983. // var list = new MasterList(typeof(Roster));
  1984. // list.ShowDialog();
  1985. // }
  1986. private void OvertimeRulesButton_Click()
  1987. {
  1988. var list = new MasterList(typeof(OvertimeRule));
  1989. list.ShowDialog();
  1990. }
  1991. private void StandardLeaveButton_Click()
  1992. {
  1993. var list = new MasterList(typeof(StandardLeave));
  1994. list.ShowDialog();
  1995. }
  1996. private void SecurityGroupsButton_Click()
  1997. {
  1998. var list = new MasterList(typeof(SecurityGroup));
  1999. list.ShowDialog();
  2000. Security.Reset();
  2001. }
  2002. private void ImportDatabase_Click(object sender, RoutedEventArgs e)
  2003. {
  2004. Utility.DuplicateDatabase();
  2005. }
  2006. private void DeliveriesButton_Click(object sender, RoutedEventArgs e)
  2007. {
  2008. LoadWindow<DeliveryPanel>((Fluent.Button)sender);
  2009. }
  2010. private void TaskSetupButton_Click(object sender, RoutedEventArgs e)
  2011. {
  2012. var list = new MasterList(typeof(KanbanType));
  2013. list.ShowDialog();
  2014. }
  2015. private void TrolleySetup_Click()
  2016. {
  2017. var list = new MasterList(typeof(ManufacturingTrolley));
  2018. list.ShowDialog();
  2019. }
  2020. private void LostTimeSetup_Click()
  2021. {
  2022. var list = new MasterList(typeof(ManufacturingLostTime));
  2023. list.ShowDialog();
  2024. }
  2025. private void FactoryAllocationButton_Click(object sender, RoutedEventArgs e)
  2026. {
  2027. LoadWindow<ManufacturingAllocationPanel>((Fluent.Button)sender);
  2028. }
  2029. private void Messages_Checked(object sender, RoutedEventArgs e)
  2030. {
  2031. LoadWindow<NotificationPanel>((Fluent.Button)sender);
  2032. }
  2033. private void DatabaseActivityButton_Click(object sender, RoutedEventArgs e)
  2034. {
  2035. LoadWindow<DatabaseActivityDashboard>((Fluent.Button)sender);
  2036. }
  2037. private void FactoryProductivityButton_Click(object sender, RoutedEventArgs e)
  2038. {
  2039. LoadWindow<FactoryProductivityDashboard>((Fluent.Button)sender);
  2040. }
  2041. private void TemplateAnalysisButton_Click(object sender, RoutedEventArgs e)
  2042. {
  2043. LoadWindow<ManufacturingTemplateAnalysis>((Fluent.Button)sender);
  2044. }
  2045. private void FactoryAnalysisButton_Click(object sender, RoutedEventArgs e)
  2046. {
  2047. LoadWindow<FactoryFloorAnalysis>((Fluent.Button)sender);
  2048. }
  2049. private void UserActivityButton_Click(object sender, RoutedEventArgs e)
  2050. {
  2051. LoadWindow<UserActivity>((Fluent.Button)sender);
  2052. }
  2053. private void QAAnalysisButton_Click(object sender, RoutedEventArgs e)
  2054. {
  2055. LoadWindow<QADashboard>((Fluent.Button)sender);
  2056. }
  2057. private void QuickStatus_Click(object sender, RoutedEventArgs e)
  2058. {
  2059. LoadWindow<WidgetDashboard>((Fluent.Button)sender);
  2060. }
  2061. private void ConsignmentButton_Click(object sender, RoutedEventArgs e)
  2062. {
  2063. LoadWindow<ConsignmentsPanel>((Fluent.Button)sender);
  2064. }
  2065. private void ConsignmentTypesButton_Click()
  2066. {
  2067. var list = new MasterList(typeof(ConsignmentType));
  2068. list.ShowDialog();
  2069. }
  2070. private void PurchaseOrderCategoriesButton_Click()
  2071. {
  2072. var list = new MasterList(typeof(PurchaseOrderCategory));
  2073. list.ShowDialog();
  2074. }
  2075. private void DeliveryTypesButton_Click()
  2076. {
  2077. var list = new MasterList(typeof(DeliveryType));
  2078. list.ShowDialog();
  2079. }
  2080. private void ConfigureModules_Click(object sender, RoutedEventArgs e)
  2081. {
  2082. var window = new ModuleConfigurationWindow(DbFactory.Provider.URL);
  2083. if (window.ShowDialog() == true)
  2084. MessageBox.Show("These changes will be applied when the database is restarted!");
  2085. }
  2086. //private void NotificationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
  2087. //{
  2088. // if (NotificationsList.SelectedIndex < 0)
  2089. // return;
  2090. // var editors = NotificationsList.FindVisualChildren<InABox.DynamicGrid.ExtendedRichTextEditor>().ToArray();
  2091. // var selected = editors[NotificationsList.SelectedIndex];
  2092. // selected.Text = (String)selected.Tag; //NotificationsList.SelectedIndex.ToString();
  2093. //}
  2094. //private void ViewNotification_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
  2095. //{
  2096. // Notification notification = (sender as Label).Tag as Notification;
  2097. // NotificationDetails details = new NotificationDetails(notification);
  2098. // details.ShowDialog();
  2099. // ReloadNotifications();
  2100. //}
  2101. private void DailyReport_Checked(object sender, RoutedEventArgs e)
  2102. {
  2103. LoadWindow<DailyReport>((Fluent.Button)sender);
  2104. }
  2105. private void Library_Click(object sender, RoutedEventArgs e)
  2106. {
  2107. Process.Start(
  2108. new ProcessStartInfo
  2109. {
  2110. FileName = App.DatabaseSettings.LibraryLocation,
  2111. UseShellExecute = true,
  2112. Verb = "open"
  2113. }
  2114. );
  2115. }
  2116. private void SendNotificationClick(object sender, RoutedEventArgs e)
  2117. {
  2118. var form = new NotificationForm { Description = "" };
  2119. if (form.ShowDialog() == true)
  2120. ReloadNotifications();
  2121. }
  2122. private void CompanyInformation_Click(object sender, RoutedEventArgs e)
  2123. {
  2124. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  2125. if (info == null)
  2126. info = new CompanyInformation();
  2127. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  2128. }
  2129. private void StockWarehouseList_Click()
  2130. {
  2131. var list = new MasterList(typeof(StockWarehouse));
  2132. list.ShowDialog();
  2133. }
  2134. private void Dashboards_Checked(object sender, RoutedEventArgs e)
  2135. {
  2136. LoadWindow<UtilityDashboard>((Fluent.Button)sender);
  2137. }
  2138. private void QuoteDiagramSymbols_Checked()
  2139. {
  2140. var list = new MasterList(typeof(QuoteDiagramSymbol), "Section.Name");
  2141. list.ShowDialog();
  2142. QuoteDiagramSymbolCache.Refresh();
  2143. }
  2144. private void QuoteDiagramSymbolTypes_Checked()
  2145. {
  2146. var list = new MasterList(typeof(QuoteDiagramSymbolSection));
  2147. list.ShowDialog();
  2148. QuoteDiagramSymbolCache.Refresh();
  2149. }
  2150. private void QuoteTakeOffUnits_Click()
  2151. {
  2152. var list = new MasterList(typeof(QuoteTakeOffUnit));
  2153. list.ShowDialog();
  2154. }
  2155. private void JobDocumentMileStoneButton_OnClick()
  2156. {
  2157. var list = new MasterList(typeof(JobDocumentSetMileStoneType));
  2158. list.ShowDialog();
  2159. }
  2160. // private void JobDocumentTagButton_OnClick()
  2161. // {
  2162. // var list = new MasterList(typeof(JobDocumentSetTag));
  2163. // list.ShowDialog();
  2164. // }
  2165. private void Setup_Click(object sender, RoutedEventArgs e)
  2166. {
  2167. var tab = _ribbon.SelectedTabItem;
  2168. if (tab is null)
  2169. return;
  2170. var items = new List<ISetupActionItem>();
  2171. if (SetupActions.TryGetValue(tab, out var actions))
  2172. {
  2173. foreach (var action in actions)
  2174. {
  2175. items.Add(action);
  2176. }
  2177. }
  2178. if (PanelSetupActions.Any())
  2179. {
  2180. AddSetupSeparator(items);
  2181. foreach (var action in PanelSetupActions)
  2182. {
  2183. items.Add(action);
  2184. }
  2185. }
  2186. items = items.Where(x => x is not SetupActionItem setup || setup.IsVisible()).ToList();
  2187. var menu = new ContextMenu();
  2188. for (var i = 0; i < items.Count; ++i)
  2189. {
  2190. var item = items[i];
  2191. if (item is SetupActionItem setupAction)
  2192. {
  2193. menu.AddItem(setupAction.Name, setupAction.Image, setupAction.Action);
  2194. }
  2195. else if (item is SetupSeparator && i > 0 && i < items.Count - 1)
  2196. {
  2197. var last = items[i - 1];
  2198. if (last is not SetupSeparator)
  2199. menu.AddSeparator();
  2200. }
  2201. }
  2202. if (CurrentPanel?.GetType().HasInterface(typeof(IPropertiesPanel<>)) == true && Security.IsAllowed<CanConfigurePanels>())
  2203. {
  2204. menu.AddItem("Configure Panel", PRSDesktop.Resources.edit, ConfigurePanel_Click);
  2205. }
  2206. if (menu.Items.Count == 0)
  2207. {
  2208. menu.AddItem("No Items", null, null, false);
  2209. }
  2210. menu.IsOpen = true;
  2211. }
  2212. private void InitializePanelProperties(IBasePanel panel)
  2213. {
  2214. var propertiesInterface = panel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>));
  2215. if (propertiesInterface is not null)
  2216. {
  2217. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2218. var method = typeof(MainWindow)
  2219. .GetMethod(nameof(InitializePanelPropertiesGeneric), BindingFlags.NonPublic | BindingFlags.Instance)
  2220. ?.MakeGenericMethod(panel.GetType(), propertiesType)
  2221. .Invoke(this, new object?[] { panel });
  2222. }
  2223. }
  2224. private void InitializePanelPropertiesGeneric<TPanel, TProperties>(TPanel panel)
  2225. where TPanel : IPropertiesPanel<TProperties>
  2226. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2227. {
  2228. panel.Properties = LoadPanelProperties<TPanel, TProperties>();
  2229. }
  2230. private TProperties LoadPanelProperties<TPanel, TProperties>()
  2231. where TPanel : IPropertiesPanel<TProperties>
  2232. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2233. {
  2234. var config = new GlobalConfiguration<TProperties>();
  2235. return config.Load();
  2236. }
  2237. private void SavePanelProperties<TPanel, TProperties>(TProperties properties)
  2238. where TPanel : IPropertiesPanel<TProperties>
  2239. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2240. {
  2241. var config = new GlobalConfiguration<TProperties>();
  2242. config.Save(properties);
  2243. }
  2244. private void EditPanelProperties<TPanel, TProperties>()
  2245. where TPanel : IPropertiesPanel<TProperties>
  2246. where TProperties : BaseObject, GlobalConfigurationSettings, new()
  2247. {
  2248. var properties = LoadPanelProperties<TPanel, TProperties>();
  2249. var editor = new DynamicEditorForm(typeof(TProperties));
  2250. editor.Items = new BaseObject[] { properties };
  2251. if (editor.ShowDialog() == true)
  2252. {
  2253. SavePanelProperties<TPanel, TProperties>(properties);
  2254. }
  2255. }
  2256. private void ConfigurePanel_Click()
  2257. {
  2258. if (CurrentPanel is null) return;
  2259. var propertiesInterface = CurrentPanel.GetType().GetInterfaceDefinition(typeof(IPropertiesPanel<>))!;
  2260. var propertiesType = propertiesInterface.GenericTypeArguments[0];
  2261. var method = typeof(MainWindow)
  2262. .GetMethod(nameof(EditPanelProperties), BindingFlags.NonPublic | BindingFlags.Instance)
  2263. ?.MakeGenericMethod(CurrentPanel.GetType(), propertiesType)
  2264. .Invoke(this, Array.Empty<object?>());
  2265. }
  2266. private void StartForm<TEntityForm, TEntity, TEntityLink>(DigitalForm form)
  2267. where TEntityForm : EntityForm<TEntity, TEntityLink>, new()
  2268. where TEntity : Entity, new()
  2269. where TEntityLink : EntityLink<TEntity>, new()
  2270. {
  2271. var entityForm = new TEntityForm();
  2272. entityForm.Form.ID = form.ID;
  2273. entityForm.Form.Description = form.Description;
  2274. var entity = DFUtils.NewEntity<TEntityForm, TEntity, TEntityLink>(form);
  2275. if (DynamicFormEditWindow.EditDigitalForm(entityForm, out var dataModel, entity))
  2276. {
  2277. dataModel.Update(null);
  2278. }
  2279. }
  2280. private void Forms_Click(object sender, RoutedEventArgs e)
  2281. {
  2282. var select = new MultiSelectDialog<DigitalForm>(
  2283. Filter<DigitalForm>.And(
  2284. LookupFactory.DefineFilter<KanbanForm, DigitalForm>(Array.Empty<KanbanForm>()),
  2285. new Filter<DigitalForm>(x => x.ID).InQuery(
  2286. new Filter<EmployeeDigitalForm>(x => x.Employee.ID).IsEqualTo(App.EmployeeID),
  2287. x => x.Form.ID)),
  2288. LookupFactory.DefineColumns<DigitalForm>()
  2289. .Add(x => x.Description),
  2290. false);
  2291. if (select.ShowDialog() == true)
  2292. {
  2293. var digitalForm = select.Data().Rows.FirstOrDefault()?.ToObject<DigitalForm>();
  2294. if (digitalForm is not null)
  2295. {
  2296. StartForm<KanbanForm, Kanban, KanbanLink>(digitalForm);
  2297. }
  2298. };
  2299. }
  2300. #endregion
  2301. private bool OutstandingDailyReports(bool refresh)
  2302. {
  2303. if (!Security.IsAllowed<CanViewDailyReports>() || Security.IsAllowed<BypassOutstandingDailyReports>())
  2304. return false;
  2305. if (refresh)
  2306. RefreshTimeSheets();
  2307. if (_timesheets == null)
  2308. return false;
  2309. return _timesheets.Rows.Any(r => r.Get<TimeSheet, DateTime>(c => c.Date).Date < DateTime.Today);
  2310. }
  2311. private void Window_Unloaded(object sender, RoutedEventArgs e)
  2312. {
  2313. }
  2314. //private bool _closingFromSystemMenu = false;
  2315. private void Window_Closing(object sender, CancelEventArgs e)
  2316. {
  2317. /*if (!_closingFromSystemMenu && !CoreUtils.GetVersion().Equals("???"))
  2318. {
  2319. WindowState = WindowState.Minimized;
  2320. e.Cancel = true;
  2321. return;
  2322. }*/
  2323. App.IsClosing = true;
  2324. FinalizeAutoTimesheet();
  2325. if (!CoreUtils.GetVersion().Equals("???"))
  2326. scheduler.Stop();
  2327. if (CurrentPanel != null)
  2328. CurrentPanel.Shutdown();
  2329. CurrentPanel = null;
  2330. CurrentTab = null;
  2331. UpdateRibbonColors();
  2332. if (!CoreUtils.GetVersion().Equals("???"))
  2333. if (station.ID != Guid.Empty)
  2334. ExecuteLogout();
  2335. }
  2336. private void FinalizeAutoTimesheet()
  2337. {
  2338. if (Security.IsAllowed<AutoGenerateTimesheet>())
  2339. {
  2340. var check = new Client<TimeSheet>().Query(
  2341. new Filter<TimeSheet>(x => x.Date).IsEqualTo(DateTime.Today).And(x => x.EmployeeLink.ID).IsEqualTo(App.EmployeeID).And(x => x.Finish)
  2342. .IsEqualTo(TimeSpan.Zero)
  2343. );
  2344. if (check.Rows.Any())
  2345. {
  2346. var ts = check.Rows.First().ToObject<TimeSheet>();
  2347. if (DateTime.Now.TimeOfDay < ts.Start.Add(new TimeSpan(0, 2, 0)))
  2348. {
  2349. new Client<TimeSheet>().Delete(ts, "Deleting Auto TimeSheet because TimeBench Bypass is enabled", (o, ex) => { });
  2350. }
  2351. else
  2352. {
  2353. ts.Finish = DateTime.Now.TimeOfDay;
  2354. new Client<TimeSheet>().Save(ts, "Clocking off Auto Timesheet because Timesheet Bypass is enabled", (o, ex) => { });
  2355. }
  2356. }
  2357. }
  2358. }
  2359. private void RibbonWindow_Closed(object sender, EventArgs e)
  2360. {
  2361. DisconnectRecorderNotes();
  2362. Application.Current.Shutdown();
  2363. }
  2364. #region Notifications + Heartbeat
  2365. private void ReceiveNotification(Notification notification)
  2366. {
  2367. if (Security.CanView<Notification>())
  2368. {
  2369. Notifications.AddNotification(notification);
  2370. }
  2371. if (CurrentPanel is NotificationPanel panel)
  2372. {
  2373. panel.AddNotification(notification);
  2374. }
  2375. }
  2376. private void Notifications_Tick(object? sender, EventArgs e)
  2377. {
  2378. if (ClientFactory.UserGuid != Guid.Empty)
  2379. {
  2380. try
  2381. {
  2382. ReloadNotifications();
  2383. }
  2384. catch (Exception err)
  2385. {
  2386. Logger.Send(LogType.Error, ClientFactory.UserID,
  2387. string.Format("Exception in Notifications_Tick:ReloadNotifications() {0}\n{1}", err.Message, err.StackTrace));
  2388. }
  2389. Heartbeat(DateTime.Now - CurrentPanel_Ticks, false);
  2390. try
  2391. {
  2392. CheckIsLoggedOn();
  2393. }
  2394. catch (Exception err2)
  2395. {
  2396. Logger.Send(LogType.Error, ClientFactory.UserID,
  2397. string.Format("Exception in Notifications_Tick:CheckIsLoggedOn() {0}\n{1}", err2.Message, err2.StackTrace));
  2398. }
  2399. }
  2400. //else
  2401. //{
  2402. // Logger.Send(LogType.Information, ClientFactory.UserID, "Notifications_Tick: ClientFactory.UserGuid is empty");
  2403. //}
  2404. }
  2405. private void CheckIsLoggedOn()
  2406. {
  2407. if (CoreUtils.GetVersion().Equals("???"))
  2408. return;
  2409. var bLogout = false;
  2410. if (!Security.IsAllowed<CanBypassTimeBench>())
  2411. if (!IsClockedOn())
  2412. {
  2413. Logger.Send(LogType.Information, ClientFactory.UserID, "User is no longer clocked in!");
  2414. bLogout = true;
  2415. Dispatcher.Invoke(() => { Logout(); });
  2416. }
  2417. if (!bLogout)
  2418. new Client<Login>().Query(
  2419. new Filter<Login>(x => x.User.ID).IsEqualTo(ClientFactory.UserGuid),
  2420. new Columns<Login>(x => x.StationID),
  2421. null,
  2422. (o, e) =>
  2423. {
  2424. if (e is RemoteException remote)
  2425. {
  2426. if (remote.Status == StatusCode.Unauthenticated)
  2427. {
  2428. Logger.Send(LogType.Information, ClientFactory.UserID, "User has been logged out");
  2429. Dispatcher.Invoke(() =>
  2430. {
  2431. Logout("You have been logged out due to inactivity");
  2432. });
  2433. }
  2434. else
  2435. {
  2436. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(remote));
  2437. }
  2438. }
  2439. else if (e is not null)
  2440. {
  2441. Logger.Send(LogType.Information, ClientFactory.UserID, CoreUtils.FormatException(e));
  2442. }
  2443. else if (o is not null)
  2444. {
  2445. var row = o.Rows.FirstOrDefault();
  2446. if (row == null)
  2447. {
  2448. station.ID = Guid.Empty;
  2449. new Client<Login>().Save(station, "", (o1, e1) => { });
  2450. }
  2451. else if (!row.Get<Login, string>(c => c.StationID).Equals(station.StationID))
  2452. {
  2453. Logger.Send(LogType.Information, ClientFactory.UserID, "User logged in somewhere else!");
  2454. bLogout = true;
  2455. Dispatcher.Invoke(() => { Logout(); });
  2456. }
  2457. }
  2458. }
  2459. );
  2460. }
  2461. private void Heartbeat(TimeSpan time, bool closing)
  2462. {
  2463. //Task.Run(() =>
  2464. //{
  2465. try
  2466. {
  2467. bool IsClockedOn = this.IsClockedOn();
  2468. if (IsClockedOn)
  2469. {
  2470. if ((_kanbantrackingassignment != null) && (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay))
  2471. {
  2472. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  2473. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  2474. }
  2475. if (Security.IsAllowed<MonitorApplicationWindows>())
  2476. {
  2477. if (ActivityHistory == null)
  2478. ActivityHistory = new LocalConfiguration<DailyActivityHistory>().Load();
  2479. var appname = OpenWindowGetter.GetActiveWindowProcess();
  2480. var title = OpenWindowGetter.GetActiveWindowTitle();
  2481. ActivityHistory.Activities[DateTime.Now] = (!string.IsNullOrWhiteSpace(appname) ? appname.Trim() + " - " : "") + title;
  2482. new LocalConfiguration<DailyActivityHistory>().Save(ActivityHistory);
  2483. }
  2484. }
  2485. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0:hh\\:mm}{1}", time, closing ? " (closing)" : ""));
  2486. if (!closing && time.TotalMinutes < 5)
  2487. return;
  2488. CurrentPanel_Ticks = DateTime.Now;
  2489. if (CurrentPanel != null)
  2490. {
  2491. //Logger.Send(LogType.Information, "", string.Format("Heartbeat: {0}", CurrentPanel_Label));
  2492. if (ClientFactory.IsSupported<ModuleTracking>())
  2493. {
  2494. var keys = CurrentPanel_Keys;
  2495. CurrentPanel_Keys = 0;
  2496. var clicks = CurrentPanel_Clicks;
  2497. CurrentPanel_Clicks = 0;
  2498. var tracking = new ModuleTracking
  2499. {
  2500. Date = DateTime.Today,
  2501. Module = CurrentPanel_Label,
  2502. Clicks = clicks,
  2503. Keys = keys,
  2504. ActiveTime = clicks + keys > 0 ? time : new TimeSpan(),
  2505. IdleTime = clicks + keys == 0 ? time : new TimeSpan()
  2506. };
  2507. tracking.User.ID = ClientFactory.UserGuid;
  2508. new Client<ModuleTracking>().Save(tracking, "", (mt, ex) => { });
  2509. }
  2510. CurrentPanel.Heartbeat(time);
  2511. }
  2512. }
  2513. catch (Exception err)
  2514. {
  2515. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("Exception in Heartbeat: {0}\n{1}", err.Message, err.StackTrace));
  2516. }
  2517. //});
  2518. }
  2519. private void Notifications_Changed(object sender)
  2520. {
  2521. if (Notifications.IsActive)
  2522. {
  2523. Notifications.Visibility = Visibility.Visible;
  2524. DockingGrid.ColumnDefinitions[1].Width = new GridLength(4, GridUnitType.Pixel);
  2525. DockingGrid.ColumnDefinitions[2].Width = Equals(0.0, DockingGrid.ColumnDefinitions[2].Width.Value)
  2526. ? new GridLength(300, GridUnitType.Pixel)
  2527. : DockingGrid.ColumnDefinitions[2].Width;
  2528. }
  2529. else
  2530. {
  2531. Notifications.Visibility = Visibility.Collapsed;
  2532. DockingGrid.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Pixel);
  2533. DockingGrid.ColumnDefinitions[2].Width = new GridLength(0, GridUnitType.Pixel);
  2534. }
  2535. }
  2536. private void ReloadNotifications()
  2537. {
  2538. if (Security.CanView<Notification>())
  2539. Notifications.Refresh();
  2540. if (!NotificationsWatchDog.IsEnabled)
  2541. {
  2542. //Logger.Send(LogType.Information, ClientFactory.UserID, "Enabling Heartbeat");
  2543. NotificationsWatchDog.IsEnabled = true;
  2544. }
  2545. }
  2546. #endregion
  2547. private void RibbonWindow_PreviewMouseUp(object sender, MouseButtonEventArgs e)
  2548. {
  2549. if (CurrentPanel != null)
  2550. CurrentPanel_Clicks++;
  2551. }
  2552. private void RibbonWindow_PreviewKeyUp(object sender, KeyEventArgs e)
  2553. {
  2554. if (CurrentPanel != null)
  2555. CurrentPanel_Keys++;
  2556. }
  2557. #region Recording
  2558. //private IntPtr myHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  2559. //{
  2560. // switch (msg)
  2561. // {
  2562. // case 0x100:
  2563. // if (_subject != null)
  2564. // {
  2565. // _recorder.Stop();
  2566. // pausestarted = DateTime.Now;
  2567. // _subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2568. // }
  2569. // break;
  2570. // default:
  2571. // messages.TryGetValue(msg, out int value);
  2572. // messages[msg] = value + 1;
  2573. // break;
  2574. // }
  2575. // return IntPtr.Zero;
  2576. //}
  2577. private void RecordScreenButton_Click(object sender, RoutedEventArgs e)
  2578. {
  2579. ToggleRecording();
  2580. }
  2581. private bool ToggleRecording()
  2582. {
  2583. if (!Security.IsAllowed<CanRecordScreen>())
  2584. return true;
  2585. if (_recorder is null)
  2586. {
  2587. var windowInteropHelper = new WindowInteropHelper(this);
  2588. var screen = Screen.FromHandle(windowInteropHelper.Handle);
  2589. _screenleft = screen.WorkingArea.Left;
  2590. _screentop = screen.WorkingArea.Top;
  2591. _screenwidth = screen.WorkingArea.Width;
  2592. _screenheight = screen.WorkingArea.Height;
  2593. //VIDEO_WIDTH = _screenwidth;
  2594. //VIDEO_HEIGHT = _screenheight;
  2595. //SetupJPEGEncoder();
  2596. messages.Clear();
  2597. _bitmaps.Clear();
  2598. ConnectToRecordNotes();
  2599. StartAudio();
  2600. _recorder = new DispatcherTimer();
  2601. _recorder.Tick += (timer, args) => { TakeScreenShot(); };
  2602. _recorder.Interval = TimeSpan.FromMilliseconds(1000 / FRAMES_PER_SECOND);
  2603. _recorder.Start();
  2604. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsBitmapImage();
  2605. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2606. RecordingNotesButton.Visibility = Visibility.Visible;
  2607. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2608. AudioRecordingButton.Visibility = Visibility.Visible;
  2609. }
  2610. else
  2611. {
  2612. using (new WaitCursor())
  2613. {
  2614. StopRecording();
  2615. _recorder.Stop();
  2616. _recorder = null;
  2617. DisconnectRecorderNotes();
  2618. VideoRecordingStatus.Source = PRSDesktop.Resources.videorecording.AsGrayScale().AsBitmapImage();
  2619. RecordingNotesStatus.Source = PRSDesktop.Resources.speechbubble.AsGrayScale().AsBitmapImage();
  2620. RecordingNotesButton.Visibility = Visibility.Hidden;
  2621. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2622. AudioRecordingButton.Visibility = Visibility.Hidden;
  2623. var filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
  2624. string.Format("PRS Screen Recording {0:yyyy-MM-dd hh-mm-ss-ff}.avi", DateTime.Now));
  2625. ProcessScreenShots(filename);
  2626. }
  2627. }
  2628. return true;
  2629. }
  2630. private void StopRecording()
  2631. {
  2632. try
  2633. {
  2634. _audio?.StopRecording();
  2635. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2636. }
  2637. catch (Exception e)
  2638. {
  2639. Logger.Send(LogType.Error, "", string.Format("Unable to stop Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2640. }
  2641. }
  2642. private void StartAudio()
  2643. {
  2644. _audioMuted = true;
  2645. _audioStream = new MemoryStream();
  2646. _audio = new WaveIn
  2647. {
  2648. DeviceNumber = 0,
  2649. WaveFormat = new WaveFormat(44100, 16, 2)
  2650. };
  2651. _audio.DataAvailable += (o, e) =>
  2652. {
  2653. var buf = _audioMuted ? new byte[e.BytesRecorded] : e.Buffer;
  2654. _audioStream.Write(buf, 0, e.BytesRecorded);
  2655. };
  2656. try
  2657. {
  2658. _audio.StartRecording();
  2659. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2660. }
  2661. catch (Exception e)
  2662. {
  2663. Logger.Send(LogType.Error, "", string.Format("Unable to start Audio Recording: {0}\n{1}", e.Message, e.StackTrace));
  2664. AudioRecordingStatus.Source = PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage();
  2665. }
  2666. }
  2667. private bool ToggleRecordingAudio()
  2668. {
  2669. if (!Security.IsAllowed<CanRecordScreen>())
  2670. return true;
  2671. if (_recorder != null)
  2672. {
  2673. _audioMuted = !_audioMuted;
  2674. AudioRecordingStatus.Source = _audioMuted
  2675. ? PRSDesktop.Resources.audiorecording.AsGrayScale().AsBitmapImage()
  2676. : PRSDesktop.Resources.audiorecording.AsBitmapImage();
  2677. }
  2678. return true;
  2679. }
  2680. private void DisconnectRecorderNotes()
  2681. {
  2682. if (_client != null)
  2683. {
  2684. _client.WriteAsync("QUIT");
  2685. _client.StopAsync();
  2686. _client = null;
  2687. }
  2688. }
  2689. private void ConnectToRecordNotes()
  2690. {
  2691. var filename = Debugger.IsAttached
  2692. ? "c:\\development\\comal\\prsrecordingnotes\\bin\\debug\\prsrecordingnotes.exe"
  2693. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "recordingnotes", "prsrecordingnotes.exe");
  2694. Logger.Send(LogType.Information, "", "Recording Notes: " + filename);
  2695. _recordingnotes = Process.Start(filename);
  2696. //PipeSecurity sec = new System.IO.Pipes.PipeSecurity();
  2697. //sec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
  2698. _client = new PipeServer<string>("PRSScreenRecorder"); //, sec);
  2699. _client.ClientConnected += (o, args) => args.Connection.WriteAsync("Connected to PRSScreenRecorder");
  2700. _client.MessageReceived += (o, args) =>
  2701. {
  2702. if (string.Equals(args.Message, "RESUME"))
  2703. Dispatcher.Invoke(() =>
  2704. {
  2705. _audio?.StartRecording();
  2706. totalpauses += DateTime.Now - pausestarted;
  2707. _recorder?.Start();
  2708. Activate();
  2709. Focus();
  2710. });
  2711. };
  2712. _client.StartAsync();
  2713. }
  2714. private bool ShowRecordingNotes()
  2715. {
  2716. if (_recorder != null)
  2717. {
  2718. _audio?.StopRecording();
  2719. _recorder.Stop();
  2720. pausestarted = DateTime.Now;
  2721. _client?.WriteAsync("EDIT");
  2722. //_subject.OnNext(new WampEvent() { Arguments = new[] { "EDIT" } });
  2723. }
  2724. return true;
  2725. }
  2726. private void TakeScreenShot()
  2727. {
  2728. using (var bmp = new ScreenCapture().CaptureScreen(_screenleft, _screentop, _screenwidth, _screenheight))
  2729. {
  2730. var cursor = PointToScreen(Mouse.GetPosition(this));
  2731. using (var g = Graphics.FromImage(bmp))
  2732. {
  2733. var brush = new SolidBrush(System.Drawing.Color.FromArgb(128, 255, 255, 0));
  2734. g.FillEllipse(brush, new RectangleF((float)cursor.X - 25F, (float)cursor.Y - 25F, 50F, 50F));
  2735. var pen = new Pen(System.Drawing.Color.Black, 0.75F);
  2736. g.DrawLine(pen, (float)cursor.X - 10F, (float)cursor.Y, (float)cursor.X + 10F, (float)cursor.Y);
  2737. g.DrawLine(pen, (float)cursor.X, (float)cursor.Y - 10F, (float)cursor.X, (float)cursor.Y + 10F);
  2738. }
  2739. var key = DateTime.Now - totalpauses;
  2740. using (var reduced = ReduceBitmap(bmp, VIDEO_WIDTH, VIDEO_HEIGHT))
  2741. {
  2742. var ms = new MemoryStream();
  2743. reduced.Save(ms, ImageFormat.Png);
  2744. ms.Position = 0;
  2745. _bitmaps[key] = ms;
  2746. }
  2747. }
  2748. }
  2749. public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
  2750. {
  2751. var reduced = new Bitmap(reducedWidth, reducedHeight);
  2752. using (var dc = Graphics.FromImage(reduced))
  2753. {
  2754. // Figure out the ratio
  2755. var ratioX = (double)reducedWidth / original.Width;
  2756. var ratioY = (double)reducedHeight / original.Height;
  2757. // use whichever multiplier is smaller
  2758. var ratio = ratioX < ratioY ? ratioX : ratioY;
  2759. // now we can get the new height and width
  2760. var newHeight = Convert.ToInt32(original.Height * ratio);
  2761. var newWidth = Convert.ToInt32(original.Width * ratio);
  2762. // Now calculate the X,Y position of the upper-left corner
  2763. // (one of these will always be zero)
  2764. var posX = Convert.ToInt32((reducedWidth - original.Width * ratio) / 2);
  2765. var posY = Convert.ToInt32((reducedHeight - original.Height * ratio) / 2);
  2766. dc.InterpolationMode = InterpolationMode.HighQualityBicubic;
  2767. dc.Clear(System.Drawing.Color.Black); // white padding
  2768. //dc.DrawImage(original, posX, posY, newWidth, newHeight);
  2769. dc.DrawImage(original, new Rectangle(posX, posY, newWidth, newHeight), new Rectangle(0, 0, original.Width, original.Height),
  2770. GraphicsUnit.Pixel);
  2771. }
  2772. return reduced;
  2773. }
  2774. public static byte[] BitmapToByteArray(Bitmap bitmap, int width, int height)
  2775. {
  2776. // and buffer of appropriate size for storing its bits
  2777. var buffer = new byte[width * height * 4];
  2778. var pixelFormat = PixelFormat.Format32bppRgb;
  2779. // Now copy bits from bitmap to buffer
  2780. var bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);
  2781. //Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2782. Marshal.Copy(bits.Scan0, buffer, 0, buffer.Length);
  2783. bitmap.UnlockBits(bits);
  2784. return buffer;
  2785. }
  2786. private void ProcessScreenShots(string filename)
  2787. {
  2788. if (!_bitmaps.Any() || _audioStream is null)
  2789. return;
  2790. Progress.Show("Saving Video");
  2791. var framRate = 10;
  2792. using (var writer = new AviWriter(filename))
  2793. {
  2794. writer.FramesPerSecond = framRate;
  2795. writer.EmitIndex1 = true;
  2796. _audioStream.Position = 0;
  2797. var audio = writer.AddAudioStream(2);
  2798. //audio.WriteBlock(_audioStream.GetBuffer(), 0, (int)_audioStream.Length);
  2799. //File.WriteAllBytes(Path.ChangeExtension(filename, "wav"), _audioStream.GetBuffer());
  2800. var audioByteRate = audio.BitsPerSample / 8 * audio.ChannelCount * audio.SamplesPerSecond;
  2801. var audioBlockSize = (int)(audioByteRate / writer.FramesPerSecond);
  2802. var audioBuffer = new byte[audioBlockSize];
  2803. _audioStream.Position = 0;
  2804. var encoder = new MJpegWpfVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT, 50);
  2805. var stream = writer.AddEncodingVideoStream(encoder, true, VIDEO_WIDTH, VIDEO_HEIGHT);
  2806. //var encoder = new SharpAvi.Codecs.UncompressedVideoEncoder(VIDEO_WIDTH, VIDEO_HEIGHT);
  2807. //var stream = writer.AddEncodingVideoStream(encoder,true,VIDEO_WIDTH, VIDEO_HEIGHT);
  2808. //stream.Codec = CodecIds.Uncompressed;
  2809. //stream.BitsPerPixel = BitsPerPixel.Bpp16;
  2810. IEnumerable<DateTime> keys = _bitmaps.Keys.OrderBy(x => x);
  2811. var start = keys.First();
  2812. var end = keys.Last();
  2813. for (var cur = start; cur <= end; cur = cur + TimeSpan.FromMilliseconds(100))
  2814. {
  2815. Progress.SetMessage(string.Format("Processing ({0:F2} complete)",
  2816. (cur - start).TotalSeconds * 100.0F / (end - start).TotalSeconds));
  2817. var key = keys.LastOrDefault(x => x <= cur);
  2818. if (_bitmaps.ContainsKey(key))
  2819. {
  2820. var frame = (Image.FromStream(_bitmaps[key]) as Bitmap)!;
  2821. //frame.RotateFlip(RotateFlipType.RotateNoneFlipY);
  2822. var buf = BitmapToByteArray(frame, stream.Width, stream.Height);
  2823. stream.WriteFrame(true, buf, 0, buf.Length);
  2824. if (_audioStream.Position < _audioStream.Length)
  2825. {
  2826. var bytes = _audioStream.Read(audioBuffer, 0, audioBlockSize);
  2827. audio.WriteBlock(audioBuffer, 0, bytes);
  2828. }
  2829. }
  2830. }
  2831. writer.Close();
  2832. //foreach (var key in _bitmaps.Keys)
  2833. // File.Delete(_bitmaps[key]);
  2834. }
  2835. Progress.SetMessage("Transcoding");
  2836. //var inputFile = new MediaFile { Filename = filename };
  2837. //var outputFile = new MediaFile { Filename = Path.ChangeExtension(filename, "mp4") };
  2838. //using (var engine = new Engine())
  2839. //{
  2840. // //engine.ConvertProgressEvent += ConvertProgressEvent;
  2841. // engine.Convert(inputFile, outputFile);
  2842. //}
  2843. Progress.Close();
  2844. var dirName = Path.GetDirectoryName(filename);
  2845. if (dirName is not null)
  2846. {
  2847. var startInfo = new ProcessStartInfo(dirName);
  2848. startInfo.Verb = "open";
  2849. startInfo.UseShellExecute = true;
  2850. Process.Start(startInfo);
  2851. //MessageBox.Show("Recording Saved");
  2852. }
  2853. }
  2854. private void VideoRecordingButton_Click(object sender, RoutedEventArgs e)
  2855. {
  2856. ToggleRecording();
  2857. }
  2858. private void AudioRecordingButton_Click(object sender, RoutedEventArgs e)
  2859. {
  2860. ToggleRecordingAudio();
  2861. }
  2862. private void RecordingNotesButton_Click(object sender, RoutedEventArgs e)
  2863. {
  2864. ShowRecordingNotes();
  2865. }
  2866. #endregion
  2867. public static void ActivateWindow(Window window)
  2868. {
  2869. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2870. var threadId1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
  2871. var threadId2 = GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  2872. if (threadId1 != threadId2)
  2873. {
  2874. AttachThreadInput(threadId1, threadId2, true);
  2875. SetForegroundWindow(hwnd);
  2876. AttachThreadInput(threadId1, threadId2, false);
  2877. }
  2878. else
  2879. {
  2880. SetForegroundWindow(hwnd);
  2881. }
  2882. }
  2883. private static IntPtr GetForegroundWindow()
  2884. {
  2885. var active = GetActiveWindow();
  2886. var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => new WindowInteropHelper(x).Handle == active);
  2887. var hwnd = new WindowInteropHelper(window).EnsureHandle();
  2888. return hwnd;
  2889. }
  2890. [DllImport("user32.dll", SetLastError = true)]
  2891. private static extern IntPtr SetForegroundWindow(IntPtr hWnd);
  2892. [DllImport("user32.dll")]
  2893. private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
  2894. [DllImport("user32.dll")]
  2895. private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
  2896. [DllImport("user32.dll")]
  2897. private static extern IntPtr GetActiveWindow();
  2898. //private void ConvertProgressEvent(object sender, ConvertProgressEventArgs e)
  2899. //{
  2900. // Dispatcher.Invoke(() =>
  2901. // {
  2902. // try
  2903. // {
  2904. // if (e.TotalDuration.TotalSeconds != 0.0F)
  2905. // Progress.SetMessage(String.Format("Transcoding ({0:F2}% complete)", e.ProcessedDuration.TotalSeconds * 100.0F / e.TotalDuration.TotalSeconds));
  2906. // }
  2907. // catch (Exception err)
  2908. // {
  2909. // }
  2910. // });
  2911. //}
  2912. #region Check For Updates
  2913. private string GetUpdateLocation()
  2914. {
  2915. if (App.DatabaseSettings.DatabaseType == DatabaseType.Networked)
  2916. {
  2917. var domain = App.DatabaseSettings.URL.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).Last();
  2918. var port = App.DatabaseSettings.Port;
  2919. var client = new HttpClient { BaseAddress = new Uri($"https://{domain}:{port}") };
  2920. string url;
  2921. try
  2922. {
  2923. client.GetAsync("operations").Wait();
  2924. url = $"https://{domain}";
  2925. }
  2926. catch (Exception)
  2927. {
  2928. url = $"http://{domain}";
  2929. }
  2930. return $"{url}:{port}";
  2931. }
  2932. else
  2933. return Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  2934. }
  2935. private string GetLatestVersion(string location)
  2936. {
  2937. return App.DatabaseSettings.DatabaseType switch
  2938. {
  2939. DatabaseType.Networked => Update.GetRemoteFile($"{location}/version").Content,
  2940. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "version.txt")),
  2941. _ => "",
  2942. };
  2943. }
  2944. private string GetReleaseNotes(string location)
  2945. {
  2946. return App.DatabaseSettings.DatabaseType switch
  2947. {
  2948. DatabaseType.Networked => Update.GetRemoteFile($"{location}/releasenotes").Content,
  2949. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllText(Path.Combine(location, "Release Notes.txt")),
  2950. _ => "",
  2951. };
  2952. }
  2953. private byte[]? GetInstaller(string location)
  2954. {
  2955. return App.DatabaseSettings.DatabaseType switch
  2956. {
  2957. DatabaseType.Networked => Update.GetRemoteFile($"{location}/install").RawBytes,
  2958. DatabaseType.Standalone or DatabaseType.Local => File.ReadAllBytes(Path.Combine(location, "PRSDesktopSetup.exe")),
  2959. _ => null,
  2960. };
  2961. }
  2962. private void CheckForUpdates()
  2963. {
  2964. Update.CheckForUpdates(
  2965. GetUpdateLocation, GetLatestVersion, GetReleaseNotes, GetInstaller, null, App.AutoUpdateSettings.Elevated, "PRSDesktopSetup.exe");
  2966. }
  2967. #endregion
  2968. #region Modules
  2969. public void CreatePanelAction(PanelAction action)
  2970. {
  2971. if (_ribbon.SelectedTabItem is null)
  2972. return;
  2973. var Actions = FindRibbonBar(_ribbon.SelectedTabItem, x => x.Header.Equals("Actions"));
  2974. if (Actions is not null)
  2975. {
  2976. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  2977. {
  2978. var sep = new RibbonSeparator();
  2979. CurrentModules.Add(sep);
  2980. Actions.Items.Add(sep);
  2981. }
  2982. var button = new RibbonButton
  2983. {
  2984. Label = action.Caption,
  2985. LargeIcon = action.Image.AsBitmapImage(),
  2986. SizeForm = SizeForm.Large,
  2987. MinWidth = 60,
  2988. Tag = action
  2989. };
  2990. button.Click += PaneActionClick;
  2991. CurrentModules.Add(button);
  2992. Actions.Items.Add(button);
  2993. }
  2994. }
  2995. private List<ISetupActionItem> PanelSetupActions = new();
  2996. public void CreateSetupAction(PanelAction action)
  2997. {
  2998. if (_ribbon.SelectedTabItem is null)
  2999. return;
  3000. AddSetupAction(PanelSetupActions, action.Caption, () =>
  3001. {
  3002. action.Execute();
  3003. }, action.Image);
  3004. }
  3005. private void PaneActionClick(object sender, RoutedEventArgs e)
  3006. {
  3007. var button = (Control)sender;
  3008. var action = (PanelAction)button.Tag;
  3009. action.Execute();
  3010. }
  3011. private void ReloadModules(string sectionName, DataModel model)
  3012. {
  3013. foreach (var module in CurrentModules)
  3014. {
  3015. if (module.Parent is Fluent.RibbonGroupBox bar)
  3016. bar.Items.Remove(module);
  3017. }
  3018. CurrentModules.Clear();
  3019. PanelSetupActions.Clear();
  3020. if (CurrentPanel != null)
  3021. {
  3022. CurrentPanel.CreateToolbarButtons(this);
  3023. CreateModules(sectionName, model, new Progress<Tuple<string, Bitmap, CustomModule>>(CreateModuleButton));
  3024. }
  3025. }
  3026. private void CreateModules(string section, DataModel model, IProgress<Tuple<string, Bitmap, CustomModule>> progress)
  3027. {
  3028. if (ClientFactory.IsSupported<CustomModule>())
  3029. {
  3030. foreach (var (module, image) in CustomModuleUtils.LoadCustomModuleThumbnails(section, model))
  3031. {
  3032. progress.Report(new Tuple<string, Bitmap, CustomModule>(module.Name ?? "", image, module));
  3033. }
  3034. }
  3035. }
  3036. private void CreateModuleButton(Tuple<string, Bitmap, CustomModule> module)
  3037. {
  3038. Fluent.RibbonGroupBox? Actions = CurrentTab != null
  3039. ? FindRibbonBar(CurrentTab, x => x.Header.Equals("Actions"))
  3040. : null;
  3041. if (Actions != null)
  3042. {
  3043. if (!CurrentModules.Any(x => x.GetType().Equals(typeof(RibbonSeparator))))
  3044. {
  3045. var sep = new RibbonSeparator();
  3046. CurrentModules.Add(sep);
  3047. Actions.Items.Add(sep);
  3048. }
  3049. if (!CurrentModules.Any(x => x is Fluent.Button button && module.Item1.Equals(button.Header)))
  3050. {
  3051. var button = new Fluent.Button
  3052. {
  3053. Header = module.Item1,
  3054. LargeIcon = module.Item2.AsBitmapImage(),
  3055. MinWidth = 60,
  3056. Tag = module.Item3
  3057. };
  3058. button.Click += Module_Click;
  3059. CurrentModules.Add(button);
  3060. Actions.Items.Add(button);
  3061. }
  3062. }
  3063. }
  3064. private void Module_Click(object sender, RoutedEventArgs e)
  3065. {
  3066. if (CurrentPanel != null)
  3067. {
  3068. var item = (Fluent.Button)sender;
  3069. var code = (CustomModule)item.Tag;
  3070. if (!string.IsNullOrWhiteSpace(code.Script))
  3071. try
  3072. {
  3073. Selection selection;
  3074. if (code.SelectedRecords && code.AllRecords)
  3075. selection = RecordSelectionDialog.Execute();
  3076. else if (code.SelectedRecords)
  3077. selection = Selection.Selected;
  3078. else if (code.AllRecords)
  3079. selection = Selection.All;
  3080. else
  3081. selection = Selection.None;
  3082. var result = ScriptDocument.RunCustomModule(CurrentPanel.DataModel(selection), CurrentPanel.Selected(), code.Script);
  3083. if (result)
  3084. CurrentPanel.Refresh();
  3085. }
  3086. catch (CompileException c)
  3087. {
  3088. MessageBox.Show(c.Message);
  3089. }
  3090. catch (Exception err)
  3091. {
  3092. MessageBox.Show(CoreUtils.FormatException(err));
  3093. }
  3094. else
  3095. MessageBox.Show("Unable to load " + item.Header);
  3096. }
  3097. }
  3098. private void ManageModules()
  3099. {
  3100. if (CurrentPanel != null)
  3101. {
  3102. var section = CurrentPanel.SectionName;
  3103. var dataModel = CurrentPanel.DataModel(Selection.Selected);
  3104. var manager = new CustomModuleManager()
  3105. {
  3106. Section = section,
  3107. DataModel = dataModel
  3108. };
  3109. manager.ShowDialog();
  3110. ReloadModules(section, dataModel);
  3111. }
  3112. }
  3113. private void ManageModulesClick(object sender, RoutedEventArgs e)
  3114. {
  3115. ManageModules();
  3116. }
  3117. #endregion
  3118. #region Report Buttons
  3119. private void ReloadReports(string section, DataModel model)
  3120. {
  3121. if (CurrentTab is null)
  3122. return;
  3123. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3124. if (ReportsBar is not null)
  3125. {
  3126. ReportsBar.Visibility = Security.IsAllowed<CanPrintReports>() ? Visibility.Visible : Visibility.Collapsed;
  3127. //ReportsBar.IsLauncherVisible = Security.IsAllowed<CanDesignReports>();
  3128. ReportsBar.Items.Clear();
  3129. CreateReports(section, model, new Progress<Tuple<string, Guid>>(CreateReportButton));
  3130. }
  3131. }
  3132. private void CreateReports(string section, DataModel model, IProgress<Tuple<string, Guid>> progress)
  3133. {
  3134. var client = new Client<ReportTemplate>();
  3135. var templates = client.Query(
  3136. new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  3137. .And(x => x.Section).IsEqualTo(section)
  3138. .And(x => x.Visible).IsEqualTo(true),
  3139. new Columns<ReportTemplate>(x => x.ID, x => x.Name),
  3140. new SortOrder<ReportTemplate>(x => x.Name)
  3141. );
  3142. foreach (var row in templates.Rows)
  3143. progress.Report(new Tuple<string, Guid>(row.Get<ReportTemplate, string>(x => x.Name), row.Get<ReportTemplate, Guid>(x => x.ID)));
  3144. }
  3145. public void CreateReportButton(Tuple<string, Guid> report)
  3146. {
  3147. if (CurrentTab is null)
  3148. return;
  3149. var ReportsBar = FindRibbonBar(CurrentTab, x => x.Header.Equals("Print"));
  3150. if (ReportsBar is not null)
  3151. {
  3152. var bFound = false;
  3153. foreach (var item in ReportsBar.Items)
  3154. {
  3155. if (item is RibbonButton button && report.Item2.Equals(button.Tag))
  3156. bFound = true;
  3157. }
  3158. if (!bFound)
  3159. {
  3160. var button = new RibbonButton
  3161. {
  3162. Label = report.Item1,
  3163. LargeIcon = PRSDesktop.Resources.printer.AsBitmapImage(),
  3164. Tag = report.Item2,
  3165. SizeForm = SizeForm.Large,
  3166. MinWidth = 60
  3167. };
  3168. if (Security.IsAllowed<CanDesignReports>())
  3169. {
  3170. var menu = new ContextMenu();
  3171. menu.AddItem("Design Report", PRSDesktop.Resources.pencil, report.Item2, ReportButtonMenu_DesignReport_Click);
  3172. button.ContextMenu = menu;
  3173. }
  3174. button.Click += ReportMenu_Checked;
  3175. ReportsBar.Items.Add(button);
  3176. }
  3177. }
  3178. }
  3179. private void ReportButtonMenu_DesignReport_Click(Guid templateID)
  3180. {
  3181. if (CurrentPanel is null)
  3182. return;
  3183. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(templateID)).FirstOrDefault();
  3184. if (template is null)
  3185. {
  3186. Logger.Send(LogType.Error, "", $"No Report Template with ID '{templateID}'");
  3187. MessageBox.Show("Report does not exist!");
  3188. return;
  3189. }
  3190. ReportUtils.DesignReport(template, CurrentPanel.DataModel(Selection.None));
  3191. }
  3192. private void ReportMenu_Checked(object sender, RoutedEventArgs e)
  3193. {
  3194. if (CurrentPanel is null)
  3195. return;
  3196. var item = (RibbonButton)sender;
  3197. var id = (Guid)item.Tag;
  3198. var template = new Client<ReportTemplate>().Load(new Filter<ReportTemplate>(x => x.ID).IsEqualTo(id)).FirstOrDefault();
  3199. if (template == null)
  3200. {
  3201. Logger.Send(LogType.Error, "", $"No Report Template with ID '{id}'");
  3202. MessageBox.Show("Report does not exist!");
  3203. return;
  3204. }
  3205. var selection = Selection.None;
  3206. if (template.SelectedRecords && template.AllRecords)
  3207. selection = RecordSelectionDialog.Execute();
  3208. else if (template.SelectedRecords)
  3209. selection = Selection.Selected;
  3210. else if (template.AllRecords)
  3211. selection = Selection.All;
  3212. else
  3213. MessageBox.Show("Report must have either [Selected Records] or [All Records] checked to display!");
  3214. if (selection != Selection.None)
  3215. ReportUtils.PreviewReport(template, CurrentPanel.DataModel(selection), false, Security.IsAllowed<CanDesignReports>());
  3216. }
  3217. private void ManageReports()
  3218. {
  3219. if (CurrentTab is null || CurrentPanel is null)
  3220. return;
  3221. var section = CurrentPanel.SectionName;
  3222. var model = CurrentPanel.DataModel(Selection.None);
  3223. if (model == null)
  3224. {
  3225. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3226. return;
  3227. }
  3228. var form = new ReportManager { DataModel = model, Section = section, Populate = true };
  3229. form.ShowDialog();
  3230. ReloadReports(section, model);
  3231. }
  3232. private void ManageEmailTemplates()
  3233. {
  3234. if (CurrentTab is null || CurrentPanel is null)
  3235. return;
  3236. var section = CurrentPanel.SectionName;
  3237. var model = CurrentPanel.DataModel(Selection.None);
  3238. if (model == null)
  3239. {
  3240. MessageBox.Show("No DataModel for " + CurrentTab.Header);
  3241. return;
  3242. }
  3243. var window = new EmailTemplateManagerWindow(model);
  3244. window.ShowDialog();
  3245. }
  3246. private void ManageReportsMenu_Click(object sender, RoutedEventArgs e)
  3247. {
  3248. ManageReports();
  3249. }
  3250. #endregion
  3251. #region Tracking Kanban
  3252. private void SelectTask_Click(object sender, RoutedEventArgs e)
  3253. {
  3254. ContextMenu menu = new ContextMenu();
  3255. MenuItem others = new MenuItem() { Header = "Other Tasks" };
  3256. using (new WaitCursor())
  3257. {
  3258. var kanbans = new Client<KanbanSubscriber>().Query(
  3259. new Filter<KanbanSubscriber>(x => x.Employee.UserLink.ID).IsEqualTo(ClientFactory.UserGuid)
  3260. .And(x => x.Kanban.Completed).IsEqualTo(DateTime.MinValue)
  3261. .And(x => x.Kanban.Closed).IsEqualTo(DateTime.MinValue),
  3262. new Columns<KanbanSubscriber>(x => x.Kanban.ID)
  3263. .Add(x => x.Kanban.Number)
  3264. .Add(x => x.Kanban.Title)
  3265. .Add(x => x.Assignee),
  3266. new SortOrder<KanbanSubscriber>(x => x.Kanban.Number, SortDirection.Ascending)
  3267. );
  3268. foreach (var row in kanbans.Rows)
  3269. {
  3270. CreateTaskMenu(row.Get<KanbanSubscriber, bool>(c => c.Assignee) ? menu.Items : others.Items,
  3271. String.Format("{0} {1}",
  3272. row.Get<KanbanSubscriber, int>(c => c.Kanban.Number),
  3273. row.Get<KanbanSubscriber, String>(c => c.Kanban.Title)),
  3274. row.Get<KanbanSubscriber, Guid>(c => c.Kanban.ID)
  3275. );
  3276. }
  3277. menu.Items.Add(new Separator());
  3278. menu.Items.Add(others);
  3279. menu.Items.Add(new Separator());
  3280. CreateTaskMenu(menu.Items, "(No Task Selected)", Guid.Empty);
  3281. }
  3282. menu.IsOpen = true;
  3283. }
  3284. private Assignment? _kanbantrackingassignment = null;
  3285. private void SetTrackingKanban(Guid kanbanID, string header)
  3286. {
  3287. SelectedTaskName.Content = header;
  3288. var createNewAssignment = false;
  3289. if (_kanbantrackingassignment is not null)
  3290. {
  3291. if (_kanbantrackingassignment.Actual.Finish < DateTime.Now.TimeOfDay)
  3292. {
  3293. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay;
  3294. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3295. }
  3296. // Update Existing Kanban
  3297. if (kanbanID == Guid.Empty)
  3298. _kanbantrackingassignment = null;
  3299. else if (_kanbantrackingassignment.Task.ID != kanbanID)
  3300. {
  3301. createNewAssignment = true;
  3302. }
  3303. }
  3304. else if (kanbanID != Guid.Empty)
  3305. {
  3306. createNewAssignment = true;
  3307. }
  3308. if (createNewAssignment)
  3309. {
  3310. _kanbantrackingassignment = new Assignment();
  3311. _kanbantrackingassignment.Task.ID = kanbanID;
  3312. _kanbantrackingassignment.EmployeeLink.ID = App.EmployeeID;
  3313. _kanbantrackingassignment.Title = header;
  3314. _kanbantrackingassignment.Date = DateTime.Today;
  3315. _kanbantrackingassignment.Actual.Start = DateTime.Now.TimeOfDay;
  3316. _kanbantrackingassignment.Actual.Finish = DateTime.Now.TimeOfDay.Add(new TimeSpan(0, 2, 0));
  3317. new Client<Assignment>().Save(_kanbantrackingassignment, "");
  3318. }
  3319. }
  3320. private void ClearTrackingKanban()
  3321. => SetTrackingKanban(Guid.Empty, "(No Task Selected)");
  3322. private void CreateTaskMenu(ItemCollection items, String title, Guid id)
  3323. {
  3324. var item = new MenuItem()
  3325. {
  3326. Header = title,
  3327. Tag = id
  3328. };
  3329. item.Click += (o, args) =>
  3330. {
  3331. if (o is not MenuItem menu) return;
  3332. SetTrackingKanban((Guid)item.Tag, (menu.Header as string) ?? "");
  3333. };
  3334. items.Add(item);
  3335. }
  3336. #endregion
  3337. private void DockPanel_OnIsActiveChanged(object? sender, EventArgs e)
  3338. {
  3339. var layout = sender as LayoutAnchorable;
  3340. if (layout == null)
  3341. return;
  3342. var content = layout.Content as DependencyObject;
  3343. var dock = content is IDockPanel panel ? panel : content?.FindVisualChildren<IDockPanel>().FirstOrDefault();
  3344. if (dock == null)
  3345. return;
  3346. if (layout.IsActive && layout.IsVisible)
  3347. dock.Refresh();
  3348. }
  3349. private void _ribbon_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  3350. {
  3351. e.Handled = true;
  3352. }
  3353. #region Backstage Functions
  3354. private void DatabaseSettings_OnClick(object sender, RoutedEventArgs e)
  3355. {
  3356. var config = new DataBaseConfiguration();
  3357. if (config.ShowDialog() == true)
  3358. {
  3359. var newsettings = new LocalConfiguration<DatabaseSettings>(App.Profile).Load();
  3360. if (newsettings.RestartRequired(App.DatabaseSettings))
  3361. MessageBox.Show("Please restart the application to apply these changes!");
  3362. if ((newsettings.DatabaseType == DatabaseType.Standalone) && (newsettings.ColorScheme != App.DatabaseSettings.ColorScheme))
  3363. {
  3364. App.DatabaseSettings.ColorScheme = newsettings.ColorScheme;
  3365. ApplyColorScheme();
  3366. }
  3367. }
  3368. }
  3369. private void CompanyInformation_OnClick(object sender, RoutedEventArgs e)
  3370. {
  3371. var info = new Client<CompanyInformation>().Load().FirstOrDefault();
  3372. if (info == null)
  3373. info = new CompanyInformation();
  3374. new DynamicDataGrid<CompanyInformation>().EditItems(new[] { info });
  3375. }
  3376. private void SecurityDefaultsButton_OnClick(object sender, RoutedEventArgs e)
  3377. {
  3378. var window = new GlobalTokenWindow();
  3379. window.ShowDialog();
  3380. Security.Reset();
  3381. }
  3382. private void SystemLogsButton_OnClick(object sender, RoutedEventArgs e)
  3383. {
  3384. var logfile = Path.Combine(CoreUtils.GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  3385. if (File.Exists(logfile))
  3386. {
  3387. var startInfo = new ProcessStartInfo("notepad.exe", logfile);
  3388. startInfo.Verb = "open";
  3389. startInfo.UseShellExecute = true;
  3390. Process.Start(startInfo);
  3391. }
  3392. else
  3393. {
  3394. MessageBox.Show(logfile + " does not exist!");
  3395. }
  3396. }
  3397. private void DocumentTypeList_OnClick(object sender, RoutedEventArgs e)
  3398. {
  3399. var list = new MasterList(typeof(DocumentType));
  3400. list.ShowDialog();
  3401. }
  3402. private void DocumentList_OnClick(object sender, RoutedEventArgs e)
  3403. {
  3404. var list = new MasterList(typeof(Document));
  3405. list.ShowDialog();
  3406. }
  3407. private void QAFormSetupButton_OnClick(object sender, RoutedEventArgs e)
  3408. {
  3409. var list = new MasterList(typeof(DigitalForm), "AppliesTo", null, true);
  3410. list.ShowDialog();
  3411. }
  3412. private void EditDetailsButton_OnClick(object sender, RoutedEventArgs e)
  3413. {
  3414. var employee = new Client<Employee>().Query(
  3415. new Filter<Employee>(x => x.UserLink.ID).IsEqualTo(ClientFactory.UserGuid))
  3416. .Rows.FirstOrDefault()?.ToObject<Employee>();
  3417. var item = new MyDetailsConfiguration(employee);
  3418. item.User = ClientFactory.UserGuid;
  3419. var buttons = new DynamicEditorButtons();
  3420. buttons.Add("Change Password", null, item, (sender, item) =>
  3421. {
  3422. var details = (item as MyDetailsConfiguration)!;
  3423. var changePassword = new ChangePassword(details.User);
  3424. if (changePassword.ShowDialog() == true && changePassword.Password != null)
  3425. {
  3426. var newUser = new User();
  3427. newUser.ID = details.User;
  3428. ChangePassword.ChangeUserPassword(newUser, changePassword.Password);
  3429. new Client<User>().Save(newUser, "Changed Password");
  3430. MessageBox.Show("Password changed!");
  3431. }
  3432. });
  3433. var editor = new DynamicEditorForm(typeof(MyDetailsConfiguration), buttons: buttons);
  3434. if (employee == null)
  3435. {
  3436. editor.OnFormCustomiseEditor += (sender, items, column, editor) =>
  3437. {
  3438. editor.Editable = Editable.Disabled;
  3439. };
  3440. }
  3441. editor.Items = new BaseObject[] { item };
  3442. if (editor.ShowDialog() == true)
  3443. {
  3444. if (employee != null)
  3445. {
  3446. item.SaveTo(employee);
  3447. new Client<Employee>().Save(employee, "Edited by user");
  3448. }
  3449. }
  3450. }
  3451. private void LogoutButton_OnClick(object sender, RoutedEventArgs e)
  3452. {
  3453. Logout();
  3454. }
  3455. private void LoginButton_OnClick(object sender, RoutedEventArgs e)
  3456. {
  3457. if (DoLogin(false) == ValidationResult.VALID)
  3458. AfterLogin();
  3459. }
  3460. private void ExitButton_OnClick(object sender, RoutedEventArgs e)
  3461. {
  3462. //_closingFromSystemMenu = true;
  3463. Close();
  3464. }
  3465. #endregion
  3466. }
  3467. }