using GB5Shared.DTO.Framework.Criteria; using GB5Shared.DTO.Framework.Login; using GB5Shared.QueryExecutor; using GB5Shared.Resource.Response; using GB5Shared.Validation; using Newtonsoft.Json; using WiDAL.DTOs; using WiDAL.Query.Wi; namespace WiDAL.CustomCode.WiSection { public class WiSectionDAL : IWiSectionDAL { private readonly IQueryExecutor _qe; private readonly IValidation _Validation; public WiSectionDAL(IQueryExecutor qe, IValidation validation) { _qe = qe; _Validation = validation; } public async Task GetById(int WiSectionId, LoginDTO login, CancellationToken ct) { var result = await _qe.QuerySingleAsync(login, WiSectionQB.GET_BY_ID, new { wiSectionId = WiSectionId, TenantId = login.ClientId }); return JsonConvert.SerializeObject(result); } public async Task Save(WiSectionDTO dto, bool isNew, LoginDTO login, CancellationToken ct) { try { string sql = isNew ? WiSectionQB.INSERT : WiSectionQB.UPDATE; var rows = await _qe.ExecuteAsync(login, sql, dto); // 🔥 important check if (rows == 0) { throw new Exception(isNew ? "Insert failed!" : "Update failed! No matching record."); } return dto.WiSectionId; } catch (Exception ex) { string error = await _Validation.HandleException(ex, isNew ? ErrorResponse.SaveErrorMessage : ErrorResponse.UpdateErrorMessage); throw new Exception(error); } } public async Task GetSelectListWiSection(CriteriaDTO criteriaDTO, LoginDTO login, CancellationToken ct) { var result = await _qe.QueryAsync( login, WiSectionQB.GET_SELECTLIST_WISECTION); return JsonConvert.SerializeObject(result); } public async Task DeleteWiSection(int WiSectionId, LoginDTO loginDTO) { try { string sql = WiSectionQB.DELETE_WISECTION; var parameter = new { wiSectionId = WiSectionId }; var result = await _qe.ExecuteAsync(loginDTO, sql, parameter); if (result > 0) return SuccessResponse.DeleteSuccessMessage; else return ErrorResponse.DeleteNotFoundMessage; } catch (Exception ex) { string error = await _Validation.HandleException(ex, ErrorResponse.DeleteErrorMessage); throw new Exception(error); } } public async Task> GetSectionFullAsync(CriteriaDTO criteriaDTO,LoginDTO loginDTO) { var wiSectionDict = new Dictionary(); await _qe.QueryMultiMapAsync( loginDTO, WiSectionQB.GET_LIST_SECTION_STEP, (parent, child) => { if (!wiSectionDict.TryGetValue(parent.WiSectionId, out var existingParent)) { existingParent = parent; existingParent.Steps = new List(); wiSectionDict.Add( parent.WiSectionId, existingParent); } if (child != null && child.WiStepId != 0) { existingParent.Steps.Add(child); } return existingParent; }, null, splitOn: "WiStepId"); return wiSectionDict.Values.ToList(); } } }