BillTimberlinePoster.cs 21 KB

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