using Administrationservices; using static Administrationservices.administrationService; using Grpc.Core; using System; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using System.Text.Json; using ServicesDAO.Repositories; // <-- IMPORTANTE: Para IProfileRepository namespace server { class TemporaryServiceInfo { public int idservice { get; set; } public string name { get; set; } } class TemporaryProductInfo { public int idproduct { get; set; } public string name { get; set; } } // AGREGAMOS 'partial' PARA UNIRLO CON EL OTRO ARCHIVO public partial class IDAOAdmin : administrationServiceBase { // --- CAMPOS PARA LA NUEVA LÓGICA (Inyección de Dependencias) --- private readonly IProfileRepository _profileRepo; private readonly ILogger _logger; private readonly ServicesDAO _servicesDAO; // --- CONSTRUCTOR ACTUALIZADO --- // Este constructor es llamado automáticamente por Program.cs // e inyecta el repositorio y el logger. public IDAOAdmin(IProfileRepository profileRepo, ILogger logger, ServicesDAO servicesDAO) { _profileRepo = profileRepo; _logger = logger; _servicesDAO = servicesDAO; } String messageError = "IDAOServices \n "; public override async Task setRoleAndAccess(SetRoleRequest request, ServerCallContext context) { String result = _servicesDAO.setRoleAccess(request.Idrole, request.Idorganization, request.RoleName, request.Description, request.CreatedBy, request.CanView, request.CanEdit, request.CanDelete, request.JsonServices, request.Active, request.IdmenuComponent); bool bresult = result.Equals("Success") ? true : false; if (String.IsNullOrEmpty(result)) throw new RpcException(new Status(StatusCode.NotFound, messageError + "Can't save information")); return new SetRoleResponse() { Success = bresult, Message = result }; } public override async Task setMenuComponent(SetMenuComponentRequest request, ServerCallContext context) { String result = _servicesDAO.setMenuComponent(request.IdmenuComponent, request.ComponentName, request.ComponentPath, request.Description); bool bresult = result.Equals("Success") ? true : false; if (result == null) throw new RpcException(new Status(StatusCode.NotFound, messageError + "Can't save information")); return new SetMenuComponentResponse() { Success = bresult, Message = result }; } public override async Task getAllMenuComponents(GetAllMenuComponentsRequest request, ServerCallContext context) { ; var response = new GetAllMenuComponentsResponse(); DataTable? result = _servicesDAO.getMenuComponent(request.IdmenuComponentFilter, request.ComponentNameFilter); if (result == null) throw new RpcException(new Status(StatusCode.NotFound, messageError + "No results for filter component information")); else { if (result.Rows.Count > 0) { foreach (DataRow row in result.Rows) { MenuComponent item = new MenuComponent() { IdmenuComponent = Convert.ToInt32(row["idmenu_component"].ToString()), ComponentName = row["component_name"].ToString(), Description = row["description"].ToString(), ComponentPath = row["path"].ToString(), }; response.Components.Add(item); } } else throw new RpcException(new Status(StatusCode.NotFound, messageError + "No results for component's information")); } return response; } public override async Task getUserAccessInfo(GetUserAccessInfoRequest request, ServerCallContext context) { var response = new GetUserAccessInfoResponse(); DataTable? result = _servicesDAO.getUserAccessInfo(request.UserId, request.OrganizationId); if (result == null) throw new RpcException(new Status(StatusCode.NotFound, messageError + "No results for user information")); else { if (result.Rows.Count > 0) { foreach (DataRow row in result.Rows) { var userAccessInfo = new UserAccessInfo { UserId = row.Field("UserId"), Username = row.Field("Username"), OrganizationId = row.Field("OrganizationId"), OrganizationName = row.Field("OrganizationName") }; userAccessInfo.Roles.Add(new Role { RoleId = row.Field("RoleId"), RoleName = row.Field("RoleName") }); try { string? menuComponentsJson = row.Field("MenuComponents"); if (!string.IsNullOrEmpty(menuComponentsJson)) { var menuComponents = JsonSerializer.Deserialize>(menuComponentsJson); if (menuComponents != null) { userAccessInfo.MenuComponents.AddRange(menuComponents); } } } catch (JsonException ex) { Console.WriteLine($"Warning: Error deserializing MenuComponents JSON - {ex.Message}"); } try { string? servicesJson = row.Field("Services"); if (!string.IsNullOrEmpty(servicesJson)) { var services = JsonSerializer.Deserialize>(servicesJson); if (services != null) { userAccessInfo.Services.AddRange(services); } } } catch (JsonException ex) { Console.WriteLine($"Warning: Error deserializing Services JSON - {ex.Message}"); } response.UserAccessInfo.Add(userAccessInfo); } } } return await Task.FromResult(response); } public override async Task setUserRole(SetUserRoleRequest request, ServerCallContext context) { String result = _servicesDAO.setUserRole(request.UserId, request.Idorganization, request.Idrole, request.AssignedBy); bool bresult = result.Equals("Success") ? true : false; if (result == null) throw new RpcException(new Status(StatusCode.NotFound, messageError + "Can't save information")); return new SetUserRoleResponse() { Success = bresult, Message = result }; } public override async Task getRoleInfo(GetRoleInfoRequest request, ServerCallContext context) { all_roles list_roles = new all_roles(); DataTable? result = _servicesDAO.getprofiles(request.Idrole, request.Idorganization); if (result == null) throw new RpcException(new Status(StatusCode.NotFound, messageError + "No results for user information")); else { if (result.Rows.Count > 0) { foreach (DataRow row in result.Rows) { var v_roleinfo = new RoleInfo(); try { v_roleinfo = new RoleInfo() { Idrole = row.Field("idrole"), Idorganization = row.Field("idorganization"), RoleName = row.Field("role_name"), Description = row.Field("description"), LastModified = row.Field("last_modified").ToString("yyyy-MM-dd HH:mm:ss"), CreatedBy = row.Field("created_by"), }; } catch (Exception ex) { Console.WriteLine($"Warning: Error setting response for GetRoleInfoResponse - {ex.Message}"); } try { var menuComponents_string = row.Field("menu_access_json"); if (!String.IsNullOrEmpty(menuComponents_string)) { menuComponents_string = menuComponents_string.Replace("\\\"", "\"").Replace("\\\\", "\\"); var menuComponents = JsonSerializer.Deserialize(menuComponents_string); foreach (DataRow row_components in menuComponents.Rows) { MenuComponentAccess component = new MenuComponentAccess() { ComponentName = row.Field("component_name"), IdmenuComponent = row.Field("idmenu_component") }; v_roleinfo.MenuComponents.Add(component); } } } catch (Exception ex) { Console.WriteLine($"Warning: Error processing 'menu_access_json' - {ex.Message}"); } try { var servicesJson_string = row.Field("services_json"); if (!String.IsNullOrEmpty(servicesJson_string)) { servicesJson_string = servicesJson_string.Replace("\\\"", "\"").Replace("\\\\", "\\"); List tempServices = JsonSerializer.Deserialize>(servicesJson_string); foreach (var temp in tempServices) { v_roleinfo.Services.Add(new ServiceInfo { Servicesid = temp.idservice, Name = temp.name }); } } } catch (Exception ex) { Console.WriteLine($"Warning: Error processing 'services_json' - {ex.Message}"); } try { var productsJson = row.Field("products_json"); if (!string.IsNullOrEmpty(productsJson)) { productsJson = productsJson.Replace("\\\"", "\"").Replace("\\\\", "\\"); List tempServices = JsonSerializer.Deserialize>(productsJson); foreach (var temp in tempServices) { v_roleinfo.Products.Add(new ProductTypeInfo { Id = temp.idproduct, ProductName = temp.name }); } } } catch (Exception ex) { Console.WriteLine($"Warning: Error processing 'products_json' - {ex.Message}"); } list_roles.Response.Add(v_roleinfo); } } } return new all_roles(list_roles); } } }