StockMovementTimberlinePoster.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. public bool IgnoreMovementsWithNoPurchaseGL { get; set; } = true;
  148. protected override string DefaultScript()
  149. {
  150. return @"
  151. using PRS.Shared;
  152. using InABox.Core;
  153. using System.Collections.Generic;
  154. public class Module
  155. {
  156. public void BeforePost(IDataModel<StockMovement> model)
  157. {
  158. // Perform pre-processing
  159. }
  160. public bool ProcessDirectCostLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineDirectCost line)
  161. {
  162. // Do extra processing for a direct cost line; return false to fail this movement
  163. return true;
  164. }
  165. public bool ProcessGLLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineGL line)
  166. {
  167. // Do extra processing for a GL line; return false to fail this movement
  168. return true;
  169. }
  170. public void AfterPost(IDataModel<StockMovement> model)
  171. {
  172. // Perform post-processing
  173. }
  174. }";
  175. }
  176. }
  177. public class StockMovementTimberlineResult : TimberlinePostResult<IStockMovementTimberlineLine, StockMovement>
  178. {
  179. }
  180. public class StockMovementTimberlinePoster : ITimberlinePoster<StockMovement, StockMovementTimberlineSettings>
  181. {
  182. public ScriptDocument? Script { get; set; }
  183. public StockMovementTimberlineSettings Settings { get; set; }
  184. public bool BeforePost(IDataModel<StockMovement> model)
  185. {
  186. model.SetIsDefault<Document>(false, alias: "CompanyLogo");
  187. model.SetIsDefault<CoreTable>(false, alias: "CompanyInformation");
  188. model.SetIsDefault<Employee>(false);
  189. model.SetColumns(Columns.None<StockMovement>().Add(x => x.ID).Add(x => x.Transaction));
  190. model.AddChildTable<StockMovement, StockMovement>(x => x.Transaction, x => x.Transaction,
  191. parentalias: "StockMovement", childalias: "FullTransactions",
  192. isdefault: true,
  193. columns: Columns.None<StockMovement>().Add(x => x.ID)
  194. .Add(x => x.Transaction)
  195. .Add(x => x.Job.ID)
  196. .Add(x => x.Product.ID)
  197. .Add(x => x.Type)
  198. .Add(x => x.Units)
  199. .Add(x => x.Cost)
  200. .Add(x => x.Value)
  201. .Add(x => x.Date)
  202. .Add(x => x.Batch.ID)
  203. );
  204. model.AddLookupTable<StockMovement, Product>(x => x.Product.ID, x => x.ID, sourcealias: "FullTransactions",
  205. isdefault: true,
  206. columns: Columns.None<Product>().Add(x => x.ID)
  207. .Add(x => x.Name)
  208. .Add(x => x.CostCentre.Code)
  209. .Add(x => x.PurchaseGL.Code)
  210. .Add(x => x.SellGL.Code));
  211. model.AddLookupTable<StockMovement, Job>(x => x.Job.ID, x => x.ID, sourcealias: "FullTransactions",
  212. isdefault: true,
  213. columns: Columns.None<Job>().Add(x => x.ID)
  214. .Add(x => x.JobNumber));
  215. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  216. return true;
  217. }
  218. private bool ProcessDirectCostLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineDirectCost line)
  219. {
  220. return Script?.Execute(methodname: "ProcessDirectCostLine", parameters: new object[] { model, stockMovement, line }) != false;
  221. }
  222. private bool ProcessGLLine(IDataModel<StockMovement> model, StockMovement stockMovement, StockMovementTimberlineGL line)
  223. {
  224. return Script?.Execute(methodname: "ProcessGLLine", parameters: new object[] { model, stockMovement, line }) != false;
  225. }
  226. private StockMovementTimberlineResult DoProcess(IDataModel<StockMovement> model)
  227. {
  228. var result = new StockMovementTimberlineResult();
  229. var firstMovements = model.GetTable<StockMovement>();
  230. var full = model.GetTable<StockMovement>("FullTransactions")
  231. .ToObjects<StockMovement>().GroupBy(x => x.Transaction);
  232. var products = model.GetTable<Product>().ToObjects<Product>()
  233. .ToDictionary(x => x.ID, x => x);
  234. var jobs = model.GetTable<Job>().ToObjects<Job>()
  235. .ToDictionary(x => x.ID, x => x);
  236. StockMovementTimberlineDirectCost CreateDirectCost(StockMovement movement)
  237. {
  238. var job = jobs[movement.Job.ID];
  239. var product = products[movement.Product.ID];
  240. var directCost = new StockMovementTimberlineDirectCost
  241. {
  242. Job = job.JobNumber,
  243. Extra = "",
  244. CostCode = product.CostCentre.Code,
  245. Category = "",
  246. Units = Math.Round(movement.Units, 4),
  247. UnitCost = Math.Round(movement.Cost, 4),
  248. TransactionType = StockMovementTimberlineTransactionType.IVCost
  249. };
  250. return ModifyLine(directCost, movement);
  251. }
  252. T ModifyLine<T>(T line, StockMovement movement)
  253. where T : IStockMovementTimberlineLine
  254. {
  255. var product = products[movement.Product.ID];
  256. line.TransactionDate = movement.Date;
  257. line.AccountingDate = movement.Date;
  258. line.Description = product.Name;
  259. line.Amount = Math.Round(movement.Value, 4);
  260. line.CreditAccount = product.PurchaseGL.Code;
  261. return line;
  262. }
  263. foreach (var transaction in full)
  264. {
  265. var mvts = transaction.ToArray();
  266. var ignorableTransfer = Settings.IgnoreNetZeroTransfers
  267. && mvts.Length == 2
  268. && mvts.Any(x => x.Type == StockMovementType.TransferOut)
  269. && mvts.Any(x => x.Type == StockMovementType.TransferIn)
  270. && mvts[0].Job.ID == mvts[1].Job.ID
  271. && mvts.Sum(x => x.Qty).IsEffectivelyEqual(0)
  272. && mvts.Sum(x => x.Qty * x.Cost).IsEffectivelyEqual(0);
  273. // I think we will fail all the movements if any one movement in the transaction failed. All the successful ones,
  274. // rather than saving them with AddSuccess immediately, we will put here first, and only succeed them if every movement succeeded.
  275. var successful = new List<(StockMovement mvt, IStockMovementTimberlineLine? line)>();
  276. void AddMovement(StockMovement mvt, IStockMovementTimberlineLine line)
  277. {
  278. if(Settings.IgnoreMovementsWithNoPurchaseGL && line.CreditAccount.IsNullOrWhiteSpace())
  279. {
  280. successful.Add((mvt, null));
  281. }
  282. else
  283. {
  284. successful.Add((mvt, line));
  285. }
  286. }
  287. void IgnoreMovement(StockMovement mvt)
  288. {
  289. successful.Add((mvt, null));
  290. }
  291. foreach(var mvt in mvts)
  292. {
  293. switch (mvt.Type)
  294. {
  295. case StockMovementType.Issue:
  296. if(mvt.Job.ID == Guid.Empty)
  297. {
  298. // Issue to General Stock
  299. var gl = new StockMovementTimberlineGL { };
  300. gl = ModifyLine(gl, mvt);
  301. var product = products[mvt.Product.ID];
  302. gl.DebitAccount = product.SellGL.Code.NotWhiteSpaceOr(Settings.StockTakeGL);
  303. if (ProcessGLLine(model, mvt, gl))
  304. {
  305. AddMovement(mvt, gl);
  306. }
  307. else
  308. {
  309. result.AddFailed(mvt, "Failed by script.");
  310. }
  311. }
  312. else
  313. {
  314. // Ignore issues to a job.
  315. IgnoreMovement(mvt);
  316. }
  317. break;
  318. case StockMovementType.Receive:
  319. IgnoreMovement(mvt);
  320. break;
  321. case StockMovementType.StockTake:
  322. if (mvt.Units.IsEffectivelyEqual(0.0))
  323. {
  324. // Ignore empty stocktakes
  325. IgnoreMovement(mvt);
  326. }
  327. else
  328. {
  329. if (mvt.Job.ID == Guid.Empty)
  330. {
  331. // StockTake in General Stock
  332. var gl = new StockMovementTimberlineGL { };
  333. gl = ModifyLine(gl, mvt);
  334. var product = products[mvt.Product.ID];
  335. gl.DebitAccount = product.SellGL.Code.NotWhiteSpaceOr(Settings.StockTakeGL);
  336. if (ProcessGLLine(model, mvt, gl))
  337. {
  338. AddMovement(mvt, gl);
  339. }
  340. else
  341. {
  342. result.AddFailed(mvt, "Failed by script.");
  343. }
  344. }
  345. else
  346. {
  347. // StockTake in Job Holding
  348. var dc = CreateDirectCost(mvt);
  349. if (ProcessDirectCostLine(model, mvt, dc))
  350. {
  351. AddMovement(mvt, dc);
  352. }
  353. else
  354. {
  355. result.AddFailed(mvt, "Failed by script.");
  356. }
  357. }
  358. }
  359. break;
  360. case StockMovementType.TransferOut:
  361. case StockMovementType.TransferIn:
  362. if(mvt.Job.ID != Guid.Empty && !ignorableTransfer)
  363. {
  364. var directCost = CreateDirectCost(mvt);
  365. if(ProcessDirectCostLine(model, mvt, directCost))
  366. {
  367. AddMovement(mvt, directCost);
  368. }
  369. else
  370. {
  371. result.AddFailed(mvt, "Failed by script.");
  372. }
  373. }
  374. else
  375. {
  376. IgnoreMovement(mvt);
  377. }
  378. break;
  379. }
  380. }
  381. if(successful.Count < mvts.Length)
  382. {
  383. foreach(var (mvt, _) in successful)
  384. {
  385. result.AddFailed(mvt, "Transaction was unsuccessful.");
  386. }
  387. }
  388. else
  389. {
  390. foreach(var (mvt, item) in successful)
  391. {
  392. result.AddSuccess(mvt, item);
  393. }
  394. }
  395. }
  396. return result;
  397. }
  398. public IPostResult<StockMovement> Process(IDataModel<StockMovement> model)
  399. {
  400. var result = DoProcess(model);
  401. var dlg = new SaveFileDialog()
  402. {
  403. Title = "Select Output File",
  404. Filter = "CSV Files (*.csv)|*.csv"
  405. };
  406. if (dlg.ShowDialog() == true)
  407. {
  408. using (var writer = new StreamWriter(dlg.FileName))
  409. {
  410. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  411. foreach (var line in result.Exports.Distinct())
  412. {
  413. // Write the record.
  414. if(line is StockMovementTimberlineDirectCost dc)
  415. {
  416. csv.WriteRecord(dc);
  417. }
  418. else if(line is StockMovementTimberlineGL gl)
  419. {
  420. csv.WriteRecord(gl);
  421. }
  422. csv.NextRecord();
  423. }
  424. }
  425. }
  426. else
  427. {
  428. throw new PostCancelledException();
  429. }
  430. return result;
  431. }
  432. public void AfterPost(IDataModel<StockMovement> model, IPostResult<StockMovement> result)
  433. {
  434. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  435. }
  436. }
  437. public class StockMovementTimberlinePosterEngine<T> : TimberlinePosterEngine<StockMovement, StockMovementTimberlineSettings>
  438. {
  439. }