@page "/sales/customerform" @page "/sales/customerform/{CustomerId:int}" @using System.ComponentModel.DataAnnotations @using phronCare.UIBlazor.Pages.Shared.Modals @using phronCare.UIBlazor.Services.Sales @inject IModalService Modal @inject HttpClient _httpClient @inject NavigationManager Navigation @inject IToastService toastService @inject AuthenticationStateProvider authenticationStateProvider @inject AccountTypeService accountTypeService @inject TaxConditionService taxConditionService

Formulario: cliente

@foreach (var type in accountTypes) { }
@foreach (var tax in taxConditions) { }



Documentos
@foreach (var tipo in documentTypes) { }

@if (customer.PhSCustomerDocuments?.Any() == true) { @foreach (var doc in customer.PhSCustomerDocuments) { }
Tipo Número
@documentTypes.FirstOrDefault(t => t.Id == doc.DocumenttypesId)?.Name @doc.DocumentNumber
}
Direcciones
@if (editingAddress.Country == "Argentina" && provincesByCountry.TryGetValue("Argentina", out var provincias)) { } else { }
@if (editingIndex != -1) { }
@if (customer.PhSCustomerAddresses.Any()) { @foreach (var address in customer.PhSCustomerAddresses.Select((value, index) => new { value, index })) { }
Sucursal Dirección Ciudad Provincia País
@address.value.BusinessName @address.value.Streetaddress1 @address.value.City @address.value.Stateprovince @address.value.Country
}
@code { [Parameter] public int? CustomerId { get; set; } private ECustomer customer { get; set; } = new(); private List accountTypes = new(); private List taxConditions = new(); private List documentTypes = new(); private ECustomerDocument documentFormModel = new(); private bool isSaving = false; private string returnUrl = "/sales/customers"; private List countries = new() { "Argentina", "Brasil", "Chile", "Uruguay", "Paraguay", "Estados Unidos", "Canadá", "México", "Alemania", "Reino Unido", "Francia", "Italia", "España" }; private Dictionary> provincesByCountry = new() { { "Argentina", new List { "Buenos Aires", "CABA", "Catamarca", "Chaco", "Chubut", "Córdoba", "Corrientes", "Entre Ríos", "Formosa", "Jujuy", "La Pampa", "La Rioja", "Mendoza", "Misiones", "Neuquén", "Río Negro", "Salta", "San Juan", "San Luis", "Santa Cruz", "Santa Fe", "Santiago del Estero", "Tierra del Fuego", "Tucumán" } } }; private ECustomerAddress editingAddress = new(); private int editingIndex = -1; private void OnCountryChanged(ChangeEventArgs e) { var selectedCountry = e.Value?.ToString(); editingAddress.Country = selectedCountry; editingAddress.Stateprovince = string.Empty; // Resetear la provincia si cambia el país } private void AddOrUpdateAddress() { var context = new ValidationContext(editingAddress, null, null); var results = new List(); if (!Validator.TryValidateObject(editingAddress, context, results, true)) { // Mostrar errores en un toast o en pantalla foreach (var error in results) { toastService.ShowError(error.ErrorMessage); } return; } if (editingIndex == -1) { // Agregar nueva dirección customer.PhSCustomerAddresses.Add(editingAddress); } else { // Actualizar dirección existente var existing = customer.PhSCustomerAddresses.ElementAt(editingIndex); existing.BusinessName = editingAddress.BusinessName; existing.Streetaddress1 = editingAddress.Streetaddress1; existing.Streetaddress2 = editingAddress.Streetaddress2; existing.City = editingAddress.City; existing.Stateprovince = editingAddress.Stateprovince; existing.Postalcode = editingAddress.Postalcode; existing.Country = editingAddress.Country; existing.Latitude = editingAddress.Latitude; existing.Longitude = editingAddress.Longitude; existing.Phonenumber = editingAddress.Phonenumber; existing.Email = editingAddress.Email; existing.Notes = editingAddress.Notes; } ResetAddressForm(); } private void EditAddress(int index) { var addr = customer.PhSCustomerAddresses.ElementAt(index); editingAddress = new ECustomerAddress { Id = addr.Id, // Incluí el Id como mencionamos antes, para no perder referencia BusinessName = addr.BusinessName, Streetaddress1 = addr.Streetaddress1, Streetaddress2 = addr.Streetaddress2, City = addr.City, Stateprovince = addr.Stateprovince, Postalcode = addr.Postalcode, Country = addr.Country, Latitude = addr.Latitude, Longitude = addr.Longitude, Phonenumber = addr.Phonenumber, Email = addr.Email, Notes = addr.Notes }; editingIndex = index; } private void RemoveAddress(int index) { var itemToRemove = customer.PhSCustomerAddresses.ElementAt(index); customer.PhSCustomerAddresses.Remove(itemToRemove); ResetAddressForm(); } private void CancelAddressEdit() { ResetAddressForm(); } private void ResetAddressForm() { editingAddress = new(); editingIndex = -1; } protected override async Task OnInitializedAsync() { await LoadAccountTypes(); await LoadTaxConditions(); await LoadDocumentTypes(); if (CustomerId.HasValue) { // Cargar datos del cliente existente desde la API customer = await _httpClient.GetFromJsonAsync($"/api/Customer/{CustomerId.Value}") ?? new(); } } private async Task LoadAccountTypes() { accountTypes = await accountTypeService.GetAllAsync(); } private async Task LoadTaxConditions() { taxConditions = await taxConditionService.GetAllAsync(); } private async Task LoadDocumentTypes() { var result = await _httpClient.GetFromJsonAsync>("/api/DocumentType/GetAll"); documentTypes = result ?? new(); } private void AddCustomerDocument() { if (!string.IsNullOrWhiteSpace(documentFormModel.DocumentNumber)) { customer.PhSCustomerDocuments.Add(documentFormModel); documentFormModel = new(); } } private void RemoveCustomerDocument(ECustomerDocument document) { customer.PhSCustomerDocuments.Remove(document); } private void RemoveCustomerAddress(ECustomerAddress address) { customer.PhSCustomerAddresses.Remove(address); } private async Task HandleValidSubmit() { var parameters = new ModalParameters(); parameters.Add("Message", "¿Desea guardar los cambios del cliente?"); var modal = Modal.Show("Confirmacion", parameters); var result = await modal.Result; if (result.Cancelled) return; try { HttpResponseMessage response; if (CustomerId.HasValue) { response = await _httpClient.PutAsJsonAsync("/api/Customer/Update", customer); } else { response = await _httpClient.PostAsJsonAsync("/api/Customer/Create", customer); } if (response.IsSuccessStatusCode) { toastService.ShowSuccess("Cliente guardado exitosamente"); Navigation.NavigateTo(returnUrl); } else { var error = await response.Content.ReadAsStringAsync(); toastService.ShowError($"Error: {error}"); } } catch (Exception ex) { toastService.ShowError($"Error: {ex.Message}"); } } private void Cancel() { Navigation.NavigateTo(returnUrl); } }