Skip to content

Commit

Permalink
Funciona el agregar pedido
Browse files Browse the repository at this point in the history
  • Loading branch information
frhgm committed Nov 22, 2022
1 parent d70beac commit fb8a70d
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 55 deletions.
2 changes: 1 addition & 1 deletion app/App.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:app"
StartupUri="Ventanas\Modales\Agregar_Subasta.xaml">
StartupUri="Ventanas\Modales\Agregar_Pedido.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
Expand Down
3 changes: 2 additions & 1 deletion app/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ public partial class App : Application
{
public SubastaDataService subastaDataService;
public PedidosDataService pedidoDataService;

public SolicitudesDataService solicitudDataService;
protected override void OnStartup(StartupEventArgs e)
{
XamlDisplay.Init();
base.OnStartup(e);
subastaDataService = new();
pedidoDataService = new();
solicitudDataService = new();
}
}
}
2 changes: 1 addition & 1 deletion app/Ventanas/Modales/Agregar_Pedido.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
Title="Agregar_Pedido" Height="600" Width="800">
<Grid ShowGridLines="True">
<Grid ShowGridLines="False">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
Expand Down
21 changes: 10 additions & 11 deletions app/Ventanas/Modales/Agregar_Pedido.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ namespace app.Ventanas.Modales
{
public partial class Agregar_Pedido : Window
{
private readonly SolicitudesDataService _solicitudDataService = new();
private readonly PedidosDataService _dataService = new();
private SolicitudPedido solicitudSeleccionada = null;
App _app = ((App)Application.Current);
private CrearPedido _pedidoPorCrear = new CrearPedido();

public Agregar_Pedido()
Expand All @@ -36,7 +35,7 @@ private async void BuscarProductos_Productor_OnClick(object sender, RoutedEventA
// TODO Lograr poblar (o no) DataGrid con Productos_Productores coincidentes con Productos_Clientes
// 1. Traer los producto_cliente de la solcitud seleccionada
// TRAIGO LOS DETALLES DE UNA SOLICITUD EN PARTICULAR
var detalles = await _solicitudDataService.TraerDetallesSolcitudPedido(solicitudSeleccionada.Id);
var detalles = await _app.solicitudDataService.TraerDetallesSolcitudPedido(solicitudSeleccionada.Id);
List<ProductoCliente> productosClientes = new List<ProductoCliente>();
foreach (var detalle in detalles.DetallesSolicitudPedido)
{
Expand All @@ -50,14 +49,14 @@ private async void BuscarProductos_Productor_OnClick(object sender, RoutedEventA
// LLAMO LOS PRODUCTOS PRODUCTORES COINCIDENTES CON PRODUCTOS CLIENTES
foreach (var pc in productosClientes)
{
var pp = await _dataService.TraerProductosProductorPedido(pc.Id);
var pp = await _app.pedidoDataService.TraerProductosProductorPedido(pc.Id);
if (pp == null)
{
puedeCrearPedido = false;
}
else
{
var detalle = await _dataService.PoblarDetallePedido(pp.Id, pc.Id);
var detalle = await _app.pedidoDataService.PoblarDetallePedido(pp.Id, pc.Id);
// TODO Controlar que no intente agregar si es null, o vacio
filasPorAgregar.Add(detalle);
}
Expand All @@ -73,18 +72,18 @@ private async void BuscarProductos_Productor_OnClick(object sender, RoutedEventA
totalAPagar += fila.Total;
DetallesPedidoDG.Items.Add(fila);
CrearDetallePedido crearDetalle = new CrearDetallePedido();
crearDetalle.Calidad = fila.Calidad.ToString();
crearDetalle.Cantidad = fila.CantidadProductoCliente.ToString();
crearDetalle.Precio = fila.Precio.ToString();
crearDetalle.Calidad = fila.Calidad;
crearDetalle.Cantidad = fila.CantidadProductoCliente;
crearDetalle.Precio = fila.Precio;
crearDetalle.Productor_Id = fila.ProductorRut;
crearDetalle.ProductoId = fila.ProductoId;
detallesPedido.Add(crearDetalle);
}

LblTotal.Content = $"Total: {totalAPagar.ToString("C", CultureInfo.CurrentCulture)}";
CrearPedido crearPedido = new CrearPedido();
crearPedido.Total = totalAPagar.ToString();
crearPedido.SolicitudId = solicitudSeleccionada.Id.ToString();
// crearPedido.Total = totalAPagar;
crearPedido.SolicitudId = solicitudSeleccionada.Id;
crearPedido.DetallePedido = detallesPedido;

_pedidoPorCrear = crearPedido;
Expand All @@ -98,7 +97,7 @@ private async void BuscarProductos_Productor_OnClick(object sender, RoutedEventA

private async void CrearPedido_OnClick(object sender, RoutedEventArgs e)
{
bool pedidoCreado = await _dataService.CrearPedido(_pedidoPorCrear);
bool pedidoCreado = await _app.pedidoDataService.CrearPedido(_pedidoPorCrear);

if (pedidoCreado)
{
Expand Down
6 changes: 3 additions & 3 deletions app/Ventanas/Modales/Agregar_Subasta.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace app.Ventanas.Modales
public partial class Agregar_Subasta : Window
{
App _app = ((App)Application.Current);
private Pedido pedidoSeleccionado;
private classLibrary.DTOs.Pedidos _pedidosSeleccionado;

public Agregar_Subasta()
{
Expand All @@ -21,7 +21,7 @@ public Agregar_Subasta()

private async void AgregarSubasta_OnClick(object sender, RoutedEventArgs e)
{
CrearSubasta subasta = new(pedidoSeleccionado.PedidoId, Convert.ToInt32(AddMontoMinimo.Text));
CrearSubasta subasta = new(_pedidosSeleccionado.PedidoId, Convert.ToInt32(AddMontoMinimo.Text));
var subastaCreada = await _app.subastaDataService.CrearSubasta(subasta);
// var subastaCreada = await _dataService.CrearSubasta(subasta);
if (subastaCreada)
Expand All @@ -33,7 +33,7 @@ private async void AgregarSubasta_OnClick(object sender, RoutedEventArgs e)
private void AddPedido_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cb = (ComboBox)sender;
pedidoSeleccionado = (Pedido)cb.SelectedItem;
_pedidosSeleccionado = (classLibrary.DTOs.Pedidos)cb.SelectedItem;
}
}
}
14 changes: 9 additions & 5 deletions app/Ventanas/Pedidos.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
FontSize="18" />
<!-- Tamanio de fuente para presentacion FontSize="17" -->
<DataGrid
x:Name="SolicitudesDG"
x:Name="PedidosDG"
Grid.Row="1"
Margin="5"
AutoGenerateColumns="False"
Expand All @@ -48,11 +48,15 @@
IsReadOnly="True"
IsSynchronizedWithCurrentItem="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="Id" />
<DataGridTextColumn Binding="{Binding Oferta}" Header="Oferta" />
<DataGridTextColumn Binding="{Binding Fecha}" Header="Fecha" />
<DataGridTextColumn Binding="{Binding Estado}" Header="Estado" />
<DataGridTextColumn Binding="{Binding PedidoId}" Header="Id" />
<DataGridTextColumn Binding="{Binding OfertaSubastaId}" Header="Oferta" />
<DataGridTextColumn Binding="{Binding FechaPedido}" Header="Fecha" />
<DataGridTextColumn Binding="{Binding EstadoPedido}" Header="Estado" />
<DataGridTextColumn Binding="{Binding Total}" Header="Total" />
<DataGridTextColumn Binding="{Binding SolicitudId}" Header="Solicitud" />
<DataGridTextColumn Binding="{Binding FechaSolicitud}" Header="Fecha" />
<DataGridTextColumn Binding="{Binding Direccion}" Header="Direccion" />
<DataGridTextColumn Binding="{Binding UsuarioId}" Header="Usuario" />
<!-- <DataGridTemplateColumn Width="80" Header="Editar"> -->
<!-- <DataGridTemplateColumn.CellTemplate> -->
<!-- <DataTemplate> -->
Expand Down
10 changes: 6 additions & 4 deletions app/Ventanas/Pedidos.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Windows.Controls;
using classLibrary.DTO;
using System.Data;
using System.Globalization;
using app.Ventanas.Modales;
using classLibrary.DataServices;
using classLibrary.DTOs;
Expand All @@ -21,8 +22,8 @@ namespace app.Ventanas
/// </summary>
public partial class Pedidos
{
App _app = ((App)Application.Current);
List<EntradaMenu> menus = new();
private readonly SolicitudesDataService dataService = new();
private int rolId;


Expand All @@ -37,6 +38,7 @@ public Pedidos()
return;
}
AgregarMenus();
CargarPedidos();
}

public void MenuSeleccionadoSet(object sender, EventArgs e, string menu)
Expand Down Expand Up @@ -92,10 +94,10 @@ public void AgregarMenus()
/// <summary>
/// Se llama al metodo TraerUsuarios, que va a buscar al servidor sp_get_all_users, y pobla el DataGrid con esta lista
/// </summary>
private async void CargarSolicitudes()
private async void CargarPedidos()
{
var solicitudes = await dataService.TraerSolicitudes();
SolicitudesDG.ItemsSource = solicitudes.solicitudes_pedidos;
var pedidos = await _app.pedidoDataService.TraerPedidos();
PedidosDG.ItemsSource = pedidos.pedidos;
}

private async void BorrarUsuario_Click(object sender, RoutedEventArgs e)
Expand Down
6 changes: 3 additions & 3 deletions classLibrary/DTOs/CrearDetallePedido.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ public class CrearDetallePedido
{
[JsonPropertyName("producto_id")] public int ProductoId { get; set; }
[JsonPropertyName("productor_id")] public string Productor_Id { get; set; }
[JsonPropertyName("calidad")] public string Calidad { get; set; }
[JsonPropertyName("cantidad")] public string Cantidad { get; set; }
[JsonPropertyName("precio")] public string Precio { get; set; }
[JsonPropertyName("calidad")] public int Calidad { get; set; }
[JsonPropertyName("cantidad")] public int Cantidad { get; set; }
[JsonPropertyName("precio")] public int Precio { get; set; }
}

public class ListaFilasProductoProductor
Expand Down
15 changes: 9 additions & 6 deletions classLibrary/DTOs/Pedido.cs → classLibrary/DTOs/Pedidos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ namespace classLibrary.DTOs
// [JsonPropertyName("pedido")]
// public Pedido pedido { get; set; }
// }
[JsonObject("pedido")]
public class Pedido
{
public CrearPedido pedido { get; set; }
}
public class CrearPedido
{
[JsonPropertyName("solicitud_id")] public string SolicitudId { get; set; }
[JsonPropertyName("total")] public string Total { get; set; }
[JsonPropertyName("solicitud_id")] public int SolicitudId { get; set; }
// [JsonPropertyName("total")] public int Total { get; set; }
[JsonPropertyName(("detalle_pedido"))] public List<CrearDetallePedido> DetallePedido { get; set; }
}

public class Pedido
public class Pedidos
{
[JsonPropertyName("pedido_id")] public int PedidoId { get; set; }

Expand All @@ -44,7 +47,7 @@ public class Pedido
[JsonPropertyName("usuario_id")] public string UsuarioId { get; set; }
public string Mostrar_Pedido { get; set; }

public Pedido(int pedidoId, object ofertaSubastaId, DateTime fechaPedido, int estadoPedidoId,
public Pedidos(int pedidoId, object ofertaSubastaId, DateTime fechaPedido, int estadoPedidoId,
string estadoPedido, int total, int solicitudId, DateTime fechaSolicitud, string direccion, object nota,
string usuarioId)
{
Expand All @@ -65,6 +68,6 @@ public Pedido(int pedidoId, object ofertaSubastaId, DateTime fechaPedido, int es

public class ListaPedidos
{
public List<Pedido> pedidos { get; set; }
public List<Pedidos> pedidos { get; set; }
}
}
95 changes: 75 additions & 20 deletions classLibrary/Data Services/PedidosDataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,33 +138,29 @@ await _httpClient.PostAsJsonAsync($"{_baseAddress}sp_detalle_pedido_populate/",

public async Task<bool> CrearPedido(CrearPedido crearPedido)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// System.Net.ServicePointManager.Expect100Continue = false;
Pedido pedido = new();
pedido.pedido = crearPedido;
try
{
CrearPedido creacion = new CrearPedido();
creacion = crearPedido;

object json = new { in_objeto_json = JsonSerializer.Serialize(creacion) };
string jsonSolicitud =
JsonSerializer.Serialize<object>(json, _jsonSerializerOptions);

// string jsonSolicitud = JsonConvert.SerializeObject(json);

// jsonSolicitud = jsonSolicitud.Replace("\"", "\\\"");

StringContent content = new StringContent(jsonSolicitud, Encoding.UTF8, "text/plain");
var x = content.ReadAsStringAsync();

string in_objeto_json = "{'in_objeto_json': '".Replace("'", "\"");
string jsonSerializado = JsonSerializer.Serialize(pedido).Replace("\"", "\\\"");
// string jsonSerializado =
// "{\"pedido\":{\"solicitud_id\":172,\"detalle_pedido\":[{\"producto_id\":4,\"calidad\":5,\"productor_id\":\"1-1\",\"cantidad\":111,\"precio\":5000}]}}"
// .Replace("\"", "\\\"");
string final = in_objeto_json + jsonSerializado;
string ultimaLlave = "'}".Replace("'", "\"");
final += ultimaLlave;
StringContent content = new StringContent(final, Encoding.Default, "application/json");
var x = await content.ReadAsStringAsync();
HttpResponseMessage response =
await _httpClient.PostAsync($"{_baseAddress}sp_insert_pedido_y_detalle/", content);
var y = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Debug.WriteLine("Pedido ingresado!");
// var responseContent = response.Content.ReadAsStringAsync().Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
ResponseGeneral APIResponse =
JsonSerializer.Deserialize<ResponseGeneral>(response.Content.ReadAsStringAsync().Result,
_jsonSerializerOptions);
JsonSerializer.Deserialize<ResponseGeneral>(responseContent, _jsonSerializerOptions);
if (APIResponse.Glosa != null || APIResponse is null)
{
return false;
Expand All @@ -187,4 +183,63 @@ public async Task<bool> CrearPedido(CrearPedido crearPedido)
return false;
}
}
}
}
// public async Task<bool> CrearPedido(CrearPedido crearPedido)
// {
// // System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// // System.Net.ServicePointManager.Expect100Continue = false;
// Pedido pedido = new();
// pedido.pedido = crearPedido;
// try
// {
// object pedidoParams = new { in_objeto_json = JsonConvert.SerializeObject(pedido) };
// HttpResponseMessage response = await _httpClient.PostAsJsonAsync($"{_baseAddress}sp_insert_pedido_y_detalle/", pedidoParams);
// // string jsonSerializado = JsonSerializer.Serialize(pedido).Replace("\"", "\\\"");
// //
// // string in_objeto_json = "{'in_objeto_json': '".Replace("'", "\"");
// // // string jsonSerializado =
// // // "{\"pedido\":{\"solicitud_id\":172,\"detalle_pedido\":[{\"producto_id\":4,\"calidad\":5,\"productor_id\":\"1-1\",\"cantidad\":111,\"precio\":5000}]}}"
// // // .Replace("\"", "\\\"");
// // string final = in_objeto_json + jsonSerializado;
// // string ultimaLlave = "'}".Replace("'", "\"");
// //
// // final+=ultimaLlave;
// // // string jsonSolicitud = JsonConvert.SerializeObject(json);
// //
// //
// // StringContent content = new StringContent(final, Encoding.Default, "text/plain");
// // Debug.WriteLine(content);
// //
// // var x = await content.ReadAsStringAsync();
// // Console.WriteLine(x);
// // HttpResponseMessage response =
// // await _httpClient.PostAsync($"{_baseAddress}sp_insert_pedido_y_detalle/", content);
// var y = response.Content.ReadAsStringAsync().Result;
// if (response.IsSuccessStatusCode)
// {
// Debug.WriteLine("Pedido ingresado!");
// // var responseContent = response.Content.ReadAsStringAsync().Result;
// ResponseGeneral APIResponse =
// JsonSerializer.Deserialize<ResponseGeneral>(response.Content.ReadAsStringAsync().Result,
// _jsonSerializerOptions);
// if (APIResponse.Glosa != null || APIResponse is null)
// {
// return false;
// }
//
// return true;
// }
// else
// {
// var result = response.Content.ReadAsStringAsync().Result;
// Debug.WriteLine($"No fue un status 2XX: {response.StatusCode}");
// return false;
// }
// }
// catch (Exception ex)
// {
// Debug.WriteLine($"Hubo un error {ex.Message}");
// }
//
// return false;
// }
1 change: 1 addition & 0 deletions classLibrary/Data Services/UsuariosDataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public async Task<Usuario> Login(string rut, string pass)
try
{
HttpResponseMessage response = await _httpClient.PostAsJsonAsync($"{_baseAddress}sp_login/", userParams);
var x = response.Content.ReadAsStringAsync().Result;

if (response.IsSuccessStatusCode)
{
Expand Down

0 comments on commit fb8a70d

Please sign in to comment.