ProjectEntryExt.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using PX.Common;
  6. using PX.Data;
  7. using PX.Objects.CM;
  8. using PX.Objects.GL;
  9. using PX.Objects.IN;
  10. using PX.Objects.PM;
  11. namespace ProjectEntryLaborAdjust
  12. {
  13. public class ProjectEntryExt : PXGraphExtension<ProjectEntry>
  14. {
  15. private const string SlotLaborUpdate = "RevBudSetLabor"; // <-- new flag
  16. private const string LaborInvCD = "L023";
  17. private const string ExcludedBranchCD = "301";
  18. private const string ExcludedBillRule = "PROGRESS";
  19. private const decimal PMRate = 90m;
  20. private int? _laborInvID;
  21. private int? LaborInvID
  22. {
  23. get
  24. {
  25. if (_laborInvID == null)
  26. _laborInvID = InventoryItem.UK.Find(Base, LaborInvCD)?.InventoryID;
  27. return _laborInvID;
  28. }
  29. }
  30. protected bool Skip => Base.IsImport || Base.IsContractBasedAPI || Base.IsCopyPasteContext;
  31. protected void _(Events.RowUpdated<PMRevenueBudget> e)
  32. {
  33. if (IsExcludedProject()) // ← add this line
  34. return;
  35. var row = (PMRevenueBudget)e.Row;
  36. var old = (PMRevenueBudget)e.OldRow;
  37. if (row == null || old == null || Skip) return;
  38. // Prevent recursion
  39. if (PXContext.GetSlot<bool?>(SlotLaborUpdate) == true) return;
  40. // Only react when Original Budgeted Amount changed
  41. if (e.Cache.ObjectsEqual<PMRevenueBudget.curyAmount>(row, old))
  42. {
  43. return;
  44. }
  45. // Ignore if user is editing the labor line itself
  46. if (LaborInvID != null && row.InventoryID == LaborInvID) return;
  47. // ---- Calculate totals/hours (exclude labor line) -----------------
  48. decimal totalRevised = GetRevisedRevenueTotalUI(LaborInvCD);
  49. decimal pmHours = GetPMHours(totalRevised);
  50. PXContext.SetSlot<bool?>(SlotLaborUpdate, true);
  51. try
  52. {
  53. var cache = Base.RevenueBudget.Cache;
  54. PMRevenueBudget laborLine = FindRevenueLineByInventoryCd(LaborInvCD);
  55. if (laborLine != null)
  56. {
  57. var c = Base.RevenueBudget.Cache;
  58. if (laborLine.Qty != pmHours)
  59. c.SetValueExt<PMRevenueBudget.qty>(laborLine, pmHours);
  60. if (laborLine.CuryUnitRate != PMRate)
  61. c.SetValueExt<PMRevenueBudget.curyUnitRate>(laborLine, PMRate);
  62. // DO NOT set curyAmount – let the formula do it.
  63. c.Update(laborLine);
  64. }
  65. else
  66. {
  67. CreateRevenueBudgetLine(
  68. inventoryCD: LaborInvCD,
  69. taskID: row.ProjectTaskID,
  70. accountGroupID: row.AccountGroupID,
  71. qty: pmHours,
  72. rate: PMRate,
  73. amount: pmHours * PMRate,
  74. uom: row.UOM,
  75. description: "Auto-added PM Labor"
  76. );
  77. }
  78. }
  79. finally
  80. {
  81. PXContext.SetSlot<bool?>(SlotLaborUpdate, false);
  82. }
  83. // ---- Popup & save -----------------------------------
  84. /*ShowPopupOnce(totalOrig);*/
  85. // Base.Actions.PressSave();
  86. }
  87. protected void _(Events.RowPersisting<PMRevenueBudget> e)
  88. {
  89. if (IsExcludedProject()) // ← add this line
  90. return;
  91. var row = (PMRevenueBudget)e.Row;
  92. if (row == null || e.Operation == PXDBOperation.Delete) return;
  93. if (Skip || PXContext.GetSlot<bool?>(SlotLaborUpdate) == true) return;
  94. if (LaborInvID != null && row.InventoryID == LaborInvID)
  95. {
  96. // ensure both currency and base rates are correct right before save
  97. decimal baseRate;
  98. PXCurrencyAttribute.CuryConvBase<PMRevenueBudget.curyUnitRate>(e.Cache, row, PMRate, out baseRate);
  99. if (row.CuryUnitRate != PMRate)
  100. e.Cache.SetValue<PMRevenueBudget.curyUnitRate>(row, PMRate);
  101. }
  102. }
  103. private bool IsExcludedProject()
  104. {
  105. PMProject proj = Base.Project.Current;
  106. if (proj == null) return false;
  107. // Branch check (BranchCD = 301) --------------------------------
  108. if (proj.DefaultBranchID != null)
  109. {
  110. Branch br = PXSelect<Branch,
  111. Where<Branch.branchID, Equal<Required<Branch.branchID>>>>
  112. .Select(Base, proj.DefaultBranchID);
  113. if (br?.BranchCD?.Trim() == ExcludedBranchCD)
  114. return true;
  115. }
  116. // Billing‑rule check (BillingRule = PROGRESS) ------------------
  117. // Field name differs by Acumatica build; common ones shown.
  118. string billRule = proj.BillingID; // e.g., 2021 R1+
  119. if (!string.IsNullOrEmpty(billRule) &&
  120. string.Equals(billRule.Trim(), ExcludedBillRule,
  121. StringComparison.OrdinalIgnoreCase))
  122. return true;
  123. return false;
  124. }
  125. public static bool IsActive()
  126. {
  127. return true;
  128. }
  129. protected void _(Events.FieldUpdated<PMRevenueBudget, PMRevenueBudget.curyUnitRate> e)
  130. {
  131. var r = (PMRevenueBudget)e.Row;
  132. if (r == null) return;
  133. PXTrace.WriteInformation($"curyUnitRate UPDATED -> {r.CuryUnitRate} (Inv={r.InventoryID})");
  134. }
  135. private PMRevenueBudget FindRevenueLineByInventoryCd(string inventoryCD)
  136. {
  137. if (string.IsNullOrEmpty(inventoryCD))
  138. return null;
  139. // Resolve InventoryID from the CD
  140. InventoryItem inv = InventoryItem.UK.Find(Base, inventoryCD);
  141. if (inv == null) return null;
  142. int? projID = Base.Project.Current?.ContractID;
  143. if (projID == null) return null;
  144. // 1) Cache (includes unsaved rows already on screen)
  145. var cached = Base.RevenueBudget.Cache.Cached
  146. .Cast<PMRevenueBudget>()
  147. .FirstOrDefault(r => r.ProjectID == projID
  148. && r.InventoryID == inv.InventoryID
  149. && r.Type == AccountType.Income);
  150. if (cached != null) return cached;
  151. // 2) DB (readonly, excludes unsaved edits)
  152. var db = PXSelectReadonly<PMRevenueBudget,
  153. Where<PMRevenueBudget.projectID, Equal<Required<PMRevenueBudget.projectID>>,
  154. And<PMRevenueBudget.inventoryID, Equal<Required<PMRevenueBudget.inventoryID>>,
  155. And<PMRevenueBudget.type, Equal<AccountType.income>>>>>
  156. .Select(Base, projID, inv.InventoryID)
  157. .RowCast<PMRevenueBudget>()
  158. .FirstOrDefault();
  159. return db;
  160. }
  161. public PMRevenueBudget CreateRevenueBudgetLine(
  162. int? inventoryID = null, string inventoryCD = null,
  163. int? taskID = null, string taskCD = null,
  164. int? accountGroupID = null, string accountGroupCD = null,
  165. decimal? qty = null,
  166. decimal? rate = null,
  167. decimal? amount = null, // if null, amount = qty * rate (when both provided)
  168. string uom = null,
  169. string description = null,
  170. int? costCodeID = null // optional
  171. )
  172. {
  173. // Resolve keys ----------------------------------------------------
  174. int? projectID = Base.Project.Current?.ContractID;
  175. if (projectID == null)
  176. throw new PXException();
  177. if (inventoryID == null && !string.IsNullOrEmpty(inventoryCD))
  178. inventoryID = InventoryItem.UK.Find(Base, inventoryCD)?.InventoryID;
  179. if (taskID == null && !string.IsNullOrEmpty(taskCD))
  180. taskID = PXSelect<PMTask,
  181. Where<PMTask.projectID, Equal<Required<PMTask.projectID>>,
  182. And<PMTask.taskCD, Equal<Required<PMTask.taskCD>>>>>
  183. .Select(Base, projectID, taskCD)
  184. ?.FirstOrDefault()?.GetItem<PMTask>()?.TaskID;
  185. if (accountGroupID == null && !string.IsNullOrEmpty(accountGroupCD))
  186. accountGroupID = PMAccountGroup.UK.Find(Base, accountGroupCD)?.GroupID;
  187. if (qty == null) qty = 0m;
  188. if (rate == null) rate = 0m;
  189. if (amount == null) amount = qty * rate;
  190. // Insert skeleton row --------------------------------------------
  191. var cache = Base.RevenueBudget.Cache;
  192. var line = new PMRevenueBudget
  193. {
  194. ProjectID = projectID,
  195. Type = AccountType.Income // revenue
  196. };
  197. line = (PMRevenueBudget)cache.Insert(line);
  198. // Set fields via SetValueExt so defaults/validations run ----------
  199. if (taskID != null)
  200. cache.SetValueExt<PMRevenueBudget.projectTaskID>(line, taskID);
  201. if (accountGroupID != null)
  202. cache.SetValueExt<PMRevenueBudget.accountGroupID>(line, accountGroupID);
  203. if (inventoryID != null)
  204. cache.SetValueExt<PMRevenueBudget.inventoryID>(line, inventoryID);
  205. if (costCodeID != null)
  206. cache.SetValueExt<PMRevenueBudget.costCodeID>(line, costCodeID);
  207. if (!string.IsNullOrEmpty(uom))
  208. cache.SetValueExt<PMRevenueBudget.uOM>(line, uom);
  209. if (qty != null)
  210. cache.SetValueExt<PMRevenueBudget.qty>(line, qty);
  211. if (rate != null)
  212. cache.SetValueExt<PMRevenueBudget.curyUnitRate>(line, rate);
  213. if (amount != null)
  214. cache.SetValueExt<PMRevenueBudget.curyAmount>(line, amount);
  215. if (!string.IsNullOrEmpty(description))
  216. cache.SetValueExt<PMRevenueBudget.description>(line, description);
  217. // Final update so cache/state is consistent
  218. line = (PMRevenueBudget)cache.Update(line);
  219. return line;
  220. }
  221. private decimal GetPMHours(decimal jobSize)
  222. {
  223. if (jobSize < 0m) return 0m; // or throw
  224. switch (jobSize)
  225. {
  226. case var n when n <= 1000m: return 1.0m;
  227. case var n when n <= 2500m: return 1.5m;
  228. case var n when n <= 5000m: return 3.0m;
  229. case var n when n <= 7500m: return 3.5m;
  230. case var n when n <= 10000m: return 5.0m;
  231. case var n when n <= 25000m: return 6.0m;
  232. case var n when n <= 50000m: return 9.0m;
  233. default: return 10.5m;
  234. }
  235. }
  236. private decimal GetRevisedRevenueTotalUI(params string[] excludeCDs)
  237. {
  238. // Resolve the IDs to skip
  239. var skip = new HashSet<int?>(
  240. (excludeCDs ?? new string[0])
  241. .Select(cd => InventoryItem.UK.Find(Base, cd)?.InventoryID)
  242. .Where(id => id != null)
  243. .Cast<int?>()
  244. );
  245. decimal total = 0m;
  246. // Select() returns rows currently in cache + remaining DB rows for the view
  247. foreach (PMRevenueBudget line in Base.RevenueBudget.Select().RowCast<PMRevenueBudget>())
  248. {
  249. if (line.Type == AccountType.Income && !skip.Contains(line.InventoryID))
  250. total += line.CuryRevisedAmount ?? 0m; // or CuryAmount if you want "original"
  251. }
  252. return total;
  253. }
  254. }
  255. }