MainWindow.xaml.cs 175 KB

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