MainWindow.xaml.cs 180 KB

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