MainWindow.xaml.cs 176 KB

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