MainWindow.xaml.cs 170 KB

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