SupplierBillPanel.xaml.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using Comal.Classes;
  8. using InABox.Clients;
  9. using InABox.Configuration;
  10. using InABox.Core;
  11. using InABox.DynamicGrid;
  12. using InABox.WPF;
  13. using InABox.Wpf;
  14. using System.Threading.Tasks;
  15. using System.IO;
  16. using System.Collections.ObjectModel;
  17. using System.Windows.Media;
  18. using System.Runtime.CompilerServices;
  19. using SuperSocket.ClientEngine;
  20. namespace PRSDesktop;
  21. public class SupplierBillPanelSettings : IUserConfigurationSettings
  22. {
  23. public SupplierBillPanelSettings()
  24. {
  25. AnchorWidth = 500F;
  26. ViewType = ScreenViewType.Combined;
  27. }
  28. public ScreenViewType ViewType { get; set; }
  29. public double AnchorWidth { get; set; }
  30. }
  31. public class SupplierBillPanelProperties : BaseObject, IGlobalConfigurationSettings
  32. {
  33. [IntegerEditor]
  34. [EditorSequence(1)]
  35. public int CurrencyDecimalPlaces { get; set; } = 2;
  36. [EditorSequence(2)]
  37. [CheckBoxEditor]
  38. public bool AllowBlankBillNumbers { get; set; }
  39. }
  40. public partial class SupplierBillPanel : UserControl, IPanel<Bill>, IPropertiesPanel<SupplierBillPanelProperties, CanConfigureAccountsPanels>, INotifyPropertyChanged
  41. {
  42. private SupplierBillPanelSettings settings;
  43. private SupplierBillEditLayout EditLayout;
  44. public SupplierBillPanel()
  45. {
  46. InitializeComponent();
  47. }
  48. #region IPanel Interface
  49. public bool IsReady { get; set; }
  50. public event DataModelUpdateEvent? OnUpdateDataModel;
  51. public Dictionary<string, object[]> Selected()
  52. {
  53. return new Dictionary<string, object[]> { { typeof(Bill).EntityName(), Bills.SelectedRows } };
  54. }
  55. public void CreateToolbarButtons(IPanelHost host)
  56. {
  57. AccountsSetupActions.Standard(host);
  58. PostUtils.CreateToolbarButtons(host,
  59. () => (DataModel(Selection.Selected) as IDataModel<Bill>)!,
  60. () => Bills.Refresh(false, true),
  61. true);
  62. host.CreateSetupSeparator();
  63. host.CreateSetupActionIfCanView<BillApprovalSet>("Bill Approval Sets", PRSDesktop.Resources.bill, (action) =>
  64. {
  65. var list = new MasterList(typeof(BillApprovalSet));
  66. list.ShowDialog();
  67. });
  68. host.CreateSetupActionIf<ManageBillApprovals>("Bill Approval Settings", PRSDesktop.Resources.edit, (action) =>
  69. {
  70. var settings = new GlobalConfiguration<BillApprovalSettings>().Load();
  71. if (DynamicGridUtils.EditEntity(settings))
  72. {
  73. new GlobalConfiguration<BillApprovalSettings>().Save(settings);
  74. }
  75. });
  76. }
  77. public string SectionName => "Supplier Bills";
  78. public SupplierBillPanelProperties Properties { get; set; }
  79. public DataModel DataModel(Selection selection)
  80. {
  81. var ids = Bills.ExtractValues(x => x.ID, selection).ToArray();
  82. return new BaseDataModel<Bill>(new Filter<Bill>(x => x.ID).InList(ids));
  83. }
  84. public void Refresh()
  85. {
  86. if (CheckSaved())
  87. {
  88. Bills.Refresh(false, true);
  89. SetChanged(false);
  90. }
  91. }
  92. public void Setup()
  93. {
  94. settings = new UserConfiguration<SupplierBillPanelSettings>().Load();
  95. SplitPanel.View = settings.ViewType == ScreenViewType.Register ? DynamicSplitPanelView.Master :
  96. settings.ViewType == ScreenViewType.Details ? DynamicSplitPanelView.Detail : DynamicSplitPanelView.Combined;
  97. SplitPanel.AnchorWidth = settings.AnchorWidth;
  98. EditLayout = new();
  99. EditLayout.Approve += EditLayout_Approve;
  100. Bill.SetLayout(EditLayout);
  101. Bills.Refresh(true, false);
  102. BillPanelDocumentCache.Cache.ClearOld();
  103. }
  104. #region Approval
  105. private BillApproval? _approval = null;
  106. private DynamicOneToManyGrid<Bill, BillApproval>? _approvalPage = null;
  107. private SupplierBillLineGrid? _billLinePage = null;
  108. private void EditLayout_Approve()
  109. {
  110. if (_approval is null) return;
  111. if(_approval.Approved == DateTime.MinValue)
  112. {
  113. _approval.Approved = DateTime.Now;
  114. EditLayout.IsApproved = true;
  115. }
  116. else
  117. {
  118. _approval.Approved = DateTime.MinValue;
  119. EditLayout.IsApproved = false;
  120. }
  121. Bill.DoChanged();
  122. if(_approvalPage is not null)
  123. {
  124. _approvalPage.SaveItem(_approval);
  125. _approvalPage.Refresh(false, true);
  126. _approvalPage.DoChanged();
  127. }
  128. }
  129. private void SaveApproval()
  130. {
  131. if (_approvalPage is not null || _approval is null) return;
  132. Client.Save(_approval, "Approval updated by user.");
  133. }
  134. private void CancelApproval()
  135. {
  136. UpdateApproval();
  137. }
  138. private void UpdateApproval()
  139. {
  140. if(_bills is not null && _bills.Length == 1)
  141. {
  142. if(Bill.Pages.TryGetPage<DynamicOneToManyGrid<Bill, BillApproval>>(out _approvalPage))
  143. {
  144. _approval = _approvalPage.Items.FirstOrDefault(x => x.Employee.ID == App.EmployeeID);
  145. _approvalPage.OnChanged -= _approvalPage_OnChanged;
  146. _approvalPage.OnChanged += _approvalPage_OnChanged;
  147. }
  148. else
  149. {
  150. _approval = Client.Query<BillApproval>(
  151. new Filter<BillApproval>(x => x.Employee.ID).IsEqualTo(App.EmployeeID)
  152. .And(x => x.Bill.ID).IsEqualTo(_bills[0].ID),
  153. Columns.Required<BillApproval>().Add(x => x.Approved))
  154. .ToObjects<BillApproval>().FirstOrDefault();
  155. }
  156. EditLayout.CanApprove = _approval is not null;
  157. EditLayout.IsApproved = _approval is not null ? _approval.Approved != DateTime.MinValue : false;
  158. if(Bill.Pages.TryGetPage(out _billLinePage))
  159. {
  160. _billLinePage.OnChanged -= BillLinePage_OnChanged;
  161. _billLinePage.OnChanged += BillLinePage_OnChanged;
  162. EditLayout.BillAmount = _billLinePage.Items.Sum(x => x.IncTax);
  163. EditLayout.POAmount = _billLinePage.Items.Sum(x =>
  164. {
  165. return x.OrderItem.IncTax + x.Consignment.IncTax;
  166. });
  167. }
  168. }
  169. else
  170. {
  171. _approval = null;
  172. EditLayout.CanApprove = false;
  173. }
  174. }
  175. private void _approvalPage_OnChanged(object? sender, EventArgs e)
  176. {
  177. EditLayout.CanApprove = _approval is not null;
  178. EditLayout.IsApproved = _approval is not null ? _approval.Approved != DateTime.MinValue : false;
  179. }
  180. private void BillLinePage_OnChanged(object? sender, EventArgs e)
  181. {
  182. if (_billLinePage is null) return;
  183. EditLayout.BillAmount = _billLinePage.Items.Sum(x => x.IncTax);
  184. EditLayout.POAmount = _billLinePage.Items.Sum(x =>
  185. {
  186. return x.OrderItem.IncTax + x.Consignment.IncTax;
  187. });
  188. }
  189. #endregion
  190. private void CheckSaved(CancelEventArgs cancel)
  191. {
  192. if (!bChanged)
  193. {
  194. return;
  195. }
  196. var result = MessageBox.Show("You have an unsaved Supplier Bill; do you wish to save these changes?", "Save Changes?", MessageBoxButton.YesNoCancel);
  197. if (result == MessageBoxResult.Yes)
  198. {
  199. Bill.SaveItem(cancel);
  200. if (!cancel.Cancel)
  201. {
  202. MessageBox.Show("Purchase Order saved.");
  203. }
  204. }
  205. else if (result == MessageBoxResult.Cancel)
  206. {
  207. cancel.Cancel = true;
  208. }
  209. }
  210. private bool CheckSaved()
  211. {
  212. var cancel = new CancelEventArgs();
  213. CheckSaved(cancel);
  214. return !cancel.Cancel;
  215. }
  216. public void Shutdown(CancelEventArgs? cancel)
  217. {
  218. if(cancel is not null)
  219. {
  220. CheckSaved(cancel);
  221. }
  222. }
  223. public void Heartbeat(TimeSpan time)
  224. {
  225. }
  226. #endregion
  227. private Bill[]? _bills = null;
  228. private CoreRow[]? _editRows = null;
  229. private void Bills_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  230. {
  231. if(SplitPanel.View != DynamicSplitPanelView.Master)
  232. {
  233. ReloadBills();
  234. }
  235. }
  236. private void ReloadBills()
  237. {
  238. var newRows = Bills.SelectedRows;
  239. if (newRows.Length != 0)
  240. {
  241. if(_editRows is null || !newRows.CompareTo(_editRows))
  242. {
  243. _editRows = Bills.SelectedRows;
  244. _bills = Bills.LoadBills(_editRows);
  245. Bills.InitialiseEditorForm(Bill, _bills, null, true);
  246. Bill.Visibility = Visibility.Visible;
  247. LinkDocumentPage();
  248. UpdateApproval();
  249. }
  250. }
  251. else
  252. {
  253. _bills = null;
  254. _editRows = null;
  255. Bill.Visibility = Visibility.Hidden;
  256. ClearDocumentPage();
  257. UpdateApproval();
  258. }
  259. }
  260. private void Bill_OnOnOK()
  261. {
  262. using (new WaitCursor())
  263. {
  264. var cancel = new System.ComponentModel.CancelEventArgs();
  265. Bill.SaveItem(cancel);
  266. if (!cancel.Cancel)
  267. {
  268. SaveApproval();
  269. if(_editRows is not null && _bills is not null)
  270. {
  271. Bills.UpdateRows(_editRows, _bills);
  272. }
  273. ReloadBills();
  274. SetChanged(false);
  275. }
  276. }
  277. }
  278. private void Bill_OnOnCancel()
  279. {
  280. CancelApproval();
  281. ReloadBills();
  282. SetChanged(false);
  283. }
  284. private void SetChanged(bool changed)
  285. {
  286. bChanged = changed;
  287. Bills.IsEnabled = !changed;
  288. Bill.HideButtons = !changed;
  289. if (!changed)
  290. {
  291. bDocumentsChanged = false;
  292. DoPropertyChanged(nameof(CanRotateImage));
  293. }
  294. }
  295. private bool bChanged = false;
  296. private void Bill_OnOnChanged(object? sender, EventArgs e)
  297. {
  298. SetChanged(true);
  299. }
  300. private void SplitPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  301. {
  302. settings.ViewType = SplitPanel.View == DynamicSplitPanelView.Master ? ScreenViewType.Register :
  303. SplitPanel.View == DynamicSplitPanelView.Detail ? ScreenViewType.Details : ScreenViewType.Combined;
  304. settings.AnchorWidth = SplitPanel.AnchorWidth;
  305. new UserConfiguration<SupplierBillPanelSettings>().Save(settings);
  306. }
  307. #region Documents
  308. private DynamicDocumentGrid<BillDocument, Bill, BillLink>? DocumentPage;
  309. public bool CanRotateImage => !bDocumentsChanged;
  310. private void ClearDocumentPage()
  311. {
  312. ViewList.Documents = [];
  313. }
  314. private void LinkDocumentPage()
  315. {
  316. DocumentPage = Bill.Pages.OfType<DynamicDocumentGrid<BillDocument, Bill, BillLink>>().FirstOrDefault();
  317. if(DocumentPage is not null)
  318. {
  319. DocumentPage.AfterRefresh += (o, e) =>
  320. {
  321. if (bRefreshingDocuments)
  322. {
  323. return;
  324. }
  325. ReloadViewList(true);
  326. };
  327. DocumentPage.OnChanged += DocumentPage_OnChanged;
  328. }
  329. }
  330. private bool bRefreshingDocuments = false;
  331. private bool bDocumentsChanged = false;
  332. private void DocumentPage_OnChanged(object? sender, EventArgs e)
  333. {
  334. bDocumentsChanged = true;
  335. DoPropertyChanged(nameof(CanRotateImage));
  336. if (bRefreshingDocuments)
  337. {
  338. return;
  339. }
  340. ReloadViewList();
  341. }
  342. private void ReloadViewList(bool force = false)
  343. {
  344. if(DocumentPage is null)
  345. {
  346. return;
  347. }
  348. ViewList.UpdateViewList(DocumentPage.LoadItems(DocumentPage.Data.Rows), force);
  349. }
  350. private void ViewList_UpdateDocument(BillDocument document, Document doc)
  351. {
  352. if(DocumentPage is null)
  353. {
  354. return;
  355. }
  356. if (Path.GetExtension(doc.FileName) == ".pdf")
  357. {
  358. document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256);
  359. }
  360. Client.Save(document, "");
  361. BillPanelDocumentCache.Cache.Add(new DocumentCachedDocument(doc));
  362. DocumentPage.Refresh(false, true);
  363. ViewList.UpdateViewList(DocumentPage.LoadItems(DocumentPage.Data.Rows), true);
  364. }
  365. private void Documents_DragOver(object sender, DragEventArgs e)
  366. {
  367. if(Bills.SelectedRows.Length == 0)
  368. {
  369. e.Effects = DragDropEffects.None;
  370. }
  371. else
  372. {
  373. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  374. {
  375. e.Effects = DragDropEffects.Copy;
  376. }
  377. else
  378. {
  379. e.Effects = DragDropEffects.None;
  380. }
  381. }
  382. e.Handled = true;
  383. }
  384. private void Documents_Drop(object sender, DragEventArgs e)
  385. {
  386. if(Bills.SelectedRows.Length == 0 || DocumentPage is null)
  387. {
  388. return;
  389. }
  390. var selectedBill = Bills.SelectedRows[0].ToObject<Bill>();
  391. Task.Run(() =>
  392. {
  393. Dispatcher.Invoke(() =>
  394. {
  395. Progress.Show("Uploading documents");
  396. try
  397. {
  398. var result = DocumentUtils.HandleFileDrop(e);
  399. if (result is not null)
  400. {
  401. var docs = new List<Document>();
  402. foreach (var (filename, stream) in result)
  403. {
  404. var doc = new Document();
  405. doc.FileName = filename;
  406. if (stream is null)
  407. {
  408. doc.Data = File.ReadAllBytes(filename);
  409. doc.TimeStamp = new FileInfo(filename).LastWriteTime;
  410. }
  411. else
  412. {
  413. using var memStream = new MemoryStream();
  414. stream.CopyTo(memStream);
  415. doc.Data = memStream.ToArray();
  416. doc.TimeStamp = DateTime.Now;
  417. }
  418. doc.CRC = CoreUtils.CalculateCRC(doc.Data);
  419. docs.Add(doc);
  420. }
  421. Client.Save(docs, "Initial Upload");
  422. var billDocs = new List<BillDocument>();
  423. foreach (var doc in docs)
  424. {
  425. var billDoc = new BillDocument();
  426. billDoc.DocumentLink.CopyFrom(doc);
  427. billDoc.EntityLink.CopyFrom(selectedBill);
  428. billDocs.Add(billDoc);
  429. }
  430. DocumentPage.SaveItems(billDocs);
  431. try
  432. {
  433. bRefreshingDocuments = true;
  434. DocumentPage.DoChanged();
  435. }
  436. finally
  437. {
  438. bRefreshingDocuments = false;
  439. }
  440. }
  441. Progress.Close();
  442. }
  443. catch (Exception e)
  444. {
  445. Progress.Close();
  446. MessageWindow.ShowError("Could not upload documents.", e);
  447. }
  448. });
  449. });
  450. }
  451. #endregion
  452. public event PropertyChangedEventHandler? PropertyChanged;
  453. protected void DoPropertyChanged([CallerMemberName] string propertyName = "")
  454. {
  455. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  456. }
  457. }
  458. public class BillDocumentViewList : DocumentViewList<BillDocument>
  459. {
  460. protected override IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids)
  461. {
  462. return BillPanelDocumentCache.Cache.LoadDocuments(ids, checkTimestamp: true);
  463. }
  464. protected override Guid GetID(BillDocument document)
  465. {
  466. return document.ID;
  467. }
  468. protected override Guid GetDocumentID(BillDocument document)
  469. {
  470. return document.DocumentLink.ID;
  471. }
  472. }
  473. public class BillPanelDocumentCache : DocumentCache
  474. {
  475. public override TimeSpan MaxAge => TimeSpan.FromHours(1);
  476. private static BillPanelDocumentCache? _cache;
  477. public static BillPanelDocumentCache Cache
  478. {
  479. get
  480. {
  481. _cache ??= DocumentCaches.GetOrRegister<BillPanelDocumentCache>();
  482. return _cache;
  483. }
  484. }
  485. public BillPanelDocumentCache() : base(nameof(BillPanelDocumentCache))
  486. {
  487. }
  488. }