MainWindow.xaml.cs 172 KB

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