BillTimberlinePoster.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. using Comal.Classes;
  2. using ControlzEx.Standard;
  3. using CsvHelper;
  4. using CsvHelper.Configuration;
  5. using CsvHelper.Configuration.Attributes;
  6. using FastReport.Utils;
  7. using InABox.Core;
  8. using InABox.Core.Postable;
  9. using InABox.Poster.Timberline;
  10. using InABox.Scripting;
  11. using Microsoft.Win32;
  12. using NPOI.SS.Formula.Functions;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using System.Windows;
  21. using static System.Windows.Forms.VisualStyles.VisualStyleElement;
  22. namespace PRS.Shared
  23. {
  24. public class BillTimberlineHeader
  25. {
  26. [Ignore]
  27. public List<BillTimberlineDistribution> Distributions { get; set; } = new();
  28. [Index(0)]
  29. public string RecordID { get; set; } = "APIF";
  30. [Index(1)]
  31. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  32. public string Vendor { get; set; } = "";
  33. [Index(2)]
  34. [TypeConverter(typeof(TimberlinePosterStringConverter), 15)]
  35. public string Invoice { get; set; } = "";
  36. [Index(3)]
  37. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  38. public string Description { get; set; } = "";
  39. [Index(4)]
  40. public double Amount { get; set; }
  41. [Index(5)]
  42. public double Tax { get; set; }
  43. [Index(6)]
  44. public double DiscountOffered { get; set; }
  45. [Index(7)]
  46. public double MiscDeduction { get; set; }
  47. [Index(8)]
  48. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  49. public DateTime InvoiceDate { get; set; }
  50. [Index(9)]
  51. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  52. public DateTime DateReceived { get; set; }
  53. [Index(10)]
  54. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  55. public DateTime DiscountDate { get; set; }
  56. [Index(11)]
  57. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  58. public DateTime PaymentDate { get; set; }
  59. [Index(12)]
  60. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  61. public DateTime AccountingDate { get; set; }
  62. [Index(13)]
  63. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  64. public string InvoiceCode1 { get; set; } = "";
  65. [Index(14)]
  66. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  67. public string InvoiceCode2 { get; set; } = "";
  68. [Index(15)]
  69. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  70. public string SmryPayeeName { get; set; } = "";
  71. [Index(16)]
  72. [TypeConverter(typeof(TimberlinePosterStringConverter), 33)]
  73. public string SmryPayeeAddress1 { get; set; } = "";
  74. [Index(17)]
  75. [TypeConverter(typeof(TimberlinePosterStringConverter), 33)]
  76. public string SmryPayeeAddress2 { get; set; } = "";
  77. [Index(18)]
  78. [TypeConverter(typeof(TimberlinePosterStringConverter), 15)]
  79. public string SmryPayeeCity { get; set; } = "";
  80. [Index(19)]
  81. [TypeConverter(typeof(TimberlinePosterStringConverter), 4)]
  82. public string SmryPayeeState { get; set; } = "";
  83. [Index(20)]
  84. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  85. public string SmryPayeeZip { get; set; } = "";
  86. }
  87. public class BillTimberlineDistribution
  88. {
  89. [Index(0)]
  90. public string RecordID { get; set; } = "APDF";
  91. [Index(1)]
  92. [TypeConverter(typeof(TimberlinePosterStringConverter), 12)]
  93. public string Commitment { get; set; } = "";
  94. [Index(2)]
  95. public int CommitmentLineItem { get; set; }
  96. [Index(3)]
  97. [TypeConverter(typeof(TimberlinePosterStringConverter), 7)]
  98. public string Equipment { get; set; } = "";
  99. [Index(4)]
  100. [TypeConverter(typeof(TimberlinePosterStringConverter), 6)]
  101. public string EQCostCode { get; set; } = "";
  102. [Index(5)]
  103. [TypeConverter(typeof(TimberlinePosterStringConverter), 6)]
  104. public string Job { get; set; } = "";
  105. [Index(6)]
  106. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  107. public string Extra { get; set; } = "";
  108. [Index(7)]
  109. [TypeConverter(typeof(TimberlinePosterStringConverter), 7)]
  110. public string CostCode { get; set; } = "";
  111. [Index(8)]
  112. [TypeConverter(typeof(TimberlinePosterStringConverter), 3)]
  113. public string Category { get; set; } = "";
  114. [Index(9)]
  115. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  116. public string BLStdItem { get; set; } = "";
  117. [Index(10)]
  118. [TypeConverter(typeof(TimberlinePosterStringConverter), 8)]
  119. public string Reserved { get; set; } = "";
  120. [Index(11)]
  121. [TypeConverter(typeof(TimberlinePosterStringConverter), int.MaxValue)] // int.MaxValue because it was chopping the accounts in PRS
  122. public string ExpenseAccount { get; set; } = "";
  123. [Index(12)]
  124. [TypeConverter(typeof(TimberlinePosterStringConverter), int.MaxValue)] // int.MaxValue because it was chopping the accounts in PRS
  125. public string APAccount { get; set; } = "";
  126. [Index(13)]
  127. public double TaxablePayments { get; set; }
  128. [Index(14)]
  129. [TypeConverter(typeof(TimberlinePosterStringConverter), 6)]
  130. public string TaxGroup { get; set; } = "";
  131. [Index(15)]
  132. public double Units { get; set; }
  133. [Index(16)]
  134. public double UnitCost { get; set; }
  135. [Index(17)]
  136. public double Amount { get; set; }
  137. [Index(18)]
  138. public double Tax { get; set; }
  139. [Index(19)]
  140. public double TaxLiability { get; set; }
  141. [Index(20)]
  142. public double DiscountOffered { get; set; }
  143. [Index(21)]
  144. public double Retainage { get; set; }
  145. [Index(22)]
  146. public double MiscDeduction { get; set; }
  147. [Index(23)]
  148. [BooleanTrueValues("t", "T", "1", "Y", "y")]
  149. [BooleanFalseValues("f", "F", "0", "N", "n")]
  150. public bool TaxablePaymentsExempt { get; set; }
  151. [Index(24)]
  152. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  153. public string DistCode { get; set; } = "";
  154. [Index(25)]
  155. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  156. public string Draw { get; set; } = "";
  157. [Index(26)]
  158. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  159. public string MiscEntry1 { get; set; } = "";
  160. [Index(27)]
  161. public double MiscEntryUnits1 { get; set; }
  162. [Index(28)]
  163. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  164. public string MiscEntry2 { get; set; } = "";
  165. [Index(29)]
  166. public double MiscEntryUnits2 { get; set; }
  167. [Index(30)]
  168. public double MeterOdometer { get; set; }
  169. [Index(31)]
  170. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  171. public string Description { get; set; } = "";
  172. [Index(32)]
  173. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  174. public string Authorization { get; set; } = "";
  175. [Index(33)]
  176. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  177. public string JointPayee { get; set; } = "";
  178. }
  179. public class BillTimberlineSettings : TimberlinePosterSettings<Bill>
  180. {
  181. protected override string DefaultScript()
  182. {
  183. return @"
  184. using PRS.Shared;
  185. using InABox.Core;
  186. using System.Collections.Generic;
  187. public class Module
  188. {
  189. public void BeforePost(IDataModel<Bill> model)
  190. {
  191. // Perform pre-processing
  192. }
  193. public bool ProcessHeader(IDataModel<Bill> model, Bill bill, BillTimberlineHeader header)
  194. {
  195. // Do extra processing for a header line; return false to fail this header
  196. return true;
  197. }
  198. public bool ProcessLine(IDataModel<Bill> model, BillLine bill, BillTimberlineDistribution distribution)
  199. {
  200. // Do extra processing for a distribution line; return false to fail this header
  201. return true;
  202. }
  203. public void AfterPost(IDataModel<Bill> model)
  204. {
  205. // Perform post-processing;
  206. }
  207. }";
  208. }
  209. }
  210. public class BillTimberlineResult : TimberlinePostResult<BillTimberlineHeader, Bill>
  211. {
  212. }
  213. public class BillTimberlinePoster : ITimberlinePoster<Bill, BillTimberlineSettings>
  214. {
  215. public ScriptDocument? Script { get; set; }
  216. public BillTimberlineSettings Settings { get; set; }
  217. public bool BeforePost(IDataModel<Bill> model)
  218. {
  219. model.SetIsDefault<Document>(false, alias: "CompanyLogo");
  220. model.SetIsDefault<CoreTable>(false, alias: "CompanyInformation");
  221. model.SetIsDefault<Employee>(false);
  222. model.SetColumns(new Columns<Bill>(x => x.ID)
  223. .Add(x => x.SupplierLink.Code)
  224. .Add(x => x.Description)
  225. .Add(x => x.Number)
  226. .Add(x => x.IncTax)
  227. .Add(x => x.Tax)
  228. .Add(x => x.BillDate)
  229. .Add(x => x.AccountingDate)
  230. .Add(x => x.PaymentDate)
  231. .Add(x => x.Approved));
  232. model.SetColumns(new Columns<BillLine>(x => x.ID)
  233. .Add(x => x.BillLink.ID)
  234. .Add(x => x.TaxCode.Code)
  235. .Add(x => x.IncTax)
  236. .Add(x => x.Tax)
  237. .Add(x => x.Description)
  238. .Add(x => x.PurchaseGL.Code)
  239. .Add(x => x.OrderItem.ID)
  240. .Add(x => x.Job.JobNumber),
  241. alias: "Bill_BillLine");
  242. model.SetIsDefault<BillLine>(true, "Bill_BillLine");
  243. model.AddChildTable<BillLine, PurchaseOrderItem>(x => x.OrderItem.ID, x => x.ID, isdefault: true,
  244. parentalias: "Bill_BillLine", childalias: "POItem",
  245. columns: new Columns<PurchaseOrderItem>(x => x.ID)
  246. .Add(x => x.PurchaseOrderLink.PONumber)
  247. .Add(x => x.Job.JobNumber)
  248. .Add(x => x.Qty)
  249. .Add(x => x.Description)
  250. .Add(x => x.Cost)
  251. .Add(x => x.PostedReference)
  252. );
  253. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  254. return true;
  255. }
  256. private bool ProcessHeader(IDataModel<Bill> model, Bill bill, BillTimberlineHeader header)
  257. {
  258. return Script?.Execute(methodname: "ProcessHeader", parameters: new object[] { model, bill, header }) != false;
  259. }
  260. private bool ProcessLine(IDataModel<Bill> model, BillLine bill, BillTimberlineDistribution distribution)
  261. {
  262. return Script?.Execute(methodname: "ProcessLine", parameters: new object[] { model, bill, distribution }) != false;
  263. }
  264. private BillTimberlineResult DoProcess(IDataModel<Bill> model)
  265. {
  266. var result = new BillTimberlineResult();
  267. var lines = model.GetTable<BillLine>("Bill_BillLine").ToObjects<BillLine>()
  268. .GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToList());
  269. var purchaseOrderItems = model.GetTable<PurchaseOrderItem>("POItem").ToObjects<PurchaseOrderItem>()
  270. .ToDictionary(x => x.ID, x => x);
  271. var bills = model.GetTable<Bill>().ToObjects<Bill>();
  272. if(bills.Any(x => x.Approved.IsEmpty()))
  273. {
  274. throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing.");
  275. }
  276. foreach (var bill in bills)
  277. {
  278. var apif = new BillTimberlineHeader
  279. {
  280. Vendor = bill.SupplierLink.Code,
  281. Invoice = bill.Number,
  282. Description = bill.Description,
  283. Amount = bill.IncTax,
  284. Tax = bill.Tax,
  285. // DiscountOffered
  286. // Misc. Deduction
  287. InvoiceDate = bill.BillDate,
  288. // DateReceived doesn't exist
  289. DiscountDate = bill.BillDate,
  290. PaymentDate = bill.PaymentDate,
  291. AccountingDate = bill.AccountingDate,
  292. // InvoiceCode1
  293. // InvoiceCode2
  294. // SmryPayeeName
  295. // SmryPayeeAddress1
  296. // SmryPayeeAddress2
  297. // SmryPayeeCity
  298. // SmryPayeeState
  299. // SmryPayeeZip
  300. };
  301. if (!ProcessHeader(model, bill, apif))
  302. {
  303. result.AddFailed(bill, "Failed by script.");
  304. }
  305. else
  306. {
  307. var success = true;
  308. var billLines = lines.GetValueOrDefault(bill.ID) ?? new List<BillLine>();
  309. foreach (var billLine in billLines)
  310. {
  311. var apdf = new BillTimberlineDistribution
  312. {
  313. // Equipment
  314. // EQ Cost Code
  315. // Extra
  316. // Cost Code
  317. // Category
  318. /// BL STd Item
  319. // Reserved
  320. ExpenseAccount = billLine.PurchaseGL.Code,
  321. // AP Account
  322. // Taxable Payments
  323. TaxGroup = billLine.TaxCode.Code,
  324. Amount = billLine.IncTax,
  325. Tax = billLine.Tax,
  326. // Tax Liability
  327. // Discount OFfered
  328. // Retainage
  329. // MIsc Deduction
  330. // Tax Payments Exempt
  331. // Dist Code
  332. // Misc Entry 1
  333. // Misc Units 1
  334. // Misc Entry 2
  335. // Misc Units 2
  336. // Meter
  337. Description = billLine.Description,
  338. // Authorization
  339. // Joint Payee
  340. };
  341. if (purchaseOrderItems.TryGetValue(billLine.OrderItem.ID, out var poItem))
  342. {
  343. apdf.Commitment = poItem.PurchaseOrderLink.PONumber;
  344. apdf.Job = poItem.Job.JobNumber;
  345. if (int.TryParse(poItem.PostedReference, out var itemNumber))
  346. {
  347. apdf.CommitmentLineItem = itemNumber;
  348. billLine.PostedReference = poItem.PostedReference;
  349. }
  350. apdf.Units = poItem.Qty;
  351. apdf.UnitCost = poItem.Cost;
  352. apdf.Description = poItem.Description.NotWhiteSpaceOr(apdf.Description);
  353. }
  354. else
  355. {
  356. apdf.Job = billLine.Job.JobNumber;
  357. }
  358. if (!ProcessLine(model, billLine, apdf))
  359. {
  360. success = false;
  361. break;
  362. }
  363. apif.Distributions.Add(apdf);
  364. }
  365. if (success)
  366. {
  367. foreach(var billLine in billLines)
  368. {
  369. result.AddFragment(billLine);
  370. }
  371. result.AddSuccess(bill, apif);
  372. }
  373. else
  374. {
  375. result.AddFailed(bill, "Failed by script.");
  376. }
  377. }
  378. }
  379. return result;
  380. }
  381. public IPostResult<Bill> Process(IDataModel<Bill> model)
  382. {
  383. var result = DoProcess(model);
  384. var dlg = new SaveFileDialog()
  385. {
  386. Filter = "CSV Files (*.csv)|*.csv"
  387. };
  388. if (dlg.ShowDialog() == true)
  389. {
  390. using (var writer = new StreamWriter(dlg.FileName))
  391. {
  392. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  393. foreach (var apif in result.Exports)
  394. {
  395. csv.WriteRecord(apif);
  396. csv.NextRecord();
  397. foreach (var apdf in apif.Distributions)
  398. {
  399. csv.WriteRecord(apdf);
  400. csv.NextRecord();
  401. }
  402. }
  403. }
  404. while (true)
  405. {
  406. var logDlg = new OpenFileDialog
  407. {
  408. InitialDirectory = Path.GetDirectoryName(dlg.FileName),
  409. FileName = "APREJECT.txt",
  410. Filter = "All Files (*.*) | *.*",
  411. Title = "Please select APREJECT.txt"
  412. };
  413. if (logDlg.ShowDialog() == true)
  414. {
  415. var rejectedHeaders = new List<BillTimberlineHeader?>();
  416. using (var reader = new StreamReader(logDlg.FileName))
  417. {
  418. using var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)
  419. {
  420. HasHeaderRecord = false
  421. });
  422. var i = 1;
  423. while (csv.Read())
  424. {
  425. var id = csv.GetField(0);
  426. if (id == "APIF")
  427. {
  428. var header = csv.GetRecord<BillTimberlineHeader>();
  429. if (header is not null)
  430. {
  431. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(header.Invoice) == true);
  432. if (entry is not null)
  433. {
  434. (entry.Item1 as IPostable).FailPost("");
  435. }
  436. }
  437. else
  438. {
  439. Logger.Send(LogType.Error, "", "Bill Timberline export: Unable to parse header from CSV line in rejection file.");
  440. MessageBox.Show($"Invalid line {i} in file; skipping.");
  441. }
  442. }
  443. else if (id == "APDF")
  444. {
  445. // Ignoring these because the reject file contains the header as well, and we don't need to fail BillLines, because
  446. // they aren't postable.
  447. /*var line = csv.GetRecord<BillTimberlineDistribution>();
  448. if (line is not null)
  449. {
  450. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(line.Invoice) == true);
  451. if (entry is not null)
  452. {
  453. (entry.Item1 as IPostable).FailPost("");
  454. }
  455. }
  456. else
  457. {
  458. Logger.Send(LogType.Error, "", "Bill Timberline export: Unable to parse line from CSV line in rejection file.");
  459. MessageBox.Show("Invalid line in file; skipping.");
  460. }*/
  461. }
  462. ++i;
  463. }
  464. }
  465. return result;
  466. }
  467. else
  468. {
  469. if (MessageBox.Show("Do you wish to cancel the export?", "Cancel Export?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  470. {
  471. throw new PostCancelledException();
  472. }
  473. else if (MessageBox.Show("Did everything post successfully?", "Successful?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  474. {
  475. return result;
  476. }
  477. }
  478. }
  479. }
  480. else
  481. {
  482. throw new PostCancelledException();
  483. }
  484. }
  485. public void AfterPost(IDataModel<Bill> model, IPostResult<Bill> result)
  486. {
  487. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  488. }
  489. }
  490. public class BillTimberlinePosterEngine<T> : TimberlinePosterEngine<Bill, BillTimberlineSettings>
  491. {
  492. }
  493. }