MainWindow.xaml.cs 175 KB

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