var cfg_products = new Object()
var gis_admin = false


function products_default_config(){
    webix.ajax().get('/config', {'fields': 'main_products'}, {
        error: function(text, data, xhr) {
            msg = 'Error al consultar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            cfg_products['inventario'] = values.chk_llevar_inventario
            cfg_products['predial'] = values.chk_config_cuenta_predial
            cfg_products['codigo_barras'] = values.chk_config_codigo_barras
            cfg_products['con_impuestos'] = values.chk_config_precio_con_impuestos
            cfg_products['default_unit'] = values.default_unidad
            cfg_products['default_tax'] = values.default_tax
            if(cfg_products['inventario']){
                $$('grid_products').showColumn('existencia')
            }
            //~ show('cant_by_packing', values.chk_use_packing)
            show('cmd_show_exists', values.chk_multi_stock)
        }
    })

    webix.ajax().get('/users', {'opt': 'is_admin'}, {
        error: function(text, data, xhr) {
            msg = 'Error al consultar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json()
            gis_admin = values.is_admin
            if(values.is_admin){
                $$('cmd_add_inventory').show()
                //~ $$('cmd_products_add').show()
            }
        }
    })

}


var products_controllers = {
    init: function(){
        $$('cmd_new_product').attachEvent('onItemClick', cmd_new_product_click)
        $$("cmd_edit_product").attachEvent("onItemClick", cmd_edit_product_click)
        $$("cmd_delete_product").attachEvent("onItemClick", cmd_delete_product_click)
        $$("cmd_save_product").attachEvent("onItemClick", cmd_save_product_click)
        $$("cmd_cancel_product").attachEvent("onItemClick", cmd_cancel_product_click)
        $$("cmd_import_products").attachEvent("onItemClick", cmd_import_products_click)
        $$("cmd_add_inventory").attachEvent("onItemClick", cmd_add_inventory_click)
        $$("cmd_products_add").attachEvent("onItemClick", cmd_products_add_click)
        $$('cmd_add_products_from_xml').attachEvent('onItemClick', cmd_add_products_from_xml_click)
        $$('cmd_show_exists').attachEvent('onItemClick', cmd_show_exists_click)
        $$('cmd_save_products_add').attachEvent('onItemClick', cmd_save_products_add_click)
        $$('cmd_close_products_add').attachEvent('onItemClick', cmd_close_products_add_click)
        $$("chk_automatica").attachEvent("onChange", chk_automatica_change)
        $$("valor_unitario").attachEvent("onChange", valor_unitario_change)
        $$('precio_con_impuestos').attachEvent('onChange', precio_con_impuestos_change)
        $$('precio_con_impuestos').attachEvent('onTimedKeyPress', precio_con_impuestos_key_up);
        $$("chk_inventario").attachEvent("onChange", chk_inventario_change)
        $$('grid_products').attachEvent('onItemDblClick', cmd_edit_product_click)
        products_default_config()
    }
}


function configurar_producto(){
    show('cuenta_predial', cfg_products['predial'])
    show('codigo_barras', cfg_products['codigo_barras'])
    show('precio_con_impuestos', cfg_products['con_impuestos'])
    show('chk_inventario', cfg_products['inventario'])
    show('txt_existencia', cfg_products['inventario'])
    show('txt_minimo', cfg_products['inventario'])
}


function get_categorias(){
    webix.ajax().sync().get('/values/categorias', function(text, data){
        var values = data.json()
        $$('categoria').getList().parse(values, 'plainjs')
    })
}


function get_products(){
    var grid = $$('grid_products')
    webix.ajax().get('/products', {}, {
        error: function(text, data, xhr) {
            msg_error('Error al consultar')
        },
        success: function(text, data, xhr) {
            var values = data.json();
            grid.clearAll();
            if (values.ok){
                grid.parse(values.rows, 'json');
                grid.refresh()
            };
        }
    });
}


