MainWindow.xaml.cs 166 KB

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