MainWindow.xaml.cs 179 KB

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