function cmd_new_product_click(id, e, node){
    get_taxes()
    $$('unidad').getList().load('/values/unidades')
    configurar_producto()
    $$('form_product').setValues({
        id: 0, es_activo_producto: true})
    add_config({'key': 'id_product', 'value': ''})
    get_new_key()
    get_categorias()
    $$('unidad').setValue(cfg_products['default_unit'])
    $$('grid_product_taxes').select(cfg_products['default_tax'])
    $$('grid_products').clearSelection()
    $$("multi_products").setValue("product_new")
}


function cmd_edit_product_click(){
    get_taxes()
    $$('unidad').getList().load('/values/unidades')
    configurar_producto()

    var grid = $$('grid_products')
    var row = grid.getSelectedItem()
    if(row == undefined){
        msg_error('Selecciona un Producto')
        return
    }

    $$('categoria').getList().load('/values/categorias')

    webix.ajax().get('/products', {id: row['id']}, {
        error: function(text, data, xhr) {
            msg_error(text)
        },
        success: function(text, data, xhr){
            var values = data.json()
            $$('form_product').setValues(values.row)
            add_config({'key': 'id_product', 'value': values.row.id})
            for(i = 0; i < values.taxes.length; i++){
                $$('grid_product_taxes').select(values.taxes[i], true)
            }
        }
    })
    $$('multi_products').setValue('product_new')

};


function delete_product(id){
    webix.ajax().del('/products', {id:id}, function(text, xml, xhr){
        var msg = 'Producto eliminado correctamente'
        if(xhr.status == 200){
            $$('grid_products').remove(id)
            msg_ok(msg)
        }else{
            msg = 'No se pudo eliminar'
            msg_error(msg)
        }
    })
}


function cmd_delete_product_click(id, e, node){
    var row = $$('grid_products').getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un Producto')
        return
    }

    var msg = '¿Estás seguro de eliminar el Producto?<BR><BR>'
    msg += '(' + row['clave'] + ') ' + row['descripcion']
    msg += '<BR><BR>ESTA ACCIÓN NO SE PUEDE DESHACER<BR><BR>Se recomienda '
    msg += 'solo desactivar el producto en vez de eliminar'
    webix.confirm({
        title: 'Eliminar Producto',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if (result){
                delete_product(row['id'])
            }
        }
    })
}


function validate_sat_key_product(key, text){
    var result = false
    webix.ajax().sync().get('/values/satkey', {key:key}, function(text, data){
        result = data.json()
    })
    if(text){
        if(result.ok){
            return '<b>' + result.text + '</b>'
        }else{
            return '<b><font color="red">' + result.text + '</font></b>'
        }
    }
    return result.ok
}


function update_grid_products(values){
    var msg = 'Producto agregado correctamente'
    if(values.new){
        $$('form_product').clear()
        $$('grid_products').add(values.row)
    }else{
        msg = 'Producto actualizado correctamente'
        $$("grid_products").updateItem(values.row['id'], values.row)
    }
    $$('grid_products').refresh()
    $$('multi_products').setValue('products_home')
    msg_ok(msg)
}


