SupplierBillPanel.xaml.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. _approvalPage?.SaveItem(_approval);
  116. _approvalPage?.Refresh(false, true);
  117. _approvalPage?.DoChanged();
  118. }
  119. else
  120. {
  121. _approval.Approved = DateTime.MinValue;
  122. EditLayout.IsApproved = false;
  123. _approvalPage?.SaveItem(_approval);
  124. _approvalPage?.Refresh(false, true);
  125. _approvalPage?.DoChanged();
  126. }
  127. }
  128. private void UpdateApproval()
  129. {
  130. if(_bills is not null && _bills.Length == 1)
  131. {
  132. if(Bill.Pages.TryGetPage<DynamicOneToManyGrid<Bill, BillApproval>>(out _approvalPage))
  133. {
  134. _approval = _approvalPage.Items.FirstOrDefault(x => x.Employee.ID == App.EmployeeID);
  135. EditLayout.CanApprove = _approval is not null;
  136. EditLayout.IsApproved = _approval is not null ? _approval.Approved != DateTime.MinValue : false;
  137. if(Bill.Pages.TryGetPage(out _billLinePage))
  138. {
  139. _billLinePage.OnChanged += BillLinePage_OnChanged;
  140. EditLayout.BillAmount = _billLinePage.Items.Sum(x => x.IncTax);
  141. EditLayout.POAmount = _billLinePage.Items.Sum(x =>
  142. {
  143. return x.OrderItem.IncTax + x.Consignment.IncTax;
  144. });
  145. }
  146. }
  147. else
  148. {
  149. _approval = null;
  150. EditLayout.CanApprove = false;
  151. }
  152. }
  153. else
  154. {
  155. _approval = null;
  156. EditLayout.CanApprove = false;
  157. }
  158. }
  159. private void BillLinePage_OnChanged(object? sender, EventArgs e)
  160. {
  161. if (_billLinePage is null) return;
  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. #endregion
  169. private void CheckSaved(CancelEventArgs cancel)
  170. {
  171. if (!bChanged)
  172. {
  173. return;
  174. }
  175. var result = MessageBox.Show("You have an unsaved Supplier Bill; do you wish to save these changes?", "Save Changes?", MessageBoxButton.YesNoCancel);
  176. if (result == MessageBoxResult.Yes)
  177. {
  178. Bill.SaveItem(cancel);
  179. if (!cancel.Cancel)
  180. {
  181. MessageBox.Show("Purchase Order saved.");
  182. }
  183. }
  184. else if (result == MessageBoxResult.Cancel)
  185. {
  186. cancel.Cancel = true;
  187. }
  188. }
  189. private bool CheckSaved()
  190. {
  191. var cancel = new CancelEventArgs();
  192. CheckSaved(cancel);
  193. return !cancel.Cancel;
  194. }
  195. public void Shutdown(CancelEventArgs? cancel)
  196. {
  197. if(cancel is not null)
  198. {
  199. CheckSaved(cancel);
  200. }
  201. }
  202. public void Heartbeat(TimeSpan time)
  203. {
  204. }
  205. #endregion
  206. private Bill[]? _bills = null;
  207. private CoreRow[]? _editRows = null;
  208. private void Bills_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  209. {
  210. if(SplitPanel.View != DynamicSplitPanelView.Master)
  211. {
  212. ReloadBills();
  213. }
  214. }
  215. private void ReloadBills()
  216. {
  217. var newRows = Bills.SelectedRows;
  218. if (newRows.Length != 0)
  219. {
  220. if(_editRows is null || !newRows.CompareTo(_editRows))
  221. {
  222. _editRows = Bills.SelectedRows;
  223. _bills = Bills.LoadBills(_editRows);
  224. Bills.InitialiseEditorForm(Bill, _bills, null, true);
  225. Bill.Visibility = Visibility.Visible;
  226. LinkDocumentPage();
  227. UpdateApproval();
  228. }
  229. }
  230. else
  231. {
  232. _bills = null;
  233. _editRows = null;
  234. Bill.Visibility = Visibility.Hidden;
  235. ClearDocumentPage();
  236. UpdateApproval();
  237. }
  238. }
  239. private void Bill_OnOnOK()
  240. {
  241. using (new WaitCursor())
  242. {
  243. var cancel = new System.ComponentModel.CancelEventArgs();
  244. Bill.SaveItem(cancel);
  245. if (!cancel.Cancel)
  246. {
  247. if(_editRows is not null && _bills is not null)
  248. {
  249. Bills.UpdateRows(_editRows, _bills);
  250. }
  251. ReloadBills();
  252. SetChanged(false);
  253. }
  254. }
  255. }
  256. private void Bill_OnOnCancel()
  257. {
  258. ReloadBills();
  259. SetChanged(false);
  260. }
  261. private void SetChanged(bool changed)
  262. {
  263. bChanged = changed;
  264. Bills.IsEnabled = !changed;
  265. Bill.HideButtons = !changed;
  266. if (!changed)
  267. {
  268. bDocumentsChanged = false;
  269. DoPropertyChanged(nameof(CanRotateImage));
  270. }
  271. }
  272. private bool bChanged = false;
  273. private void Bill_OnOnChanged(object? sender, EventArgs e)
  274. {
  275. SetChanged(true);
  276. }
  277. private void SplitPanel_OnChanged(object sender, DynamicSplitPanelSettings e)
  278. {
  279. settings.ViewType = SplitPanel.View == DynamicSplitPanelView.Master ? ScreenViewType.Register :
  280. SplitPanel.View == DynamicSplitPanelView.Detail ? ScreenViewType.Details : ScreenViewType.Combined;
  281. settings.AnchorWidth = SplitPanel.AnchorWidth;
  282. new UserConfiguration<SupplierBillPanelSettings>().Save(settings);
  283. }
  284. #region Documents
  285. private DynamicDocumentGrid<BillDocument, Bill, BillLink>? DocumentPage;
  286. public bool CanRotateImage => !bDocumentsChanged;
  287. private void ClearDocumentPage()
  288. {
  289. ViewList.Documents = [];
  290. }
  291. private void LinkDocumentPage()
  292. {
  293. DocumentPage = Bill.Pages.OfType<DynamicDocumentGrid<BillDocument, Bill, BillLink>>().FirstOrDefault();
  294. if(DocumentPage is not null)
  295. {
  296. DocumentPage.AfterRefresh += (o, e) =>
  297. {
  298. if (bRefreshingDocuments)
  299. {
  300. return;
  301. }
  302. ReloadViewList(true);
  303. };
  304. DocumentPage.OnChanged += DocumentPage_OnChanged;
  305. }
  306. }
  307. private bool bRefreshingDocuments = false;
  308. private bool bDocumentsChanged = false;
  309. private void DocumentPage_OnChanged(object? sender, EventArgs e)
  310. {
  311. bDocumentsChanged = true;
  312. DoPropertyChanged(nameof(CanRotateImage));
  313. if (bRefreshingDocuments)
  314. {
  315. return;
  316. }
  317. ReloadViewList();
  318. }
  319. private void ReloadViewList(bool force = false)
  320. {
  321. if(DocumentPage is null)
  322. {
  323. return;
  324. }
  325. ViewList.UpdateViewList(DocumentPage.LoadItems(DocumentPage.Data.Rows), force);
  326. }
  327. private void ViewList_UpdateDocument(BillDocument document, Document doc)
  328. {
  329. if(DocumentPage is null)
  330. {
  331. return;
  332. }
  333. if (Path.GetExtension(doc.FileName) == ".pdf")
  334. {
  335. document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256);
  336. }
  337. Client.Save(document, "");
  338. BillPanelDocumentCache.Cache.Add(new DocumentCachedDocument(doc));
  339. DocumentPage.Refresh(false, true);
  340. ViewList.UpdateViewList(DocumentPage.LoadItems(DocumentPage.Data.Rows), true);
  341. }
  342. private void Documents_DragOver(object sender, DragEventArgs e)
  343. {
  344. if(Bills.SelectedRows.Length == 0)
  345. {
  346. e.Effects = DragDropEffects.None;
  347. }
  348. else
  349. {
  350. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  351. {
  352. e.Effects = DragDropEffects.Copy;
  353. }
  354. else
  355. {
  356. e.Effects = DragDropEffects.None;
  357. }
  358. }
  359. e.Handled = true;
  360. }
  361. private void Documents_Drop(object sender, DragEventArgs e)
  362. {
  363. if(Bills.SelectedRows.Length == 0 || DocumentPage is null)
  364. {
  365. return;
  366. }
  367. var selectedBill = Bills.SelectedRows[0].ToObject<Bill>();
  368. Task.Run(() =>
  369. {
  370. Dispatcher.Invoke(() =>
  371. {
  372. Progress.Show("Uploading documents");
  373. try
  374. {
  375. var result = DocumentUtils.HandleFileDrop(e);
  376. if (result is not null)
  377. {
  378. var docs = new List<Document>();
  379. foreach (var (filename, stream) in result)
  380. {
  381. var doc = new Document();
  382. doc.FileName = filename;
  383. if (stream is null)
  384. {
  385. doc.Data = File.ReadAllBytes(filename);
  386. doc.TimeStamp = new FileInfo(filename).LastWriteTime;
  387. }
  388. else
  389. {
  390. using var memStream = new MemoryStream();
  391. stream.CopyTo(memStream);
  392. doc.Data = memStream.ToArray();
  393. doc.TimeStamp = DateTime.Now;
  394. }
  395. doc.CRC = CoreUtils.CalculateCRC(doc.Data);
  396. docs.Add(doc);
  397. }
  398. Client.Save(docs, "Initial Upload");
  399. var billDocs = new List<BillDocument>();
  400. foreach (var doc in docs)
  401. {
  402. var billDoc = new BillDocument();
  403. billDoc.DocumentLink.CopyFrom(doc);
  404. billDoc.EntityLink.CopyFrom(selectedBill);
  405. billDocs.Add(billDoc);
  406. }
  407. DocumentPage.SaveItems(billDocs);
  408. try
  409. {
  410. bRefreshingDocuments = true;
  411. DocumentPage.DoChanged();
  412. }
  413. finally
  414. {
  415. bRefreshingDocuments = false;
  416. }
  417. }
  418. Progress.Close();
  419. }
  420. catch (Exception e)
  421. {
  422. Progress.Close();
  423. MessageWindow.ShowError("Could not upload documents.", e);
  424. }
  425. });
  426. });
  427. }
  428. #endregion
  429. public event PropertyChangedEventHandler? PropertyChanged;
  430. protected void DoPropertyChanged([CallerMemberName] string propertyName = "")
  431. {
  432. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  433. }
  434. }
  435. public class BillDocumentViewList : DocumentViewList<BillDocument>
  436. {
  437. protected override IEnumerable<Document> LoadDocuments(IEnumerable<Guid> ids)
  438. {
  439. return BillPanelDocumentCache.Cache.LoadDocuments(ids, checkTimestamp: true);
  440. }
  441. protected override Guid GetID(BillDocument document)
  442. {
  443. return document.ID;
  444. }
  445. protected override Guid GetDocumentID(BillDocument document)
  446. {
  447. return document.DocumentLink.ID;
  448. }
  449. }
  450. public class BillPanelDocumentCache : DocumentCache
  451. {
  452. public override TimeSpan MaxAge => TimeSpan.FromHours(1);
  453. private static BillPanelDocumentCache? _cache;
  454. public static BillPanelDocumentCache Cache
  455. {
  456. get
  457. {
  458. _cache ??= DocumentCaches.GetOrRegister<BillPanelDocumentCache>();
  459. return _cache;
  460. }
  461. }
  462. public BillPanelDocumentCache() : base(nameof(BillPanelDocumentCache))
  463. {
  464. }
  465. }