MainWindow.xaml.cs 178 KB

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