MainWindow.xaml.cs 171 KB

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