BillTimberlinePoster.cs 21 KB

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