function cmd_save_product_click(id, e, node){
    var msg = ''
    var form = this.getFormView()

    if(!form.validate()){
        msg_error('Valores inválidos')
        return
    }

    var rows = $$('grid_product_taxes').getSelectedId(true, true)

    var values = form.getValues();

    if(!validate_sat_key_product(values.clave_sat, false)){
        msg_error('La clave SAT no existe')
        return
    }

    if(values.descripcion.length > 1000){
        msg_error('Descripción con ' + values.descripcion.length + 'caracteres, captura solo 1000 caracteres')
        return
    }

    if(values['objeto_impuesto']=='01' && rows.length > 0){
        msg = 'Si Objeto de Impuestos = 01, no debes seleccionar ningún impuesto'
        msg_error(msg)
        return
    }
    if(values['objeto_impuesto']=='02' && rows.length == 0){
        msg = 'Si Objeto de Impuestos = 02, debes de seleccionar al menos un impuesto'
        msg_error(msg)
        return
    }

    values['taxes'] = JSON.stringify(rows)

    webix.ajax().sync().post('products', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                update_grid_products(values)
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function cmd_cancel_product_click(id, e, node){
    $$("multi_products").setValue("products_home")
};


function chk_automatica_change(new_value, old_value){
    var value = Boolean(new_value)
    if (value){
        var value = get_config('id_product')
        if(value){
            $$("clave").setValue(value)
            $$("clave").refresh()
        }else{
            get_new_key()
        }
        $$("clave").config.readonly = true
        $$('form_product').focus('clave_sat')
    } else {
        $$("clave").setValue('')
        $$("clave").config.readonly = false
        $$('form_product').focus('clave')
    }
    $$("clave").refresh()
}


function chk_inventario_change(new_value, old_value){
    var value = Boolean(new_value)
    if(value){
        $$('txt_existencia').enable()
        $$('txt_minimo').enable()
    }else{
        $$('txt_existencia').disable()
        $$('txt_minimo').disable()
        $$('txt_existencia').setValue(0)
        $$('txt_minimo').setValue(0)
    }
}


function get_new_key(){
    webix.ajax().get('/values/newkey', {
        error: function(text, data, xhr) {
            msg_error(text)
        },
        success: function(text, data, xhr) {
            var values = data.json();
            $$("clave").setValue(values.value)
            $$("clave").refresh()
        }
    })
}


function valor_unitario_change(new_value, old_value){
    if(!isFinite(new_value)){
        this.config.value = old_value
        this.refresh()
    }
}


function precio_con_impuestos_change(new_value, old_value){
    if(!isFinite(new_value)){
        this.config.value = old_value
        this.refresh()
    }
}


function calcular_sin_impuestos(value, taxes){
    var vu = $$('valor_unitario')
    var precio = value

    taxes.forEach(function(tax){
        var tasa = 1.00 + tax.tasa.to_float()
        if(tax.tipo == 'T' && tax.name == 'IVA'){
            precio = (value / tasa).round(DECIMALES)
        }
    })
    vu.setValue(precio)
}

function precio_con_impuestos_key_up(){
    var value = this.getValue()

    if(!value){
        return
    }

    var taxes = $$('grid_product_taxes').getSelectedItem(true)
    if (taxes.length == 0){
        msg = 'Selecciona al menos un impuesto'
        msg_error(msg)
        return
    }

    if(!isFinite(value)){
        msg = 'Captura un valor válido'
        msg_error(msg)
        return
    }
    calcular_sin_impuestos(parseFloat(value), taxes)
}


function cmd_import_products_click(){
    win_import_products.init()
    $$('win_import_products').show()
}


function cmd_upload_products_click(){
    var form = $$('form_upload_products')

    var values = form.getValues()

    if(!$$('lst_upload_products').count()){
        $$('win_import_products').close()
        return
    }

    if($$('lst_upload_products').count() > 1){
        msg = 'Selecciona solo un archivo'
        msg_error(msg)
        return
    }

    var template = $$('up_products').files.getItem($$('up_products').files.getFirstId())

    if(template.type.toLowerCase() != 'ods'){
        msg = 'Archivo inválido.\n\nSe requiere un archivo ODS'
        msg_error(msg)
        return
    }

    msg = '¿Estás seguro de importar este archivo?'
    webix.confirm({
        title: 'Importar Productos',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                $$('up_products').send()
            }
        }
    })
}


function up_products_upload_complete(response){
    if(response.status != 'server'){
        msg = 'Ocurrio un error al subir el archivo'
        msg_error(msg)
        return
    }
    msg = 'Archivo subido correctamente.\n\nComenzando importación.'
    msg_ok(msg)
    $$('win_import_products').close()

    webix.ajax().post('/products', {opt: 'import'}, {
        error: function(text, data, xhr) {
            msg = 'Error al importar'
            msg_error(msg)
        },
        success: function(text, data, xhr) {
            var values = data.json();
            if (values.ok){
                get_products()
                webix.alert({
                    title: 'Importación terminada',
                    text: values.msg,
                })
            }else{
                msg_error(values.msg)
            }
        }
    })
}


