using System.Data.Common; using System.Linq; using GB5Shared.DTO.Framework.Criteria; using GB5Shared.DTO.Framework.Login; using GB5Shared.QueryExecutor; using GB5Shared.Resource.Response; using GB5Shared.Validation; using CRMSalesDAL.DTO.Deal; using CRMSalesDAL.Query.Deal; using Newtonsoft.Json; namespace CRMSalesDAL.CustomCode.Deal; public class DealDAL : IDealDAL { private readonly IQueryExecutor _QueryExecutor; private readonly IValidation _Validation; public DealDAL(IQueryExecutor queryExecutor, IValidation validation) { _QueryExecutor = queryExecutor; _Validation = validation; } public async Task GetDeal(int dealId, LoginDTO loginDTO, CancellationToken ct) { try { var result = await _QueryExecutor .QuerySingleAsync(loginDTO, DealQB.GET_DEAL, new { DealId = dealId }, cancellationToken: ct) .ConfigureAwait(false); return JsonConvert.SerializeObject(result); } catch { throw; } } public async Task GetSelectListDeal(CriteriaDTO criteriaDTO, LoginDTO loginDTO, CancellationToken ct) { try { var result = await _QueryExecutor .QueryAsync(loginDTO, DealQB.GET_SELECTLIST_DEAL, null!, cancellationToken: ct) .ConfigureAwait(false); return JsonConvert.SerializeObject(result); } catch { throw; } } public async Task GetDealStage(int dealId, LoginDTO loginDTO, CancellationToken ct) { try { // QuerySingleOrDefaultAsync does not exist on IQueryExecutor (per GB5Solution/CLAUDE.md) — // QueryAsync + FirstOrDefault() is the mandated substitute for an optional single row. var rows = await _QueryExecutor .QueryAsync(loginDTO, DealQB.GET_DEAL_STAGE, new { DealId = dealId }, cancellationToken: ct) .ConfigureAwait(false); var list = rows.ToList(); return list.Count > 0 ? list[0] : (byte?)null; } catch { throw; } } public async Task SaveDeal(DealDTO dealDTO, LoginDTO loginDTO, DbTransaction tx, CancellationToken ct) { try { return await _QueryExecutor .ExecuteAsync(loginDTO, DealQB.SAVE_DEAL, dealDTO, tx, ct) .ConfigureAwait(false); } catch (Exception ex) { string error = await _Validation.HandleException(ex, ErrorResponse.SaveErrorMessage); throw new Exception(error); } } public async Task UpdateDeal(DealDTO dealDTO, LoginDTO loginDTO, DbTransaction tx, CancellationToken ct) { try { return await _QueryExecutor .ExecuteAsync(loginDTO, DealQB.UPDATE_DEAL, dealDTO, tx, ct) .ConfigureAwait(false); } catch (Exception ex) { string error = await _Validation.HandleException(ex, ErrorResponse.UpdateErrorMessage); throw new Exception(error); } } public async Task DeleteDeal(int dealId, LoginDTO loginDTO, CancellationToken ct) { try { int result = await _QueryExecutor .ExecuteAsync(loginDTO, DealQB.DELETE_DEAL, new { DealId = dealId }, cancellationToken: ct) .ConfigureAwait(false); return result > 0 ? SuccessResponse.DeleteSuccessMessage : ErrorResponse.DeleteNotFoundMessage; } catch (Exception ex) { string error = await _Validation.HandleException(ex, ErrorResponse.DeleteErrorMessage); throw new Exception(error); } } }