MainWindow.xaml.cs 178 KB

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