BillTimberlinePoster.cs 20 KB

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