LicenseRenewalForm.xaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Windows;
  5. using InABox.Clients;
  6. using InABox.Core;
  7. using InABox.DynamicGrid;
  8. using InABox.Wpf;
  9. using InABox.WPF;
  10. using System.Windows.Controls;
  11. using System.Drawing;
  12. using Image = System.Windows.Controls.Image;
  13. using System.Diagnostics;
  14. using InABox.Client.Remote.Json;
  15. using InABox.Configuration;
  16. using Microsoft.Win32;
  17. using PRS.Shared;
  18. using Stripe;
  19. namespace PRSServer.Forms.DatabaseLicense;
  20. /// <summary>
  21. /// Interaction logic for LicenseRenewal.xaml
  22. /// </summary>
  23. public partial class LicenseRenewalForm : ThemableWindow, IDynamicEditorHost
  24. {
  25. public static HttpJsonClient LicenseClient = new("https", "remote.prsdigital.com.au", 5000);
  26. //public static HttpJsonClient LicenseClient = new("http", "127.0.0.1", 8001);
  27. private static readonly EncryptedLocalConfiguration<LicenseRegistrationDetails> _config = new("g6+BoQpyti5bHsTZOY5Nbqq3Q3c90n0m3qZaQ3eAwkk=");
  28. private LicenseRegistrationDetails _licenseRegistrationDetails;
  29. private LicenseData? _currentLicense;
  30. public LicenseData? CurrentLicense
  31. {
  32. get => _currentLicense;
  33. set
  34. {
  35. _currentLicense = value;
  36. Modules.CurrentLicense = value;
  37. }
  38. }
  39. public int RenewalPeriod
  40. {
  41. get
  42. {
  43. if (int.TryParse(RenewalPeriodEditor.Value?.ToString(), out var period))
  44. {
  45. return period;
  46. }
  47. return 0;
  48. }
  49. set
  50. {
  51. RenewalPeriodEditor.Value = value;
  52. CalculateDiscounts();
  53. }
  54. }
  55. public DateTime RenewalDate
  56. {
  57. get
  58. {
  59. if(CurrentLicense == null)
  60. {
  61. return DateTime.MinValue;
  62. }
  63. if (CurrentLicense.Expiry > DateTime.Now)
  64. {
  65. return CurrentLicense.Expiry.Date;
  66. }
  67. return DateTime.Today;
  68. }
  69. }
  70. private DateTime _renewalAvailable;
  71. public DateTime RenewalAvailableFrom
  72. {
  73. get => _renewalAvailable;
  74. set
  75. {
  76. _renewalAvailable = value;
  77. if (!CanRenew)
  78. {
  79. RenewalAvailableLabel.Content = $"Renewal available from {value:dd MMM yyyy}";
  80. }
  81. }
  82. }
  83. public bool CanRenew => RenewalAvailableFrom.Date <= DateTime.Today || (CurrentLicense != null && CurrentLicense.Expiry <= DateTime.Now);
  84. public DateTime NewExpiration
  85. {
  86. get => RenewalDate.AddMonths(RenewalPeriod);
  87. }
  88. public List<LicenseTrackingItem> LicenseItems { get; private set; }
  89. public int Licenses { get; private set; }
  90. public double Gross { get; private set; }
  91. public double Discount { get; private set; }
  92. public double Net => Gross - Discount;
  93. public LicenseRenewalForm()
  94. {
  95. InitializeComponent();
  96. // This should get us the RegistrationID, which we need in order
  97. // to get the License Pricing from the Server
  98. _licenseRegistrationDetails = _config.Load(false);
  99. LastRenewal.EditorDefinition = new DateEditor();
  100. LastRenewal.Configure();
  101. LastRenewal.IsEnabled = false;
  102. CurrentExpiry.EditorDefinition = new DateEditor();
  103. CurrentExpiry.Configure();
  104. CurrentExpiry.IsEnabled = false;
  105. RenewalPeriodEditor.EditorDefinition = new ComboLookupEditor(typeof(RenewalPeriodLookups));
  106. RenewalPeriodEditor.Host = this;
  107. RenewalPeriodEditor.Configure();
  108. var lookups = new RenewalPeriodLookups(null).AsTable("RenewalPeriod");
  109. RenewalPeriodEditor.LoadLookups(lookups);
  110. NewExpiry.EditorDefinition = new DateEditor();
  111. NewExpiry.Configure();
  112. NewExpiry.IsEnabled = false;
  113. GrossLicenseFee.EditorDefinition = new CurrencyEditor();
  114. GrossLicenseFee.Configure();
  115. GrossLicenseFee.IsEnabled = false;
  116. DiscountEditor.EditorDefinition = new DoubleEditor();
  117. DiscountEditor.Configure();
  118. DiscountEditor.IsEnabled = false;
  119. NettLicenseFee.EditorDefinition = new CurrencyEditor();
  120. NettLicenseFee.Configure();
  121. NettLicenseFee.IsEnabled = false;
  122. Help.Content = new Image { Source = Properties.Resources.help.AsBitmapImage(Color.White) };
  123. Help.Click += Help_Click;
  124. }
  125. private void Help_Click(object sender, RoutedEventArgs e)
  126. {
  127. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/License_Renewal") { UseShellExecute = true });
  128. }
  129. private void LoadData()
  130. {
  131. var result = Progress.ShowModal<bool>("Getting License", progress =>
  132. {
  133. try
  134. {
  135. progress.Report("Loading License");
  136. CurrentLicense = LoadCurrentLicense();
  137. progress.Report("Checking Server");
  138. if (!LicenseClient.Ping("ping"))
  139. return Result.Error("Server Unavailable");
  140. progress.Report("Retrieving Data");
  141. RetrieveFees();
  142. progress.Report("Scanning Data");
  143. LoadUserTracking();
  144. foreach (var item in LicenseItems)
  145. item.Rate = LicenseUtils.GetLicenseFee(item.Type);
  146. return Result.Ok(true);
  147. }
  148. catch (Exception e)
  149. {
  150. return Result.Error(e.Message);
  151. }
  152. });
  153. if (result.Get(out var success, out var error) && success)
  154. {
  155. UpdateWindow();
  156. }
  157. else
  158. {
  159. MessageWindow.ShowMessage(error ?? "Error", "Error");
  160. LicenseItems = new();
  161. IsEnabled = false;
  162. UpdateWindow();
  163. }
  164. }
  165. private void UpdateWindow()
  166. {
  167. // Always a minimum of one license required!
  168. Licenses = Math.Max(1, LicenseItems.OrderByDescending(x => x.Users).FirstOrDefault()?.Users ?? 0);
  169. Modules.Items = LicenseItems;
  170. Modules.Refresh(true, true);
  171. var lookups = new RenewalPeriodLookups(null).AsTable("RenewalPeriod");
  172. RenewalPeriodEditor.LoadLookups(lookups);
  173. RenewalPeriodEditor.Loaded = true;
  174. RenewalPeriod = LicenseUtils.TimeDiscountLevels().OrderBy(x => x).FirstOrDefault();
  175. PayWithStripe.IsEnabled = CanRenew;
  176. if (!PayWithStripe.IsEnabled)
  177. {
  178. PayTooltip.Visibility = Visibility.Visible;
  179. PayTooltip.Content = new Label { Content = $"Renewal available from {RenewalAvailableFrom:dd MMM yyyy}" };
  180. }
  181. else
  182. PayTooltip.Visibility = Visibility.Collapsed;
  183. LastRenewal.Loaded = true;
  184. CurrentExpiry.Loaded = true;
  185. NewExpiry.Loaded = true;
  186. //PayWithStripe.IsEnabled = false;
  187. PayTooltip.Visibility = Visibility.Visible;
  188. PayTooltip.Content = new Label { Content = "Loading..." };
  189. LastRenewal.Value = CurrentLicense?.LastRenewal ?? DateTime.MinValue;
  190. CurrentExpiry.Value = CurrentLicense?.Expiry ?? DateTime.MinValue;
  191. RenewalAvailableFrom = CurrentLicense?.RenewalAvailable ?? DateTime.MinValue;
  192. }
  193. private void Window_Loaded(object sender, RoutedEventArgs e)
  194. {
  195. LoadData();
  196. }
  197. private void RetrieveFees()
  198. {
  199. var summary = LicenseClient.PostRequest<LicenseFeeResponse>(
  200. new LicenseFeeRequest() { RegistrationID = CurrentLicense?.CustomerID ?? Guid.Empty },
  201. nameof(LicenseFeeRequest)
  202. );
  203. LicenseUtils.LoadSummary(summary);
  204. }
  205. private void LoadUserTracking()
  206. {
  207. var renewaldate = _currentLicense?.LastRenewal ?? DateTime.MinValue;
  208. var filter = !renewaldate.IsEmpty()
  209. ? new Filter<UserTracking>(x => x.Date).IsGreaterThanOrEqualTo(renewaldate).And(x => x.TotalWrite).IsNotEqualTo(0)
  210. : new Filter<UserTracking>(x => x.TotalWrite).IsNotEqualTo(0);
  211. var data = new Client<UserTracking>()
  212. .Query(
  213. filter,
  214. InABox.Core.Columns.None<UserTracking>().Add(x => x.User.ID)
  215. .Add(x => x.Type));
  216. var typesummary = data.Rows.GroupBy(r => r.Get<UserTracking, String>(c => c.Type)).ToArray();
  217. //Licenses = data.ExtractValues<UserTracking, Guid>(x => x.User.ID).Distinct().Count();
  218. var licensemap = LicenseUtils.LicenseMap();
  219. var result = new List<LicenseTrackingItem>();
  220. foreach (var map in licensemap)
  221. {
  222. var type = map.Value.EntityName();
  223. var item = result.FirstOrDefault(x => Equals(x.Type, type));
  224. if (item == null)
  225. {
  226. item = new LicenseTrackingItem()
  227. {
  228. Type = type,
  229. Caption = map.Value.GetCaption(),
  230. };
  231. result.Add(item);
  232. }
  233. var users = typesummary
  234. .FirstOrDefault(x => Equals(x.Key, map.Key.EntityName().Split('.').Last()))?
  235. .Select(r=>r.Get<UserTracking,Guid>(x=>x.User.ID))
  236. .Distinct()
  237. .Where(x=>!item.UserIDs.Contains(x));
  238. if (users != null)
  239. item.UserIDs.AddRange(users);
  240. }
  241. LicenseItems = result
  242. .OrderBy(x=>x.Caption)
  243. .ToList();
  244. }
  245. private static LicenseData? LoadCurrentLicense()
  246. {
  247. var license = new Client<License>().Query(
  248. new Filter<License>().All(),
  249. InABox.Core.Columns.None<License>().Add(x => x.Data))
  250. .Rows.FirstOrDefault()?.ToObject<License>();
  251. if(license == null)
  252. {
  253. MessageBox.Show("No current license found. Please see the documentation on how to proceed.");
  254. return null;
  255. }
  256. if(!LicenseUtils.TryDecryptLicense(license.Data, out var data, out var error))
  257. {
  258. MessageBox.Show("Current license is corrupt. Please see the documentation on how to proceed.");
  259. return null;
  260. }
  261. return data;
  262. }
  263. private void RenewalPeriod_OnEditorValueChanged(IDynamicEditorControl sender, Dictionary<string, object> values)
  264. {
  265. CalculateDiscounts();
  266. }
  267. private void CalculateDiscounts()
  268. {
  269. double CalcDiscount(double amount, int months)
  270. {
  271. return (amount * (LicenseUtils.GetUserDiscount(Licenses) / 100.0F)) +
  272. (amount * (LicenseUtils.GetTimeDiscount(months) / 100.0F));
  273. }
  274. var periodInMonths = RenewalPeriod;
  275. NewExpiry.Value = NewExpiration;
  276. double total = 0.0F;
  277. if (CurrentLicense?.IsDynamic == true)
  278. {
  279. foreach (var row in Modules.Data.Rows)
  280. total += row.Get<LicenseTrackingItem, double>(x => x.ExGST) * periodInMonths;
  281. Gross = total;
  282. Discount = CalcDiscount(total, periodInMonths);
  283. }
  284. else
  285. {
  286. foreach (var row in Modules.Data.Rows)
  287. total += Licenses * LicenseUtils.GetLicenseFee(row.Get<LicenseTrackingItem, String>(x => x.Type)) * periodInMonths;
  288. Gross = Math.Round(total) - 0.05;
  289. Gross = total;
  290. Discount = Math.Round(CalcDiscount(total, periodInMonths) * 20F) / 20F;
  291. }
  292. GrossLicenseFee.Value = Gross;
  293. DiscountEditor.Value = Discount;
  294. NettLicenseFee.Value = Net;
  295. PayWithStripe.IsEnabled = CanRenew && Net > 0;
  296. }
  297. private class RenewalPeriodLookups : LookupGenerator<object>
  298. {
  299. public RenewalPeriodLookups(object[] items) : base(items)
  300. {
  301. }
  302. protected override void DoGenerateLookups()
  303. {
  304. foreach (var period in LicenseUtils.TimeDiscountLevels())
  305. AddValue(period, string.Format("{0} month{1}", period, period > 1 ? "s" : ""));
  306. }
  307. }
  308. private void PayNowClick(object sender, RoutedEventArgs e)
  309. {
  310. if (!LicenseClient.Ping("ping"))
  311. {
  312. MessageBox.Show("The PRS server is not available right now. Please try again later.");
  313. return;
  314. }
  315. var grid = new LicenseRegistrationGrid();
  316. if (grid.EditItems(new LicenseRegistrationDetails[] { _licenseRegistrationDetails }))
  317. {
  318. _config.Save(_licenseRegistrationDetails);
  319. Result<string, string> result = Result.Error("Incomplete");
  320. var renewalRequest = CreateRenewal();
  321. Progress.ShowModal("Processing", progress =>
  322. {
  323. if (renewalRequest.Net > 0.0F)
  324. {
  325. // Process the Stripe Payment
  326. progress.Report("Processing Payment");
  327. result = ProcessStripePayment();
  328. if (!result.IsOK)
  329. return;
  330. }
  331. else
  332. result = Result.Ok("no payment required");
  333. progress.Report("Creating Renewal");
  334. if (result.Get(out var value, out var error))
  335. {
  336. result = RenewLicense(renewalRequest, value);
  337. }
  338. if(result.Get(out value, out error))
  339. {
  340. progress.Report("Saving License");
  341. SaveLicense(value);
  342. }
  343. });
  344. if (!result.Get(out var value, out var error))
  345. MessageWindow.ShowMessage(error, "Error");
  346. else
  347. {
  348. MessageWindow.ShowMessage("License Updated Successfully!","Success");
  349. Close();
  350. }
  351. }
  352. }
  353. private Result<string, string> ProcessStripePayment()
  354. {
  355. var result = "";
  356. var error = "";
  357. try
  358. {
  359. StripeConfiguration.ApiKey =
  360. "pk_live_51MRSuPIyPMVqmkXNiIu0BjTHWrfIvsWalXqYsebuTr27JF08jwk9KunHfvTrI30bojbQJgr0fWD3RkBXVnDsF75v00ryCeqOav";
  361. //StripeConfiguration.ApiKey = "sk_test_51MRSuPIyPMVqmkXN8TeGxDAGBeFx0pLzn3fsHBR8X1oMBKQVwGPEbuv6DNIu0qSmuflpmFfQ4N8c3vzdknKa7G0o00wTOXwCeW";
  362. var cardoptions = new TokenCreateOptions()
  363. {
  364. Card = new TokenCardOptions()
  365. {
  366. Number = _licenseRegistrationDetails.Card.CardNumber.Replace(" ", ""),
  367. ExpMonth = _licenseRegistrationDetails.Card.Month,
  368. ExpYear = _licenseRegistrationDetails.Card.Year,
  369. Cvc = _licenseRegistrationDetails.Card.Cvv
  370. }
  371. };
  372. var service = new TokenService();
  373. var token = service.Create(cardoptions);
  374. var chargeoptions = new ChargeCreateOptions()
  375. {
  376. Amount = Convert.ToInt64(Gross * 100),
  377. Currency = "AUD",
  378. Description = "PRS Renewal",
  379. Source = token.Id
  380. };
  381. var chargeservice = new ChargeService();
  382. var charge = chargeservice.Create(chargeoptions);
  383. if (charge.Paid)
  384. result = charge.Id;
  385. else
  386. error = string.Format("{0}: {1}", charge.FailureCode, charge.FailureMessage);
  387. }
  388. catch (Exception ex)
  389. {
  390. error = $"{ex.Message}";
  391. }
  392. if (!string.IsNullOrWhiteSpace(error))
  393. return Result.Error(error);
  394. return Result.Ok(result);
  395. }
  396. private LicenseRenewalRequest CreateRenewal()
  397. {
  398. return new LicenseRenewalRequest
  399. {
  400. Company = _licenseRegistrationDetails.Company,
  401. DateRenewed = RenewalDate,
  402. OldLicense = CurrentLicense,
  403. NewExpiry = NewExpiration,
  404. LicenseTracking = LicenseItems.ToArray(),
  405. Gross = Gross,
  406. Discount = Discount,
  407. Net = Net,
  408. Addresses = LicenseUtils.GetMacAddresses(),
  409. };
  410. }
  411. private Result<string, string> RenewLicense(LicenseRenewalRequest renewalRequest, String transactionID)
  412. {
  413. renewalRequest.TransactionID = transactionID;
  414. try
  415. {
  416. var result = LicenseClient.PostRequest<LicenseRenewalResult>(renewalRequest, nameof(LicenseRenewalRequest));
  417. return Result.Ok(result.License);
  418. }
  419. catch (Exception e)
  420. {
  421. return Result.Error(e.Message);
  422. }
  423. }
  424. private void SaveLicense(string license)
  425. {
  426. using var client = new Client<License>();
  427. var oldLicenses = client
  428. .Query(
  429. new Filter<License>().All(),
  430. InABox.Core.Columns.None<License>().Add(x => x.ID))
  431. .Rows.Select(x => x.ToObject<License>()).ToList();
  432. client.Delete(oldLicenses, "");
  433. client.Save(new License() { Data = license }, "");
  434. }
  435. #region IDynamicEditorHost
  436. public void LoadLookups(ILookupEditorControl editor)
  437. {
  438. }
  439. public BaseObject[] GetItems()
  440. {
  441. return new BaseObject[] { };
  442. }
  443. public Type GetEditorType() => typeof(BaseObject);
  444. public BaseEditor? GetEditor(DynamicGridColumn column)
  445. {
  446. return new NullEditor();
  447. }
  448. #endregion
  449. private void EnterKey_Click(object sender, RoutedEventArgs e)
  450. {
  451. if (EnterKey?.ContextMenu != null)
  452. EnterKey.ContextMenu.IsOpen = true;
  453. }
  454. private void CreateManualRequest(object sender, RoutedEventArgs e)
  455. {
  456. var request = new LicenseRequest()
  457. {
  458. CustomerID = CurrentLicense?.CustomerID ?? Guid.Empty,
  459. Addresses = LicenseUtils.GetMacAddresses(),
  460. IsDynamic = CurrentLicense?.IsDynamic ?? false,
  461. };
  462. SaveFileDialog sfd = new SaveFileDialog()
  463. {
  464. FileName = "license.request"
  465. };
  466. if (sfd.ShowDialog() == true)
  467. {
  468. System.IO.File.WriteAllText(sfd.FileName, LicenseUtils.EncryptLicenseRequest(request));
  469. MessageWindow.ShowMessage("Please email this file to support@prsdigital.com.au!","Request Created");
  470. }
  471. }
  472. private void LoadManualResponse(object sender, RoutedEventArgs e)
  473. {
  474. var ofd = new OpenFileDialog()
  475. {
  476. FileName = "license.key",
  477. Filter = "License Files (*.key)|*.key"
  478. };
  479. if (ofd.ShowDialog() == true && System.IO.File.Exists(ofd.FileName))
  480. {
  481. var text = System.IO.File.ReadAllText(ofd.FileName);
  482. if (LicenseUtils.TryDecryptLicense(text, out var data, out var _))
  483. {
  484. if (LicenseUtils.ValidateMacAddresses(data.Addresses))
  485. {
  486. SaveLicense(text);
  487. MessageWindow.ShowMessage("License Updated", "Success");
  488. Close();
  489. }
  490. else
  491. MessageWindow.ShowMessage("License Key is not valid!","Invalid Key");
  492. }
  493. else
  494. MessageWindow.ShowMessage("License Key is not valid!","Bad Key");
  495. }
  496. }
  497. }