StockMovementTimberlinePoster.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. using Comal.Classes;
  2. using CsvHelper.Configuration.Attributes;
  3. using CsvHelper.Configuration;
  4. using CsvHelper;
  5. using InABox.Core.Postable;
  6. using InABox.Core;
  7. using InABox.Poster.Timberline;
  8. using InABox.Scripting;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using Microsoft.Win32;
  17. using CsvHelper.TypeConversion;
  18. using NPOI.SS.Formula.Functions;
  19. using Columns = InABox.Core.Columns;
  20. namespace PRS.Shared;
  21. public interface IStockMovementTimberlineLine
  22. {
  23. DateTime TransactionDate { get; set; }
  24. DateTime AccountingDate { get; set; }
  25. string Description { get; set; }
  26. double Amount { get; set; }
  27. string DebitAccount { get; set; }
  28. string CreditAccount { get; set; }
  29. string Reference1 { get; set; }
  30. string Reference2 { get; set; }
  31. }
  32. public enum StockMovementTimberlineTransactionType
  33. {
  34. APCost = 1,
  35. JCCost = 2,
  36. PRCost = 3,
  37. EQCost = 4,
  38. IVCost = 5
  39. }
  40. public class StockMovementTimberlineTransactionTypeConverter : DefaultTypeConverter
  41. {
  42. public override object? ConvertFromString(string? text, IReaderRow row, MemberMapData memberMapData)
  43. {
  44. if (Enum.TryParse<StockMovementTimberlineTransactionType>(text, out var type))
  45. {
  46. return type;
  47. }
  48. return base.ConvertFromString(text, row, memberMapData);
  49. }
  50. public override string? ConvertToString(object? value, IWriterRow row, MemberMapData memberMapData)
  51. {
  52. if (value is StockMovementTimberlineTransactionType type)
  53. {
  54. return ((int)type).ToString();
  55. }
  56. return "";
  57. }
  58. }
  59. public class StockMovementTimberlineDirectCost : IStockMovementTimberlineLine
  60. {
  61. [Ignore]
  62. public StockMovementBatchType BatchType { get; set; }
  63. [Index(0)]
  64. public string RecordID { get; set; } = "DC";
  65. [Index(1)]
  66. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  67. public string Job { get; set; }
  68. [Index(2)]
  69. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  70. public string Extra { get; set; }
  71. [Index(3)]
  72. [TypeConverter(typeof(TimberlinePosterStringConverter), 12)]
  73. public string CostCode { get; set; }
  74. [Index(4)]
  75. [TypeConverter(typeof(TimberlinePosterStringConverter), 3)]
  76. public string Category { get; set; }
  77. [Index(5)]
  78. [TypeConverter(typeof(StockMovementTimberlineTransactionTypeConverter))]
  79. public StockMovementTimberlineTransactionType TransactionType { get; set; }
  80. [Index(6)]
  81. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  82. public DateTime TransactionDate { get; set; }
  83. [Index(7)]
  84. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  85. public DateTime AccountingDate { get; set; }
  86. [Index(8)]
  87. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  88. public string Description { get; set; }
  89. [Index(9)]
  90. public double Units { get; set; }
  91. [Index(10)]
  92. public double UnitCost { get; set; }
  93. [Index(11)]
  94. public double Amount { get; set; }
  95. [Index(12)]
  96. [TypeConverter(typeof(TimberlinePosterStringConverter), 25)]
  97. public string DebitAccount { get; set; }
  98. [Index(13)]
  99. [TypeConverter(typeof(TimberlinePosterStringConverter), 25)]
  100. public string CreditAccount { get; set; }
  101. [Index(14)]
  102. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  103. public string Reference1 { get; set; }
  104. [Index(15)]
  105. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  106. public string Reference2 { get; set; }
  107. [Index(16)]
  108. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  109. public string StandardItem { get; set; }
  110. }
  111. public class StockMovementTimberlineGL : IStockMovementTimberlineLine
  112. {
  113. [Ignore]
  114. public StockMovementBatchType BatchType { get; set; }
  115. [Index(0)]
  116. public string RecordID { get; set; } = "GL";
  117. [Index(1)]
  118. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  119. public DateTime TransactionDate { get; set; }
  120. [Index(2)]
  121. [TypeConverter(typeof(TimberlinePosterDateConverter))]
  122. public DateTime AccountingDate { get; set; }
  123. [Index(3)]
  124. [TypeConverter(typeof(TimberlinePosterStringConverter), 30)]
  125. public string Description { get; set; }
  126. [Index(4)]
  127. public double Amount { get; set; }
  128. [Index(5)]
  129. [TypeConverter(typeof(TimberlinePosterStringConverter), 25)]
  130. public string DebitAccount { get; set; }
  131. [Index(6)]
  132. [TypeConverter(typeof(TimberlinePosterStringConverter), 25)]
  133. public string CreditAccount { get; set; }
  134. [Index(7)]
  135. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  136. public string Reference1 { get; set; }
  137. [Index(8)]
  138. [TypeConverter(typeof(TimberlinePosterStringConverter), 10)]
  139. public string Reference2 { get; set; }
  140. }
  141. public class StockMovementTimberlineSettings : TimberlinePosterSettings<StockMovement>
  142. {
  143. [TextBoxEditor]
  144. public string StockTakeGL { get; set; }
  145. [CheckBoxEditor]
  146. public bool IgnoreNetZeroTransfers { get; set; }
  147. protected override string DefaultScript()
  148. {
  149. return @"
  150. using PRS.Shared;
  151. using InABox.Core;
  152. using System.Collections.Generic;
  153. public class Module
  154. {
  155. public void BeforePost(IDataModel<StockMovement> model)
  156. {
  157. // Perform pre-processing
  158. }
  159. public bool ProcessDirectCostLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineDirectCost line)
  160. {
  161. // Do extra processing for a direct cost line; return false to fail this movement
  162. return true;
  163. }
  164. public bool ProcessGLLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineGL line)
  165. {
  166. // Do extra processing for a GL line; return false to fail this movement
  167. return true;
  168. }
  169. public void AfterPost(IDataModel<StockMovement> model)
  170. {
  171. // Perform post-processing
  172. }
  173. }";
  174. }
  175. }
  176. public class StockMovementTimberlineResult : TimberlinePostResult<IStockMovementTimberlineLine, StockMovement>
  177. {
  178. }
  179. public class StockMovementTimberlinePoster : ITimberlinePoster<StockMovement, StockMovementTimberlineSettings>
  180. {
  181. public ScriptDocument? Script { get; set; }
  182. public StockMovementTimberlineSettings Settings { get; set; }
  183. public bool BeforePost(IDataModel<StockMovement> model)
  184. {
  185. model.SetIsDefault<Document>(false, alias: "CompanyLogo");
  186. model.SetIsDefault<CoreTable>(false, alias: "CompanyInformation");
  187. model.SetIsDefault<Employee>(false);
  188. model.SetColumns(Columns.None<StockMovement>().Add(x => x.ID).Add(x => x.Transaction));
  189. model.AddChildTable<StockMovement, StockMovement>(x => x.Transaction, x => x.Transaction,
  190. parentalias: "StockMovement", childalias: "FullTransactions",
  191. isdefault: true,
  192. columns: Columns.None<StockMovement>().Add(x => x.ID)
  193. .Add(x => x.Transaction)
  194. .Add(x => x.Job.ID)
  195. .Add(x => x.Product.ID)
  196. .Add(x => x.Type)
  197. .Add(x => x.Units)
  198. .Add(x => x.Cost)
  199. .Add(x => x.Value)
  200. .Add(x => x.Date)
  201. .Add(x => x.Batch.ID)
  202. );
  203. model.AddLookupTable<StockMovement, Product>(x => x.Product.ID, x => x.ID, sourcealias: "FullTransactions",
  204. isdefault: true,
  205. columns: Columns.None<Product>().Add(x => x.ID)
  206. .Add(x => x.Name)
  207. .Add(x => x.CostCentre.Code)
  208. .Add(x => x.PurchaseGL.Code));
  209. model.AddLookupTable<StockMovement, Job>(x => x.Job.ID, x => x.ID, sourcealias: "FullTransactions",
  210. isdefault: true,
  211. columns: Columns.None<Job>().Add(x => x.ID)
  212. .Add(x => x.JobNumber));
  213. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  214. return true;
  215. }
  216. private bool ProcessDirectCostLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineDirectCost line)
  217. {
  218. return Script?.Execute(methodname: "ProcessDirectCostLine", parameters: new object[] { model, stockMovement, line }) != false;
  219. }
  220. private bool ProcessGLLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineGL line)
  221. {
  222. return Script?.Execute(methodname: "ProcessGLLine", parameters: new object[] { model, stockMovement, line }) != false;
  223. }
  224. private StockMovementTimberlineResult DoProcess(IDataModel<StockMovement> model)
  225. {
  226. var result = new StockMovementTimberlineResult();
  227. var firstMovements = model.GetTable<StockMovement>();
  228. var full = model.GetTable<StockMovement>("FullTransactions")
  229. .ToObjects<StockMovement>().GroupBy(x => x.Transaction);
  230. var products = model.GetTable<Product>().ToObjects<Product>()
  231. .ToDictionary(x => x.ID, x => x);
  232. var jobs = model.GetTable<Job>().ToObjects<Job>()
  233. .ToDictionary(x => x.ID, x => x);
  234. StockMovementTimberlineDirectCost CreateDirectCost(StockMovement movement)
  235. {
  236. var job = jobs[movement.Job.ID];
  237. var product = products[movement.Product.ID];
  238. var directCost = new StockMovementTimberlineDirectCost
  239. {
  240. Job = job.JobNumber,
  241. Extra = "",
  242. CostCode = product.CostCentre.Code,
  243. Category = "",
  244. Units = Math.Round(movement.Units, 4),
  245. UnitCost = Math.Round(movement.Cost, 4),
  246. TransactionType = StockMovementTimberlineTransactionType.IVCost
  247. };
  248. return ModifyLine(directCost, movement);
  249. }
  250. T ModifyLine<T>(T line, StockMovement movement)
  251. where T : IStockMovementTimberlineLine
  252. {
  253. var product = products[movement.Product.ID];
  254. line.TransactionDate = movement.Date;
  255. line.AccountingDate = movement.Date;
  256. line.Description = product.Name;
  257. line.Amount = Math.Round(movement.Value, 4);
  258. line.CreditAccount = product.PurchaseGL.Code;
  259. return line;
  260. }
  261. foreach (var transaction in full)
  262. {
  263. var mvts = transaction.ToArray();
  264. var ignorableTransfer = Settings.IgnoreNetZeroTransfers
  265. && mvts.Length == 2
  266. && mvts.Any(x => x.Type == StockMovementType.TransferOut)
  267. && mvts.Any(x => x.Type == StockMovementType.TransferIn)
  268. && mvts[0].Job.ID == mvts[1].Job.ID
  269. && mvts.Sum(x => x.Qty).IsEffectivelyEqual(0)
  270. && mvts.Sum(x => x.Qty * x.Cost).IsEffectivelyEqual(0);
  271. // I think we will fail all the movements if any one movement in the transaction failed. All the successful ones,
  272. // rather than saving them with AddSuccess immediately, we will put here first, and only succeed them if every movement succeeded.
  273. var successful = new List<(StockMovement mvt, IStockMovementTimberlineLine? line)>();
  274. foreach(var mvt in mvts)
  275. {
  276. switch (mvt.Type)
  277. {
  278. case StockMovementType.Issue:
  279. if(mvt.Job.ID == Guid.Empty)
  280. {
  281. // Issue to General Stock
  282. var gl = new StockMovementTimberlineGL { };
  283. gl = ModifyLine(gl, mvt);
  284. var product = products[mvt.Product.ID];
  285. gl.DebitAccount = product.SellGL.Code.NotWhiteSpaceOr(Settings.StockTakeGL);
  286. if (ProcessGLLine(model, mvt, gl))
  287. {
  288. successful.Add((mvt, gl));
  289. }
  290. else
  291. {
  292. result.AddFailed(mvt, "Failed by script.");
  293. }
  294. }
  295. else
  296. {
  297. // Ignore issues to a job.
  298. successful.Add((mvt, null));
  299. }
  300. break;
  301. case StockMovementType.Receive:
  302. successful.Add((mvt, null));
  303. break;
  304. case StockMovementType.StockTake:
  305. if(mvt.Job.ID == Guid.Empty)
  306. {
  307. // StockTake in General Stock
  308. var gl = new StockMovementTimberlineGL { };
  309. gl = ModifyLine(gl, mvt);
  310. var product = products[mvt.Product.ID];
  311. gl.DebitAccount = product.SellGL.Code.NotWhiteSpaceOr(Settings.StockTakeGL);
  312. if (ProcessGLLine(model, mvt, gl))
  313. {
  314. successful.Add((mvt, gl));
  315. }
  316. else
  317. {
  318. result.AddFailed(mvt, "Failed by script.");
  319. }
  320. }
  321. else
  322. {
  323. // StockTake in Job Holding
  324. var dc = CreateDirectCost(mvt);
  325. if (ProcessDirectCostLine(model, mvt, dc))
  326. {
  327. successful.Add((mvt, dc));
  328. }
  329. else
  330. {
  331. result.AddFailed(mvt, "Failed by script.");
  332. }
  333. }
  334. break;
  335. case StockMovementType.TransferOut:
  336. case StockMovementType.TransferIn:
  337. if(mvt.Job.ID != Guid.Empty && !ignorableTransfer)
  338. {
  339. var directCost = CreateDirectCost(mvt);
  340. if(ProcessDirectCostLine(model, mvt, directCost))
  341. {
  342. successful.Add((mvt, directCost));
  343. }
  344. else
  345. {
  346. result.AddFailed(mvt, "Failed by script.");
  347. }
  348. }
  349. else
  350. {
  351. successful.Add((mvt, null));
  352. }
  353. break;
  354. }
  355. }
  356. if(successful.Count < mvts.Length)
  357. {
  358. foreach(var (mvt, _) in successful)
  359. {
  360. result.AddFailed(mvt, "Transaction was unsuccessful.");
  361. }
  362. }
  363. else
  364. {
  365. foreach(var (mvt, item) in successful)
  366. {
  367. result.AddSuccess(mvt, item);
  368. }
  369. }
  370. }
  371. return result;
  372. }
  373. public IPostResult<StockMovement> Process(IDataModel<StockMovement> model)
  374. {
  375. var result = DoProcess(model);
  376. var dlg = new SaveFileDialog()
  377. {
  378. Title = "Select Output File",
  379. Filter = "CSV Files (*.csv)|*.csv"
  380. };
  381. if (dlg.ShowDialog() == true)
  382. {
  383. using (var writer = new StreamWriter(dlg.FileName))
  384. {
  385. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  386. foreach (var line in result.Exports.Distinct())
  387. {
  388. // Write the record.
  389. if(line is StockMovementTimberlineDirectCost dc)
  390. {
  391. csv.WriteRecord(dc);
  392. }
  393. else if(line is StockMovementTimberlineGL gl)
  394. {
  395. csv.WriteRecord(gl);
  396. }
  397. csv.NextRecord();
  398. }
  399. }
  400. }
  401. else
  402. {
  403. throw new PostCancelledException();
  404. }
  405. return result;
  406. }
  407. public void AfterPost(IDataModel<StockMovement> model, IPostResult<StockMovement> result)
  408. {
  409. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  410. }
  411. }
  412. public class StockMovementTimberlinePosterEngine<T> : TimberlinePosterEngine<StockMovement, StockMovementTimberlineSettings>
  413. {
  414. }