//~ Add inventory
function cmd_add_inventory_click(id, e, node){
    var row = $$('grid_products').getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un Producto')
        return
    }

    win_add_inventory.init()
    $$('txt_add_id').setValue(row.id)
    $$('txt_add_key').setValue(row.clave)
    $$('txt_add_unit').setValue(row.unidad)
    $$('txt_add_description').setValue(row.descripcion)
    $$('lst_warehouses').getList().load('/warehouse?opt=for_select')
    $$('win_add_inventory').show()
}


//~ Show details inventory
function cmd_show_exists_click(id, e, node){
    var row = $$('grid_products').getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un Producto')
        return
    }
    win_show_exists.init()
    $$('txt_id_product').setValue(row.id)
    $$('grid_warehouse_exists').load('warehouseproduct?opt=by_product&id=' + row.id)

    if(gis_admin){
        $$('lst_warehouse_target').getList().load('/warehouse?opt=for_select')
    }else{
        $$('lbl_title_move').hide()
        $$('txt_cant_to_move').hide()
        $$('lst_warehouse_target').hide()
        $$('cmd_warehouse_move').hide()
    }

    $$('win_show_exists').show()
}


function cmd_warehouse_move_click(id, e, node){
    var id_product = $$('txt_id_product').getValue()
    var row = $$('grid_warehouse_exists').getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un Almacen origen')
        return
    }
    var warehouse_source = row.id
    var cant_to_move = $$('txt_cant_to_move').getValue()
    var warehouse_target = $$('lst_warehouse_target').getValue()

    if(!cant_to_move){
        msg_error('La cantidad no puede ser cero')
        return
    }

    if(cant_to_move > row.exists){
        msg_error('La cantidad a mover no puede ser mayor a la existencia')
        return
    }

    if (warehouse_target == ''){
        msg_error('Selecciona un Almacen destino')
        return
    }

    if (warehouse_source == warehouse_target){
        msg_error('Los almacenes origen y destino deben ser diferentes')
        return
    }

    var values = {
            id_product: id_product,
            cant: cant_to_move,
            source: warehouse_source,
            target: warehouse_target
        }

    msg = '¿Estás seguro de hacer este movimiento?'
    webix.confirm({
        title: 'Movimiento de Almacen',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                _warehouse_movement(values)
            }
        }
    })
}


function _warehouse_movement(args){
    var values = {
        opt: 'warehouse_movement',
        values: args,
    }

    webix.ajax().sync().post('inventoryentries', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                $$('txt_cant_to_move').setValue(0)
                $$('lst_warehouse_target').setValue('')
                $$('grid_warehouse_exists').load('warehouseproduct?opt=by_product&id=' + args.id_product)
                $$('grid_warehouse_exists').clearSelection()
                msg_ok('Movimiento realizado correctamente')
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function cmd_win_show_exists_close_click(id, e, node){
    $$('win_show_exists').close()
}


//~ Add products
function cmd_products_add_click(id, e, node){
    $$("multi_products").setValue("product_add")
    cfg_products['partner_id'] = 0
    cfg_products['partner_rfc'] = ''
}

//~ Close add products
function cmd_close_products_add_click(id, e, node){
    var grid = $$('grid_partner_products')

    $$('multi_invoices').setValue('products_home')
    $$('lbl_partner').setValue('')
    grid.clearAll()
}


function _add_entries_inventory(data){
    var grid = $$('grid_partner_products')
    var values = {
        opt: 'create',
        values: data,
    }

    webix.ajax().sync().post('inventoryentries', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                get_products()
                $$('multi_invoices').setValue('products_home')
                $$('lbl_partner').setValue('')
                grid.clearAll()
            }else{
                msg_error(values.msg)
            }
        }
    })

}

