ProjectEntryExt.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. using PX.Common;
  2. using PX.Data;
  3. using PX.Objects.GL;
  4. using PX.Objects.IN;
  5. using PX.Objects.PM;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. namespace ProjectEntryLaborAdjust
  10. {
  11. // ===================== GRAPH EXTENSION (RULE-DRIVEN) =====================
  12. public class ProjectEntryExt : PXGraphExtension<ProjectEntry>
  13. {
  14. private const string SlotLaborUpdate = "RevBudSetLabor";
  15. // List of rules to process — add new classes here in Initialize()
  16. private readonly List<LaborRuleBase> _rules = new List<LaborRuleBase>();
  17. // Cache InventoryID lookups for rule CDs
  18. private readonly Dictionary<string, int?> _invIdCache =
  19. new Dictionary<string, int?>(StringComparer.OrdinalIgnoreCase);
  20. protected bool Skip => Base.IsImport || Base.IsContractBasedAPI || Base.IsCopyPasteContext;
  21. public override void Initialize()
  22. {
  23. base.Initialize();
  24. _rules.Clear();
  25. _rules.Add(new L023PmLaborRule()); // uses AR pricing (no fixed rate)
  26. //_rules.Add(new L014LaborRule()); // fixed rate example
  27. // _rules.Add(new L001LaborRule());
  28. }
  29. // -------------------- Event Handlers --------------------
  30. protected void _(Events.RowUpdated<PMRevenueBudget> e)
  31. {
  32. var row = (PMRevenueBudget)e.Row;
  33. var old = (PMRevenueBudget)e.OldRow;
  34. if (row == null || old == null || Skip) return;
  35. if (PXContext.GetSlot<bool?>(SlotLaborUpdate) == true) return;
  36. // Only react when Original Budgeted Amount changed
  37. if (e.Cache.ObjectsEqual<PMRevenueBudget.curyAmount>(row, old)) return;
  38. // Build once
  39. string[] laborCDs = _rules.Select(r => r.InventoryCD).ToArray();
  40. int?[] laborIDs = laborCDs.Select(GetInventoryIdCached).ToArray();
  41. // If editing any labor line, skip to avoid recursion
  42. if (row.InventoryID != null && laborIDs.Contains(row.InventoryID))
  43. return;
  44. // Exclude ALL labor lines from the job-size total
  45. decimal totalRevised = GetRevisedRevenueTotalUI(laborCDs);
  46. // Resolve project context for per-rule exclusions
  47. PMProject proj = Base.Project.Current;
  48. string branchCD = ResolveBranchCD(proj?.DefaultBranchID);
  49. string templateCD = ResolveTemplateCD(proj?.TemplateID);
  50. string billRule = ResolveBillRule(proj);
  51. DateTime? projectCreatedDate = proj?.CreatedDateTime;
  52. PXContext.SetSlot<bool?>(SlotLaborUpdate, true);
  53. try
  54. {
  55. foreach (var rule in _rules)
  56. {
  57. // Per-rule exclusion check
  58. if (rule.IsExcludedFor(branchCD, templateCD, billRule, projectCreatedDate))
  59. {
  60. continue;
  61. }
  62. decimal hours = rule.GetHours(totalRevised, projectCreatedDate); ;
  63. UpsertLaborLine(rule, hours, row);
  64. }
  65. }
  66. finally
  67. {
  68. PXContext.SetSlot<bool?>(SlotLaborUpdate, false);
  69. }
  70. }
  71. // Re-assert fixed rates right before save
  72. protected void _(Events.RowPersisting<PMRevenueBudget> e)
  73. {
  74. var row = (PMRevenueBudget)e.Row;
  75. if (row == null || e.Operation == PXDBOperation.Delete) return;
  76. if (Skip || PXContext.GetSlot<bool?>(SlotLaborUpdate) == true) return;
  77. // if this row corresponds to a rule WITH a fixed rate, ensure the rate is set
  78. foreach (var rule in _rules)
  79. {
  80. var invID = GetInventoryIdCached(rule.InventoryCD);
  81. if (invID == null) continue;
  82. if (row.InventoryID == invID && rule.FixedUnitRate.HasValue)
  83. {
  84. decimal desiredRate = rule.FixedUnitRate.Value;
  85. // Using SetValue (not SetValueExt) at persist-time avoids extra field events
  86. if (row.CuryUnitRate != desiredRate)
  87. e.Cache.SetValue<PMRevenueBudget.curyUnitRate>(row, desiredRate);
  88. break; // at most one match
  89. }
  90. }
  91. }
  92. protected void _(Events.FieldUpdated<PMRevenueBudget, PMRevenueBudget.curyUnitRate> e)
  93. {
  94. var r = (PMRevenueBudget)e.Row;
  95. if (r == null) return;
  96. PXTrace.WriteInformation($"curyUnitRate UPDATED -> {r.CuryUnitRate} (Inv={r.InventoryID})");
  97. }
  98. // -------------------- Core Helpers --------------------
  99. private int? GetInventoryIdCached(string inventoryCD)
  100. {
  101. if (string.IsNullOrWhiteSpace(inventoryCD)) return null;
  102. int? cached;
  103. if (_invIdCache.TryGetValue(inventoryCD, out cached))
  104. return cached;
  105. var id = InventoryItem.UK.Find(Base, inventoryCD)?.InventoryID;
  106. _invIdCache[inventoryCD] = id;
  107. return id;
  108. }
  109. private void UpsertLaborLine(LaborRuleBase rule, decimal hours, PMRevenueBudget contextRow)
  110. {
  111. var cache = Base.RevenueBudget.Cache;
  112. var laborLine = FindRevenueLineByInventoryCd(rule.InventoryCD);
  113. if (laborLine != null)
  114. {
  115. bool qtyChanged = laborLine.Qty != hours;
  116. if (qtyChanged)
  117. cache.SetValueExt<PMRevenueBudget.qty>(laborLine, hours);
  118. // Rate logic (safe, minimal events):
  119. if (rule.FixedUnitRate.HasValue)
  120. {
  121. // Explicit fixed rate supplied by the rule
  122. decimal desiredRate = rule.FixedUnitRate.Value;
  123. if (laborLine.CuryUnitRate != desiredRate)
  124. cache.SetValueExt<PMRevenueBudget.curyUnitRate>(laborLine, desiredRate);
  125. }
  126. else if (qtyChanged)
  127. {
  128. // No explicit rate: re-apply pricing defaults when qty changed
  129. cache.SetDefaultExt<PMRevenueBudget.curyUnitRate>(laborLine);
  130. }
  131. cache.Update(laborLine);
  132. }
  133. else
  134. {
  135. // Creating a new line — pass rate if provided, and compute amount if we have both qty & rate
  136. decimal? rate = rule.FixedUnitRate;
  137. decimal? amount = rate.HasValue ? (decimal?)(hours * rate.Value) : null;
  138. CreateRevenueBudgetLine(
  139. inventoryID: null,
  140. inventoryCD: rule.InventoryCD,
  141. taskID: contextRow.ProjectTaskID,
  142. accountGroupID: contextRow.AccountGroupID,
  143. qty: hours,
  144. rate: rate, // if null → pricing defaults
  145. amount: amount, // if null → formula
  146. uom: contextRow.UOM,
  147. description: rule.Description
  148. );
  149. }
  150. }
  151. private string ResolveBranchCD(int? branchID)
  152. {
  153. if (branchID == null) return null;
  154. Branch br = PXSelect<Branch,
  155. Where<Branch.branchID, Equal<Required<Branch.branchID>>>>
  156. .Select(Base, branchID);
  157. return br?.BranchCD;
  158. }
  159. private string ResolveTemplateCD(int? templateProjectID)
  160. {
  161. if (templateProjectID == null) return null;
  162. PMProject tmpl = PMProject.PK.Find(Base, templateProjectID);
  163. return tmpl?.ContractCD;
  164. }
  165. private string ResolveBillRule(PMProject proj)
  166. {
  167. return proj?.BillingID;
  168. }
  169. private PMRevenueBudget FindRevenueLineByInventoryCd(string inventoryCD)
  170. {
  171. if (string.IsNullOrEmpty(inventoryCD))
  172. return null;
  173. InventoryItem inv = InventoryItem.UK.Find(Base, inventoryCD);
  174. if (inv == null) return null;
  175. int? projID = Base.Project.Current?.ContractID;
  176. if (projID == null) return null;
  177. var cached = Base.RevenueBudget.Cache.Cached
  178. .Cast<PMRevenueBudget>()
  179. .FirstOrDefault(r => r.ProjectID == projID
  180. && r.InventoryID == inv.InventoryID
  181. && r.Type == AccountType.Income);
  182. if (cached != null) return cached;
  183. var db = PXSelectReadonly<PMRevenueBudget,
  184. Where<PMRevenueBudget.projectID, Equal<Required<PMRevenueBudget.projectID>>,
  185. And<PMRevenueBudget.inventoryID, Equal<Required<PMRevenueBudget.inventoryID>>,
  186. And<PMRevenueBudget.type, Equal<AccountType.income>>>>>
  187. .Select(Base, projID, inv.InventoryID)
  188. .RowCast<PMRevenueBudget>()
  189. .FirstOrDefault();
  190. return db;
  191. }
  192. public PMRevenueBudget CreateRevenueBudgetLine(
  193. int? inventoryID = null, string inventoryCD = null,
  194. int? taskID = null, string taskCD = null,
  195. int? accountGroupID = null, string accountGroupCD = null,
  196. decimal? qty = null,
  197. decimal? rate = null,
  198. decimal? amount = null, // if null, amount = qty * rate (when both provided) or by formula
  199. string uom = null,
  200. string description = null,
  201. int? costCodeID = null // optional
  202. )
  203. {
  204. // Resolve keys
  205. int? projectID = Base.Project.Current?.ContractID;
  206. if (projectID == null)
  207. throw new PXException();
  208. if (inventoryID == null && !string.IsNullOrEmpty(inventoryCD))
  209. inventoryID = InventoryItem.UK.Find(Base, inventoryCD)?.InventoryID;
  210. if (taskID == null && !string.IsNullOrEmpty(taskCD))
  211. taskID = PXSelect<PMTask,
  212. Where<PMTask.projectID, Equal<Required<PMTask.projectID>>,
  213. And<PMTask.taskCD, Equal<Required<PMTask.taskCD>>>>>
  214. .Select(Base, projectID, taskCD)
  215. ?.FirstOrDefault()?.GetItem<PMTask>()?.TaskID;
  216. if (accountGroupID == null && !string.IsNullOrEmpty(accountGroupCD))
  217. accountGroupID = PMAccountGroup.UK.Find(Base, accountGroupCD)?.GroupID;
  218. if (qty == null) qty = 0m;
  219. if (rate == null) rate = 0m; // safe default; logic below decides how to set rate
  220. if (amount == null && qty.HasValue && rate.HasValue && rate.Value != 0m)
  221. amount = qty * rate;
  222. var cache = Base.RevenueBudget.Cache;
  223. var line = new PMRevenueBudget
  224. {
  225. ProjectID = projectID,
  226. Type = AccountType.Income
  227. };
  228. line = (PMRevenueBudget)cache.Insert(line);
  229. if (taskID != null)
  230. cache.SetValueExt<PMRevenueBudget.projectTaskID>(line, taskID);
  231. if (accountGroupID != null)
  232. cache.SetValueExt<PMRevenueBudget.accountGroupID>(line, accountGroupID);
  233. if (inventoryID != null)
  234. cache.SetValueExt<PMRevenueBudget.inventoryID>(line, inventoryID);
  235. if (costCodeID != null)
  236. cache.SetValueExt<PMRevenueBudget.costCodeID>(line, costCodeID);
  237. if (!string.IsNullOrEmpty(uom))
  238. cache.SetValueExt<PMRevenueBudget.uOM>(line, uom);
  239. if (qty != null)
  240. cache.SetValueExt<PMRevenueBudget.qty>(line, qty);
  241. if (!string.IsNullOrEmpty(description))
  242. cache.SetValueExt<PMRevenueBudget.description>(line, description);
  243. // Unit rate + amount logic mirrors the single-code pattern
  244. if (rate.HasValue && rate.Value != 0m)
  245. {
  246. cache.SetValueExt<PMRevenueBudget.curyUnitRate>(line, rate.Value);
  247. if (amount.HasValue)
  248. cache.SetValueExt<PMRevenueBudget.curyAmount>(line, amount.Value);
  249. }
  250. else
  251. {
  252. // No explicit rate: let AR Sales Price default
  253. cache.SetDefaultExt<PMRevenueBudget.curyUnitRate>(line);
  254. }
  255. line = (PMRevenueBudget)cache.Update(line);
  256. return line;
  257. }
  258. private decimal GetRevisedRevenueTotalUI(params string[] excludeCDs)
  259. {
  260. var skip = new HashSet<int?>(
  261. (excludeCDs ?? new string[0])
  262. .Select(cd => InventoryItem.UK.Find(Base, cd)?.InventoryID)
  263. .Where(id => id != null)
  264. .Cast<int?>()
  265. );
  266. decimal total = 0m;
  267. foreach (PMRevenueBudget line in Base.RevenueBudget.Select().RowCast<PMRevenueBudget>())
  268. {
  269. if (line.Type == AccountType.Income && !skip.Contains(line.InventoryID))
  270. total += line.CuryRevisedAmount ?? 0m;
  271. }
  272. return total;
  273. }
  274. public static bool IsActive()
  275. {
  276. return true;
  277. }
  278. }
  279. }