MainWindow.xaml.cs 167 KB

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