MainWindow.xaml.cs 178 KB

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