using GB5Shared.DTO.Framework.AutoNumber; using GB5Shared.DTO.Framework.Criteria; using GB5Shared.DTO.Framework.Login; using GB5Shared.GenerateAutoNumber; using GB5Shared.Resource.Response; using GB5Shared.Validation; using Newtonsoft.Json; using WiDAL.CustomCode.WiProcess; using WiDAL.DTOs; namespace WiBLL.WiProcess; public class WiProcessBLL : IWiProcessBLL { private readonly IWiProcessDAL _dal; private readonly AutoNumber _autoNumber; private readonly IValidation _validation; public WiProcessBLL(IWiProcessDAL dal, AutoNumber autoNumber, IValidation validation) { _dal = dal; _autoNumber = autoNumber; _validation = validation; } public async Task GetList(LoginDTO login, CancellationToken ct) => await _dal.GetList(login, ct).ConfigureAwait(false); public async Task GetById(int wiProcessId, LoginDTO login, CancellationToken ct) => await _dal.GetById(wiProcessId, login, ct).ConfigureAwait(false); public async Task Save(WiProcessDTO dto, LoginDTO login, CancellationToken ct) { if (dto == null) throw new ArgumentNullException(nameof(dto)); AutoNumberDTO? autoNumberDTO = null; try { await _validation.NotEmpty(dto.WiProcessCode, nameof(dto.WiProcessCode)); await _validation.NotEmpty(dto.WiProcessName, nameof(dto.WiProcessName)); dto.TenantId = login.ClientId; dto.ModifiedById = login.UserId; bool isNew = dto.WiProcessId == 0; // ✅ decide BEFORE changing ID if (isNew) { autoNumberDTO = await _autoNumber.GetNumberAsync(1, "WIPROCESS", login); dto.WiProcessId = autoNumberDTO.StartNumber; // ID changes here dto.CreatedById = login.UserId; } // ✅ pass isNew to DAL await _dal.Save(dto, isNew, login, ct); return isNew ? string.Format(SuccessResponse.SaveSuccessWithCodeAndName, dto.WiProcessCode, dto.WiProcessName) : string.Format(SuccessResponse.UpdateSuccessWithCodeAndName, dto.WiProcessCode, dto.WiProcessName); } catch { if (autoNumberDTO != null && dto.WiProcessId > 0) { await _autoNumber.RollbackAutoNumber("WIPROCESS", dto.WiProcessId, login); } throw; } } public async Task GetSelectListWiProcess(CriteriaDTO criteriaDTO, LoginDTO login, CancellationToken ct) => await _dal.GetSelectListWiProcess(criteriaDTO, login, ct); public async Task DeleteWiProcess(int WiProcessId, LoginDTO loginDTO) { try { return await _dal.DeleteWiProcess(WiProcessId, loginDTO); } catch (Exception) { throw; } } }