BillTimberlinePoster.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 MiscEntry1 { get; set; } = "";
  157. [Index(26)]
  158. public double MiscEntryUnits1 { get; set; }
  159. [Index(27)]
  160. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  161. public string MiscEntry2 { get; set; } = "";
  162. [Index(28)]
  163. public double MiscEntryUnits2 { get; set; }
  164. [Index(29)]
  165. public double MeterOdometer { get; set; }
  166. [Index(30)]
  167. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  168. public string Description { get; set; } = "";
  169. [Index(31)]
  170. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  171. public string Authorization { get; set; } = "";
  172. [Index(32)]
  173. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  174. public string JointPayee { get; set; } = "";
  175. }
  176. public class BillTimberlineSettings : TimberlinePosterSettings<Bill>
  177. {
  178. protected override string DefaultScript()
  179. {
  180. return @"
  181. using PRS.Shared;
  182. using InABox.Core;
  183. using System.Collections.Generic;
  184. public class Module
  185. {
  186. public void BeforePost(IDataModel<Bill> model)
  187. {
  188. // Perform pre-processing
  189. }
  190. public bool ProcessHeader(IDataModel<Bill> model, Bill bill, BillTimberlineHeader header)
  191. {
  192. // Do extra processing for a header line; return false to fail this header
  193. return true;
  194. }
  195. public bool ProcessLine(IDataModel<Bill> model, BillLine bill, BillTimberlineDistribution distribution)
  196. {
  197. // Do extra processing for a distribution line; return false to fail this header
  198. return true;
  199. }
  200. public void AfterPost(IDataModel<Bill> model)
  201. {
  202. // Perform post-processing;
  203. }
  204. }";
  205. }
  206. }
  207. public class BillTimberlineResult : TimberlinePostResult<BillTimberlineHeader, Bill>
  208. {
  209. }
  210. public class BillTimberlinePoster : ITimberlinePoster<Bill, BillTimberlineSettings>
  211. {
  212. public ScriptDocument? Script { get; set; }
  213. public BillTimberlineSettings Settings { get; set; }
  214. public bool BeforePost(IDataModel<Bill> model)
  215. {
  216. model.SetIsDefault<Document>(false, alias: "CompanyLogo");
  217. model.SetIsDefault<CoreTable>(false, alias: "CompanyInformation");
  218. model.SetIsDefault<Employee>(false);
  219. model.SetColumns(new Columns<Bill>(x => x.ID)
  220. .Add(x => x.SupplierLink.Code)
  221. .Add(x => x.Description)
  222. .Add(x => x.Number)
  223. .Add(x => x.IncTax)
  224. .Add(x => x.Tax)
  225. .Add(x => x.BillDate)
  226. .Add(x => x.AccountingDate)
  227. .Add(x => x.PaymentDate)
  228. .Add(x => x.Approved));
  229. model.SetColumns(new Columns<BillLine>(x => x.ID)
  230. .Add(x => x.BillLink.ID)
  231. .Add(x => x.TaxCode.Code)
  232. .Add(x => x.IncTax)
  233. .Add(x => x.Tax)
  234. .Add(x => x.Description)
  235. .Add(x => x.PurchaseGL.Code)
  236. .Add(x => x.OrderItem.ID)
  237. .Add(x => x.Job.JobNumber),
  238. alias: "Bill_BillLine");
  239. model.SetIsDefault<BillLine>(true, "Bill_BillLine");
  240. model.AddChildTable<BillLine, PurchaseOrderItem>(x => x.OrderItem.ID, x => x.ID, isdefault: true,
  241. parentalias: "Bill_BillLine", childalias: "POItem",
  242. columns: new Columns<PurchaseOrderItem>(x => x.ID)
  243. .Add(x => x.PurchaseOrderLink.PONumber)
  244. .Add(x => x.Job.JobNumber)
  245. .Add(x => x.Qty)
  246. .Add(x => x.Cost)
  247. .Add(x => x.PostedReference)
  248. );
  249. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  250. return true;
  251. }
  252. private bool ProcessHeader(IDataModel<Bill> model, Bill bill, BillTimberlineHeader header)
  253. {
  254. return Script?.Execute(methodname: "ProcessHeader", parameters: new object[] { model, bill, header }) != false;
  255. }
  256. private bool ProcessLine(IDataModel<Bill> model, BillLine bill, BillTimberlineDistribution distribution)
  257. {
  258. return Script?.Execute(methodname: "ProcessLine", parameters: new object[] { model, bill, distribution }) != false;
  259. }
  260. private BillTimberlineResult DoProcess(IDataModel<Bill> model)
  261. {
  262. var result = new BillTimberlineResult();
  263. var lines = model.GetTable<BillLine>("Bill_BillLine").ToObjects<BillLine>()
  264. .GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToList());
  265. var purchaseOrderItems = model.GetTable<PurchaseOrderItem>("POItem").ToObjects<PurchaseOrderItem>()
  266. .ToDictionary(x => x.ID, x => x);
  267. var bills = model.GetTable<Bill>().ToObjects<Bill>();
  268. if(bills.Any(x => x.Approved.IsEmpty()))
  269. {
  270. throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing.");
  271. }
  272. foreach (var bill in bills)
  273. {
  274. var apif = new BillTimberlineHeader
  275. {
  276. Vendor = bill.SupplierLink.Code,
  277. Invoice = bill.Number,
  278. Description = bill.Description,
  279. Amount = bill.IncTax,
  280. Tax = bill.Tax,
  281. // DiscountOffered
  282. // Misc. Deduction
  283. InvoiceDate = bill.BillDate,
  284. // DateReceived doesn't exist
  285. DiscountDate = bill.BillDate,
  286. PaymentDate = bill.PaymentDate,
  287. AccountingDate = bill.AccountingDate,
  288. // InvoiceCode1
  289. // InvoiceCode2
  290. // SmryPayeeName
  291. // SmryPayeeAddress1
  292. // SmryPayeeAddress2
  293. // SmryPayeeCity
  294. // SmryPayeeState
  295. // SmryPayeeZip
  296. };
  297. if (!ProcessHeader(model, bill, apif))
  298. {
  299. result.AddFailed(bill, "Failed by script.");
  300. }
  301. else
  302. {
  303. var success = true;
  304. var billLines = lines.GetValueOrDefault(bill.ID) ?? new List<BillLine>();
  305. foreach (var billLine in billLines)
  306. {
  307. var apdf = new BillTimberlineDistribution
  308. {
  309. // Equipment
  310. // EQ Cost Code
  311. // Extra
  312. // Cost Code
  313. // Category
  314. /// BL STd Item
  315. // Reserved
  316. ExpenseAccount = billLine.PurchaseGL.Code,
  317. // AP Account
  318. // Taxable Payments
  319. TaxGroup = billLine.TaxCode.Code,
  320. Amount = billLine.IncTax,
  321. Tax = billLine.Tax,
  322. // Tax Liability
  323. // Discount OFfered
  324. // Retainage
  325. // MIsc Deduction
  326. // Tax Payments Exempt
  327. // Dist Code
  328. // Misc Entry 1
  329. // Misc Units 1
  330. // Misc Entry 2
  331. // Misc Units 2
  332. // Meter
  333. Description = billLine.Description,
  334. // Authorization
  335. // Joint Payee
  336. };
  337. if (purchaseOrderItems.TryGetValue(billLine.OrderItem.ID, out var poItem))
  338. {
  339. apdf.Commitment = poItem.PurchaseOrderLink.PONumber;
  340. apdf.Job = poItem.Job.JobNumber;
  341. if (int.TryParse(poItem.PostedReference, out var itemNumber))
  342. {
  343. apdf.CommitmentLineItem = itemNumber;
  344. billLine.PostedReference = poItem.PostedReference;
  345. }
  346. apdf.Units = poItem.Qty;
  347. apdf.UnitCost = poItem.Cost;
  348. }
  349. else
  350. {
  351. apdf.Job = billLine.Job.JobNumber;
  352. }
  353. if (!ProcessLine(model, billLine, apdf))
  354. {
  355. success = false;
  356. break;
  357. }
  358. apif.Distributions.Add(apdf);
  359. }
  360. if (success)
  361. {
  362. foreach(var billLine in billLines)
  363. {
  364. result.AddFragment(billLine);
  365. }
  366. result.AddSuccess(bill, apif);
  367. }
  368. else
  369. {
  370. result.AddFailed(bill, "Failed by script.");
  371. }
  372. }
  373. }
  374. return result;
  375. }
  376. public IPostResult<Bill> Process(IDataModel<Bill> model)
  377. {
  378. var result = DoProcess(model);
  379. var dlg = new SaveFileDialog()
  380. {
  381. Filter = "CSV Files (*.csv)|*.csv"
  382. };
  383. if (dlg.ShowDialog() == true)
  384. {
  385. using (var writer = new StreamWriter(dlg.FileName))
  386. {
  387. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  388. foreach (var apif in result.Exports)
  389. {
  390. csv.WriteRecord(apif);
  391. csv.NextRecord();
  392. foreach (var apdf in apif.Distributions)
  393. {
  394. csv.WriteRecord(apdf);
  395. csv.NextRecord();
  396. }
  397. }
  398. }
  399. while (true)
  400. {
  401. var logDlg = new OpenFileDialog
  402. {
  403. InitialDirectory = Path.GetDirectoryName(dlg.FileName),
  404. FileName = "APREJECT.txt",
  405. Filter = "All Files (*.*) | *.*",
  406. Title = "Please select APREJECT.txt"
  407. };
  408. if (logDlg.ShowDialog() == true)
  409. {
  410. var rejectedHeaders = new List<BillTimberlineHeader?>();
  411. using (var reader = new StreamReader(logDlg.FileName))
  412. {
  413. using var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)
  414. {
  415. HasHeaderRecord = false
  416. });
  417. var i = 1;
  418. while (csv.Read())
  419. {
  420. var id = csv.GetField(0);
  421. if (id == "APIF")
  422. {
  423. var header = csv.GetRecord<BillTimberlineHeader>();
  424. if (header is not null)
  425. {
  426. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(header.Invoice) == true);
  427. if (entry is not null)
  428. {
  429. (entry.Item1 as IPostable).FailPost("");
  430. }
  431. }
  432. else
  433. {
  434. Logger.Send(LogType.Error, "", "Bill Timberline export: Unable to parse header from CSV line in rejection file.");
  435. MessageBox.Show($"Invalid line {i} in file; skipping.");
  436. }
  437. }
  438. else if (id == "APDF")
  439. {
  440. // Ignoring these because the reject file contains the header as well, and we don't need to fail BillLines, because
  441. // they aren't postable.
  442. /*var line = csv.GetRecord<BillTimberlineDistribution>();
  443. if (line is not null)
  444. {
  445. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(line.Invoice) == true);
  446. if (entry is not null)
  447. {
  448. (entry.Item1 as IPostable).FailPost("");
  449. }
  450. }
  451. else
  452. {
  453. Logger.Send(LogType.Error, "", "Bill Timberline export: Unable to parse line from CSV line in rejection file.");
  454. MessageBox.Show("Invalid line in file; skipping.");
  455. }*/
  456. }
  457. ++i;
  458. }
  459. }
  460. return result;
  461. }
  462. else
  463. {
  464. if (MessageBox.Show("Do you wish to cancel the export?", "Cancel Export?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  465. {
  466. throw new PostCancelledException();
  467. }
  468. else if (MessageBox.Show("Did everything post successfully?", "Successful?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  469. {
  470. return result;
  471. }
  472. }
  473. }
  474. }
  475. else
  476. {
  477. throw new PostCancelledException();
  478. }
  479. }
  480. public void AfterPost(IDataModel<Bill> model, IPostResult<Bill> result)
  481. {
  482. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  483. }
  484. }
  485. public class BillTimberlinePosterEngine<T> : TimberlinePosterEngine<Bill, BillTimberlineSettings>
  486. {
  487. }
  488. }