BillTimberlinePoster.cs 21 KB

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