MainWindow.xaml.cs 179 KB

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