Files
SIG/Inventarios/AjustesSeccionAlmacen.aspx.vb

623 lines
34 KiB
VB.net

Imports System.Data
Imports Extensiones
Imports GemBox.Spreadsheet
Partial Class Inventarios_AjustesSeccionAlmacen
Inherits ClsPaginas
Private Sub Inventarios_AjustesSeccionAlmacen_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CargaCombos()
End If
End Sub
Private Sub CargaCombos()
Dim DtAlmacenes As DataTable = GlobalDTAlmacenUsuarios(UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, CveTipoAlmacen:=-1).FiltraParametros("CveTipoAlmacen in (1,2,12,14,16, 26)")
DdlAlmacen.DataSource = DtAlmacenes
DdlAlmacen.DataBind()
DdlAlmacenExcel.DataSource = DtAlmacenes
DdlAlmacenExcel.DataBind()
DdlClasificaciones.DataSource = GlobalDTClasificaciones(UsuarioActual.CveEmpresa)
DdlClasificaciones.DataBind()
DdlClasificaciones.Items.Insert(0, New ListItem("Todos", "-1"))
If Not String.IsNullOrWhiteSpace(UsuarioActual.Empresa.Funcionalidad(147)) Then GvD.Columns(4).HeaderText = UsuarioActual.Empresa.Funcionalidad(147) : GvD.Columns(10).HeaderText = String.Format("Nueva {0}", UsuarioActual.Empresa.Funcionalidad(147))
End Sub
Private Sub BtnConsultar_Click(sender As Object, e As EventArgs) Handles BtnConsultar.Click
CargaDatos()
End Sub
Private Sub CargaDatos()
Dim ObjInv As New ClsInventarios
Dim CvePS As String = If(DdlPS.SelectedValue = "", "-1", DdlPS.SelectedValue)
Dim FolioAux As String = If(TxtFolioFiltro.Text.Length > 0, TxtFolioFiltro.Text, "-1")
If ObjInv.GetMovimientosDetalleSeccionesAlmacen(DdlAlmacen.SelectedValue.ToEntero, DdlClasificaciones.SelectedValue.ToEntero, UsuarioActual.CveEmpresa, FolioAux, CvePS.ToEntero) Then
GvD.DataSource = ObjInv.DtResultados
If ObjInv.DtResultados.FiltraParametros("Serie <> '' ").Rows.Count = 0 Then GvD.columns(2).visible = False
If ObjInv.DtResultados.FiltraParametros("Lote <> ''").Rows.Count = 0 Then GvD.columns(3).visible = False
If ObjInv.DtResultados.FiltraParametros("FechaCaducidad IS NOT NULL ").Rows.Count = 0 Then GvD.columns(4).visible = False
If ObjInv.DtResultados.FiltraParametros("CveSeccionAlmacen > 0").Rows.Count = 0 Then GvD.columns(5).visible = False
End If
ObjInv.Dispose()
GvD.DataBind()
UppD.Update()
End Sub
Private Sub GvD_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvD.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
CargaSeccionesAlmacen(e.Row.FCDropDownList("DDlS"), DdlAlmacen.SelectedValue.ToEntero, e.Row.DBCampo("CvePS").ToEntero, UsuarioActual.CveEmpresa)
e.Row.FCDropDownList("DDlS").DataSource = GlobalDTSeccionAlmacen(UsuarioActual.CveEmpresa, DdlAlmacen.SelectedValue.ToEntero)
e.Row.FCDropDownList("DDlS").DataBind()
Dim ExistenciasAux As Decimal = e.Row.DataKey("Existencia").ToDecimal
e.Row.FCRangeValidator("RVR").Enabled = ExistenciasAux > 0
If ExistenciasAux > 0 Then
e.Row.FCRangeValidator("RVR").MaximumValue = ExistenciasAux.ToString("N3")
Else
e.Row.FCCheckBox("Chk").Visible = False
e.Row.FCRangeValidator("RVR").MaximumValue = 0
End If
End If
End Sub
Private Sub BtnCambiarSeccion_Click(sender As Object, e As EventArgs) Handles BtnCambiarSeccion.Click
Dim ObjInventario As New ClsInventarios
Dim ObjPS As New ClsProductosServicios(ObjInventario.IniciaTransacSQL)
Dim ObjConta As New ClsContabilidad(ObjInventario.IniciaTransacSQL)
Dim Dtt As DataTable = Nothing
Dim CveMovimientoEntrada As Integer = 0
Dim Folio = 0
Dim ErrorMovInv As Boolean = False
Dim TextoError = ""
Dim Contador As Integer = 0
Dim CveAlmacen As Integer = DdlAlmacen.SelectedValue.ToEntero
Dim Fecha As Date = DateTime.Now
'AGREGAMOS LA ENTRADA
Dim CveMovimientoSalida As Integer = ObjInventario.AddMovimiento(CveAlmacen, 3, 1, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1,
Observaciones:="", Modulo:="ASA/G1")
Folio = ObjInventario.Folio
If CveMovimientoSalida <= 0 Then
TextoError = "No se pudo generar el movimiento de salida correctamente"
ErrorMovInv = True
Else
Dim CveMovimientoDetalleEntrada As Integer = 0
Dim Cont As Integer = 0
Dim Lista As New Hashtable
Dim ListaCaducidad As New Hashtable
Dim ListaLote As New Hashtable
Dim Cantidad As Decimal = 0
For Each gvr As GridViewRow In GvD.Rows
Dim FechaCaducidadOriginal As String = gvr.DataKey("FechaCaducidad")
Dim FechaCaducidadNueva As String = gvr.FCTextBox("TxtFechaCadNueva").Text
Dim LoteOriginal As String = gvr.DataKey("Lote")
Dim LoteNuevo As String = gvr.FCTextBox("TxtLote").Text
'que este seleccionado y que tenga diferente seccion
Dim Modificar As Boolean = False
If gvr.FCCheckBox("Chk").Checked AndAlso gvr.FCDropDownList("DDlS").SelectedValue.ToEntero <> gvr.DataKey("CveSeccionAlmacen").ToEntero Then
If gvr.DataKey("CveSeccionAlmacen").ToEntero > 0 Then
ObjPS.UpdateAplicaSeccionAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, True)
Else
ObjPS.UpdateAplicaSeccionAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, False)
End If
If Not Lista.ContainsKey(gvr.DataKey("CvePS").ToEntero) Then Lista.Add(gvr.DataKey("CvePS").ToEntero, gvr.FCDropDownList("DDlS").SelectedValue.ToEntero) 'guardo que dato le corresponde
Modificar = True
End If
If gvr.FCCheckBox("ChkEditCaducidad").Checked And FechaCaducidadNueva.Length > 0 And FechaCaducidadNueva <> FechaCaducidadOriginal Then
If Not ListaCaducidad.ContainsKey(gvr.DataKey("CvePS").ToEntero) Then ListaCaducidad.Add(gvr.DataKey("CvePS").ToEntero, FechaCaducidadNueva) 'guardo que dato le corresponde
Modificar = True
If FechaCaducidadOriginal = "" Then
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, False, False)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, True, True)
End If
End If
If gvr.FCCheckBox("ChkLote").Checked And LoteNuevo.Length > 0 And LoteNuevo <> LoteOriginal Then
If Not ListaLote.ContainsKey(gvr.DataKey("CvePS").ToEntero) Then ListaLote.Add(gvr.DataKey("CvePS").ToEntero, LoteNuevo) 'guardo que dato le corresponde
Modificar = True
If LoteOriginal = "" Then
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, False, False)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(gvr.DataKey("CvePS").ToEntero, UsuarioActual.CveEmpresa, True, True)
End If
End If
If Modificar Then
Cantidad = gvr.FCTextBox("TxtCantidad").Text.ToDecimal()
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalida, Cantidad, gvr.DataKey("CveUM").ToEntero, gvr.DataKey("CvePS").ToEntero, 0, -1, CveSeccionAlmacen:=gvr.DataKey("CveSeccionAlmacen").ToEntero, Serie:=gvr.DataKey("Serie"), Lote:=gvr.DataKey("Lote"), FechaCaducidad:=gvr.DataKey("FechaCaducidad").ToDate) Then
ErrorMovInv = True
TextoError = "Ocurrió un error al guardar los movimientos de salida"
Exit For
End If
Contador += 1
End If
Next
If Not ErrorMovInv AndAlso Contador > 0 Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) Then
Dim resultado As DataTable = ObjInventario.DtResultados
CveMovimientoEntrada = ObjInventario.AddMovimiento(CveAlmacen, 2, 1, Fecha, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, Observaciones:="", CveMovimientoRelacionado:=CveMovimientoSalida, Modulo:="ASA/G1")
Dim ind As Integer = 0
For Each Row As DataRow In resultado.Rows
Dim CvePS = Row("CvePS").ToString().ToEntero()
Cantidad = Row("Cantidad").ToString.ToDecimal()
Dim PU As Decimal = Row("PUOriginal").ToString().ToDecimal()
Dim CveUM As Integer = Row("CveUM").ToString().ToEntero()
Dim CveSeccionAlmacen As Integer = Lista(Row("CvePS").ToString().ToEntero()) 'GvD.Rows(ind).FCDropDownList("DDlS").SelectedValue.ToEntero ' IfNull(Row("CveSeccionAlmacen"), "-1").ToString().ToEntero()
Dim CostoIndirecto As Decimal = Row("CostoIndirecto").ToString().ToDecimal()
Dim Serie As String = Row("Serie").ToString()
Dim Lote As String = Row("Lote").ToString()
Dim FechaCaducidad As Date = MinFecha
If ListaCaducidad.ContainsKey(CvePS) Then
FechaCaducidad = ListaCaducidad(CvePS).ToString.ToDate
Else
FechaCaducidad = IfNull(Row("FechaCaducidad"), MinFecha).ToString.ToDate
End If
If ListaLote.ContainsKey(CvePS) Then
Lote = ListaLote(CvePS).ToString
Else
Lote = Row("Lote").ToString()
End If
'actualizamos el PS, para que tenga el aplica seccion
If CveSeccionAlmacen > 0 Then
If Lista.ContainsKey(CvePS) Then
ObjPS.UpdateAplicaSeccionAlmacen(Row("CvePS").ToString().ToEntero(), UsuarioActual.CveEmpresa, True)
End If
If Not ObjInventario.AddProductosServiciosAlmacenSeccion(CvePS, CveAlmacen, CveSeccionAlmacen) Then
ErrorMovInv = True
End If
End If
If Lote = "" Then
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(Row("CvePS").ToString().ToEntero(), UsuarioActual.CveEmpresa, False, False)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(Row("CvePS").ToString().ToEntero(), UsuarioActual.CveEmpresa, True, True)
End If
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, Cantidad, CveUM, CvePS, PU, -1, CostoIndirecto:=CostoIndirecto, CveSeccionAlmacen:=CveSeccionAlmacen, Lote:=Lote, Serie:=Serie, FechaCaducidad:=FechaCaducidad, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
ErrorMovInv = True
Exit For
End If
ind += 1
Next
'inserto la prepoliza
If Not ErrorMovInv AndAlso CveMovimientoEntrada > 0 AndAlso CveMovimientoSalida > 0 Then
Dim Concepto As String = "Ajuste Sección"
Dim IdCtaContableOrigen As Integer = 0
Dim CvePrePoliza As Integer = ObjConta.AddPrePolizas("Inventario/AjusteAlmacen", 53, 0, 0, 1, Fecha, Concepto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
Dim importe As Decimal = resultado.SUMD("Total").RoundSQL
Dim contabilizable As Boolean = False
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importe, Concepto, 68, Concepto, Fecha, IdCtaContableOrigen, -1, CveMovimientoAlmacen:=CveMovimientoSalida, Contabilizable:=contabilizable, ImporteMX:=importe) Then
ErrorMovInv = True
End If
If Not ErrorMovInv AndAlso Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importe, Concepto, 68, Concepto, Fecha, IdCtaContableOrigen, -1, CveMovimientoAlmacen:=CveMovimientoEntrada, Contabilizable:=contabilizable, ImporteMX:=importe) Then
ErrorMovInv = True
End If
End If
resultado.Dispose()
Else
TextoError = "No se pudo registrar el movimiento"
ErrorMovInv = True
End If
End If
Lista = Nothing
End If
If Not ErrorMovInv Then
If Contador > 0 Then
ObjInventario.Commit()
GlobalDTInvPSSeccionesAlmacen(UsuarioActual.CveEmpresa, -1, -1) = Nothing
CargaDatos()
Alert("El Movimiento quede registrado correctamente", TipoMensaje.MsgInformacion)
Else
ObjInventario.RollBack()
Alert("No se especificaron productos", TipoMensaje.MsgError)
End If
Else
ObjInventario.RollBack()
Alert("Ocurrio un error al registrar el movimiento", TipoMensaje.MsgError)
End If
ObjInventario.Dispose()
ObjConta.Dispose()
ObjPS.Dispose()
End Sub
Protected Sub BtnDescargar_Click(sender As Object, e As EventArgs) Handles BtnDescargar.Click
If GvD.Rows.Count > 0 Then
DescargarExcel()
Else
Dim Directorio As String = ModExtensiones.DirectorioBaseEmpresas & "Empresas\Grales\Formatos\FormatoAjusteSecCad.xlsx"
Dim Archivo As New IO.FileInfo(Directorio)
If Archivo.Exists Then
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AddHeader("Content-Disposition", "attachment; filename=" + Archivo.Name)
Response.AddHeader("Content-Length", Archivo.Length.ToString())
Response.ContentType = "text/plain"
Response.Flush()
Response.TransmitFile(Archivo.FullName)
Response.End()
End If
End If
End Sub
Private Sub DescargarExcel()
Dim DtExcel As DataTable = (From row As GridViewRow In GvD.Rows
Where row.RowType = DataControlRowType.DataRow
Select New With
{
.Cantidad = row.DataKey("Existencia"),
.Codigo = row.DataKey("Codigo"),
.PS = row.DataKey("PS"),
.SeccionAlmacen = row.DataKey("SeccionAlmacen"),
.Serie = row.DataKey("Serie"),
.Lote = row.DataKey("Lote"),
.FechaCaducidad = row.DataKey("FechaCaducidad")
}).QueryToDataTable(True)
If DtExcel.Rows.Count < 1 Then
Alert("No hay resultados en la busqueda.", TipoMensaje.MsgAdvertencia)
Exit Sub
End If
DtExcel.TableName = "Ajustes"
DtExcel.Columns("Codigo").ColumnName = "Código"
DtExcel.Columns("PS").ColumnName = "Producto/Servicio"
SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet)
Dim FileExcel As New ExcelFile()
Dim worksheet = FileExcel.Worksheets.Add(DtExcel.TableName)
worksheet.InsertDataTable(DtExcel, New InsertDataTableOptions() With
{
.ColumnHeaders = True,
.StartRow = 0,
.StartColumn = 0
})
worksheet.Rows(0).Style.FillPattern.SetPattern(FillPatternStyle.Solid, SpreadsheetColor.FromArgb(75, 119, 190), SpreadsheetColor.FromArgb(255, 255, 255))
worksheet.Rows(0).Style.Font.Color = SpreadsheetColor.FromArgb(255, 255, 255)
Dim columnCount = worksheet.CalculateMaxUsedColumns()
For i = 0 To columnCount
worksheet.Columns(i).AutoFit(1, worksheet.Rows(0), worksheet.Rows(worksheet.Rows.Count - 1))
Next
FileExcel.Save(Response, "FormatoAjusteSecCad.xlsx", SaveOptions.XlsxDefault)
End Sub
Protected Sub BtnCargaExcel_Click(sender As Object, e As EventArgs) Handles BtnCargaExcel.Click
If TxtExcel.getfiles().Archivos.Count > 0 Then
Dim file As Archivo = TxtExcel.getfiles().Archivos(0)
Dim Directorio As String = AppDomain.CurrentDomain.BaseDirectory & file.patch
Dim Tipo As String = If(file.Extencion.Contiene("xlsx", "xlsx", "xlsm", "xlsb"), "EXCEL", "")
If Tipo = "EXCEL" Then
Dim CveAlmacen As Integer = DdlAlmacenExcel.SelectedValue.ToEntero()
Dim CveSubProyecto As Integer = GlobalDTAlmacen(UsuarioActual.CveEmpresa).FiltroPrimeroValor("CveSubProyecto", $"CveAlmacen={CveAlmacen}")
CargarArchivo(Directorio, file.filename, CveAlmacen, CveSubProyecto)
Else
Alert("El archivo no es de tipo excel", TipoMensaje.MsgAdvertencia)
End If
Else
Alert("No existe el archivo. Favor de subir un archivo excel a la plataforma.", TipoMensaje.MsgError)
End If
End Sub
Private Sub CargarArchivo(Ruta As String, FileName As String, CveAlmacen As Integer, CveSubProyecto As Integer)
Dim DtExcel As DataTable = ReadExcelFile(Ruta + FileName, True)
Dim ErrorArchivo = False
If Not ErrorArchivo AndAlso DtExcel IsNot Nothing Then
If Not DtExcel.Columns(0).ColumnName = "Cantidad" Then
Alert("El nombre de la primera columna debe ser 'Código'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(1).ColumnName = "Código" Then
Alert("El nombre de la segunda columna debe ser 'Código'.Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(2).ColumnName = "Producto/Servicio" Then
Alert("El nombre de la tercera columna debe ser 'Producto/Servicio'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(3).ColumnName = "SeccionAlmacen" Then
Alert("El nombre de la cuarta columna debe ser 'SeccionAlmacen'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(4).ColumnName = "Serie" Then
Alert("El nombre de la quinta columna debe ser 'Serie'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(5).ColumnName = "Lote" Then
Alert("El nombre de la sexta columna debe ser 'Lote'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
If Not DtExcel.Columns(6).ColumnName = "FechaCaducidad" Then
Alert("El nombre de la séptima columna debe ser 'FechaCaducidad'. Favor de corregirlo", TipoMensaje.MsgError)
Exit Sub
End If
DtExcel.TableName = "Datos"
If Not ErrorArchivo Then
Dim ErrorMovInv As Boolean = False
Dim CodigosNoEncontrados As New StringBuilder()
Dim SeccionesNoEncontradas As New StringBuilder()
Dim ExistenciasNoEncontradas As New StringBuilder()
Dim NumAgregados As Integer = 0
Dim ObjInventario As New ClsInventarios()
Dim ObjPS As New ClsProductosServicios(ObjInventario.IniciaTransacSQL())
Dim ObjConta As New ClsContabilidad(ObjInventario.IniciaTransacSQL)
Try
Dim DtExistenciasSecciones As DataTable = Nothing
If ObjInventario.GetMovimientosDetalleSeccionesAlmacen(DdlAlmacenExcel.SelectedValue.ToEntero, -1, UsuarioActual.CveEmpresa, "-1", -1) Then
DtExistenciasSecciones = ObjInventario.DtResultados.Copy()
End If
'SALIDA ALMACÉN
Dim CveMovimientoSalida = ObjInventario.AddMovimiento(CveAlmacen, 3, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, Observaciones:="", TipoCambio:=-1,
MovimientoFijo:=False, Modulo:="ASA/SA")
'ENTRADA ALMACÉN
Dim CveMovimientoEntrada = ObjInventario.AddMovimiento(CveAlmacen, 2, 1, Now, -1, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa, -1, -1, -1, -1, Observaciones:="", TipoCambio:=-1,
MovimientoFijo:=False, Modulo:="ASA/EA", CveMovimientoRelacionado:=CveMovimientoSalida)
Dim dtSecciones As DataTable = GlobalDTSeccionAlmacen(UsuarioActual.CveEmpresa, CveAlmacen)
dtSecciones.CaseSensitive = False
Dim resultado As DataTable = Nothing
DtExcel = DtExcel.FiltraParametros("Código <> ''")
For Each RowExcel As DataRow In DtExcel.Rows
Dim Codigo As String = RowExcel("Código").ToString.Trim()
'Dim PS As String = RowExcel("Producto/Servicio").ToString().Trim()
Dim DrPS As DataRow = GlobalDTPSSimplificado(UsuarioActual.CveEmpresa).FiltroPrimero($"Codigo='{Codigo}'")
If Codigo <> "" AndAlso DrPS IsNot Nothing Then
If Not ErrorMovInv Then
Dim CantidadEntrada As Decimal = RowExcel("Cantidad").ToString().ToDecimal()
Dim CvePS As Integer = DrPS("CvePS").ToString().ToEntero()
Dim CveUM As Integer = DrPS("CveUnidadMedida").ToString().ToEntero()
Dim SeccionAlmacen As String = RowExcel("SeccionAlmacen").ToString.Trim
Dim CveSeccionAlmacen As Integer = -1
Dim DrSeccion As DataRow = dtSecciones.FiltroPrimero($"SeccionAlmacen='{SeccionAlmacen}'")
If DrSeccion IsNot Nothing Then
CveSeccionAlmacen = DrSeccion("CveSeccion").ToString().ToEntero()
End If
Dim Serie As String = RowExcel("Serie").ToString().Trim
Dim Lote As String = RowExcel("Lote").ToString()
Dim FechaCaducidad As Date = IfNull(RowExcel("FechaCaducidad"), MinFecha).ToString.ToDate
Dim RowExistencia As DataRow = DtExistenciasSecciones.FiltroPrimero($"CvePS={CvePS} and ISNULL(Serie,'') = '{Serie}'", Orderby:="Serie,Lote,FechaCaducidad")
If RowExistencia IsNot Nothing Then
Dim CveSeccionAlmacenSalida As Integer = RowExistencia("CveSeccionAlmacen").ToString().ToEntero()
Dim CantidadSalida As Decimal = RowExcel("Cantidad").ToString().ToDecimal()
Dim SerieSalida As String = RowExistencia("Serie").ToString()
Dim LoteSalida As String = RowExistencia("Lote").ToString()
Dim FechaCaducidadSalida As Date = IfNull(RowExistencia("FechaCaducidad"), MinFecha).ToString.ToDate
Dim PUSalida As Decimal = RowExistencia("PU").ToString()
'condicion para ajustar la seccion y permita hacer los cambios en el trigger
If CveSeccionAlmacenSalida > 0 Then
ErrorMovInv = Not ObjPS.UpdateAplicaSeccionAlmacen(CvePS, UsuarioActual.CveEmpresa, True)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaSeccionAlmacen(CvePS, UsuarioActual.CveEmpresa, False)
End If
If LoteSalida = "" Then
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(CvePS, UsuarioActual.CveEmpresa, False, False)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(CvePS, UsuarioActual.CveEmpresa, True, True)
End If
'GENERA LA SALIDA DE LOS PRODUCTOS QUE VIENEN EN EL EXCEL
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoSalida, CantidadSalida, CveUM, CvePS, PUSalida, CveSeccionAlmacen:=CveSeccionAlmacenSalida, Serie:=SerieSalida, Lote:=LoteSalida, FechaCaducidad:=FechaCaducidadSalida, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
ErrorMovInv = True
Exit For
End If
Dim CveMovimientoDetalleSalida As Integer = ObjInventario.CveMovimientoDetalle
ErrorMovInv = CveMovimientoDetalleSalida <= 0
'GENERA LA ENTRADA DE LOS PRODUCTOS QUE SE DIERON SALIDA
If Not ErrorMovInv Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa, CveMovimientoDetalle:=CveMovimientoDetalleSalida) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then
resultado = ObjInventario.DtResultados
Dim RowEntrada As DataRow = ObjInventario.DtResultados.Rows(0)
Dim CvePSEntrada = RowEntrada("CvePS").ToString().ToEntero()
Dim PUEntrada As Decimal = RowEntrada("PUOriginal").ToString().ToDecimal()
Dim CveUMEntrada As Integer = RowEntrada("CveUM").ToString().ToEntero()
Dim CostoIndirecto As Decimal = RowEntrada("CostoIndirecto").ToString().ToDecimal()
'ACTUALIZAMOS EL PS, PARA QUE TENGA EL APLICA SECCION
If CveSeccionAlmacen > 0 Then
ErrorMovInv = Not ObjPS.UpdateAplicaSeccionAlmacen(CvePS, UsuarioActual.CveEmpresa, True)
If Not ObjInventario.AddProductosServiciosAlmacenSeccion(CvePS, CveAlmacen, CveSeccionAlmacen) Then
ErrorMovInv = True
End If
End If
If Lote = "" Then
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(CvePS, UsuarioActual.CveEmpresa, False, False)
Else
ErrorMovInv = Not ObjPS.UpdateAplicaLoteCaducidadAlmacen(CvePS, UsuarioActual.CveEmpresa, True, True)
End If
If Not ObjInventario.AddMovimientoDetalle(CveMovimientoEntrada, CantidadEntrada, CveUMEntrada, CvePSEntrada, PUEntrada, -1, CostoIndirecto:=CostoIndirecto, CveSeccionAlmacen:=CveSeccionAlmacen, Serie:=Serie, Lote:=Lote, FechaCaducidad:=FechaCaducidad, CveUsuarioModifico:=UsuarioActual.CveUsuario) Then
ErrorMovInv = True
Exit For
End If
Else
ErrorMovInv = True
End If
End If
Else
ErrorMovInv = True
End If
If RowExistencia Is Nothing Then
Dim str As String = ""
If Serie <> "" Then Serie = String.Format(" - Serie:{0} ")
ExistenciasNoEncontradas.AppendFormat("{0} {1}<br/>", Codigo, str)
ErrorMovInv = True
End If
If CveSeccionAlmacen <= 0 And SeccionAlmacen <> "" Then
SeccionesNoEncontradas.AppendFormat("{0},", SeccionAlmacen)
ErrorMovInv = True
End If
End If
Else
ErrorMovInv = True
CodigosNoEncontrados.AppendFormat("{0},", Codigo)
End If
Next
dtSecciones.Dispose()
'inserto la prepoliza
If CveMovimientoEntrada > 0 AndAlso CveMovimientoSalida > 0 Then
If ObjInventario.GetMovimientosDetalle(CveMovimientoSalida, UsuarioActual.CveEmpresa) AndAlso ObjInventario.DtResultados.Rows.Count > 0 Then
resultado = ObjInventario.DtResultados
Dim Concepto As String = "Ajuste Sección"
Dim IdCtaContableOrigen As Integer = 0
Dim CvePrePoliza As Integer = ObjConta.AddPrePolizas("Inventario/AjusteAlmacen", 53, 0, 0, 1, Now, Concepto, UsuarioActual.CveUsuario, UsuarioActual.CveEmpresa)
Dim importe As Decimal = resultado.SUMD("Total").RoundAD
Dim contabilizable As Boolean = False
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, True, importe, Concepto, 68, Concepto, Now, IdCtaContableOrigen, -1, CveMovimientoAlmacen:=CveMovimientoSalida, Contabilizable:=contabilizable, ImporteMX:=importe) Then
ErrorMovInv = True
End If
If Not ObjConta.AddPrePolizasDetalle(CvePrePoliza, False, importe, Concepto, 68, Concepto, Now, IdCtaContableOrigen, -1, CveMovimientoAlmacen:=CveMovimientoEntrada, Contabilizable:=contabilizable, ImporteMX:=importe) Then
ErrorMovInv = True
End If
End If
End If
Catch ex As Exception
ErrorMovInv = True
OnError("Ocurrió un error al agregar el inventario", ex)
End Try
If ErrorMovInv Then
ObjInventario.RollBack()
Dim SbError As New StringBuilder()
SbError.Append("Ocurrió un error al guardar.<br/>")
If CodigosNoEncontrados.Length > 0 Then
SbError.Append("<br/>Los siguientes códigos no fueron encontrados en el sistema.<br/>")
SbError.Append(CodigosNoEncontrados.ToString())
End If
If ExistenciasNoEncontradas.Length > 0 Then
SbError.Append($"<br/>Los siguientes códigos no se encontraron existencias en el almacen: '{DdlAlmacenExcel.SelectedItem.Text}'.<br/>")
SbError.Append(ExistenciasNoEncontradas.ToString())
End If
If SeccionesNoEncontradas.Length > 0 Then
SbError.Append("<br/>Las siguientes secciones de almacen no fueron encontradas en el sistema.<br/>")
SbError.Append(SeccionesNoEncontradas.ToString())
End If
Alert(SbError.ToString(), TipoMensaje.MsgError)
Else
ObjInventario.Commit()
Alert("Se realizó el ajuste de los productos correctamente.")
End If
ObjInventario.Dispose()
ObjPS.Dispose()
End If
Else
Alert("Ocurrió un error al cargar el excel.", TipoMensaje.MsgError)
End If
End Sub
Protected Sub Chk_Click(sender As Object, e As EventArgs)
'Dim row As GridViewRow = (CType((CType(sender, CheckBox)).NamingContainer, GridViewRow))
'Dim ExistenciaBackup As Integer = row.DataKey("Existencia").ToEntero()
'row.FCTextBox("TxtCantidad").Enabled = Not row.FCTextBox("TxtCantidad").Enabled
'If Not row.FCTextBox("TxtCantidad").Enabled Then
' row.FCTextBox("TxtCantidad").Text = ExistenciaBackup
'End If
End Sub
Protected Sub ChkMostrarColumnas(sender As Object, e As EventArgs)
'Mostrar Lote
GvD.Columns(7).Visible = ChkMostrarLote.Checked
GvD.Columns(8).Visible = ChkMostrarLote.Checked
'Mostrar Caducidad
GvD.Columns(9).Visible = ChkMostrarFecha.Checked
GvD.Columns(10).Visible = ChkMostrarFecha.Checked
'Mostrar Sección
GvD.Columns(11).Visible = ChkMostrarSeccion.Checked
GvD.Columns(12).Visible = ChkMostrarSeccion.Checked
CargaDatos()
UppD.Update()
End Sub
End Class