MainWindow.xaml.cs 170 KB

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