ProjectEntryExt.cs 12 KB

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