//~ Save add products
function cmd_save_products_add_click(id, e, node){
    var grid = $$('grid_partner_products')
    var count = 0
    var products = []
    var validate_import = false
    var validate_cant = false

    grid.eachRow(function(row){
        var r = grid.getItem(row)
        if(r.select){
            var p = {}
            count += 1
            p.id_product = r.id_product
            p.key = r.key
            p.key_sat = r.key_sat1
            p.description = r.description1
            p.unit = r.unit
            p.unit_value = r.unit_value1
            p.cant = r.cant1
            products.push(p)

            if(p.unit_value < parseFloat(r.unit_value)){
                validate_import = true
            }
            if(p.cant > r.cant){
                validate_cant = true
            }

        }
    })

    if(!count){
        msg = 'Selecciona al menos un registro'
        msg_error(msg)
        return
    }

    if(validate_import){
        msg = 'El Valor Unitario no puede ser menor al Valor Unitario del proveedor'
        msg_error(msg)
        return
    }

    if(validate_cant){
        msg = 'La Cantidad no puede ser mayor a la Cantidad del proveedor'
        msg_error(msg)
        return
    }

    var data = {
        partner: cfg_products['partner'],
        products: products,
    }

    msg = '¿Estás seguro de ingresar estos productos? <br/><br/>\
        Esta acción no se puede deshacer.'
    webix.confirm({
        title: 'Agregar entrada',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                _add_entries_inventory(data)
            }
        }
    })
}

//~ Import from xml
function cmd_add_products_from_xml_click(){
    win_add_products_from_xml.init()
    $$('win_add_products_from_xml').show()
}

//~ Upload XML
function cmd_upload_products_from_xml_click(){
    var form = $$('form_upload_products_from_xml')
    var values = form.getValues()
    var list = $$('lst_up_products_from_xml')
    var upload = $$('up_products_from_xml')

    if(!list.count()){
        $$('win_add_products_from_xml').close()
        return
    }

    if(list.count() > 1){
        msg = 'Selecciona solo un archivo'
        msg_error(msg)
        return
    }

    var template = upload.files.getItem(upload.files.getFirstId())

    if(template.type.toLowerCase() != 'xml'){
        msg = 'Archivo inválido.\n\nSe requiere un archivo XML'
        msg_error(msg)
        return
    }

    msg = '¿Estás seguro de importar este archivo? <br/><br/>\
        Si hay datos previos seran reemplazados.'
    webix.confirm({
        title: 'Importar Productos',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                upload.send()
            }
        }
    })
}


function up_products_from_xml_upload_complete(response){
    if(response.status != 'server'){
        msg = 'Ocurrio un error al subir el archivo'
        msg_error(msg)
        return
    }

    $$('win_add_products_from_xml').close()

    if(response.error){
        msg_error(response.error)
        return
    }

    var grid = $$('grid_partner_products')
    var data = response.data
    cfg_products['partner'] = data.emisor
    //~ cfg_products['xml'] = data.xml

    var html = '<span class="webix_icon fa-user"></span><span class="lbl_partner">'
    html += data.emisor.nombre + ' (' + data.emisor.rfc + ')</span>'
    $$('lbl_partner').setValue(html)

    grid.clearAll()
    grid.parse(data.conceptos, 'json')
    grid.refresh()

}


function get_partner_product(grid, row){
    grid.refresh(row.id)

    var partner_id = cfg_products['partner'].id
    var filters = {
        opt: 'product',
        partner: cfg_products['partner'],
        product_key: row.key,
    }

    if(!partner_id){
        msg = 'El Proveedor no esta dado de alta'
        msg_ok(msg)
        return
    }

    webix.ajax().get('/partnerproducts', filters, {
        error: function(text, data, xhr) {
            msg_error('Ocurrio un error, consulta a soporte técnico.')
        },
        success: function(text, data, xhr){
            var values = data.json()
            if(values.ok){
                row['id_product'] = values.row.id_product
                row['key_sat1'] = values.row.key_sat1
                row['description1'] = values.row.description1
                row['unit_value1'] = values.row.unit_value1
                grid.refresh(row.id)
            }else{
                msg_error(values.msg)
            }
        }
    })

}


