using GB5Shared.DTO.Framework.Login; using MMDAL.CustomCode.InspectionParamSetEngine; using MMDAL.DTO.InspectionParamSetOverride; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace MMBLL.InspectionParamSetEngine { // ───────────────────────────────────────────────────────────────────────── // InspectionParamSetEngineBLL // // Stateless resolution algorithm over MINSPECTIONTYPEPARAMETERSET: // 1. Fetch all rows whose wildcarded (PartyId, ItemId) key matches the // context, for the given (always-concrete) InspectionTypeId. // 2. Keep only the max-specificity tier — return ALL ParameterSets in // that tier (a tier can legitimately carry more than one, same // many-to-many shape the default tier already allows today). // Specificity > 0 => Source "Override"; == 0 => "InspectionTypeDefault". // 3. If literally no rows exist for that InspectionTypeId at all, fall // back to Item.QualityParameterSetId (today's actual ultimate // fallback via foundry.ItemParamter.Picklist on the FE). // // No transactions — read-only resolution. // ───────────────────────────────────────────────────────────────────────── public class InspectionParamSetEngineBLL : IInspectionParamSetEngineBLL { private readonly IInspectionParamSetEngineDAL _EngineDAL; public InspectionParamSetEngineBLL(IInspectionParamSetEngineDAL engineDAL) { _EngineDAL = engineDAL; } public async Task> ResolveEffectiveParameterSetsAsync( InspectionParamSetResolveContextDTO context, LoginDTO loginDTO, CancellationToken ct) { try { var asOfDate = context.AsOfDate ?? DateTime.UtcNow; var candidates = (await _EngineDAL.GetMatchingRulesAsync( context.PartyId, context.ItemId, context.InspectionTypeId, asOfDate, loginDTO, ct) .ConfigureAwait(false)).ToList(); if (candidates.Count > 0) { int maxSpecificity = candidates.Max(c => c.MatchedSpecificity); var source = maxSpecificity > 0 ? "Override" : "InspectionTypeDefault"; return candidates .Where(c => c.MatchedSpecificity == maxSpecificity) .Select(c => new ResolvedParameterSetDTO { ParameterSetId = c.ParameterSetId, ParameterSetCode = c.ParameterSetCode, ParameterSetName = c.ParameterSetName, IsRequired = c.IsRequired, SlNo = c.SlNo, MatchedSpecificity = c.MatchedSpecificity, Source = source }) .ToList(); } // No rows at all for this InspectionTypeId — ultimate fallback. var itemDefault = await _EngineDAL .GetItemQualityParameterSetDefaultAsync(context.ItemId, loginDTO, ct) .ConfigureAwait(false); if (itemDefault == null) return Enumerable.Empty(); itemDefault.Source = "ItemQualityParameterSetDefault"; itemDefault.IsRequired = true; return new[] { itemDefault }; } catch (Exception) { throw; } } } }