Visual Basic - Filtrar Fecha

Life is soft - evento anual de software empresarial
 
Vista:

Filtrar Fecha

Publicado por Havok (1 intervención) el 01/09/2022 17:44:44
Buenos días estoy empezando a programar en visual Basic y actualmente me dieron una oportunidad de trabajo y no tuve mucho tiempo de aprender del anterior programador, sin embargo poco a poco voy aprendiendo, y mi jefe me pidió adelanto con "Filtro de fecha el cual me muestre la fecha en el reporte de ventas, pero no entiendo mucho el código del antiguo programador ya que trabaja con el método MVC y es mi primera vez con este metodo. les dejare el codigo donde manda a llamar el reporte de ventas.

Este es el controlador tiene comentariado algunas instrucción:
<Authorize(Roles:="Generar reporte de venta, Administrador")>
Function ReporteDeVentas() As ActionResult
'VISTA QUE TIENE LA LISTA DE CODIGOS Y PRODUCTOS, PARA REALIZAR EL REPORTE
ViewBag.CodigoProducto = (From m In _db.Producto
Select m.CodigoSACOL, m.Nombre).ToArray()
Return View()
End Function
<HttpPost>
Function GenerarReporte(codigo As String) As JsonResult
Try
'ESTA FUNCION GENERA UN REPORTE DE PRODUCTO VENDIDO EN CADA FACTURA
If String.IsNullOrEmpty(codigo) Then 'VALIDAMOS SI EL CODIGO ESTA VACIO
Return New JsonResult With {.Data = "null", .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
End If
Dim ListaFacturas = (From m In _db.Factura
Select m).ToList() 'LLAMAMOS LA LISTA DE FACTURAS GUARDADAS EN LA BASE DE DATOS
If IsNothing(ListaFacturas) Then 'SI NO HAY NINGUNA, VALIDAMOS
Return New JsonResult With {.Data = "null", .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
End If
Dim ProductosDelReporte As New JArray 'LISTA VACIA DE PRODUCTOS, DONDE AÑADIREMOS LOS PRODUCTOS ENCONTRADOS, SEGUN EL CODIGO
For Each factura As Factura In ListaFacturas 'POR CADA FACTURA DE LA LISTA DE FACTURAS
Dim DetalleDeFactura As JArray = JArray.Parse(factura.detalle) 'SACAMOS EL DETALLE DE FACTURA
Dim ProductoEncontrado = (From m In DetalleDeFactura 'ESTA ES UNA QUERY, DONDE BUSCAMOS EN EL DETALLE DE LA FACTURA, LOS PRODUCTOS CON EL MISMO CODIGO. ESTO PARA EVITARNOS OTRO FOR (OJO, TAMBIEN PODEMOS HACER QUERYS A LOS ARRAYS)
Select m).Where(Function(m) m("codigo") = codigo).ToArray()

For Each item In ProductoEncontrado 'POR CADA PRODUCTO ENCONTRADO,
'LE AÑADIMOS EL CODIGO DE FACTURA Y EL ID DE LA MISMA...
' SE VERIA MAS O MENOS ASI:
'[
'{
' factura: 15002,
' id: 1,
' codigo: D2G0-0001,
' producto: Jelisan,
' cantidad: 200,
' ...
'Demas items como precio unitario, impuestos, sub-total, total, etc
'}
']
item.Item("codigo").Parent.AddBeforeSelf(New JProperty("factura", factura.codigoFactura))
item.Item("codigo").Parent.AddBeforeSelf(New JProperty("id", factura.IdFactura))
Next
ProductosDelReporte.Add(ProductoEncontrado) ' se añade el producto encontrado a la lista de productos de reporte
Next
If ProductosDelReporte.Count < 1 Then
'SI LA LISTA DE PRODUCTOS ES MENOR QUE UNO, SE DEVUELVE empty, PUES LA LISTA ESTARIA VACIA
Return New JsonResult With {.Data = "empty", .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
End If
'EN CASO DE QUE NO ESTUVIESE VACIA, SE DEVUELVE LA LISTA COMO UN ARRAY DE JSON
Dim ReporteJsonString = JsonConvert.SerializeObject(ProductosDelReporte, Formatting.Indented)
Return New JsonResult With {.Data = ReporteJsonString, .JsonRequestBehavior = JsonRequestBehavior.AllowGet}

Catch ex As Exception
'EN CASO DE EXCEPTION NO CONTROLADA
Return New JsonResult With {.Data = ex.Message, .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
End Try
End Function

esta es la vista:
@Code
ViewData("Title") = "Reporte de ventas"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h2>Reportes de ventas</h2>

<div class="row container">
<div class="col">
<label>Ingrese código o nombre de producto</label>
</div>
<div class="col">
<input class="form-control" list="productos" id="BuscadorProducto" />
<datalist id="productos">
<select>
@For Each producto In ViewBag.CodigoProducto
@<option value="@producto.codigoSACOL">@producto.Nombre</option>
Next
</select>
</datalist>
</div>
<div class="col">
<Button Class="btn btn-outline-primary" id="GenerarReporte">Generar reporte</Button>
<button class="btn btn-outline-secondary" id="LimpiarReporte">Limpiar tabla</button>
</div>
</div>
<div class="container">
<table id="Reporte" class="table">
<thead>
<tr>
<td scope="col">Factura</td>
@*<td scope="col">Fecha</td>*@
<td scope="col">Código de producto</td>
<td scope="col">Nombre de producto</td>
<td scope="col">Número de lote</td>
<td scope="col">Cantidad</td>
<td scope="col">Precio unitario</td>
<td scope="col">Subtotal</td>
<td scope="col">Impuestos</td>
<td scope="col">Total</td>
</tr>
</thead>
<tbody id="DetalleReporte">
</tbody>
<tfoot>
<tr>
<td colspan="3" id="totalTitle">
Total vendido: <Span id="total"></Span>
</td>
</tr>
</tfoot>
</table>
</div>
@section scripts
<script src="~/Scripts/Reporte.js"></script>
End section
</body>
</html>
Este es el JS
/*este script maneja la parte html del reporte,
una vez hecho click en el boton 'generar reporte',
se mandan a filtrar los datos en el server y se devuelven al frontend
para que puedan ser añadidos a la tabla...*/
$('#GenerarReporte').click(function (e) {
e.preventDefault();
//se captura el codigo del producto y se encapsula para ser enviado
codigo_de_producto = $('#BuscadorProducto').val()
const datos = {
codigo: codigo_de_producto
}
//llamada ajax donde mandamos los datos al servidor para ser procesados,... El controlador es FacturaController
$.ajax({
type: 'POST',
url: 'GenerarReporte',
content: 'application/json; charset=utf-8',
data: datos,
success: function (data) {
if (data == "null") {
swal({
type: 'error',
title: 'Error en la ejecución del reporte',
text: 'Revise que se han generado facturas o bien, el código del producto es correcto'
})
return; //mensaje de error o de datos no encontrados
}
if (data == 'empty') {
swal({
type: 'info',
title: '¡Reporte terminado!',
text: 'No se encontraron productos dentro de las facturas'
})
return;
}
try { //en caso de que la respuesta sea full exitosa...
console.log(data)
//convertimos la string en json y capturamos el detalle de la tabla
const data_as_json = JSON.parse(data);
const body_reporte = document.querySelector('#DetalleReporte');
body_reporte.innerHTML = "";
var totalReporte = 0; //variable de total vendido
for (x in data_as_json) {
//recorremos el array y añadimos las filas encontradas
body_reporte.innerHTML += `
<tr>
<td><a href="/Factura/VerDetalles/${data_as_json[x].id}">${data_as_json[x].factura}</a></td>
<td>${data_as_json[x].codigo}</td>
<td>${data_as_json[x].producto}</td>
<td>${data_as_json[x].lote}</td>
<td>${data_as_json[x].cantidad}</td>
<td>${data_as_json[x].precUnit}</td>
<td>${data_as_json[x].subTotal}</td>
<td>${data_as_json[x].impuestos}</td>
<td>${data_as_json[x].total}</td>
</tr>
`;
var totalstring = String(data_as_json[x].total);
//recogemos el valor del jarray que se llama total
//y lo vamos sumando en totalReporte
totalReporte += Number(totalstring.replace("$ ",""))
}
//lo imprimimos en el DOM
document.querySelector('#total').innerHTML = Number(totalReporte).toFixed(2);
}
catch (ex) {
swal({ //excepciones en el proceso del texto
type: 'error',
title: 'Error en el procedimiento',
text: `${ex.message}`
});
console.log(data)
return;
}
},
error: function (data) {
swal({ //excepciones del server
type: 'error',
title: '¡Error en el servidor!',
text: `Nombre del error: ${data.responseText}`
})
}
})
})

$('#LimpiarReporte').click(function (e) {
e.preventDefault();
document.querySelector('#DetalleReporte').innerHTML = ""
document.querySelector('#total').innerHTML = ""
document.querySelector('#BuscadorProducto').value = ""
return;
}) //boton para limpiar la tabla y el campo del formulario de reporte

Si me ayudan estaré muy agradecido
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder