MainWindow.xaml.cs 168 KB

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