using EntitlementBLL.Interfaces; using EntitlementDAL.DTOs; using EntitlementDAL.Interfaces; using GB5Shared.DTO.Framework.Login; using GB5Shared.GenerateAutoNumber; using GB5Shared.QueryExecutor; using GB5Shared.Resource.Response; using GB5Shared.Telemetry; using static GB5Shared.GB5Constant.Constant; namespace EntitlementBLL.Implementations; public class FeatureFlagBLL : IFeatureFlagBLL { private readonly IFeatureFlagDAL _FlagDAL; private readonly AutoNumber _AutoNumber; private readonly IQueryExecutor _QueryExecutor; public FeatureFlagBLL(IFeatureFlagDAL flagDAL, AutoNumber autoNumber, IQueryExecutor queryExecutor) { _FlagDAL = flagDAL; _AutoNumber = autoNumber; _QueryExecutor = queryExecutor; } public async Task GetAsync(int featureFlagId, LoginDTO login, CancellationToken ct) => await _FlagDAL.GetByIdAsync(featureFlagId, login, ct).ConfigureAwait(false); public async Task> GetListAsync(LoginDTO login, CancellationToken ct) => await _FlagDAL.GetListAsync(login, ct).ConfigureAwait(false); public async Task GetByFeatureCodeAsync(string featureCode, LoginDTO login, CancellationToken ct) => await _FlagDAL.GetByFeatureCodeAsync(featureCode, login, ct).ConfigureAwait(false); public async Task> GetTargetListAsync(int featureFlagId, LoginDTO login, CancellationToken ct) => await _FlagDAL.GetTargetsByFlagAsync(featureFlagId, login, ct).ConfigureAwait(false); public async Task SaveAsync(FeatureFlagDTO dto, LoginDTO login, CancellationToken ct) { if (dto is null) throw new ArgumentNullException(nameof(dto)); if (string.IsNullOrWhiteSpace(dto.FlagName)) throw new ArgumentException("FlagName is required.", nameof(dto)); if (dto.FeatureId <= 0) throw new ArgumentException("FeatureId is required.", nameof(dto)); bool isNew = dto.FeatureFlagId == 0; var tx = await _QueryExecutor.BeginTransactionAsync(login).ConfigureAwait(false); try { GB5Trace.Step("validate-feature-flag", new { dto.FeatureFlagId, isNew }); var now = DateTime.UtcNow; if (isNew) { var auto = await _AutoNumber.GetNumberAsync(1, AUTONUMBERCONSTANT.ENTITLEMENTFEATUREFLAG, login).ConfigureAwait(false); dto.FeatureFlagId = auto.StartNumber; dto.CreatedById = login.UserId; dto.CreatedOn = now; } dto.ModifiedById = login.UserId; dto.ModifiedOn = now; GB5Trace.Step("save-feature-flag", new { dto.FeatureFlagId, isNew }); if (isNew) await _FlagDAL.SaveAsync(dto, login, tx, ct).ConfigureAwait(false); else await _FlagDAL.UpdateAsync(dto, login, tx, ct).ConfigureAwait(false); await _QueryExecutor.CommitAsync(tx).ConfigureAwait(false); return isNew ? $"{SuccessResponse.SaveSuccessMessage} {dto.FeatureFlagId}" : SuccessResponse.UpdateSuccess; } catch (Exception ex) { await _QueryExecutor.RollbackAsync(tx).ConfigureAwait(false); GB5Trace.MarkFailed("save-feature-flag-failed", ex); throw; } } }