BillTimberlinePoster.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. alias: "Bill_BillLine");
  238. model.SetIsDefault<BillLine>(true, "Bill_BillLine");
  239. model.AddChildTable<BillLine, PurchaseOrderItem>(x => x.OrderItem.ID, x => x.ID, isdefault: true,
  240. parentalias: "Bill_BillLine", childalias: "POItem",
  241. columns: new Columns<PurchaseOrderItem>(x => x.ID)
  242. .Add(x => x.PurchaseOrderLink.PONumber)
  243. .Add(x => x.Job.JobNumber)
  244. .Add(x => x.Qty)
  245. .Add(x => x.Cost)
  246. .Add(x => x.PostedReference)
  247. );
  248. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  249. return true;
  250. }
  251. private bool ProcessHeader(IDataModel<Bill> model, Bill bill, BillTimberlineHeader header)
  252. {
  253. return Script?.Execute(methodname: "ProcessHeader", parameters: new object[] { model, bill, header }) != false;
  254. }
  255. private bool ProcessLine(IDataModel<Bill> model, BillLine bill, BillTimberlineDistribution distribution)
  256. {
  257. return Script?.Execute(methodname: "ProcessLine", parameters: new object[] { model, bill, distribution }) != false;
  258. }
  259. private BillTimberlineResult DoProcess(IDataModel<Bill> model)
  260. {
  261. var result = new BillTimberlineResult();
  262. var lines = model.GetTable<BillLine>("Bill_BillLine").ToObjects<BillLine>()
  263. .GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToList());
  264. var purchaseOrderItems = model.GetTable<PurchaseOrderItem>("POItem").ToObjects<PurchaseOrderItem>()
  265. .ToDictionary(x => x.ID, x => x);
  266. var bills = model.GetTable<Bill>().ToObjects<Bill>();
  267. if(bills.Any(x => x.Approved.IsEmpty()))
  268. {
  269. throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing.");
  270. }
  271. foreach (var bill in bills)
  272. {
  273. var apif = new BillTimberlineHeader
  274. {
  275. Vendor = bill.SupplierLink.Code,
  276. Invoice = bill.Number,
  277. Description = bill.Description,
  278. Amount = bill.IncTax,
  279. Tax = bill.Tax,
  280. // DiscountOffered
  281. // Misc. Deduction
  282. InvoiceDate = bill.BillDate,
  283. // DateReceived doesn't exist
  284. DiscountDate = bill.BillDate,
  285. PaymentDate = bill.PaymentDate,
  286. AccountingDate = bill.AccountingDate,
  287. // InvoiceCode1
  288. // InvoiceCode2
  289. // SmryPayeeName
  290. // SmryPayeeAddress1
  291. // SmryPayeeAddress2
  292. // SmryPayeeCity
  293. // SmryPayeeState
  294. // SmryPayeeZip
  295. };
  296. if (!ProcessHeader(model, bill, apif))
  297. {
  298. result.AddFailed(bill, "Failed by script.");
  299. }
  300. else
  301. {
  302. var success = true;
  303. var billLines = lines.GetValueOrDefault(bill.ID) ?? new List<BillLine>();
  304. foreach (var billLine in billLines)
  305. {
  306. var apdf = new BillTimberlineDistribution
  307. {
  308. // Equipment
  309. // EQ Cost Code
  310. // Extra
  311. // Cost Code
  312. // Category
  313. /// BL STd Item
  314. // Reserved
  315. ExpenseAccount = billLine.PurchaseGL.Code,
  316. // AP Account
  317. // Taxable Payments
  318. TaxGroup = billLine.TaxCode.Code,
  319. Amount = billLine.IncTax,
  320. Tax = billLine.Tax,
  321. // Tax Liability
  322. // Discount OFfered
  323. // Retainage
  324. // MIsc Deduction
  325. // Tax Payments Exempt
  326. // Dist Code
  327. // Misc Entry 1
  328. // Misc Units 1
  329. // Misc Entry 2
  330. // Misc Units 2
  331. // Meter
  332. Description = billLine.Description,
  333. // Authorization
  334. // Joint Payee
  335. };
  336. if (purchaseOrderItems.TryGetValue(billLine.OrderItem.ID, out var poItem))
  337. {
  338. apdf.Commitment = poItem.PurchaseOrderLink.PONumber;
  339. apdf.Job = poItem.Job.JobNumber;
  340. if (int.TryParse(poItem.PostedReference, out var itemNumber))
  341. {
  342. apdf.CommitmentLineItem = itemNumber;
  343. billLine.PostedReference = poItem.PostedReference;
  344. }
  345. apdf.Units = poItem.Qty;
  346. apdf.UnitCost = poItem.Cost;
  347. }
  348. if (!ProcessLine(model, billLine, apdf))
  349. {
  350. success = false;
  351. break;
  352. }
  353. apif.Distributions.Add(apdf);
  354. }
  355. if (success)
  356. {
  357. foreach(var billLine in billLines)
  358. {
  359. result.AddFragment(billLine);
  360. }
  361. result.AddSuccess(bill, apif);
  362. }
  363. else
  364. {
  365. result.AddFailed(bill, "Failed by script.");
  366. }
  367. }
  368. }
  369. return result;
  370. }
  371. public IPostResult<Bill> Process(IDataModel<Bill> model)
  372. {
  373. var result = DoProcess(model);
  374. var dlg = new SaveFileDialog()
  375. {
  376. Filter = "CSV Files (*.csv)|*.csv"
  377. };
  378. if (dlg.ShowDialog() == true)
  379. {
  380. using (var writer = new StreamWriter(dlg.FileName))
  381. {
  382. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  383. foreach (var apif in result.Exports)
  384. {
  385. csv.WriteRecord(apif);
  386. csv.NextRecord();
  387. foreach (var apdf in apif.Distributions)
  388. {
  389. csv.WriteRecord(apdf);
  390. csv.NextRecord();
  391. }
  392. }
  393. }
  394. while (true)
  395. {
  396. var logDlg = new OpenFileDialog
  397. {
  398. InitialDirectory = Path.GetDirectoryName(dlg.FileName),
  399. FileName = "APREJECT.txt",
  400. Filter = "All Files (*.*) | *.*",
  401. Title = "Please select APREJECT.txt"
  402. };
  403. if (logDlg.ShowDialog() == true)
  404. {
  405. var rejectedHeaders = new List<BillTimberlineHeader?>();
  406. using (var reader = new StreamReader(logDlg.FileName))
  407. {
  408. using var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)
  409. {
  410. HasHeaderRecord = false
  411. });
  412. var i = 1;
  413. while (csv.Read())
  414. {
  415. var id = csv.GetField(0);
  416. if (id == "APIF")
  417. {
  418. var header = csv.GetRecord<BillTimberlineHeader>();
  419. if (header is not null)
  420. {
  421. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(header.Invoice) == true);
  422. if (entry is not null)
  423. {
  424. (entry.Item1 as IPostable).FailPost("");
  425. }
  426. }
  427. else
  428. {
  429. Logger.Send(LogType.Error, "", "Bill Timberline export: Unable to parse header from CSV line in rejection file.");
  430. MessageBox.Show($"Invalid line {i} in file; skipping.");
  431. }
  432. }
  433. else if (id == "APDF")
  434. {
  435. // Ignoring these because the reject file contains the header as well, and we don't need to fail BillLines, because
  436. // they aren't postable.
  437. /*var line = csv.GetRecord<BillTimberlineDistribution>();
  438. if (line is not null)
  439. {
  440. var entry = result.Items.FirstOrDefault(x => x.Item2?.Invoice.Equals(line.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 line from CSV line in rejection file.");
  449. MessageBox.Show("Invalid line in file; skipping.");
  450. }*/
  451. }
  452. ++i;
  453. }
  454. }
  455. return result;
  456. }
  457. else
  458. {
  459. if (MessageBox.Show("Do you wish to cancel the export?", "Cancel Export?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  460. {
  461. throw new PostCancelledException();
  462. }
  463. else if (MessageBox.Show("Did everything post successfully?", "Successful?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  464. {
  465. return result;
  466. }
  467. }
  468. }
  469. }
  470. else
  471. {
  472. throw new PostCancelledException();
  473. }
  474. }
  475. public void AfterPost(IDataModel<Bill> model, IPostResult<Bill> result)
  476. {
  477. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  478. }
  479. }
  480. public class BillTimberlinePosterEngine<T> : TimberlinePosterEngine<Bill, BillTimberlineSettings>
  481. {
  482. }
  483. }