function grid_partner_products_select(row_id, state){
    var grid = $$('grid_partner_products')
    var row = grid.getItem(row_id)

    if(state){
        row['key_sat1'] = row.key_sat
        row['description1'] = row.description
        row['cant1'] = row.cant
        row['unit_value1'] = 0.0
        get_partner_product(grid, row)
    }else{
        row['key_sat1'] = ''
        row['description1'] = ''
        row['cant1'] = ''
        grid.refresh(row_id)
    }
}


function cmd_add_inventory_cancel_click(id, e, node){
    $$('win_add_inventory').close()
}


function cmd_add_inventory_save_click(id, e, node){
    var product_id = $$('txt_add_id').getValue()
    //~ var product_key = $$('txt_add_key').getValue()
    var new_cant = $$('txt_new_cant').getValue()
    var warehouse = $$('lst_warehouses').getValue()

    if(new_cant<=0) {
        msg = 'La cantidad no puede ser cero'
        msg_error(msg)
        return
    }

    if($$('lst_warehouses').isVisible()){
        if(!warehouse){
            msg = 'Selecciona un almacen'
            msg_error(msg)
            return
        }
    }

    msg = '¿Estas seguro de guardar esta entrada? <br/><br/>\
        Esta acción no se puede deshacer'

    webix.confirm({
        title: 'Agregar entrada',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                add_product_stock(product_id, new_cant, warehouse)
            }
        }
    })

}


function add_product_stock(product_id, new_cant, warehouse){
    var data = {
        product_id: product_id,
        cant: new_cant,
        warehouse: warehouse,
    }
    _add_entries_inventory_manual(product_id, data)
    $$('win_add_inventory').close()
}


function _add_entries_inventory_manual(row_id, data){
    var grid = $$('grid_products')
    var values = {
        opt: 'create_manual',
        values: data,
    }

    webix.ajax().sync().post('inventoryentries', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                grid.updateItem(row_id, values.row)
                grid.refresh()
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function cmd_adjust_stock_click(id, e, node){
    var id_product = $$('txt_id_product').getValue()
    var row = $$('grid_warehouse_exists').getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un Almacen origen')
        return
    }
    var warehouse_source = row.id
    var cant_to_adjust = $$('txt_cant_to_adjust').getValue()

    if(cant_to_adjust == 0){
        msg_error('La cantidad a ajustar no puede ser cero')
        return
    }

    if(cant_to_adjust > row.exists){
        msg_error('La cantidad a ajustar no puede ser mayor a la existencia')
        return
    }

    var values = {
            id_product: id_product,
            cant: cant_to_adjust,
            storage: warehouse_source,
        }

    msg = '¿Estás seguro de hacer este ajuste?'
    webix.confirm({
        title: 'Ajuste de Almacen',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                _adjust_stock(values)
            }
        }
    })
}


function _adjust_stock(args){
    var grid = $$('grid_products')
    var row = grid.getSelectedItem()

    var values = {
        opt: 'adjust_stock',
        values: args,
    }

    webix.ajax().sync().post('warehouseproduct', values, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            var values = data.json();
            if (values.ok) {
                $$('txt_cant_to_adjust').setValue(0)
                $$('grid_warehouse_exists').load('warehouseproduct?opt=by_product&id=' + args.id_product)
                $$('grid_warehouse_exists').clearSelection()

                grid.updateItem(row['id'], values.row)
                grid.refresh()

                msg_ok('Ajuste realizado correctamente')
            }else{
                msg_error(values.msg)
            }
        }
    })
}
