MainWindow.xaml.cs 179 KB

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