/* ESTADO ARTICULO B = BACKORDER */
SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS_VTAS (
    FECHA date,
    INACTIVOS char(1),
    MODULO varchar(20),
    BUSCAR varchar(100),
    CUALQUIERA char(1),
    COLUMNA integer,
    BUSCAR2 varchar(30),
    BUSCAR3 varchar(30),
    BUSCAR4 varchar(30),
    BUSCAR5 varchar(30))
returns (
    CODIGO varchar(20),
    DES varchar(300),
    REF varchar(50),
    GRUPO varchar(30),
    SUBGR varchar(3),
    MARCA varchar(30),
    FABRICANTE varchar(60),
    UNIDAD varchar(8),
    ESTADO varchar(30),
    TIVA integer,
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTENC numeric(18,2),
    EXISTEN numeric(18,2),
    PRECIO numeric(18,2),
    CLASE char(1))
as
DECLARE VARIABLE LISTA INTEGER;
DECLARE VARIABLE EXIST CHAR(2);
DECLARE VARIABLE SINEXIST CHAR(2);
declare variable DIG INTEGER;
declare variable OK CHAR(1);
declare variable USARDC CHAR(2);
declare variable DESCORTA VARCHAR(60);
declare variable EXISART CHAR(1);
declare variable BXDESC CHAR(2);
declare variable ARTXSUC CHAR(2);
declare variable agencia INTEGER;
declare variable FACTALT NUMERIC(18,4);
declare variable EXISCAJA CHAR(2);
BEGIN
EXISTEN = 0;
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:EXIST);
LISTA = 0;
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
if ((LISTA = 0) or (LISTA IS NULL)) then
  EXECUTE PROCEDURE lee_configuracion ('FACTURACION','FACTURAS','CODIGO DE LA LISTA DE PRECIOS A MOSTRAR EN ARTICULOS') returning_values (:LISTA);
    
if (modulo = 'FACTURACION') then
  EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (:sinexist);
else
  sinexist = 'SI';
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER EXISTENCIA EN CAJAS Y UNIDADES EN CONSULTA DE ARTICULOS') returning_values (:exiscaja);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'USAR DESCRIPCION CORTA EN LUGAR DE LA ESTANDAR EN BUSQUEDA Y DOCUMENTOS DE VENTA') returning_values (USARDC);
EXECUTE PROCEDURE LEE_CONFIGURACION ('INVENTARIO', 'ARTICULOS', 'INCLUIR RESULTADOS POR DESCRPCION EN BUSQUEDA POR DESCRIPCION ADICIONAL') returning_values (BXDESC);
EXECUTE PROCEDURE LEE_CONFIGURACION ('INVENTARIO', 'ARTICULOS', 'ACTIVAR ARTICULOS POR SUCURSAL') returning_values (ARTXSUC);
if ((USARDC = 'SI') AND (COLUMNA = 1)) then
    COLUMNA = 4;
select sucu_id from usuario where user_cod = user into :agencia;
if (LISTA > 0) then
    BEGIN
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
      if (COLUMNA = 3) then
        BEGIN
        FOR select b.arti_cod, coba_cod from barras_articulo b, articulo a
            where (upper(b.coba_cod) like upper(:buscar)) and a.arti_cod = b.arti_cod and
            ((:INACTIVOS = 'S') or ((b.coba_activo = 'S') and ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS')))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N')))
            into :codigo, :ref
            do
            begin
            select arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, marc_cod, FABR_COD, arti_clase, ARTI_DESCORTA, arti_exist, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and arti_cod = :codigo
                INTO :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO;
            OK = 'S';
            if (ARTXSUC = 'SI') then
                BEGIN
                if ((agencia is not null) and (agencia <> 0)) then
                    if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                        BEGIN
                        ESTADO = 'I';
                        if (INACTIVOS <> 'S') then
                            OK = 'N';
                        END
                END
            if (OK = 'S') then
                BEGIN
                if (USARDC = 'SI') then
                    DES = DESCORTA;
                PRECIO = 0;
                SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
                EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
                if (EXIST = 'SI') then
                    BEGIN
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                    if ((SINEXIST = 'SI')  or (existen <> 0) or (EXISART = 'N')) then
                        begin
                        OK = 'S';
                        if (EXISCAJA = 'SI') then
                            BEGIN
                            factalt = NULL;
                            SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                INTO :factalt;
                            if ((factalt IS NULL) or (factalt = 0)) then
                                existenc = 0;
                            ELSE
                                BEGIN
                                existenc = FLOOR(EXISTEN / factalt);
                                existen = EXISTEN - (existenc * factalt);
                                END
                            END
                        end
                    END
                ELSE
                    OK = 'S';
                if (ok = 'S') then
                    suspend;
                END
            end
        END
      ELSE
        BEGIN
        if (BXDESC = 'SI') then
            BEGIN
            FOR select a.arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
                ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N'))) AND
                ((:COLUMNA <> 0) or (upper(A.ARTI_COD) like upper(:buscar))) AND
                ((:columna <> 1) or (upper(A.ARTI_DES) like upper(:buscar))) AND
                ((:columna <> 4) or (upper(A.ARTI_DESCORTA) like upper(:buscar))) AND
                ((:columna <> 2) or (upper(A.ARTI_OBS) like upper(:buscar)) or (upper(A.ARTI_DES) like upper(:buscar)))
                INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :exisart, :tiva, :CONSUMO
                do
                begin
                OK = 'S';
                if (ARTXSUC = 'SI') then
                    BEGIN
                    if ((agencia is not null) and (agencia <> 0)) then
                        if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                            BEGIN
                            ESTADO = 'I';
                            if (INACTIVOS <> 'S') then
                                OK = 'N';
                            END
                    END
                if (OK = 'S') then
                    BEGIN
                    ref = '';
                    if (USARDC = 'SI') then
                        DES = DESCORTA;
                    select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                    if ((COLUMNA <> 3) or (upper(REF) like upper(:buscar))) then
                        BEGIN
                        OK = 'N';
                        PRECIO = 0;
                        SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
                        EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
                        if (EXIST = 'SI') then
                            BEGIN
                            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                            if ((SINEXIST = 'SI')  or (existen <> 0) or (EXISART = 'N')) then
                                BEGIN
                                OK = 'S';
                                if (EXISCAJA = 'SI') then
                                    BEGIN
                                    factalt = NULL;
                                    SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                        INTO :factalt;
                                    if ((factalt IS NULL) or (factalt = 0)) then
                                        existenc = 0;
                                    ELSE
                                        BEGIN
                                        existenc = FLOOR(EXISTEN / factalt);
                                        existen = EXISTEN - (existenc * factalt);
                                        END
                                    END
                                END
                            END
                        ELSE
                            OK = 'S';
                        if (ok = 'S') then
                            if (CUALQUIERA = 'S') then
                                SUSPEND;
                            ELSE
                                if (BUSCAR2 <> '') then
                                    BEGIN
                                    IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR2)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR2)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR2))))) THEN
                                        OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR3 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR3)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR3)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR3))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR4 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR4)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR4)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR4))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR5 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR5)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR5)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR5))))) THEN
                                            OK = 'N';
                                    if (OK = 'S') then
                                        SUSPEND;
                                    END
                                ELSE
                                    SUSPEND;
                        END
                    END
                END
            end
        ELSE
            BEGIN
            FOR select a.arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
                ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N'))) AND
                ((:COLUMNA <> 0) or (upper(A.ARTI_COD) like upper(:buscar))) AND
                ((:columna <> 1) or (upper(A.ARTI_DES) like upper(:buscar))) AND
                ((:columna <> 4) or (upper(A.ARTI_DESCORTA) like upper(:buscar))) AND
                ((:columna <> 2) or (upper(A.ARTI_OBS) like upper(:buscar)))
                INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :exisart, :tiva, :CONSUMO
                do
                begin
                OK = 'S';
                if (ARTXSUC = 'SI') then
                    BEGIN
                    if ((agencia is not null) and (agencia <> 0)) then
                        if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                            BEGIN
                            ESTADO = 'I';
                            if (INACTIVOS <> 'S') then
                                OK = 'N';
                            END
                    END
                if (OK = 'S') then
                    BEGIN
                    ref = '';
                    if (USARDC = 'SI') then
                        DES = DESCORTA;
                    select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                    if ((COLUMNA <> 3) or (upper(REF) like upper(:buscar))) then
                        BEGIN
                        OK = 'N';
                        PRECIO = 0;
                        SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
                        EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
                        if (EXIST = 'SI') then
                            BEGIN
                            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                            if ((SINEXIST = 'SI')  or (existen <> 0) or (EXISART = 'N')) then
                                BEGIN
                                OK = 'S';
                                if (EXISCAJA = 'SI') then
                                    BEGIN
                                    factalt = NULL;
                                    SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                        INTO :factalt;
                                    if ((factalt IS NULL) or (factalt = 0)) then
                                        existenc = 0;
                                    ELSE
                                        BEGIN
                                        existenc = FLOOR(EXISTEN / factalt);
                                        existen = EXISTEN - (existenc * factalt);
                                        END
                                    END
                                END
                            END
                        ELSE
                            OK = 'S';
                        if (ok = 'S') then
                            if (CUALQUIERA = 'S') then
                                SUSPEND;
                            ELSE
                                if (BUSCAR2 <> '') then
                                    BEGIN
                                    IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR2)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR2)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR2))))) THEN
                                        OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR3 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR3)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR3)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR3))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR4 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR4)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR4)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR4))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR5 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR5)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR5)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR5))))) THEN
                                            OK = 'N';
                                    if (OK = 'S') then
                                        SUSPEND;
                                    END
                                ELSE
                                    SUSPEND;
                        END
                    END
                END
            end
        END
    ELSE
        FOR select a.arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
            from articulo a, tarifa_iva t
            where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
            ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N')))
            INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO
            do
            begin
            OK = 'S';
            if (ARTXSUC = 'SI') then
                BEGIN
                if ((agencia is not null) and (agencia <> 0)) then
                    if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                        BEGIN
                        ESTADO = 'I';
                        if (INACTIVOS <> 'S') then
                            OK = 'N';
                        END
                END
            if (OK = 'S') then
                BEGIN
                ref = '';
                if (USARDC = 'SI') then
                    DES = DESCORTA;
                select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                PRECIO = 0;
                SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
                EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
                if (EXIST = 'SI') then
                    BEGIN
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                    if ((SINEXIST = 'SI')  or (existen <> 0) or (EXISART = 'N')) then
                        BEGIN
                        if (EXISCAJA = 'SI') then
                            BEGIN
                            factalt = NULL;
                            SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                INTO :factalt;
                            if ((factalt IS NULL) or (factalt = 0)) then
                                existenc = 0;
                            ELSE
                                BEGIN
                                existenc = FLOOR(EXISTEN / factalt);
                                existen = EXISTEN - (existenc * factalt);
                                END
                            END
                        SUSPEND;
                        END
                    END
                ELSE
                    SUSPEND;
                END
            END
    END
ELSE
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
      if (COLUMNA = 3) then
        BEGIN
        FOR select b.arti_cod, coba_cod from barras_articulo b, articulo a
            where (upper(b.coba_cod) like upper(:buscar)) and a.arti_cod = b.arti_cod and
            ((:INACTIVOS = 'S') or ((b.coba_activo = 'S') and ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS')))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N')))
            into :codigo, :ref
            do
            begin
            select arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and arti_cod = :codigo
                INTO :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO;
            OK = 'S';
            if (ARTXSUC = 'SI') then
                BEGIN
                if ((agencia is not null) and (agencia <> 0)) then
                    if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                        BEGIN
                        ESTADO = 'I';
                        if (INACTIVOS <> 'S') then
                            OK = 'N';
                        END
                END
            if (OK = 'S') then
                BEGIN
                if (USARDC = 'SI') then
                    DES = DESCORTA;
                if (EXIST = 'SI') then
                    BEGIN
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                    if (EXISCAJA = 'SI') then
                        BEGIN
                        factalt = NULL;
                        SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                            INTO :factalt;
                        if ((factalt IS NULL) or (factalt = 0)) then
                            existenc = 0;
                        ELSE
                            BEGIN
                            existenc = FLOOR(EXISTEN / factalt);
                            existen = EXISTEN - (existenc * factalt);
                            END
                        END
                    END
                suspend;
                end
            END
        END
      ELSE
        begin
        if (BXDESC = 'SI') then
            BEGIN
            FOR select arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, arti_precio, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
                ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N'))) AND
                ((:COLUMNA <> 0) or (upper(A.ARTI_COD) like upper(:buscar))) AND
                ((:columna <> 1) or (upper(A.ARTI_DES) like upper(:buscar))) AND
                ((:columna <> 4) or (upper(A.ARTI_DESCORTA) like upper(:buscar))) AND
                ((:columna <> 2) or (upper(ARTI_OBS) like upper(:buscar)) or (upper(A.ARTI_DES) like upper(:buscar)))
                INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :PRECIO, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO
                do
                begin
                OK = 'S';
                if (ARTXSUC = 'SI') then
                    BEGIN
                    if ((agencia is not null) and (agencia <> 0)) then
                        if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                            BEGIN
                            ESTADO = 'I';
                            if (INACTIVOS <> 'S') then
                                OK = 'N';
                            END
                    END
                if (OK = 'S') then
                    BEGIN
                    ref = '';
                    if (USARDC = 'SI') then
                        DES = DESCORTA;
                    select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                    if ((COLUMNA <> 3) or (upper(REF) like upper(:buscar))) then
                        BEGIN
                        if (EXIST = 'SI') then
                            BEGIN
                            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                            if ((SINEXIST = 'SI') or (existen <> 0) or (EXISART = 'N')) then
                                BEGIN
                                OK = 'S';
                                if (EXISCAJA = 'SI') then
                                    BEGIN
                                    factalt = NULL;
                                    SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                        INTO :factalt;
                                    if ((factalt IS NULL) or (factalt = 0)) then
                                        existenc = 0;
                                    ELSE
                                        BEGIN
                                        existenc = FLOOR(EXISTEN / factalt);
                                        existen = EXISTEN - (existenc * factalt);
                                        END
                                    END
                                END
                            END
                        ELSE
                            OK = 'S';
                        if (ok = 'S') then
                            if (CUALQUIERA = 'S') then
                                SUSPEND;
                            ELSE
                                if (BUSCAR2 <> '') then
                                    BEGIN
                                    IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR2)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR2)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR2))))) THEN
                                        OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR3 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR3)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR3)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR3))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR4 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR4)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR4)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR4))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR5 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR5)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR5)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR5))))) THEN
                                            OK = 'N';
                                    if (OK = 'S') then
                                        SUSPEND;
                                    END
                                ELSE
                                    SUSPEND;
                        END
                    END
                end
            END
        ELSE
            BEGIN
            FOR select arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, arti_precio, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
                from articulo a, tarifa_iva t
                where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
                ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N'))) AND
                ((:COLUMNA <> 0) or (upper(A.ARTI_COD) like upper(:buscar))) AND
                ((:columna <> 1) or (upper(A.ARTI_DES) like upper(:buscar))) AND
                ((:columna <> 4) or (upper(A.ARTI_DESCORTA) like upper(:buscar))) AND
                ((:columna <> 2) or (upper(ARTI_OBS) like upper(:buscar)))
                INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :PRECIO, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO
                do
                begin
                OK = 'S';
                if (ARTXSUC = 'SI') then
                    BEGIN
                    if ((agencia is not null) and (agencia <> 0)) then
                        if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                            BEGIN
                            ESTADO = 'I';
                            if (INACTIVOS <> 'S') then
                                OK = 'N';
                            END
                    END
                if (OK = 'S') then
                    BEGIN
                    ref = '';
                    if (USARDC = 'SI') then
                        DES = DESCORTA;
                    select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                    if ((COLUMNA <> 3) or (upper(REF) like upper(:buscar))) then
                        BEGIN
                        if (EXIST = 'SI') then
                            BEGIN
                            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                            if ((SINEXIST = 'SI') or (existen <> 0) or (EXISART = 'N')) then
                                BEGIN
                                OK = 'S';
                                if (EXISCAJA = 'SI') then
                                    BEGIN
                                    factalt = NULL;
                                    SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                        INTO :factalt;
                                    if ((factalt IS NULL) or (factalt = 0)) then
                                        existenc = 0;
                                    ELSE
                                        BEGIN
                                        existenc = FLOOR(EXISTEN / factalt);
                                        existen = EXISTEN - (existenc * factalt);
                                        END
                                    END
                                END
                            END
                        ELSE
                            OK = 'S';
                        if (ok = 'S') then
                            if (CUALQUIERA = 'S') then
                                SUSPEND;
                            ELSE
                                if (BUSCAR2 <> '') then
                                    BEGIN
                                    IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR2)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR2)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR2))))) THEN
                                        OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR3 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR3)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR3)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR3))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR4 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR4)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR4)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR4))))) THEN
                                            OK = 'N';
                                    if ((OK = 'S') AND (BUSCAR5 <> '')) then
                                        IF (NOT EXISTS (SELECT ARTI_COD FROM ARTICULO WHERE ARTI_COD = :CODIGO AND ((upper(ARTI_DES) like upper(:BUSCAR5)) or (upper(ARTI_DESCORTA) like upper(:BUSCAR5)) or (UPPER(ARTI_OBS) LIKE UPPER(:BUSCAR5))))) THEN
                                            OK = 'N';
                                    if (OK = 'S') then
                                        SUSPEND;
                                    END
                                ELSE
                                    SUSPEND;
                        END
                    END
                end
            END
        END
    ELSE
        FOR select arti_cod, arti_des, grup_cod, subg_cod, arti_unidad, esar_cod, taiv_porc, arti_precio, marc_cod, fabr_cod, arti_clase, ARTI_DESCORTA, ARTI_EXIST, T.taiv_cod, ARTI_CONSUMO
            from articulo a, tarifa_iva t
            where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
            ((:INACTIVOS = 'S') or ((a.esar_cod = 'A') or (a.esar_cod = 'B') or ((a.esar_cod = 'K') and (:MODULO <> 'COMPRAS'))) or ((:INACTIVOS = 'C') AND (esar_cod = 'N')))
            INTO :CODIGO, :DES, :GRUPO, :SUBGR, :UNIDAD, :ESTADO, :IVA, :PRECIO, :MARCA, :FABRICANTE, :CLASE, :DESCORTA, :EXISART, :tiva, :CONSUMO
            do
            begin
            OK = 'S';
            if (ARTXSUC = 'SI') then
                BEGIN
                if ((agencia is not null) and (agencia <> 0)) then
                    if (NOT EXISTS (SELECT S.ARTI_COD FROM articulos_sucursal S, USUARIO U WHERE ARTI_COD = :CODIGO AND U.user_cod = user AND (S.sucu_id = U.sucu_id))) then
                        BEGIN
                        ESTADO = 'I';
                        if (INACTIVOS <> 'S') then
                            OK = 'N';
                        END
                END
            if (OK = 'S') then
                BEGIN
                ref = '';
                if (USARDC = 'SI') then
                    DES = DESCORTA;
                select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
                if (EXIST = 'SI') then
                    BEGIN
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                    if ((SINEXIST = 'SI') or (existen <> 0) or (EXISART = 'N')) then
                        BEGIN
                        if (EXISCAJA = 'SI') then
                            BEGIN
                            factalt = NULL;
                            SELECT FIRST 1 UNAR_FACCAN FROM unidad_articulo WHERE ARTI_COD = :codigo and unar_activa = 'S' AND UNAR_FACCAN > 1 order by unar_faccan
                                INTO :factalt;
                            if ((factalt IS NULL) or (factalt = 0)) then
                                existenc = 0;
                            ELSE
                                BEGIN
                                existenc = FLOOR(EXISTEN / factalt);
                                existen = EXISTEN - (existenc * factalt);
                                END
                            END
                        SUSPEND;
                        END
                    END
                ELSE
                    SUSPEND;
                end
            END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER COTIZACION_WEB_DETALLE_BI FOR COTIZACION_WEB_DETALLE
ACTIVE BEFORE INSERT POSITION 0
as
declare variable itemax integer;
declare variable UNIDAD VARCHAR(8);
declare variable DTOGRUPO VARCHAR(10);
declare variable DTOG NUMERIC(9,4);
declare variable DTOL NUMERIC(9,4);
declare variable IVAP NUMERIC(18,2);
declare variable NIT VARCHAR(20);
declare variable PREF VARCHAR(4);
declare variable IVAINC CHAR(1);
declare variable ICOINC char(2);
BEGIN
execute procedure lee_configuracion('FACTURACION', 'ARTICULOS', 'IMPOCONSUMO INCLUIDO EN EL PRECIO BASE DE VENTA ANTES DE IVA') returning_values (:ICOINC);
/* LOS IMPUESTOS DEPENDEN DEL ENCABEZADO */
SELECT COWE_PREF, TERC_NIT FROM cotizacion_web P WHERE COWE_ID = NEW.cowe_id INTO :PREF, :NIT;
if (NEW.LIPR_COD IS NULL) then
    SELECT LIPR_COD FROM CLIENTES WHERE TERC_NIT = :NIT INTO NEW.LIPR_COD;

if (new.cowd_item is null) then
    begin
    select max(cowd_item) from cotizacion_web_detalle where cowe_id = new.cowe_id into :itemax;
    if (itemax is null) then
        new.cowd_item = 1;
    else
        new.cowd_item = :itemax + 1;
    end
if (new.arti_cod is null) then
    begin
    SELECT FIRST 1 ARTI_COD, COBA_UNIDAD from BARRAS_ARTICULO WHERE COBA_COD = new.cowd_codbar AND COBA_ACTIVO = 'S'
        INTO new.arti_cod, :UNIDAD;
    if (new.arti_cod is null) then
        begin
        SELECT ARTI_COD, ARTI_UNIDAD FROM ARTICULO WHERE ARTI_COD = new.cowd_codbar and ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))
            INTO new.arti_cod, :UNIDAD;
        if (new.arti_cod is null) then
            exception articulo_no_existe 'No se encontro el articulo ' || new.cowd_codbar;
        ELSE
            if (new.cowd_unidad is null) then
                NEW.cowd_unidad = :UNIDAD;
        end
    else
        if (new.cowd_unidad is null) then
            NEW.cowd_unidad = :UNIDAD;
    end
if (new.cowd_desc is null) then
    SELECT ARTI_DES from ARTICULO WHERE ARTI_COD = new.arti_cod INTO new.cowd_desc;

EXECUTE PROCEDURE factor_unidad_cant(NEW.arti_cod, NEW.cowd_unidad) returning_values(NEW.cowd_factor);

/* LOS DESCUENTOS */
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'DOCUMENTOS', 'SUGERIR DESCUENTO POR ITEM CON BASE EN GRUPO DE MERCANCIA Y LISTA DE PRECIOS') returning_values (:DTOGRUPO);
if (DTOGRUPO <> 'NINGUNO') then
    BEGIN
    if (NEW.cowd_dtop IS NULL) then
        BEGIN
        DTOG = 0;
        DTOL = 0;
        if ((dtogrupo = 'GRUPO') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select grup_dscto from grupo g, articulo a where a.grup_cod = g.grup_cod and a.arti_cod = NEW.arti_cod INTO DTOG;
            END
        if ((dtogrupo = 'LISTA') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select lipr_dscto from lista_precios where lipr_cod = NEW.lipr_cod INTO DTOL;
            END
        NEW.cowd_dtop = DTOG + DTOL;
        END
    END
ELSE
    BEGIN
    if (NEW.cowd_dtop IS NULL) then
        NEW.cowd_dtop = 0;
    END

new.cowd_dtom = new.cowd_prunit * new.cowd_dtop / 100;

if (new.cowd_consumo is null) then
    begin
    select PRAR_CONSUMO from PRECIOS_ARTICULO where ARTI_COD = new.ARTI_COD and LIPR_COD = new.LIPR_COD into new.cowd_consumo;
    if ((new.cowd_consumo is null) or (new.cowd_consumo <> 0)) then
        select ARTI_CONSUMO from ARTICULO where ARTI_COD = new.ARTI_COD into new.cowd_consumo;
    if (new.cowd_consumo is null) then
        new.cowd_consumo = 0;
    new.cowd_consumo = new.cowd_consumo * new.cowd_cant * new.cowd_factor;
    end

/* CALCULE EL IVA, CONSUMO Y TOTAL */
SELECT PREF_IVAINC FROM PREFIJOS WHERE TIDO_COD = 35 AND PREF_PRE = :PREF INTO :IVAINC;
SELECT TAIV_PORC FROM tarifa_iva T, ARTICULO A WHERE T.taiv_cod = A.taiv_cod AND A.arti_cod = NEW.arti_cod INTO :IVAP;
new.cowd_ivap = :ivap;
if ((new.cowd_ivamonto is null) or (NEW.cowd_ivamonto = 0)) then
    begin
    if (IVAINC = 'N') then
        begin
        if (ICOINC = 'SI') then
            new.cowd_ivamonto = ((new.cowd_cant * (new.cowd_prunit - new.cowd_dtom) - new.cowd_consumo) / 100) * :IVAP;
        else
            new.cowd_ivamonto = ((new.cowd_cant * (new.cowd_prunit - new.cowd_dtom)) / 100) * :IVAP;
        end
    else
        new.cowd_ivamonto = ((new.cowd_cant * (new.cowd_prunit - new.cowd_dtom) - new.cowd_consumo) / (100 + :IVAP)) * :IVAP;
    end
if (ICOINC = 'SI') then
    new.cowd_total = (new.cowd_cant * (new.cowd_prunit - new.cowd_dtom));
else
    new.cowd_total = (new.cowd_cant * (new.cowd_prunit - new.cowd_dtom) + new.cowd_consumo);
if (IVAINC = 'N') then
    new.cowd_total = new.cowd_total + new.cowd_ivamonto;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER FACTURA_WEB_DETALLE_BI FOR FACTURA_WEB_DETALLE
ACTIVE BEFORE INSERT POSITION 0
as
declare variable UNIDAD VARCHAR(8);
declare variable DTOGRUPO VARCHAR(10);
declare variable DTOG NUMERIC(9,4);
declare variable DTOL NUMERIC(9,4);
declare variable IVAP NUMERIC(18,2);
declare variable BOD VARCHAR(2);
declare variable PREF VARCHAR(4);
declare variable IVAINC CHAR(1);
declare variable ICOINC char(2);
declare variable DIGITOS INTEGER;
declare variable CEROS VARCHAR(10);
begin
execute procedure lee_configuracion('FACTURACION', 'ARTICULOS', 'IMPOCONSUMO INCLUIDO EN EL PRECIO BASE DE VENTA ANTES DE IVA') returning_values (:ICOINC);
execute procedure lee_configuracion('FACTURACION','DOCUMENTOS', 'REDONDEO AL MULTIPLO DE DIEZ EN TOTALES') returning_values (DIGITOS);
execute procedure lee_configuracion('FACTURACION', 'DOCUMENTOS', 'PERMITIR PRECIOS EN CERO') returning_values (CEROS);
if (new.fawd_impreso is null) then
    new.fawd_impreso = 'N';
NEW.fawd_pedlisto = 'N';
/* PRECIO CERO */
if (CEROS = 'NO') then
    if ((NEW.fawd_prunit IS NULL) or (NEW.fawd_prunit = 0)) then
        exception precio_menor_minimo 'El precio del articulo ' || new.arti_cod || ' no puede ser cero';
/* el item */
if (new.fawd_item is null) then
  begin
  SELECT MAX(fawd_item)+1 FROM factura_web_detalle WHERE facw_id = NEW.facw_id INTO NEW.fawd_item;
  if (NEW.fawd_item IS NULL) then
    NEW.fawd_item = 1;
  end
if (new.fawd_hora is null) then
    NEW.fawd_hora = CAST('NOW' AS TIME);
if (new.arti_cod is null) then
    begin
    SELECT FIRST 1 ARTI_COD, COBA_UNIDAD from BARRAS_ARTICULO WHERE COBA_COD = new.fawd_codbar AND COBA_ACTIVO = 'S'
        INTO new.arti_cod, :UNIDAD;
    if (new.arti_cod is null) then
        begin
        SELECT ARTI_COD, ARTI_UNIDAD FROM ARTICULO WHERE ARTI_COD = new.fawd_codbar and ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))
            INTO new.arti_cod, :UNIDAD;
        if (new.arti_cod is null) then
            exception articulo_no_existe 'No se encontro el articulo ' || new.fawd_codbar;
        ELSE
            if (new.fawd_unidad is null) then
                NEW.fawd_unidad = :UNIDAD;
        end
    else
        if (new.fawd_unidad is null) then
            NEW.fawd_unidad = :UNIDAD;
    end
EXECUTE PROCEDURE factor_unidad_cant(NEW.arti_cod, NEW.fawd_unidad) returning_values(NEW.fawd_factor);
if (new.fawd_desc is null) then
    select arti_des from articulo where arti_cod = new.arti_cod into new.fawd_desc;

/* LOS DESCUENTOS */
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'DOCUMENTOS', 'SUGERIR DESCUENTO POR ITEM CON BASE EN GRUPO DE MERCANCIA Y LISTA DE PRECIOS') returning_values (:DTOGRUPO);
if (DTOGRUPO <> 'NINGUNO') then
    BEGIN
    if (NEW.fawd_dtop IS NULL) then
        BEGIN
        DTOG = 0;
        DTOL = 0;
        if ((dtogrupo = 'GRUPO') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select grup_dscto from grupo g, articulo a where A.grup_cod = G.grup_cod AND a.arti_cod = NEW.arti_cod INTO DTOG;
            END
        if ((dtogrupo = 'LISTA') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select lipr_dscto from lista_precios where lipr_cod = NEW.lipr_cod INTO DTOL;
            END
        NEW.fawd_dtop = DTOG + DTOL;
        END
    END
ELSE
    BEGIN
--    if (NEW.pewd_dtop IS NULL) then
        NEW.fawd_dtop = 0;
    END

if ((NEW.fawd_dto1 IS NULL) or (new.fawd_dto1 = 0)) then
    BEGIN
    select prar_dto1 from precios_articulo where arti_cod = NEW.arti_cod and lipr_cod = new.lipr_cod INTO NEW.fawd_dto1;
    if (NEW.fawd_dto1 IS NULL) then
        NEW.fawd_dto1 = 0;
    END
if ((NEW.fawd_dto2 IS NULL) or (new.fawd_dto2 = 0)) then
    BEGIN
    select prar_dto2 from precios_articulo where arti_cod = NEW.arti_cod and lipr_cod = new.lipr_cod INTO NEW.fawd_dto2;
    if (NEW.fawd_dto2 IS NULL) then
        NEW.fawd_dto2 = 0;
    END
if (NEW.fawd_dto3 IS NULL) then
    NEW.fawd_dto3 = 0;
/* CALCULE EL MONTO DEL DESCUENTO */
new.fawd_dtom = new.fawd_prunit * new.fawd_dtop / 100;
if (new.fawd_dto1m is null) then
    new.fawd_dto1m = round((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom)) * new.fawd_dto1, :digitos*-1);
if (new.fawd_dto2m is null) then
    new.fawd_dto2m = round((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m) * new.fawd_dto2, :digitos*-1);
if (new.fawd_dto3m is null) then
    new.fawd_dto3m = round((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m) * new.fawd_dto3, :digitos*-1);

/* LA BODEGA Y LOS IMPUESTOS DEPENDEN DEL ENCABEZADO */
SELECT PT.BODE_COD, FACW_PREF FROM factura_web f, PUNTO_VENTA PT, VENDEDORES V
    WHERE FACW_ID = NEW.facw_id AND f.vend_cod = V.vend_cod AND PT.ptvt_id = V.ptvt_id
    INTO :BOD, :PREF;
if (new.bode_cod is null) then
    new.bode_cod = :BOD;

if (new.fawd_consumo is null) then
    begin
    select PRAR_CONSUMO from PRECIOS_ARTICULO where ARTI_COD = new.ARTI_COD and LIPR_COD = new.LIPR_COD into new.fawd_consumo;
    if ((new.fawd_consumo is null) or (new.fawd_consumo <> 0)) then
        select ARTI_CONSUMO from ARTICULO where ARTI_COD = new.ARTI_COD into new.fawd_consumo;
    if (new.fawd_consumo is null) then
        new.fawd_consumo = 0;
    new.fawd_consumo = new.fawd_consumo * new.fawd_cant * new.fawd_factor;
    end

/* CALCULE EL IVA, CONSUMO Y TOTAL */
SELECT PREF_IVAINC FROM PREFIJOS WHERE TIDO_COD = 31 AND PREF_PRE = :PREF INTO :IVAINC;
SELECT TAIV_PORC, a.arti_inalc FROM tarifa_iva T, ARTICULO A WHERE T.taiv_cod = A.taiv_cod AND A.arti_cod = NEW.arti_cod INTO :IVAP, new.fawd_inalcp;
new.fawd_ivap = :ivap;
if ((new.fawd_ivamonto is null) or (NEW.fawd_ivamonto = 0)) then
    begin
    if (IVAINC = 'N') then
        begin
        if (ICOINC = 'SI') then
            new.fawd_ivamonto = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m - new.fawd_consumo) / 100) * :IVAP, :digitos*-1);
        else
            new.fawd_ivamonto = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m) / 100) * :IVAP, :digitos*-1);
        end
    else
        new.fawd_ivamonto = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m - new.fawd_consumo) / (100 + :IVAP)) * :IVAP, :digitos*-1);
    end
if ((new.fawd_inalcm is null) or (NEW.fawd_inalcm = 0)) then
    begin
    if (IVAINC = 'N') then
        begin
        if (ICOINC = 'SI') then
            new.fawd_inalcm = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m - new.fawd_consumo) / 100) * new.fawd_inalcp, :digitos*-1);
        else
            new.fawd_inalcm = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m) / 100) * new.fawd_inalcp, :digitos*-1);
        end
    else
        new.fawd_inalcm = round(((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m - new.fawd_consumo) / (100 + new.fawd_inalcp)) * new.fawd_inalcp, :digitos*-1);
    end
if ((new.fawd_total is null) or (new.fawd_total = 0)) then
    begin
    if (ICOINC = 'SI') then
        new.fawd_total = round((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m), :digitos*-1);
    else
        new.fawd_total = round((new.fawd_cant * (new.fawd_prunit - new.fawd_dtom) - new.fawd_dto1m - new.fawd_dto2m - new.fawd_dto3m + new.fawd_consumo), :digitos*-1);
    if (IVAINC = 'N') then
        new.fawd_total = new.fawd_total + new.fawd_ivamonto + new.fawd_inalcm;
    end

end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER PEDIDO_WEB_DETALLE_BI FOR PEDIDO_WEB_DETALLE
ACTIVE BEFORE INSERT POSITION 0
as
declare variable itemax integer;
declare variable UNIDAD VARCHAR(8);
declare variable DTOGRUPO VARCHAR(10);
declare variable DTOG NUMERIC(9,4);
declare variable DTOL NUMERIC(9,4);
declare variable IVAP NUMERIC(18,2);
declare variable EXISTEN NUMERIC(18,2);
declare variable RESERVADO NUMERIC(18,2);
declare variable ORDENADO NUMERIC(18,2);
declare variable STAND VARCHAR(20);
declare variable BOD VARCHAR(2);
declare variable PREF VARCHAR(4);
declare variable IVAINC CHAR(1);
declare variable ICOINC char(2);
declare variable DIGITOS INTEGER;
declare variable PTOVNT INTEGER;
declare variable FECDOC DATE;
declare variable AGENCIA INTEGER;
declare variable PRCERO char(2);
declare variable VALEXIS char(2);
declare variable PRCANT char(2);
BEGIN
if (NEW.pewd_anulado IS NULL) then
    NEW.pewd_anulado = 'N';
execute procedure lee_configuracion('FACTURACION', 'ARTICULOS', 'IMPOCONSUMO INCLUIDO EN EL PRECIO BASE DE VENTA ANTES DE IVA') returning_values (:ICOINC);
execute procedure lee_configuracion('FACTURACION','DOCUMENTOS', 'REDONDEO AL MULTIPLO DE DIEZ EN TOTALES') returning_values (DIGITOS);
if (new.pewd_item is null) then
    begin
    select max(pewd_item) from pedido_web_detalle where pewe_id = new.pewe_id into :itemax;
    if (itemax is null) then
        new.pewd_item = 1;
    else
        new.pewd_item = :itemax + 1;
    end
if (new.arti_cod is null) then
    begin
    SELECT FIRST 1 ARTI_COD, COBA_UNIDAD from BARRAS_ARTICULO WHERE COBA_COD = new.pewd_codbar AND COBA_ACTIVO = 'S'
        INTO new.arti_cod, :UNIDAD;
    if (new.arti_cod is null) then
        begin
        SELECT ARTI_COD, ARTI_UNIDAD FROM ARTICULO WHERE ARTI_COD = new.pewd_codbar and ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))
            INTO new.arti_cod, :UNIDAD;
        if (new.arti_cod is null) then
            exception articulo_no_existe 'No se encontro el articulo ' || new.pewd_codbar;
        ELSE
            if (new.pewd_unidad is null) then
                NEW.pewd_unidad = :UNIDAD;
        end
    else
        if (new.pewd_unidad is null) then
            NEW.pewd_unidad = :UNIDAD;
    end
if (new.pewd_desc is null) then
    select arti_des from articulo where arti_cod = new.arti_cod into new.pewd_desc;
EXECUTE PROCEDURE factor_unidad_cant(NEW.arti_cod, NEW.pewd_unidad) returning_values(NEW.pewd_factor);

EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'DOCUMENTOS', 'PERMITIR PRECIOS EN CERO') returning_values (:PRCERO);
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'PEDIDOS', 'SUGERIR PRECIO SEGUN CANTIDAD EN PEDIDOS WEB') returning_values (:PRCANT);
if (PRCANT = 'SI') then
    SELECT FIRST 1 PRAR_FIJO * NEW.pewd_factor from precios_articulo P WHERE ARTI_COD = NEW.arti_cod AND (NEW.pewd_cant * NEW.pewd_factor) >= P.prar_cantmin AND PRAR_ESCALAS = 'S'
        ORDER BY PRAR_CANTMIN DESC
        INTO NEW.pewd_prunit;
ELSE
    if ((NEW.pewd_prunit IS NULL) or ((NEW.pewd_prunit = 0) AND (PRCERO <> 'SI')))  then
        SELECT FIRST 1 PRAR_FIJO * NEW.pewd_factor from precios_articulo P WHERE ARTI_COD = NEW.arti_cod AND LIPR_COD = NEW.lipr_cod INTO NEW.pewd_prunit;

/* LOS DESCUENTOS */
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'DOCUMENTOS', 'SUGERIR DESCUENTO POR ITEM CON BASE EN GRUPO DE MERCANCIA Y LISTA DE PRECIOS') returning_values (:DTOGRUPO);
if (DTOGRUPO <> 'NINGUNO') then
    BEGIN
    if (NEW.pewd_dtop IS NULL) then
        BEGIN
        DTOG = 0;
        DTOL = 0;
        if ((dtogrupo = 'GRUPO') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select grup_dscto from grupo g, articulo a where a.grup_cod = g.grup_cod and a.arti_cod = NEW.arti_cod INTO DTOG;
            END
        if ((dtogrupo = 'LISTA') or (dtogrupo = 'AMBOS')) Then
            BEGIN
            select lipr_dscto from lista_precios where lipr_cod = NEW.lipr_cod INTO DTOL;
            END
        NEW.pewd_dtop = DTOG + DTOL;
        END
    END
ELSE
    BEGIN
    if (NEW.pewd_dtop IS NULL) then
        NEW.pewd_dtop = 0;
    END

if (NEW.pewd_dto1 IS NULL) then
    BEGIN
    select prar_dto1 from precios_articulo where arti_cod = NEW.arti_cod INTO NEW.pewd_dto1;
    if (NEW.pewd_dto1 IS NULL) then
        NEW.pewd_dto1 = 0;
    END
if (NEW.pewd_dto2 IS NULL) then
    BEGIN
    select prar_dto2 from precios_articulo where arti_cod = NEW.arti_cod INTO NEW.pewd_dto2;
    if (NEW.pewd_dto2 IS NULL) then
        NEW.pewd_dto2 = 0;
    END
if (NEW.pewd_dto3 IS NULL) then
    NEW.pewd_dto3 = 0;
/* CALCULE EL MONTO DEL DESCUENTO */
new.pewd_dtom = new.pewd_prunit * new.pewd_dtop / 100;
if (new.pewd_dto1m is null) then
    new.pewd_dto1m = round((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom)) * new.pewd_dto1, :digitos*-1);
if (new.pewd_dto2m is null) then
    new.pewd_dto2m = round((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m) * new.pewd_dto2, :digitos*-1);
if (new.pewd_dto3m is null) then
    new.pewd_dto3m = round((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m) * new.pewd_dto3, :digitos*-1);

/* LA BODEGA Y LOS IMPUESTOS DEPENDEN DEL ENCABEZADO */
select ptvt_id, PEWE_PREF from pedido_web where pewe_id = new.pewe_id into :ptovnt, :PREF;
if (ptovnt is null) then
    SELECT first 1 PT.bode_cod, pt.sucu_id FROM pedido_web P, punto_venta PT
    WHERE PEWE_ID = NEW.pewe_id AND p.pewe_pref = pt.ptvt_prefped
    INTO :BOD, :agencia;
else
    SELECT PT.bode_cod, pt.sucu_id FROM punto_venta PT WHERE PT.ptvt_id = :ptovnt
    into :bod, :agencia;
if(agencia is null) then
  agencia = 0;
if ((new.bode_cod is null) or (NEW.bode_cod = '')) Then
    new.bode_cod = :bod;
SELECT pewe_fecha from pedido_web c where pewe_id = new.pewe_id into :fecdoc;
execute procedure lee_configuracion('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIAS DESDE EL PEDIDO') returning_values (:VALEXIS);
if (VALEXIS = 'SI') then
    BEGIN
    execute procedure existencias_unidad_bod(new.arti_cod,:fecdoc,:UNIDAD,new.bode_cod)
    returning_values (:bod,:existen,:reservado,:ordenado,:stand);
    if ((:existen-:reservado > 0) and (existen >= new.pewd_cant)) then
        new.bode_cod = :bod;
    else
        execute procedure bodega_facturacion_alterna(new.arti_cod,:fecdoc,0,:bod,new.pewd_cant) returning_values(:bod);
    execute procedure existencias_unidad_bod(new.arti_cod,:fecdoc,new.pewd_unidad,:bod)
        returning_values (:bod,:existen,:reservado,:ordenado,:stand);
    if ((existen-reservado > 0) and (existen >= new.pewd_cant)) then
        new.bode_cod = :BOD;
    else
        SELECT first 1 BODE_COD FROM articulo_bodega WHERE ARTI_COD = NEW.arti_cod AND ((SUCU_ID = :agencia) or (SUCU_ID = 0))
            INTO NEW.bode_cod;
    END
if (new.pewd_consumo is null) then
    begin
    select PRAR_CONSUMO from PRECIOS_ARTICULO where ARTI_COD = new.ARTI_COD and LIPR_COD = new.LIPR_COD into new.pewd_consumo;
    if ((new.pewd_consumo is null) or (new.pewd_consumo <> 0)) then
        select ARTI_CONSUMO from ARTICULO where ARTI_COD = new.ARTI_COD into new.pewd_consumo;
    if (new.pewd_consumo is null) then
        new.pewd_consumo = 0;
    new.pewd_consumo = new.pewd_consumo * new.pewd_cant * new.pewd_factor;
    end

/* CALCULE EL IVA, CONSUMO Y TOTAL */
SELECT PREF_IVAINC FROM PREFIJOS WHERE TIDO_COD = 34 AND PREF_PRE = :PREF INTO :IVAINC;
SELECT TAIV_PORC FROM tarifa_iva T, ARTICULO A WHERE T.taiv_cod = A.taiv_cod AND A.arti_cod = NEW.arti_cod INTO :IVAP;
new.pewd_ivap = :ivap;
if ((new.pewd_ivamonto is null) or (NEW.pewd_ivamonto = 0)) then
    begin
    if (IVAINC = 'N') then
        begin
        if (ICOINC = 'SI') then
            new.pewd_ivamonto = round(((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m - new.pewd_dto3m - new.pewd_consumo) / 100) * :IVAP, :digitos*-1);
        else
            new.pewd_ivamonto = round(((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m - new.pewd_dto3m) / 100) * :IVAP, :digitos*-1);
        end
    else
        new.pewd_ivamonto = round(((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m - new.pewd_dto3m - new.pewd_consumo) / (100 + :IVAP)) * :IVAP, :digitos*-1);
    end
--if ((new.pewd_total is null) or (new.pewd_total = 0)) then
    begin
    if (ICOINC = 'SI') then
        new.pewd_total = round((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m - new.pewd_dto3m), :digitos*-1);
    else
        new.pewd_total = round((new.pewd_cant * (new.pewd_prunit - new.pewd_dtom) - new.pewd_dto1m - new.pewd_dto2m - new.pewd_dto3m + new.pewd_consumo), :digitos*-1);
    if (IVAINC = 'N') then
        new.pewd_total = new.pewd_total + new.pewd_ivamonto;
    end

end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure UNIDADES_OFFLINE
returns (
    ARTI_COD varchar(15),
    UNAR_UNIDAD varchar(8),
    UNAR_FACCAN numeric(18,6),
    UNAR_FACPRE numeric(18,6))
as
begin
FOR SELECT ARTI_COD, ARTI_UNIDAD, 1, 1 FROM ARTICULO WHERE ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
    INTO :ARTI_COD, :UNAR_UNIDAD, :UNAR_FACCAN, :UNAR_FACPRE
    DO
    begin
    EXECUTE PROCEDURE NOMBRE_ASCII(UNAR_UNIDAD) returning_values (UNAR_UNIDAD);
    suspend;
    end

FOR select ARTI_COD, UNAR_UNIDAD, UNAR_FACCAN, UNAR_FACPRE
    FROM UNIDAD_ARTICULO where UNAR_ACTIVA = 'S'
    INTO :ARTI_COD, :UNAR_UNIDAD, :UNAR_FACCAN, :UNAR_FACPRE
    do
    begin
    EXECUTE PROCEDURE NOMBRE_ASCII(UNAR_UNIDAD) returning_values (UNAR_UNIDAD);
    suspend;
    end
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure TRAE_ARTICULO_MOVIL_INV (
    TIPO integer,
    CODIGO varchar(20),
    NIT varchar(20),
    CODBOD varchar(2),
    TIPOORD integer,
    NROORDEN varchar(12))
returns (
    ARTICULO varchar(50),
    DES varchar(60),
    DESCORTA varchar(30),
    UNIDAD varchar(8),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    CANTORD numeric(18,2),
    EXISTEN numeric(18,2),
    COSTO numeric(18,2),
    SOLOORD char(2),
    INVIMA varchar(30),
    CUM varchar(30),
    IUM varchar(30),
    CONTEXISTART char(1),
    CONFIGLOTE char(2),
    COD_BARRAS T_BARRAS)
as
declare variable LISTA integer;
declare variable CANT numeric(18,4);
declare variable FACTOR numeric(18,4);
declare variable VALEXIS varchar(10);
declare variable EXRESERV varchar(2);
declare variable IDORD integer;
declare variable ITEORD integer;
BEGIN
EXECUTE PROCEDURE lee_configuracion ('INVENTARIO', 'EXISTENCIAS', 'ACCION A TOMAR SI LA EXISTENCIA ES INSUFICIENTE') returning_values (:VALEXIS);
execute procedure lee_configuracion('COMPRAS','DOCUMENTOS','PERMITIR CANTIDADES MAYORES A LAS ORDENADAS') returning_values(:exreserv);
execute procedure lee_configuracion('INVENTARIO','ARTICULOS','COPIAR AUTOMATICAMENTE CODIGO ARTICULO COMO LOTE SI ES MAYOR A 15 CARACTERES') returning_values(:configlote);
/* BUSQUE EL CODIGO COMO ARTICULO O COMO BARRAS */

select a.ARTI_EXIST, substring(arti_des from 1 for 60), arti_descorta, arti_unidad, taiv_porc, ARTI_CONSUMO, ARTI_INVIMA, ARTI_IUM, ARTI_CUM
    from articulo a, tarifa_iva t
    where a.taiv_cod = t.taiv_cod and ARTI_COD = :CODIGO and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
    INTO :contexistart, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO, :INVIMA, :IUM, :CUM;
if (DES IS NULL) then
    begin
    select B.arti_cod, B.coba_cod, a.arti_exist, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, coba_unidad, taiv_porc, ARTI_CONSUMO, ARTI_INVIMA, ARTI_IUM, ARTI_CUM
        from articulo a, tarifa_iva t, barras_articulo b
        where a.arti_cod = b.arti_cod and a.taiv_cod = t.taiv_cod and upper(B.coba_cod) = upper(:CODIGO) and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO :codigo, :cod_barras, :contexistart, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO, :INVIMA, :IUM, :CUM;
        articulo = codigo;
    end

if (DES IS NOT NULL) then
  BEGIN
  articulo = codigo;
  EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
  /* SI HAY ORDEN VERIFIQUE QUE PERTENECE AL DOCUMENTO */
  cantord = 0;
  if (tipo = 11) then
    begin
    EXECUTE PROCEDURE ultimo_costo(:ARTICULO, CAST('NOW' AS DATE), :UNIDAD) returning_values (:COSTO);
    SELECT C.conf_valor FROM CONFIGURACION C WHERE C.conf_modulo = 'INVENTARIO' AND C.conf_categoria = 'ENTRADAS' AND C.conf_propiedad = 'VERIFICAR CODIGOS DE LA ORDEN'
        INTO :SOLOORD;
    if ((tipoord = 18) and (nroorden <> '') and (nroorden is not null)) then
        begin
        existen = null;
        for select od.orin_id, od.orid_item, od.orid_cant * od.orid_factor from ordenes_inventario o, ordeninventario_detalle od
            where o.orin_id = od.orin_id and o.orin_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and od.arti_cod = :articulo and o.orin_anulado = 'N'
            into :idord, :iteord, :cant
            do
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else
        CANTORD = 0;
    end
  if ((tipo = 12) or (TIPO = 13)) then
    begin
    SELECT C.conf_valor FROM CONFIGURACION C WHERE C.conf_modulo = 'INVENTARIO' AND C.conf_categoria = 'TRASLADOS' AND C.conf_propiedad = 'VERIFICAR CODIGOS DE LA ORDEN'
        INTO :SOLOORD;
    EXECUTE PROCEDURE costo_promedio_unidad(:ARTICULO, CAST('NOW' AS DATE), :UNIDAD) returning_values (:COSTO);
    if ((tipoord = 18) and (nroorden <> '') and (nroorden is not null)) then
        begin
        for select od.orin_id, od.orid_item, od.orid_cant * od.orid_factor from ordenes_inventario o, ordeninventario_detalle od
            where o.orin_id = od.orin_id and o.orin_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and od.arti_cod = :articulo and o.orin_anulado = 'N'
            into :idord, :iteord, :cant
            do
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else
        CANTORD = 0;
    end
  if (TIPO = 22) then
    BEGIN
    SELECT C.conf_valor FROM CONFIGURACION C WHERE C.conf_modulo = 'COMPRAS' AND C.conf_categoria = 'DOCUMENTOS' AND C.conf_propiedad = 'PERMITIR CANTIDADES MAYORES A LAS ORDENADAS'
        INTO :SOLOORD;
    if (soloord = 'SI') Then
        SOLOORD = 'NO';
    else
        SOLOORD = 'SI';
    EXECUTE PROCEDURE COSTO_PROVEEDOR (NIT, ARTICULO, 1, UNIDAD, CAST('NOW' AS DATE), 0) returning_values (:COSTO);
    if ((tipoord = 23) and (nroorden <> '') and (nroorden is not null)) then
        begin
        for select od.ordc_id, od.ocde_item, od.ocde_cant * od.ocde_factor from ordenes_compra o, ordenes_compra_detalle od
            where o.ordc_id = od.ordc_id and o.ordc_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and od.arti_cod = :articulo and o.ordc_anulado = 'N'
            into :idord, :iteord, :cant
            do
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else
        CANTORD = 0;
    END
  if (TIPO = 23) then
    BEGIN
    SELECT C.conf_valor FROM CONFIGURACION C WHERE C.conf_modulo = 'INVENTARIO' AND C.conf_categoria = 'TRASLADOS' AND C.conf_propiedad = 'VERIFICAR CODIGOS DE LA ORDEN'
        INTO :SOLOORD;
    EXECUTE PROCEDURE COSTO_PROVEEDOR (NIT, ARTICULO, 1, UNIDAD, CAST('NOW' AS DATE), 0) returning_values (:COSTO);
    if ((tipoord = 18) and (nroorden <> '') and (nroorden is not null)) then
        begin
        for select od.orin_id, od.orid_item, od.orid_cant * od.orid_factor from ordenes_inventario o, ordeninventario_detalle od
            where o.orin_id = od.orin_id and o.orin_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and od.arti_cod = :articulo and o.orin_anulado = 'N'
            into :idord, :iteord, :cant
            DO
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else
        CANTORD = 0;
    END
  if (TIPO = 32) then
    BEGIN
    SOLOORD = 'NO';
    SELECT LIPR_COD FROM CLIENTES WHERE TERC_NIT = :nit INTO :LISTA;
    if ((LISTA IS NULL) or (LISTA = 0)) then
    SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
        INTO :LISTA;
    SELECT prar_fijo FROM precios_articulo WHERE arti_cod = :articulo and lipr_cod = :LISTA INTO :COSTO;
    if ((tipoord = 31) and (nroorden <> '') and (nroorden is not null)) then
        begin
        SOLOORD = 'SI';
        for select fd.fact_id, fd.fade_item, fd.fade_cant * fd.fade_factor from facturas F, facturas_detalle fd
            where f.fact_id = fd.fact_id and f.fact_numero = right(:nroorden, 8) and f.pref_pre = left(:nroorden, strlen(:nroorden)-8)
            and fd.arti_cod = :articulo and f.fact_anulado = 'N'
            into :idord, :iteord, :cant
            DO
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else if ((tipoord = 34) and (nroorden <> '') and (nroorden is not null)) then
        begin
        SOLOORD = 'SI';
        for select PD.pedi_id, PD.pede_item, PD.pede_cant * PD.pede_factor from pedidos P, pedidos_detalle PD
            where P.pedi_id = PD.pedi_id and P.pedi_numero = right(:nroorden, 6) and P.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and PD.arti_cod = :articulo and P.pedi_anulado = 'N'
            into :idord, :iteord, :cant
            DO
            BEGIN
            execute procedure faltante(:tipoord, :tipo, :idord, :iteord) returning_values (cant, unidad, factor);
            cantord = cantord + cant;
            END
        end
    else
        CANTORD = 0;
    END

  EXECUTE PROCEDURE saldo_inventario (:articulo, :CODBOD, CAST('NOW' AS DATE)) returning_values (:EXISTEN);
  SUSPEND;
  END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure TRAE_ARTICULO_MOVILV_FAC (
    CODIGO varchar(20),
    VEND integer,
    CLIENTE varchar(20),
    SUCUCLI varchar(10),
    IDPEDWEB integer)
returns (
    DES varchar(60),
    DESCORTA varchar(30),
    UNIDAD varchar(8),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    LISTA integer,
    PRECIO numeric(18,2),
    NOMLISTA varchar(30),
    NUMREP integer,
    CODREP char(2),
    VALEXISTEVENTART char(1),
    CONTEXISTART char(1),
    DTO1 numeric(9,2),
    DTO2 numeric(9,2),
    DTO3 numeric(9,2),
    CONTROLEXISPED char(2),
    ARTICULO varchar(20))
as
declare variable DIG integer;
declare variable CODBOD varchar(2);
declare variable FECHA date;
declare variable RESERVADO numeric(18,2);
declare variable EXRESERV varchar(10);
declare variable VALIDEZ integer;
declare variable CANT numeric(18,4);
declare variable GRUPO varchar(30);
declare variable SUBGR varchar(30);
declare variable MARCA varchar(30);
declare variable ENSAMBLE char(1);
BEGIN
execute procedure lee_configuracion('FACTURACION','DOCUMENTOS','PERMITIR VARIAS OCURRENCIAS DEL MISMO ARTICULO EN UN DOCUMENTO') returning_values(:codrep);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
execute procedure lee_configuracion('INVENTARIO','EXISTENCIAS','ACCION A TOMAR SI LA EXISTENCIA ESTA RESERVADA') returning_values(:exreserv);
execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'DIAS DE VALIDEZ') returning_values (VALIDEZ);
SELECT LIPR_COD FROM CLIENTE_SUCURSALES WHERE TERC_NIT = :CLIENTE AND CLCU_COD = :SUCUCLI INTO :LISTA;
if ((LISTA IS NULL) or (LISTA = 0)) then
    SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
        INTO :LISTA;
SELECT LIPR_NOM FROM LISTA_PRECIOS WHERE LIPR_COD = :LISTA INTO :NOMLISTA;
if (LISTA > 0) then
    BEGIN
    select ARTI_EXIST, arti_des, arti_descorta, arti_unidad, taiv_porc, ARTI_CONSUMO, arti_ensamble
        from articulo a, tarifa_iva t
        where a.taiv_cod = t.taiv_cod and ARTI_COD = :CODIGO and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO CONTEXISTART, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO, :ENSAMBLE;
       if (DES IS NULL) then
        begin
         select B.arti_cod, ARTI_EXIST, arti_des, arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, arti_ensamble
                from articulo a, tarifa_iva t, barras_articulo B
                where a.arti_cod = b.arti_cod and a.taiv_cod = t.taiv_cod and upper(B.coba_cod) = upper(:CODIGO) and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
                INTO :codigo, :CONTEXISTART, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :ENSAMBLE;
            articulo = codigo;
        end
            if (CONTEXISTART = 'N') then
        CONTROLEXISPED = 'NO';
        else
        CONTROLEXISPED = 'NO';

    if (DES IS NOT NULL) then
        BEGIN
        articulo = codigo;
        SELECT PRAR_DTO1 FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P, VENDEDORES V
        WHERE L.LIPR_COD = P.LIPR_COD AND ARTI_COD = :ARTICULO AND V.vend_cod = :VEND and P.arti_cod = :articulo AND P.lipr_cod = :lista into :DTO1;
        SELECT PRAR_DTO2 FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P, VENDEDORES V
        WHERE L.LIPR_COD = P.LIPR_COD AND ARTI_COD = :ARTICULO AND V.vend_cod = :VEND and P.arti_cod = :articulo AND P.lipr_cod = :lista into :DTO2;
        DTO3 = 0;
        EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
        PRECIO = 0;
        EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
        SELECT FIRST 1 BODE_COD FROM punto_venta PT, VENDEDORES V WHERE ((PT.ptvt_id = V.ptvt_id) or (V.sucu_id = 0))  AND V.vend_cod = :VEND INTO :CODBOD;
        FECHA = CAST('NOW' AS DATE);
        if (:CONTEXISTART = 'N' or (ENSAMBLE = 'S')) then
          EXISTEN = 99999;
        ELSE
          BEGIN
          EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
          END
        if (:exreserv = 'PROHIBIR') then
            BEGIN
            RESERVADO = 0;
            SELECT SUM(RESERVADO) FROM EXISTENCIAS_UNIDAD(:CODIGO, :FECHA, :UNIDAD) INTO :RESERVADO;
            EXISTEN = EXISTEN - RESERVADO;
            END
        SELECT COUNT(ARTI_COD) FROM PEDIDO_WEB_DETALLE WHERE ARTI_COD = :codigo AND PEWE_ID = :idpedweb into :NUMREP;
        SUSPEND;
        END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure TRAE_ARTICULO_MOVILV2 (
    CODIGO varchar(20),
    VEND integer,
    CLIENTE varchar(20),
    SUCUCLI varchar(10),
    IDPEDWEB integer,
    CODBOD T_BODEGA)
returns (
    ARTICULO varchar(20),
    DES varchar(300),
    DESCORTA varchar(30),
    UNIDAD varchar(8),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    LISTA integer,
    PRECIO numeric(18,2),
    NOMLISTA varchar(30),
    NUMREP integer,
    CODREP char(2),
    VALEXISTEVENTART char(1),
    CONTEXISTART char(1),
    DTOP numeric(9,2),
    DTO1 numeric(9,2),
    DTO2 numeric(9,2),
    DTO3 numeric(9,2),
    CONTROLEXISPED char(2),
    ESCALA T_BOOLEANO,
    CAMBIOS smallint,
    FACTOR_CANTIDAD numeric(18,4),
    FACTOR_PRECIO numeric(18,4),
    TOTALITEMS varchar(30),
    IMPUP T_PORCENTAJE,
    IMPBA T_PORCENTAJE)
as
declare variable REPART varchar(10);
declare variable DIG integer;
declare variable FECHA date;
declare variable FECHAAUX date;
declare variable EXISTOT varchar(6);
declare variable RESERPEDWEB char(2);
declare variable RESERVADO numeric(18,2);
declare variable EXISPED char(2);
declare variable EXRESERV varchar(10);
declare variable VALIDEZ integer;
declare variable VERSINEX char(2);
declare variable CANTPEDWEB numeric(18,4);
declare variable CANT numeric(18,4);
declare variable FACTORU numeric(18,4);
declare variable GRUPO varchar(30);
declare variable SUBGR varchar(30);
declare variable MARCA varchar(30);
declare variable ENSAMBLE char(1);
declare variable UNIPVTA char(1);
BEGIN
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIAS DESDE EL PEDIDO') returning_values (:EXISPED);
execute procedure lee_configuracion('FACTURACION','DOCUMENTOS','PERMITIR VARIAS OCURRENCIAS DEL MISMO ARTICULO EN UN DOCUMENTO') returning_values(:repart);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (VERSINEX);
execute procedure lee_configuracion('INVENTARIO','EXISTENCIAS','ACCION A TOMAR SI LA EXISTENCIA ESTA RESERVADA') returning_values(:exreserv);
execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'DIAS DE VALIDEZ') returning_values (VALIDEZ);
execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'RESERVAR MERCANCIA CON PEDIDO WEB SIN CONFIRMAR') returning_values (:RESERPEDWEB);
execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'NUMERO DE ITEMS EN PEDIDO') returning_values (:TOTALITEMS);

if ((codbod = '') or (codbod IS NULL)) then
SELECT BODE_COD from punto_venta p, vendedores v WHERE v.vend_cod = :vend and v.PTVT_ID = p.ptvt_id into :codbod ;

if (repart = 'SI') then
    CODREP = 'SI';
ELSE
    CODREP = 'NO';
SELECT ARTI_ENSAMBLE FROM ARTICULO WHERE ARTI_COD = :CODIGO INTO :ENSAMBLE;
if (EXISPED = 'NO') then
    BEGIN
    SELECT ARTI_EVEXIS FROM ARTICULO WHERE ARTI_COD = :CODIGO INTO :VALEXISTEVENTART;
    if (VALEXISTEVENTART = 'S') then
        EXISPED = 'SI';
    END
CONTROLEXISPED = EXISPED;
SELECT LIPR_COD FROM CLIENTE_SUCURSALES WHERE TERC_NIT = :CLIENTE AND CLCU_COD = :SUCUCLI INTO :LISTA;
if ((LISTA IS NULL) or (LISTA = 0)) then
    SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
        INTO :LISTA;
SELECT LIPR_NOM FROM LISTA_PRECIOS WHERE LIPR_COD = :LISTA INTO :NOMLISTA;
if (LISTA > 0) then
    BEGIN
    select ARTI_EXIST, arti_des, arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, arti_unipvta, ARTI_IMPUP, ARTI_IMPBA
        from articulo a, tarifa_iva t
        where a.taiv_cod = t.taiv_cod and ARTI_COD = :CODIGO and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO CONTEXISTART, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :unipvta, :impup, :impba;
    if (DES IS NULL) then
        begin
         select B.arti_cod, ARTI_EXIST, arti_des, arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, arti_ensamble, arti_unipvta, ARTI_IMPUP, ARTI_IMPBA
                from articulo a, tarifa_iva t, barras_articulo B
                where a.arti_cod = b.arti_cod and a.taiv_cod = t.taiv_cod and upper(B.coba_cod) = upper(:CODIGO) and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
                INTO :codigo, :CONTEXISTART, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :ENSAMBLE, :unipvta, :impup, :IMPBA;
            articulo = codigo;
        end

    if (DES IS NOT NULL) then
      BEGIN
        articulo = codigo;
        dtop = 0;
        SELECT PRAR_DTO1 FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P, VENDEDORES V
        WHERE L.LIPR_COD = P.LIPR_COD AND ARTI_COD = :ARTICULO AND V.vend_cod = :VEND and P.arti_cod = :articulo AND P.lipr_cod = :lista into :DTO1;
        SELECT PRAR_DTO2 FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P, VENDEDORES V
        WHERE L.LIPR_COD = P.LIPR_COD AND ARTI_COD = :ARTICULO AND V.vend_cod = :VEND and P.arti_cod = :articulo AND P.lipr_cod = :lista into :DTO2;
        DTO3 = 0;
        EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
         if (unipvta = 'N') then
            begin
                EXECUTE PROCEDURE unidades_ventas(codigo) returning_values (:UNIDAD, :factor_cantidad, :factor_precio);
            end
        if ((:grupo is null)or (:grupo = '') ) then
            begin
            SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :GRUPO INTO GRUPO;
            EXECUTE PROCEDURE NOMBRE_ASCII(GRUPO) returning_values (GRUPO);
            end
        if ((:marca is null)or (:marca = '') ) then
            begin
            SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :MARCA INTO MARCA;
            EXECUTE PROCEDURE NOMBRE_ASCII(SUBGR) returning_values (SUBGR);
            end
        if ((:subgr is null)or(:subgr = '')) then
            begin
            SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :SUBGR AND GRUP_COD = :GRUPO INTO :SUBGR;
            EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
            end
        PRECIO = 0;
        SELECT prar_fijo, PRAR_ESCALAS PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO, :ESCALA;
        EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
        --CODBOD = NULL;
        /*SELECT FIRST 1 BODE_COD FROM punto_venta PT, VENDEDORES V WHERE ((PT.sucu_id = V.sucu_id) or (V.sucu_id = 0)) AND V.vend_cod = :VEND and v.ptvt_id = pt.ptvt_id
            INTO :CODBOD; */
        if (CODBOD IS NULL) then
            SELECT FIRST 1 BODE_COD FROM punto_venta PT, VENDEDORES V WHERE ((PT.sucu_id = V.sucu_id) or (V.sucu_id = 0)) AND V.vend_cod = :VEND
                INTO :CODBOD;
        FECHA = CAST('NOW' AS DATE);
        if ((:CONTEXISTART = 'N') OR (:exisped = 'NO') or (ENSAMBLE = 'S')) then
          EXISTEN = 99999;
        ELSE
          BEGIN
          if (EXISTOT = 'TOTAL') then
            begin
                EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
            --EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
            end
          ELSE
            begin
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            --EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            end
          EXECUTE PROCEDURE factor_unidad_cant(:codigo,  :UNIDAD) returning_values (:factoru);
          EXISTEN = EXISTEN / factoru;
          END
        if (:exreserv = 'PROHIBIR') then
            BEGIN
            RESERVADO = 0;
            SELECT SUM(RESERVADO) FROM EXISTENCIAS_UNIDAD_WEB(:CODIGO, :FECHA, :UNIDAD) WHERE ((BODEGA = :CODBOD) or (:existot = 'TOTAL'))
                INTO :RESERVADO;
            if (reservado is null) then
                reservado = 0;
            EXISTEN = EXISTEN - RESERVADO;
            END
        SELECT COUNT(AP.arpr_item) FROM articulos_producto AP WHERE AP.arti_cod = :codigo AND ((AP.arpr_preguntar = 'S') or (AP.arpr_quitar = 'S'))
            INTO :CAMBIOS;
        if ((EXISTEN > 0) OR (VERSINEX = 'SI')) then
            BEGIN
            SELECT COUNT(ARTI_COD) FROM PEDIDO_WEB_DETALLE WHERE ARTI_COD = :codigo AND PEWE_ID = :idpedweb into :NUMREP;
            SUSPEND;
            END
      END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure TRAE_ARTICULO_MOVIL (
    CODIGO varchar(20),
    VEND integer,
    CLIENTE varchar(20),
    SUCUCLI varchar(10),
    IDPEDWEB integer)
returns (
    DES varchar(60),
    DESCORTA varchar(30),
    CODGRUPO varchar(2),
    GRUPO varchar(30),
    CODSUBGR varchar(3),
    SUBGR varchar(30),
    CODMARCA varchar(3),
    MARCA varchar(30),
    UNIDAD varchar(8),
    ALTERNATIVA varchar(30),
    BARRAS varchar(50),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    LISTA integer,
    PRECIO numeric(18,2),
    OBS varchar(1024),
    NOMLISTA varchar(30),
    OK integer,
    VALEXIST char(1),
    CODART varchar(20))
as
declare variable DIG integer;
declare variable CODBOD varchar(2);
declare variable FECHA date;
declare variable FECHAAUX date;
declare variable EXISTOT varchar(6);
declare variable CONTEXIST char(1);
declare variable RESERPEDWEB char(2);
declare variable RESERVADO numeric(18,2);
declare variable CODREP char(2);
declare variable EXISPED char(2);
declare variable EXRESERV varchar(10);
declare variable VALIDEZ integer;
declare variable CANTPEDWEB numeric(18,4);
declare variable CANT numeric(18,4);
BEGIN
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIAS DESDE EL PEDIDO') returning_values (:EXISPED);
SELECT FIRST 1 CODLISTA FROM LISTAS_ARTICULO_WEB(:codigo,  :VEND, :cliente) where OK = 'S' INTO :LISTA;
if ((LISTA IS NULL) or (LISTA = 0)) then
    BEGIN
    SELECT LIPR_COD FROM CLIENTE_SUCURSALES WHERE TERC_NIT = :CLIENTE AND CLCU_COD = :SUCUCLI INTO :LISTA;
    if ((LISTA IS NULL) or (LISTA = 0)) then
        SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
            INTO :LISTA;
    END
SELECT LIPR_NOM FROM LISTA_PRECIOS WHERE LIPR_COD = :LISTA INTO :NOMLISTA;
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
if (LISTA > 0) then
    BEGIN
    select ARTI_EXIST, substring(arti_des from 1 for 60), arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, CAST(ARTI_OBS AS VARCHAR(1024))
        from articulo a, tarifa_iva t
        where a.taiv_cod = t.taiv_cod and ARTI_COD = :CODIGO and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO CONTEXIST, :DES, :DESCORTA, :CODGRUPO, :CODSUBGR, :UNIDAD, :IVA, :CODMARCA, :CONSUMO, :OBS;
    if (DES IS NULL) then
        begin
        barras = :codigo;
        select arti_cod from barras_articulo where coba_cod = :barras and coba_activo = 'S' into :codigo;
        select ARTI_EXIST, substring(arti_des from 1 for 60), arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, CAST(ARTI_OBS AS VARCHAR(1024))
        from articulo a, tarifa_iva t
        where a.taiv_cod = t.taiv_cod and ARTI_COD = :CODIGO and ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO CONTEXIST, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :OBS;
        CODART = :CODIGO;
        end
    else
      CODART = :CODIGO;
    SELECT FIRST 1 COBA_COD FROM BARRAS_ARTICULO B WHERE B.ARTI_COD = :CODART AND B.coba_activo = 'S'
        INTO :BARRAS;
    if (BARRAS IS NULL) then
        BARRAS = '';
    if (DES IS NULL) then
        DES = '';
    else
        BEGIN
        if (EXISPED = 'NO') then
            BEGIN
            SELECT ARTI_EVEXIS FROM ARTICULO WHERE ARTI_COD = :CODIGO INTO :valexist;
            if (VALEXIST is null) then
                VALEXIST = 'S';
            if (VALEXIST = 'S') then
                EXISPED = 'SI';
            END
        ELSE
            begin
            SELECT ARTI_EVEXIS FROM ARTICULO WHERE ARTI_COD = :CODIGO INTO :valexist;
            if (VALEXIST is null) then
                VALEXIST = 'S';
            end
        EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
        SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :CODGRUPO INTO GRUPO;
        EXECUTE PROCEDURE NOMBRE_ASCII(GRUPO) returning_values (GRUPO);

        if ((:codmarca is not null) and (:codmarca <> '') ) then
            begin
            SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMARCA INTO MARCA;
            EXECUTE PROCEDURE NOMBRE_ASCII(SUBGR) returning_values (SUBGR);
            end
        if ((:codsubgr is not null) and (:codsubgr <> '')) then
            begin
            SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :CODSUBGR AND GRUP_COD = :CODGRUPO INTO :SUBGR;
            EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
            end
        ALTERNATIVA = '';
        select FIRST 1 unar_unidad || ' x ' || unar_faccan FROM unidad_articulo WHERE ARTI_COD = :codigo INTO :alternativa;
        PRECIO = 0;
        SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
        EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
        SELECT FIRST 1 BODE_COD FROM punto_venta PT, VENDEDORES V WHERE ((PT.sucu_id = V.sucu_id) or (V.sucu_id = 0))  AND V.vend_cod = :VEND INTO :CODBOD;
        if (codbod is null) then
            execute procedure lee_configuracion('FACTURACION','PEDIDOS', 'CODIGO BODEGA A USAR EN PEDIDOS APP') returning_values (CODBOD);
        FECHA = CAST('NOW' AS DATE);
        if ((:contexist = 'N') OR (:exisped = 'NO')) then
            EXISTEN = 99999;
        ELSE
        BEGIN
        if (EXISTOT = 'TOTAL') then
            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
        ELSE
            EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
        END
        execute procedure lee_configuracion('INVENTARIO','EXISTENCIAS','ACCION A TOMAR SI LA EXISTENCIA ESTA RESERVADA') returning_values(:exreserv);
        if (:exreserv = 'PROHIBIR') then
            BEGIN
            RESERVADO = 0;
            SELECT SUM(RESERVADO) FROM EXISTENCIAS_UNIDAD(:CODIGO, :FECHA, :UNIDAD) WHERE ((BODEGA = :CODBOD) or (:existot = 'TOTAL'))
                INTO :RESERVADO;
            execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'RESERVAR MERCANCIA CON PEDIDO WEB SIN CONFIRMAR') returning_values (:RESERPEDWEB);
            if (RESERPEDWEB = 'SI') then
                BEGIN
                execute procedure LEE_CONFIGURACION('FACTURACION', 'PEDIDOS', 'DIAS DE VALIDEZ') returning_values (VALIDEZ);
                CANTPEDWEB = 0;
                FECHAAUX = :FECHA - :VALIDEZ;
                for select PD.pewd_cant * PD.pewd_factor
                    from PEDIDO_WEB P, pedido_web_detalle PD, EVENTOS_VENTAS E, ARTICULO A
                    where P.pewe_id = PD.pewe_id and PD.arti_cod = :CODIGO and P.pewe_fecha >= (:FECHAAUX) AND PEWE_FECHA <= :FECHA
                    AND P.pewe_idped = 0 AND ((P.PEWE_EVENTO = E.EVVE_ID) or (P.PEWE_EVENTO IS NULL)) AND PD.arti_cod = A.arti_cod
                    AND ((E.EVVE_EXIS = 'S') or (E.EVVE_EXIS IS NULL) or (A.arti_evexis = 'S')) AND PEWD_ANULADO = 'N'
                    AND ((PD.bode_cod = :codbod) or (:EXISTOT = 'TOTAL'))
                    into :CANT
                    do
                    begin
                    CANTPEDWEB = CANTPEDWEB + CANT;
                    end
                RESERVADO = RESERVADO + CANTPEDWEB;
                END
            EXISTEN = EXISTEN - RESERVADO;
            END
        execute procedure lee_configuracion('FACTURACION','DOCUMENTOS','PERMITIR VARIAS OCURRENCIAS DEL MISMO ARTICULO EN UN DOCUMENTO') returning_values(:codrep);
        if (:codrep = 'NO') then
            SELECT COUNT(ARTI_COD) FROM PEDIDO_WEB_DETALLE WHERE ARTI_COD = :codigo AND PEWE_ID = :idpedweb into :OK;
        else
            OK = 0;
        END
    SUSPEND;

    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure TRAE_ARTICULOS_MOVIL_OFFLINE
returns (
    CODIGO varchar(20),
    DES varchar(60),
    DESCORTA varchar(30),
    GRUPO varchar(30),
    SUBGR varchar(3),
    MARCA varchar(30),
    UNIDAD varchar(8),
    ALTERNATIVA varchar(30),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    PRECIO numeric(18,2),
    VALEXIEV char(1),
    CTREXIART char(1),
    CODREP char(2),
    EXISPED char(2),
    VEREXIST char(2),
    SINEXIST char(2))
as
DECLARE VARIABLE LISTA INTEGER;
DECLARE VARIABLE EXIST CHAR(2);
declare variable DIG INTEGER;
declare variable OK CHAR(1);
declare variable FECHA DATE;
declare variable CODBOD VARCHAR(2);
declare variable EXISTOT VARCHAR(6);
BEGIN
EXISTEN = 0;
FECHA = cast('now' as DATE);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:VEREXIST);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (:SINEXIST);
execute procedure lee_configuracion('FACTURACION','DOCUMENTOS','PERMITIR VARIAS OCURRENCIAS DEL MISMO ARTICULO EN UN DOCUMENTO') returning_values(:CODREP);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIAS DESDE EL PEDIDO') returning_values (:EXISPED);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:EXIST);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
if (LISTA > 0) then
    BEGIN
        FOR select a.arti_cod, substring(arti_des from 1 for 60), arti_descorta, arti_unidad, grup_cod, subg_cod, taiv_porc, marc_cod, ARTI_CONSUMO, ARTI_EVEXIS, ARTI_EXIST
            from articulo a, tarifa_iva t where a.taiv_cod = t.taiv_cod
            and substring(a.arti_cod from 1 FOR 2) <> '.t' and ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))
            INTO :CODIGO, :DES, :DESCORTA, :UNIDAD, :GRUPO, :SUBGR, :IVA, :MARCA, :CONSUMO, VALEXIEV, CTREXIART
            do                                                                                         
            begin
            if (VALEXIEV IS NULL) then
              VALEXIEV = 'N';
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            EXECUTE PROCEDURE NOMBRE_ASCII(UNIDAD) returning_values (UNIDAD);
            EXECUTE PROCEDURE NOMBRE_ASCII(CODIGO) returning_values (CODIGO);
            SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :GRUPO INTO GRUPO;
            SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :MARCA INTO MARCA;
            SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :SUBGR AND GRUP_COD = :GRUPO INTO :SUBGR;
            EXECUTE PROCEDURE NOMBRE_ASCII(GRUPO) returning_values (GRUPO);
            EXECUTE PROCEDURE NOMBRE_ASCII(SUBGR) returning_values (SUBGR);
            EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
            ALTERNATIVA = '';
            select FIRST 1 unar_unidad || ' x ' || unar_faccan FROM unidad_articulo WHERE ARTI_COD = :codigo INTO :alternativa;
            OK = 'N';
            PRECIO = 0;
            SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
            EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
            if (EXIST = 'SI') then
                BEGIN                                           
                if (EXISTOT = 'TOTAL') then
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                ELSE
                    BEGIN
                    select first 1 P.bode_cod from punto_venta p, usuario u where u.user_cod = USER and u.sucu_id = p.sucu_id into :codbod;
                    EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
                    END
                if ((SINEXIST = 'SI')  or (existen <> 0)) then
                    OK = 'S';
                END
            ELSE
                OK = 'S';
            if (ok = 'S') then
                SUSPEND;
            end
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REP_SISMED (
    ANO char(4),
    MESINI integer,
    MESFIN integer,
    AGENCIA integer)
returns (
    ITEM integer,
    MES integer,
    CUM varchar(30),
    IUM1 varchar(8),
    IUM2 varchar(4),
    IUM3 varchar(3),
    PRMIN numeric(18,2),
    PRMAX numeric(18,2),
    VENTAS numeric(18,2),
    CANTIDAD numeric(18,2),
    FACMIN varchar(12),
    FACMAX varchar(12),
    NUMMED integer,
    OPER char(2),
    EXPEDIENTE varchar(8),
    PRECOM varchar(3))
as
declare variable CODIGO VARCHAR(20);
declare variable FECINI DATE;
declare variable FECFIN DATE;
declare variable NUMMES INTEGER;
declare variable POSEXP INTEGER;
declare variable CUMAUX varchar(18);
begin
ITEM = 0;
/* REPORTAR VENTAS */
NUMMES = MESINI;
WHILE (NUMMES <= MESFIN) DO
    BEGIN
    MES = :NUMMES;
    /*if (NUMMES < 10) then
        MES = '0' || :NUMMES;
    ELSE
        MES = :NUMMES;*/
    FECINI = ANO || '/' || nummes || '/01';
    FECFIN = FECINI + 31;
    FECFIN = :FECFIN - EXTRACT(DAY FROM :FECFIN) + 1;
    SELECT COUNT(ARTI_COD) FROM ARTICULO A WHERE (ARTI_CUM <> '') AND (ESAR_COD <> 'I') INTO :NUMMED;
    FOR SELECT ARTI_COD, ARTI_CUM, SUBSTRING(ARTI_IUM from 1 for 8), SUBSTRING(ARTI_IUM from 9 for 4), SUBSTRING(ARTI_IUM from 13 for 3),
        POSITION('-' IN ARTI_CUM) FROM ARTICULO A WHERE (ARTI_CUM <> '') AND (ARTI_CUM IS NOT NULL) AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO :CODIGO, :CUMAUX, :IUM1, :IUM2, :IUM3, :POSEXP
        DO
        BEGIN
        if (POSEXP IS NOT NULL AND POSEXP <> 0) then
          begin
          CUM = SUBSTRING(:CUMAUX FROM 1 FOR :POSEXP-1);
          EXPEDIENTE = SUBSTRING(:CUMAUX FROM :POSEXP+1 FOR STRLEN(:CUMAUX));
          end
        else
          begin
          CUM = :CUMAUX;
          EXPEDIENTE = 0;
          end
        CANTIDAD = 0;
        FACMIN = '0';
        FACMAX = '0';
        VENTAS = 0;
        PRMIN = 0;
        PRMAX = 0;
        if ((IUM1 IS NULL) or (IUM1 = '')) THEN
          IUM1 = '0';
        if ((IUM2 IS NULL) or (IUM2 = '')) THEN
          IUM2 = '0';
        if ((IUM3 IS NULL) or (IUM3 = '')) THEN
          IUM3 = '0';
        PRECOM = IUM3;
        OPER = 'VN';
        SELECT SUM(D.fade_cant* D.FADE_FACTOR), SUM(D.fade_total-D.fade_ivamonto), MIN(D.fade_prunit/D.fade_factor), MAX(D.fade_prunit/D.fade_factor)
            FROM FACTURAS F, FACTURAS_DETALLE D, PREFIJOS P WHERE F.fact_id = D.fact_id AND D.arti_cod = :CODIGO
            AND F.fact_fecha >= :FECINI AND F.fact_fecha <= :FECFIN AND F.fact_anulado = 'N' AND D.fade_prunit <> 0
            AND P.tido_cod = 31 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA)) AND PTVT_ID = 1
            INTO :CANTIDAD, :VENTAS, :PRMIN, :PRMAX;
        if (cantidad is null) then
            cantidad = 0;
        if (ventas is null) then
            ventas = 0;
        if (prmin is null) then
            prmin = 0;
        if (prmax is null) then
            prmax = 0;
        if (cantidad <> 0) then
            begin
            select MIN(F.pref_pre || F.fact_numero) from FACTURAS F, FACTURAS_DETALLE D, PREFIJOS P
                WHERE F.fact_id = D.fact_id AND D.arti_cod = :CODIGO AND round((D.fade_prunit/D.fade_factor),2) = :PRMIN
                AND F.fact_fecha >= :FECINI AND F.fact_fecha <= :FECFIN AND F.fact_anulado = 'N' AND PTVT_ID = 1
                AND P.tido_cod = 31 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
                INTO :FACMIN;
            select MAX(F.pref_pre || F.fact_numero) from FACTURAS F, FACTURAS_DETALLE D, PREFIJOS P
                WHERE F.fact_id = D.fact_id AND D.arti_cod = :CODIGO AND ROUND((D.fade_prunit/D.fade_factor),2) = :prmax
                AND F.fact_fecha >= :FECINI AND F.fact_fecha <= :FECFIN AND F.fact_anulado = 'N' AND PTVT_ID = 1
                AND P.tido_cod = 31 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
                INTO :facmax;
            end
        else
            if (CANTIDAD = 0 or CANTIDAD IS NULL) then
                BEGIN
                   PRMIN = 0;
                   PRMAX = 0;
                   VENTAS = 0;
                   FACMIN = 0;
                   FACMAX = 0;
                END
        if (PRMIN <> 0 AND facmax IS NOT NULL AND facmin IS NOT NULL) then
          BEGIN
          ITEM = ITEM + 1;
          suspend;
          END
        END
    NUMMES = NUMMES + 1;
    END
/* REPORTAR COMPRAS */
NUMMES = MESINI;
WHILE (NUMMES <= MESFIN) DO
    BEGIN
    MES = :NUMMES;
    /*if (NUMMES < 10) then
        MES = '0' || :NUMMES;
    ELSE
        MES = :NUMMES;*/
    FECINI = ANO || '/' || nummes || '/01';
    FECFIN = FECINI + 31;
    FECFIN = :FECFIN - EXTRACT(DAY FROM :FECFIN) + 1;
    FOR SELECT ARTI_COD, ARTI_CUM, SUBSTRING(ARTI_IUM from 1 for 8), SUBSTRING(ARTI_IUM from 9 for 4), SUBSTRING(ARTI_IUM from 13 for 3),
        POSITION('-' IN ARTI_CUM) FROM ARTICULO A WHERE (ARTI_CUM <> '') AND (ARTI_CUM IS NOT NULL) AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO :CODIGO, :CUMAUX, :IUM1, :IUM2, :IUM3, :POSEXP
        DO
        BEGIN
        if (POSEXP IS NOT NULL AND POSEXP <> 0) then
          begin
          CUM = SUBSTRING(:CUMAUX FROM 1 FOR :POSEXP-1);
          EXPEDIENTE = SUBSTRING(:CUMAUX FROM :POSEXP+1 FOR STRLEN(:CUMAUX));
          end
        else
          begin
          CUM = :CUMAUX;
          EXPEDIENTE = 0;
          end
        CANTIDAD = 0;
        FACMIN = '0';
        FACMAX = '0';
        VENTAS = 0;
        PRMIN = 0;
        PRMAX = 0;
        if ((IUM1 IS NULL) or (IUM1 = '')) THEN
          IUM1 = '0';
        if ((IUM2 IS NULL) or (IUM2 = '')) THEN
          IUM2 = '0';
        if ((IUM3 IS NULL) or (IUM3 = '')) THEN
          IUM3 = '0';
        PRECOM = IUM3;
        OPER = 'CM';
        SELECT SUM(D.fcde_cant* D.fcde_factor), SUM(D.fcde_total-D.fcde_ivamonto), MIN(D.fcde_prunit/D.fcde_factor), MAX(D.fcde_prunit/D.fcde_factor)
            FROM facturas_compra F, facturas_compras_detalle D, prefijos P WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO
            AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' AND FACO_CONFIRMA = 'S'
            AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
            INTO :CANTIDAD, :VENTAS, :PRMIN, :PRMAX;
        if (cantidad is null) then
            cantidad = 0;
        if (ventas is null) then
            ventas = 0;
        if (prmin is null) then
            prmin = 0;
        if (prmax is null) then
            prmax = 0;
        if (cantidad <> 0) then
            begin
            select MIN(F.pref_pre || F.faco_numero) FROM facturas_compra F, facturas_compras_detalle D, prefijos P
                WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO AND (D.fcde_prunit / D.fcde_factor) = :prmin
                AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' AND FACO_CONFIRMA = 'S'
                AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
                INTO :FACMIN;
             select MAX(F.pref_pre || F.faco_numero) FROM facturas_compra F, facturas_compras_detalle D, prefijos P
               WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO AND (D.fcde_prunit / D.fcde_factor) = :prmax
                AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' AND FACO_CONFIRMA = 'S'
                AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
                INTO :facmax;
            end
        else
            if (CANTIDAD = 0 or CANTIDAD IS NULL) then
                BEGIN
                   PRMIN = 0;
                   PRMAX = 0;
                   VENTAS = 0;
                   FACMIN = 0;
                   FACMAX = 0;
                END
        if (PRMIN <> 0 AND facmax IS NOT NULL AND facmin IS NOT NULL) then
          BEGIN
          ITEM = ITEM + 1;
          suspend;
          END
        END
    NUMMES = NUMMES + 1;
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REP_PRECIOS_TODOS (
    ARTINI varchar(20),
    ARTFIN varchar(20),
    GRPINI varchar(2),
    GRPFIN varchar(2),
    ORDEN char(1),
    LINI integer,
    LFIN integer,
    FECHA date,
    MASIVA char(1))
returns (
    CODIGO varchar(15),
    NOMBRE varchar(300),
    UNIDAD varchar(8),
    CODGRUPO varchar(2),
    NOMGRUPO varchar(30),
    CODSUBG varchar(3),
    NOMSUBG varchar(30),
    CODMARC varchar(3),
    NOMMARC varchar(30),
    PRECIO1 numeric(18,2),
    PRECIO2 numeric(18,2),
    PRECIO3 numeric(18,2),
    PRECIO4 numeric(18,2),
    PRECIO5 numeric(18,2),
    PRECIO6 numeric(18,2),
    PRECIO7 numeric(18,2),
    PRECIO8 numeric(18,2),
    PRECIO9 numeric(18,2),
    MARGEN1 numeric(9,2),
    MARGEN2 numeric(9,2),
    MARGEN3 numeric(9,2),
    MARGEN4 numeric(9,2),
    MARGEN5 numeric(9,2),
    MARGEN6 numeric(9,2),
    MARGEN7 numeric(9,2),
    MARGEN8 numeric(9,2),
    MARGEN9 numeric(9,2),
    IVA numeric(9,2),
    COSTOP numeric(18,2),
    UCOSTO numeric(18,2),
    MENOR varchar(60))
as
declare variable CODINI VARCHAR(20);
declare variable CODFIN VARCHAR(20);
declare variable DESINI VARCHAR(20);
declare variable DESFIN VARCHAR(20);
declare variable UTIL NUMERIC(9,2);
declare variable MOU CHAR(10);
declare variable LISIVA CHAR(2);
declare variable i integer;
declare variable PRECIO NUMERIC(18,2);
declare variable MARGEN NUMERIC(18,4);
BEGIN
if (ORDEN = 'C') then
    BEGIN
    CODINI = ARTINI;
    CODFIN = ARTFIN;
    DESINI = '';
    DESFIN = 'zz';
    END
ELSE
    BEGIN
    DESINI = ARTINI;
    DESFIN = ARTFIN;
    CODINI = '';
    CODFIN = 'zz';
    END
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'SUGERIR PRECIOS CON PORCENTAJE DE MARGEN O UTILIDAD') returning_values (MOU);
FOR SELECT a.ARTI_COD, ARTI_DES, ARTI_UNIDAD, GRUP_COD, SUBG_COD, MARC_COD, TAIV_PORC
    FROM ARTICULO A, TARIFA_IVA T
    WHERE A.ARTI_COD >= :CODINI AND A.ARTI_COD <= :CODFIN AND A.GRUP_COD >= :GRPINI AND A.GRUP_COD <= :GRPFIN AND
    ARTI_DES >= :DESINI AND ARTI_DES <= :DESFIN AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K')) AND A.TAIV_COD = T.TAIV_COD
    ORDER BY ARTI_COD
    INTO :CODIGO, :NOMBRE, :UNIDAD, :CODGRUPO, :CODSUBG, :CODMARC, :IVA
    DO
    BEGIN
    SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :CODGRUPO INTO NOMGRUPO;
    SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMARC INTO NOMMARC;
    SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :CODSUBG AND GRUP_COD = :CODGRUPO INTO :NOMSUBG;
    I = 0;
    PRECIO1 = 0;
    PRECIO2 = 0;
    PRECIO3 = 0;
    PRECIO4 = 0;
    PRECIO5 = 0;
    PRECIO6 = 0;
    PRECIO7 = 0;
    PRECIO8 = 0;
    PRECIO9 = 0;
    MARGEN1 = 0;
    MARGEN2 = 0;
    MARGEN3 = 0;
    MARGEN4 = 0;
    MARGEN5 = 0;
    MARGEN6 = 0;
    MARGEN7 = 0;
    MARGEN8 = 0;
    MARGEN9 = 0;
    FOR SELECT PRAR_FIJO, PRAR_MARGEN, PRAR_UTIL, LIPR_MODIF
        FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P
        WHERE L.LIPR_COD = P.LIPR_COD AND p.arti_cod = :codigo and l.lipr_cod >= :lini and l.lipr_cod <= :lfin
        ORDER BY L.LIPR_COD
        INTO :PRECIO, :MARGEN, :UTIL, :LISIVA
        do
        BEGIN
        if (MOU = 'UTILIDAD') then
            MARGEN = UTIL;
        if (MASIVA = 'S') then
            BEGIN
            if (LISIVA = 'N') then
                PRECIO = PRECIO * (1 + (IVA / 100));
            END
        ELSE
            BEGIN
            if (LISIVA = 'S') then
                PRECIO = PRECIO / (1 + (IVA/100));
            END
        I = I + 1;
        if (I = 1) then
            BEGIN
            PRECIO1 = PRECIO;
            MARGEN1 = MARGEN;
            END
        if (I = 2) then
            BEGIN
            PRECIO2 = PRECIO;
            MARGEN2 = MARGEN;
            END
        if (I = 3) then
            BEGIN
            PRECIO3 = PRECIO;
            MARGEN3 = MARGEN;
            END
        if (I = 4) then
            BEGIN
            PRECIO4 = PRECIO;
            MARGEN4 = MARGEN;
            END
        if (I = 5) then
            BEGIN
            PRECIO5 = PRECIO;
            MARGEN5 = MARGEN;
            END
        if (I = 6) then
            BEGIN
            PRECIO6 = PRECIO;
            MARGEN6 = MARGEN;
            END
        if (I = 7) then
            BEGIN
            PRECIO7 = PRECIO;
            MARGEN7 = MARGEN;
            END
        if (I = 8) then
            BEGIN
            PRECIO8 = PRECIO;
            MARGEN8 = MARGEN;
            END
        if (I = 9) then
            BEGIN
            PRECIO9 = PRECIO;
            MARGEN9 = MARGEN;
            END
        end
    MENOR = '';
    EXECUTE PROCEDURE costo_promedio_y_ultimo(:codigo, :FECHA) returning_values (:UCOSTO, :COSTOP);
    if (MASIVA = 'S') then
        begin
        costop = costop * (1 + (IVA / 100));
        ucosto = ucosto * (1 + (IVA / 100));
        end
    if ((PRECIO1 <> 0) AND (PRECIO1 < COSTOP)) then
        MENOR = MENOR || '1,';
    if ((PRECIO2 <> 0) AND (PRECIO2 < COSTOP)) then
        MENOR = MENOR || '2,';
    if ((PRECIO3 <> 0) AND (PRECIO3 < COSTOP)) then
        MENOR = MENOR || '3,';
    if ((PRECIO4 <> 0) AND (PRECIO4 < COSTOP)) then
        MENOR = MENOR || '4,';
    if ((PRECIO5 <> 0) AND (PRECIO5 < COSTOP)) then
        MENOR = MENOR || '5,';
    if ((PRECIO6 <> 0) AND (PRECIO6 < COSTOP)) then
        MENOR = MENOR || '6,';
    if ((PRECIO7 <> 0) AND (PRECIO7 < COSTOP)) then
        MENOR = MENOR || '7,';
    if ((PRECIO8 <> 0) AND (PRECIO8 < COSTOP)) then
        MENOR = MENOR || '8,';
    if ((PRECIO9 <> 0) AND (PRECIO9 < COSTOP)) then
        MENOR = MENOR || '9,';
    SUSPEND;

    END

END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REP_LISTA_PRECIOS (
    ARTINI varchar(20),
    ARTFIN varchar(20),
    GRPINI varchar(2),
    GRPFIN varchar(2),
    ORDEN char(1),
    LISTA integer,
    LINI integer,
    LFIN integer,
    FECHA date,
    DEATRES char(1),
    MASIVA char(1),
    HOY char(1),
    EXIST char(1),
    CODBOD varchar(2))
returns (
    CODIGO varchar(15),
    NOMBRE varchar(300),
    DESCORTA varchar(30),
    REFERENCIA varchar(50),
    UNIDAD varchar(8),
    UNIDAD2 varchar(8),
    FACTOR2 numeric(18,4),
    UNIDAD3 varchar(8),
    FACTOR3 numeric(18,4),
    UNIDAD4 varchar(8),
    FACTOR4 numeric(18,4),
    CODGRUPO varchar(2),
    NOMGRUPO varchar(30),
    CODSUBG varchar(3),
    NOMSUBG varchar(30),
    CODMARC varchar(3),
    NOMMARC varchar(30),
    CODFABR varchar(3),
    NOMFABR varchar(60),
    NOMLISTA varchar(30),
    PRECIO numeric(18,2),
    PRECIO2 numeric(18,2),
    PRECIO3 numeric(18,2),
    PRECIOANT numeric(18,2),
    FECANT date,
    VARIACION numeric(18,2),
    VARTEXTO varchar(5),
    MARGEN numeric(9,2),
    IVA numeric(9,2),
    IVAMONTO numeric(18,2),
    CONSUMO numeric(18,2),
    CANTMIN numeric(18,4),
    PESO numeric(18,4),
    ANCHO numeric(18,4),
    ALTO numeric(18,4),
    LARGO numeric(18,4),
    CANT numeric(18,4),
    DTO1 numeric(9,4),
    DTO2 numeric(9,4),
    COMI numeric(9,4),
    COMIC numeric(9,4),
    FECPRE date,
    FOTO blob sub_type BINARY segment size 80,
    OBS blob sub_type TEXT segment size 80,
    TOTAL numeric(18,2))
as
declare variable CODINI VARCHAR(20);
declare variable CODFIN VARCHAR(20);
declare variable DESINI VARCHAR(20);
declare variable DESFIN VARCHAR(20);
declare variable UTIL NUMERIC(9,2);
declare variable MOU CHAR(10);
declare variable LISIVA CHAR(2);
declare variable i integer;
declare variable J integer;
declare variable PRECAUX NUMERIC(18,2);
declare variable DIG INTEGER;
declare variable UNIDADA VARCHAR(8);
declare variable FACTORA NUMERIC(18,4);
declare variable FECHOY DATE;
declare variable CODLISTA INTEGER;
declare variable PRECIOALT CHAR(2);
BEGIN
if (ORDEN = 'C') then
    BEGIN
    CODINI = ARTINI;
    CODFIN = ARTFIN;
    DESINI = '';
    DESFIN = 'zz';
    END
ELSE
    BEGIN
    DESINI = ARTINI;
    DESFIN = ARTFIN;
    CODINI = '';
    CODFIN = 'zz';
    END
FECHOY = FECHA;
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'SUGERIR PRECIOS CON PORCENTAJE DE MARGEN O UTILIDAD') returning_values (MOU);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'ARTICULOS', 'INCLUIR PRECIO EN UNIDAD ALTERNATIVA AL EXPORTAR LISTA DE PRECIOS') returning_values (PRECIOALT);
if (LISTA = 0) then
    BEGIN
    FOR SELECT a.ARTI_COD, ARTI_DES, ARTI_DESCORTA, ARTI_UNIDAD, GRUP_COD, SUBG_COD, MARC_COD, FABR_COD, TAIV_PORC, ARTI_CONSUMO,
        ARTI_FOTO, ARTI_PESO, ARTI_LARGO, ARTI_ANCHO, ARTI_ALTO, ARTI_OBS
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.ARTI_COD >= :CODINI AND A.ARTI_COD <= :CODFIN AND A.GRUP_COD >= :GRPINI AND A.GRUP_COD <= :GRPFIN AND
        ARTI_DES >= :DESINI AND ARTI_DES <= :DESFIN AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K')) AND A.TAIV_COD = T.TAIV_COD
        ORDER BY ARTI_COD
        INTO :CODIGO, :NOMBRE, :DESCORTA, UNIDAD, :CODGRUPO, :CODSUBG, :CODMARC, :CODFABR, :IVA, :CONSUMO,
            :FOTO, :PESO, :LARGO, :ANCHO, :ALTO, :OBS
        DO
        BEGIN
        SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :CODGRUPO INTO NOMGRUPO;
        SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMARC INTO NOMMARC;
        SELECT FABR_NOM FROM FABRICANTES WHERE FABR_COD = :CODFABR INTO NOMFABR;
        SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :CODSUBG AND GRUP_COD = :CODGRUPO INTO :NOMSUBG;
        SELECT MIN(COBA_COD) FROM barras_articulo WHERE ARTI_COD = :codigo INTO :referencia;
        J = 0;
        UNIDAD2 = '';
        UNIDAD3 = '';
        UNIDAD4 = '';
        factor2 = 0;
        factor3 = 0;
        factor4 = 0;
        CANT = 0;
        for SELECT UNAR_UNIDAD, UNAR_FACPRE FROM unidad_articulo WHERE ARTI_COD = :codigo AND UNAR_ACTIVA = 'S' ORDER BY UNAR_FACPRE
            INTO :unidada, :factora
            DO
            BEGIN
            if (J = 0) then
                BEGIN
                UNIDAD2 = UNIDADA;
                FACTOR2 = FACTORA;
                END
            if (J = 1) then
                BEGIN
                UNIDAD3 = UNIDADA;
                FACTOR3 = FACTORA;
                END
            if ( J = 2) then
                BEGIN
                UNIDAD4 = UNIDADA;
                FACTOR4 = FACTORA;
                END
            J = J + 1;
            END
        I = 0;
        FOR SELECT P.LIPR_COD, LIPR_NOM, PRAR_FIJO, PRAR_MARGEN, PRAR_UTIL, LIPR_MODIF, PRAR_CANTMIN, PRAR_DTO1, PRAR_DTO2, PRAR_COMIC, PRAR_COMI
            FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P
            WHERE L.LIPR_COD = P.LIPR_COD AND p.arti_cod = :codigo and l.lipr_cod >= :lini and l.lipr_cod <= :lfin AND
            ((:fecha IS NULL) or ((L.lipr_fecini <= :FECHA) AND (L.lipr_fecfin >= :FECHA)))
            ORDER BY L.LIPR_COD
            INTO :CODLISTA, :NOMLISTA, :PRECIO, :MARGEN, :UTIL, :LISIVA, :cantmin, :DTO1, :DTO2, :COMIC, :COMI
            do
            BEGIN
            if ((HOY = 'N') or (exists (select capr_id FROM cambia_precios WHERE ARTI_COD = :CODIGO AND CAPR_FECHA = :FECHOY AND LIPR_COD = :codlista))) then
                BEGIN
                FECPRE = NULL;
                SELECT FIRST 1 CAPR_FECHA FROM cambia_precios
                    WHERE ARTI_COD = :CODIGO AND LIPR_COD = :codlista AND CAPR_FECHA <= :fechoy ORDER BY CAPR_FECHA DESC
                    INTO :fecpre;
                SELECT FIRST 1 CAPR_FECHA, CAPR_PRECIO FROM cambia_precios
                    WHERE ARTI_COD = :CODIGO AND LIPR_COD = :codlista AND CAPR_FECHA < :fecpre ORDER BY CAPR_FECHA DESC
                    INTO :fecant, :precioant;
                if (PRECIOANT <> 0) then
                    if ((PRECIO / PRECIOANT) < 99999) then
                        VARIACION = ((PRECIO / PRECIOANT) * 100) - 100;
                    else
                        VARIACION = 9999999.99;
                else
                    VARIACION = 0;
                IF (VARIACION = 0) THEN
                    VARTEXTO = 'IGUAL';
                IF (VARIACION > 0) THEN
                    VARTEXTO = 'SUBIO';
                IF (VARIACION < 0) THEN
                    VARTEXTO = 'BAJO';
                if (MOU = 'UTILIDAD') then
                    MARGEN = UTIL;
                if (LISIVA = 'N') then
                    IVAMONTO = PRECIO * IVA / 100;
                ELSE
                    BEGIN
                    IVAMONTO = (PRECIO - CONSUMO) * IVA / (100 + IVA);
                    PRECIO = (PRECIO - CONSUMO) / (1 + (IVA/100));
    /*              EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO); */
                    END
                TOTAL = PRECIO + IVAMONTO + CONSUMO;
                EXECUTE PROCEDURE redondee(TOTAL, DIG) returning_values (TOTAL);
                if (DEATRES = 'N') then
                    BEGIN
                    PRECIO2 = 0;
                    if (PRECIOALT = 'SI') then
                        BEGIN
                        SELECT MIN(PRAR_FIJO) FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :codigo AND LIPR_COD <> :codlista
                            AND PRAR_CANTMIN <> 0 AND PRAR_CANTMIN < :FACTOR2 AND PRAR_FIJO < :PRECIO INTO :precio2;
                        if ((PRECIO2 = 0) or (PRECIO2 IS NULL)) then
                            PRECIO2 = TOTAL * FACTOR2;
                        ELSE
                            PRECIO2 = TOTAL * FACTOR2;
                        END
                    if (EXIST = 'S') then
                        BEGIN
                        if (CODBOD = '0') then
                            EXECUTE procedure SALDO_TOTAL_INVENTARIO (CODIGO, FECHA) returning_values (CANT);
                        else
                            EXECUTE procedure SALDO_INVENTARIO (CODIGO, :codbod, :FECHA) returning_values (CANT);
                        if (CANT > 0) then
                            SUSPEND;
                        END
                    ELSE
                        SUSPEND;
                    END
                else
                    BEGIN
                    I = I + 1;
                    if (MASIVA = 'S') then
                        PRECIO = TOTAL;
                    TOTAL = 0;
                    if (MOD(I,3) = 1) then
                        BEGIN
                        PRECAUX = PRECIO;
                        PRECIO2 = 0;
                        PRECIO3 = 0;
                        END
                    if (MOD(I,3) = 2) then
                        BEGIN
                        PRECIO2 = PRECIO;
                        PRECIO = PRECAUX;
                        END
                    if (MOD(I,3) = 0) then
                        BEGIN
                        PRECIO3 = PRECIO;
                        PRECIO = PRECAUX;
                        SUSPEND;
                        END
                    END
                END
            end
        if ((DEATRES = 'S') AND (MOD(I,3) <> 0)) then
            if (EXIST = 'S') then
                begin
                if (CODBOD = '0') then
                    EXECUTE procedure SALDO_TOTAL_INVENTARIO (CODIGO, FECHA) returning_values (CANT);
                else
                    EXECUTE procedure SALDO_INVENTARIO (CODIGO, :codbod, :FECHA) returning_values (CANT);
                if (CANT > 0) then
                    suspend;
                end
            else
                suspend;
        end
    END
ELSE
    BEGIN
    FOR SELECT a.ARTI_COD, ARTI_DES, ARTI_DESCORTA, ARTI_UNIDAD, GRUP_COD, SUBG_COD, MARC_COD, FABR_COD, TAIV_PORC, ARTI_CONSUMO,
        ARTI_FOTO, ARTI_PESO, ARTI_LARGO, ARTI_ANCHO, ARTI_ALTO, ARTI_OBS
        FROM ARTICULO A, TARIFA_IVA T, lista_articulos_det LA
        WHERE A.ARTI_COD >= :CODINI AND A.ARTI_COD <= :CODFIN AND A.GRUP_COD >= :GRPINI AND A.GRUP_COD <= :GRPFIN AND
        ARTI_DES >= :DESINI AND ARTI_DES <= :DESFIN AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K')) AND A.TAIV_COD = T.TAIV_COD AND LA.liar_id = :LISTA AND LA.arti_cod = A.arti_cod
        ORDER BY ARTI_COD
        INTO :CODIGO, :NOMBRE, :DESCORTA, UNIDAD, :CODGRUPO, :CODSUBG, :CODMARC, :CODFABR, :IVA, :CONSUMO,
            :FOTO, :PESO, :LARGO, :ANCHO, :ALTO, :OBS
        DO
        BEGIN
        SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :CODGRUPO INTO NOMGRUPO;
        SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMARC INTO NOMMARC;
        SELECT FABR_NOM FROM FABRICANTES WHERE FABR_COD = :CODFABR INTO NOMFABR;
        SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :CODSUBG AND GRUP_COD = :CODGRUPO INTO :NOMSUBG;
        SELECT MIN(COBA_COD) FROM barras_articulo WHERE ARTI_COD = :codigo INTO :referencia;
        J = 0;
        UNIDAD2 = '';
        UNIDAD3 = '';
        UNIDAD4 = '';
        factor2 = 0;
        factor3 = 0;
        factor4 = 0;
        CANT = 0;
        for SELECT UNAR_UNIDAD, UNAR_FACPRE FROM unidad_articulo WHERE ARTI_COD = :codigo AND UNAR_ACTIVA = 'S' INTO :unidada, :factora
            DO
            BEGIN
            if (J = 0) then
                BEGIN
                UNIDAD2 = UNIDADA;
                FACTOR2 = FACTORA;
                END
            if (J = 1) then
                BEGIN
                UNIDAD3 = UNIDADA;
                FACTOR3 = FACTORA;
                END
            if ( J = 2) then
                BEGIN
                UNIDAD4 = UNIDADA;
                FACTOR4 = FACTORA;
                END
            J = J + 1;
            END
        I = 0;
        FOR SELECT P.LIPR_COD, LIPR_NOM, PRAR_FIJO, PRAR_MARGEN, PRAR_UTIL, LIPR_MODIF, PRAR_CANTMIN, PRAR_DTO1, PRAR_DTO2, PRAR_COMIC, PRAR_COMI
            FROM LISTA_PRECIOS L, PRECIOS_ARTICULO P
            WHERE L.LIPR_COD = P.LIPR_COD AND p.arti_cod = :codigo and l.lipr_cod >= :lini and l.lipr_cod <= :lfin AND
            ((:fecha IS NULL) or ((L.lipr_fecini <= :FECHA) AND (L.lipr_fecfin >= :FECHA)))
            ORDER BY L.LIPR_COD
            INTO :CODLISTA, :NOMLISTA, :PRECIO, :MARGEN, :UTIL, :LISIVA, :cantmin, :DTO1, :DTO2, :COMIC, :COMI
            do
            BEGIN
            if ((HOY = 'N') or (exists (select capr_id FROM cambia_precios WHERE ARTI_COD = :CODIGO AND CAPR_FECHA = :FECHOY AND LIPR_COD = :codlista))) then
                BEGIN
                FECPRE = NULL;
                SELECT FIRST 1 CAPR_FECHA FROM cambia_precios
                    WHERE ARTI_COD = :CODIGO AND LIPR_COD = :codlista AND CAPR_FECHA <= :fechoy ORDER BY CAPR_FECHA DESC
                    INTO :fecpre;
                SELECT FIRST 1 CAPR_FECHA, CAPR_PRECIO FROM cambia_precios
                    WHERE ARTI_COD = :CODIGO AND LIPR_COD = :codlista AND CAPR_FECHA < :fecpre ORDER BY CAPR_FECHA DESC
                    INTO :fecant, :precioant;
                if (PRECIOANT <> 0) then
                    if ((PRECIO / PRECIOANT) < 99999) then
                        VARIACION = ((PRECIO / PRECIOANT) * 100) - 100;
                    else
                        VARIACION = 9999999.99;
                else
                    VARIACION = 0;
                IF (VARIACION = 0) THEN
                    VARTEXTO = 'IGUAL';
                IF (VARIACION > 0) THEN
                    VARTEXTO = 'SUBIO';
                IF (VARIACION < 0) THEN
                    VARTEXTO = 'BAJO';
                if (MOU = 'UTILIDAD') then
                    MARGEN = UTIL;
                if (LISIVA = 'N') then
                    IVAMONTO = PRECIO * IVA / 100;
                ELSE
                    BEGIN
                    IVAMONTO = (PRECIO - CONSUMO) * IVA / (100 + IVA);
                    PRECIO = (PRECIO - CONSUMO) / (1 + (IVA/100));
    /*              EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO); */
                    END
                TOTAL = PRECIO + IVAMONTO + CONSUMO;
                EXECUTE PROCEDURE redondee(TOTAL, DIG) returning_values (TOTAL);
                if (DEATRES = 'N') then
                    BEGIN
                    PRECIO2 = 0;
                    if (PRECIOALT = 'SI') then
                        BEGIN
                        SELECT MIN(PRAR_FIJO) FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :codigo AND LIPR_COD <> :codlista
                            AND PRAR_CANTMIN <> 0 AND PRAR_CANTMIN < :FACTOR2 AND PRAR_FIJO < :PRECIO INTO :precio2;
                        if ((PRECIO2 = 0) or (PRECIO2 IS NULL)) then
                            PRECIO2 = TOTAL * FACTOR2;
                        ELSE
                            PRECIO2 = PRECIO2 * FACTOR2;
                        END
                    if (EXIST = 'S') then
                        BEGIN
                        if (CODBOD = '0') then
                            EXECUTE procedure SALDO_TOTAL_INVENTARIO (CODIGO, FECHA) returning_values (CANT);
                        else
                            EXECUTE procedure SALDO_INVENTARIO (CODIGO, :codbod, :FECHA) returning_values (CANT);
                        if (CANT > 0) then
                            SUSPEND;
                        END
                    ELSE
                        SUSPEND;
                    END
                else
                    BEGIN
                    I = I + 1;
                    if (MASIVA = 'S') then
                        PRECIO = TOTAL;
                    TOTAL = 0;
                    if (MOD(I,3) = 1) then
                        BEGIN
                        PRECAUX = PRECIO;
                        PRECIO2 = 0;
                        PRECIO3 = 0;
                        END
                    if (MOD(I,3) = 2) then
                        BEGIN
                        PRECIO2 = PRECIO;
                        PRECIO = PRECAUX;
                        END
                    if (MOD(I,3) = 0) then
                        BEGIN
                        PRECIO3 = PRECIO;
                        PRECIO = PRECAUX;
                        SUSPEND;
                        END
                    END
                END
            end
        if ((DEATRES = 'S') AND (MOD(I,3) <> 0)) then
            if (EXIST = 'S') then
                begin
                if (CODBOD = '0') then
                    EXECUTE procedure SALDO_TOTAL_INVENTARIO (CODIGO, FECHA) returning_values (CANT);
                else
                    EXECUTE procedure SALDO_INVENTARIO (CODIGO, :codbod, :FECHA) returning_values (CANT);
                if (CANT > 0) then
                    suspend;
                end
            else
                suspend;
        end
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REP_COMPRAS_SISMED (
    ANO char(4),
    MESINI integer,
    MESFIN integer,
    AGENCIA integer)
returns (
    ITEM integer,
    MES char(2),
    CUM varchar(30),
    PRMIN numeric(18,2),
    PRMAX numeric(18,2),
    COMPRAS numeric(18,2),
    CANTIDAD numeric(18,2),
    FACMIN varchar(12),
    FACMAX varchar(12))
as
declare variable CODIGO VARCHAR(20);
declare variable FECINI DATE;
declare variable FECFIN DATE;
declare variable NUMMES INTEGER;
begin
ITEM = 0;
NUMMES = MESINI;
WHILE (NUMMES <= MESFIN) DO
    BEGIN
    if (NUMMES < 10) then
        MES = '0' || :NUMMES;
    ELSE
        MES = :NUMMES;
    FECINI = ANO || '/' || nummes || '/01';

    FECFIN = FECINI + 31;
    FECFIN = :FECFIN - EXTRACT(DAY FROM :FECFIN) + 1;

    FOR SELECT ARTI_COD, ARTI_CUM FROM ARTICULO A WHERE ARTI_CUM <> '' AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))
        INTO :CODIGO, :CUM
        DO
        BEGIN
        SELECT SUM(D.fcde_cant* D.fcde_factor), SUM(D.fcde_total-D.fcde_ivamonto), MIN(D.fcde_prunit/D.fcde_factor), MAX(D.fcde_prunit/D.fcde_factor)
            FROM facturas_compra F, facturas_compras_detalle D, prefijos P WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO
            AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' and faco_confirma = 'S'
            AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
            INTO :CANTIDAD, :COMPRAS, :PRMIN, :PRMAX;

        FACMIN = '';
        select MIN(F.pref_pre || F.faco_numero) FROM facturas_compra F, facturas_compras_detalle D, prefijos P
            WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO AND (D.fcde_prunit / D.fcde_factor) = :prmin
            AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' and faco_confirma = 'S'
            AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
            INTO :FACMIN;
        select MAX(F.pref_pre || F.faco_numero) FROM facturas_compra F, facturas_compras_detalle D, prefijos P
            WHERE F.faco_id = D.faco_id AND D.arti_cod = :CODIGO AND (D.fcde_prunit / D.fcde_factor) = :prmax
            AND F.faco_fecha >= :FECINI AND F.faco_fecha <= :FECFIN AND F.faco_anulado = 'N' and faco_confirma = 'S'
            AND P.tido_cod = 21 AND P.pref_pre = F.pref_pre AND ((:AGENCIA = 0) or (P.sucu_id = :AGENCIA))
            INTO :facmax;
        if (CANTIDAD <> 0) then
            BEGIN
            ITEM = ITEM + 1;
            suspend;
            END
        END
    NUMMES = NUMMES + 1;
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REP_CAMBIO_PRECIOS (
    FECINI date,
    FECFIN date,
    ARTINI varchar(20),
    ARTFIN varchar(20),
    LISTA integer)
returns (
    CODIGO varchar(15),
    NOMBRE varchar(300),
    DESCORTA varchar(30),
    REFERENCIA varchar(20),
    UNIDAD varchar(8),
    UNIDAD2 varchar(8),
    FACTOR2 numeric(18,4),
    UNIDAD3 varchar(8),
    FACTOR3 numeric(18,4),
    UNIDAD4 varchar(8),
    FACTOR4 numeric(18,4),
    CODGRUPO varchar(2),
    NOMGRUPO varchar(30),
    CODSUBG varchar(3),
    NOMSUBG varchar(30),
    CODMARC varchar(3),
    NOMMARC varchar(30),
    CODFABR varchar(3),
    NOMFABR varchar(60),
    PRECIO numeric(18,2),
    PRECIOANT numeric(18,2),
    FECHA date,
    VARIACION numeric(18,2),
    VARTEXTO varchar(5),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    PESO numeric(18,4),
    ANCHO numeric(18,4),
    ALTO numeric(18,4),
    LARGO numeric(18,4),
    CANT numeric(18,4),
    FOTO blob sub_type BINARY segment size 80,
    OBS blob sub_type TEXT segment size 80)
as
declare variable CODINI VARCHAR(20);
declare variable CODFIN VARCHAR(20);
declare variable DESINI VARCHAR(20);
declare variable DESFIN VARCHAR(20);
declare variable UTIL NUMERIC(9,2);
declare variable MOU CHAR(10);
declare variable LISIVA CHAR(2);
declare variable i integer;
declare variable J integer;
declare variable PRECAUX NUMERIC(18,2);
declare variable DIG INTEGER;
declare variable UNIDADA VARCHAR(8);
declare variable FACTORA NUMERIC(18,4);
declare variable FECHOY DATE;
declare variable CODLISTA INTEGER;
declare variable PRECIOALT CHAR(2);
BEGIN
CODINI = ARTINI;
CODFIN = ARTFIN;
DESINI = '';
DESFIN = 'zz';
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'SUGERIR PRECIOS CON PORCENTAJE DE MARGEN O UTILIDAD') returning_values (MOU);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'ARTICULOS', 'INCLUIR PRECIO EN UNIDAD ALTERNATIVA AL EXPORTAR LISTA DE PRECIOS') returning_values (PRECIOALT);
FOR SELECT a.ARTI_COD, ARTI_DES, ARTI_DESCORTA, ARTI_UNIDAD, GRUP_COD, SUBG_COD, MARC_COD, FABR_COD, TAIV_PORC, ARTI_CONSUMO,
    ARTI_FOTO, ARTI_PESO, ARTI_LARGO, ARTI_ANCHO, ARTI_ALTO, ARTI_OBS
    FROM ARTICULO A, TARIFA_IVA T
    WHERE A.ARTI_COD >= :CODINI AND A.ARTI_COD <= :CODFIN AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K')) AND A.TAIV_COD = T.TAIV_COD
    ORDER BY ARTI_COD
    INTO :CODIGO, :NOMBRE, :DESCORTA, UNIDAD, :CODGRUPO, :CODSUBG, :CODMARC, :CODFABR, :IVA, :CONSUMO,
        :FOTO, :PESO, :LARGO, :ANCHO, :ALTO, :OBS
    DO
    BEGIN
    SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :CODGRUPO INTO NOMGRUPO;
    SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMARC INTO NOMMARC;
    SELECT FABR_NOM FROM FABRICANTES WHERE FABR_COD = :CODFABR INTO NOMFABR;
    SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :CODSUBG AND GRUP_COD = :CODGRUPO INTO :NOMSUBG;
    SELECT MIN(COBA_COD) FROM barras_articulo WHERE ARTI_COD = :codigo INTO :referencia;
    J = 0;
    UNIDAD2 = '';
    UNIDAD3 = '';
    UNIDAD4 = '';
    factor2 = 0;
    factor3 = 0;
    factor4 = 0;
    CANT = 0;
    for SELECT UNAR_UNIDAD, UNAR_FACPRE FROM unidad_articulo WHERE ARTI_COD = :codigo ORDER BY UNAR_FACPRE
        INTO :unidada, :factora
        DO
        BEGIN
        if (J = 0) then
            BEGIN
            UNIDAD2 = UNIDADA;
            FACTOR2 = FACTORA;
            END
        if (J = 1) then
            BEGIN
            UNIDAD3 = UNIDADA;
            FACTOR3 = FACTORA;
            END
        if ( J = 2) then
            BEGIN
            UNIDAD4 = UNIDADA;
            FACTOR4 = FACTORA;
            END
        J = J + 1;
        END
    I = 0;
    PRECIOANT = 0;

    select first 1 CP.capr_precio FROM cambia_precios CP WHERE ARTI_COD = :CODIGO AND CAPR_FECHA < :FECINI AND LIPR_COD = :lista order by capr_fecha desc
        INTO :precioant;
    if (PRECIOANT IS NULL) then
        PRECIOANT = 0;
    FOR select CP.capr_fecha, CP.capr_precio FROM cambia_precios CP WHERE ARTI_COD = :CODIGO AND CAPR_FECHA >= :FECINI AND CAPR_FECHA <= :FECFIN AND LIPR_COD = :lista
        INTO :FECHA, :PRECIO
        DO
        BEGIN
        if (PRECIOANT <> 0) then
            if ((PRECIO / PRECIOANT) < 99999) then
                VARIACION = ((PRECIO / PRECIOANT) * 100) - 100;
            else
                VARIACION = 9999999.99;
        else
            VARIACION = 0;
        IF (VARIACION = 0) THEN
            VARTEXTO = 'IGUAL';
        IF (VARIACION > 0) THEN
            VARTEXTO = 'SUBIO';
        IF (VARIACION < 0) THEN
            VARTEXTO = 'BAJO';
        SUSPEND;
        precioant = precio;
        END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_TRASLADO_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    LOTE varchar(50),
    LOTEVEN date,
    REFER varchar(60),
    OBS varchar(1024))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO varchar(20);
declare variable UNIART varchar(8);
declare variable ORDEN varchar(12);
declare variable IDORD integer;
declare variable TIPO integer;
declare variable PREF varchar(4);
declare variable NUMERO varchar(8);
declare variable LON integer;
declare variable COSTO numeric(18,2);
declare variable ITEMO integer;
declare variable PROD varchar(20);
begin
ARTICULO = NULL;
SELECT FIRST 1 B.ARTI_COD, COBA_UNIDAD
    from BARRAS_ARTICULO B, ARTICULO A, TARIFA_IVA T
    WHERE B.ARTI_COD = A.ARTI_COD AND COBA_COD = :BARRAS AND COBA_ACTIVO = 'S' and a.esar_cod <> 'I' AND A.taiv_cod = T.taiv_cod 
    INTO :ARTICULO, :uniart;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    SELECT FIRST 1 A.ARTI_COD, ARTI_UNIDAD
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.arti_cod = :barras AND A.taiv_cod = T.taiv_cod AND (a.esar_cod <> 'I')
        INTO :ARTICULO, :UNIART;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    exception articulo_no_existe 'NO SE ENCONTRO EL ARTICULO ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIART;

select d.dinw_tiporef, d.dinw_numref from doc_inventario_web d where d.dinw_id = :id into :tipo, :orden;
ITEMO = 0;
if (TIPO = 18) then
    BEGIN
    LON = STRLEN(ORDEN);
    PREF = LEFT(ORDEN, LON - 6);
    NUMERO = right(ORDEN, 6);
    SELECT O.orin_id FROM ordenes_inventario O WHERE O.pref_pre = :PREF AND O.orin_numero = :NUMERO INTO :IDORD;
    SELECT FIRST 1 OD.orid_item, OD.orin_costo FROM ordeninventario_detalle OD WHERE OD.orin_id = :idord AND OD.arti_cod = :articulo INTO :ITEMO, :COSTO;
    END
ELSE
    if (TIPO = 15) then
        BEGIN
        LON = STRLEN(ORDEN);
        PREF = LEFT(ORDEN, LON - 6);
        NUMERO = right(ORDEN, 6);
        SELECT FIRST 1 E.ensa_id, E.arti_cod FROM ensambles E WHERE E.pref_pre = :PREF AND E.ensa_numero = :NUMERO INTO :IDORD, :PROD;
        if (PROD = ARTICULO) then
            ITEMO = 1;
        END
    ELSE
        COSTO = 0;
if (ITEMO = 0) then
    exception articulo_no_orden 'El articulo ' || articulo || ' no pertenece a la orden/ensable ' || :orden;
ITEM = 0;
SELECT MAX(diwd_item+1) FROM doc_inventario_det_web DD WHERE DD.dinw_id = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into DOC_INVENTARIO_DET_WEB (DINW_ID, DIWD_ITEM, DIWD_ARTICULO, DIWD_CODBAR, DIWD_CANT, DIWD_UNIDAD, DIWD_COSTO, DIWD_LOTE, DIWD_VENCELOTE, DIWD_REF, DIWD_ANULADO, DIWD_OBS)
    values (:ID, :ITEM, :ARTICULO, :BARRAS, :CANT, :UNIDAD, :COSTO, :LOTE, :LOTEVEN, :REFER, 'N', :OBS);
/* DEVUELVA EL TOTAL */
SELECT SUM(DD.diwd_cant * DD.diwd_costo) FROM DOC_INVENTARIO_DET_WEB DD WHERE DD.dinw_id = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_SALIDA_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    LOTE varchar(50),
    LOTEVEN date,
    REFER varchar(60),
    OBS varchar(1024))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO varchar(20);
declare variable UNIART varchar(8);
declare variable ORDEN varchar(12);
declare variable IDORD integer;
declare variable TIPO integer;
declare variable PREF varchar(4);
declare variable NUMERO varchar(8);
declare variable LON integer;
declare variable COSTO numeric(18,2);
declare variable ITEMO integer;
declare variable FECHA DATE;
begin
ARTICULO = NULL;
SELECT FIRST 1 B.ARTI_COD, COBA_UNIDAD
    from BARRAS_ARTICULO B, ARTICULO A, TARIFA_IVA T
    WHERE B.ARTI_COD = A.ARTI_COD AND COBA_COD = :BARRAS AND COBA_ACTIVO = 'S' and a.esar_cod <> 'I' AND A.taiv_cod = T.taiv_cod 
    INTO :ARTICULO, :uniart;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    SELECT FIRST 1 A.ARTI_COD, ARTI_UNIDAD
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.arti_cod = :barras AND A.taiv_cod = T.taiv_cod AND (a.esar_cod <> 'I')
        INTO :ARTICULO, :UNIART;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    exception articulo_no_existe 'NO SE ENCONTRO EL ARTICULO ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIART;

select d.dinw_tiporef, d.dinw_numref, D.dinw_fecha from doc_inventario_web d where d.dinw_id = :id into :tipo, :orden, :FECHA;
ITEMO = 0;
if ((TIPO = 18) AND (ORDEN IS NOT NULL) AND (orden <> '')) then
    BEGIN
    LON = STRLEN(ORDEN);
    PREF = LEFT(ORDEN, LON - 6);
    NUMERO = right(ORDEN, 6);
    SELECT O.orin_id FROM ordenes_inventario O WHERE O.pref_pre = :PREF AND O.orin_numero = :NUMERO INTO :IDORD;
    SELECT OD.orid_item, OD.orin_costo FROM ordeninventario_detalle OD WHERE OD.orin_id = :idord AND OD.arti_cod = :articulo INTO :ITEMO, :COSTO;
    if (ITEMO = 0) then
        exception articulo_no_orden 'El articulo ' || articulo || ' no pertenece a la orden ' || :orden;
    END
ELSE
    EXECUTE PROCEDURE costo_promedio(:articulo, :fecha) returning_values (:COSTO);
ITEM = 0;
SELECT MAX(diwd_item+1) FROM doc_inventario_det_web DD WHERE DD.dinw_id = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into DOC_INVENTARIO_DET_WEB (DINW_ID, DIWD_ITEM, DIWD_ARTICULO, DIWD_CODBAR, DIWD_CANT, DIWD_UNIDAD, DIWD_COSTO, DIWD_LOTE, DIWD_VENCELOTE, DIWD_REF, DIWD_ANULADO, DIWD_OBS)
    values (:ID, :ITEM, :ARTICULO, :BARRAS, :CANT, :UNIDAD, :COSTO, :LOTE, :LOTEVEN, :REFER, 'N', :OBS);
/* DEVUELVA EL TOTAL */
SELECT SUM(DD.diwd_cant * DD.diwd_costo) FROM DOC_INVENTARIO_DET_WEB DD WHERE DD.dinw_id = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_REMIPROV_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    LOTE varchar(50),
    LOTEVEN date,
    REFER varchar(60),
    OBS varchar(1024))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO VARCHAR(20);
declare variable UNIART VARCHAR(8);
declare variable ORDEN VARCHAR(12);
declare variable IDORD INTEGER;
declare variable TIPO INTEGER;
declare variable PREF VARCHAR(4);
declare variable NUMERO VARCHAR(8);
declare variable LON INTEGER;
declare variable COSTO NUMERIC(18,2);
begin
ARTICULO = NULL;
SELECT FIRST 1 B.ARTI_COD, COBA_UNIDAD
    from BARRAS_ARTICULO B, ARTICULO A, TARIFA_IVA T
    WHERE B.ARTI_COD = A.ARTI_COD AND COBA_COD = :BARRAS AND COBA_ACTIVO = 'S' and a.esar_cod <> 'I' AND A.taiv_cod = T.taiv_cod 
    INTO :ARTICULO, :uniart;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    SELECT FIRST 1 A.ARTI_COD, ARTI_UNIDAD
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.arti_cod = :barras AND A.taiv_cod = T.taiv_cod AND (a.esar_cod <> 'I')
        INTO :ARTICULO, :UNIART;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    exception articulo_no_existe 'NO SE ENCONTRO EL ARTICULO ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIART;

select d.dinw_tiporef, d.dinw_numref from doc_inventario_web d where d.dinw_id = :id into :tipo, :orden;
if (TIPO = 23) then
    BEGIN
    LON = STRLEN(ORDEN);
    PREF = LEFT(ORDEN, LON - 6);
    NUMERO = right(ORDEN, 6);
    SELECT O.ordc_id FROM ordenes_compra O WHERE O.pref_pre = :PREF AND O.ordc_numero = :NUMERO INTO :IDORD;
    SELECT max(OD.ocde_prunit) FROM ordenes_compra_detalle OD WHERE OD.ordc_id = :idord AND OD.arti_cod = :articulo INTO :COSTO;
    END
ELSE
    if (TIPO = 139) then
        BEGIN
        PREF = LEFT(ORDEN, LON - 6);
        NUMERO = right(ORDEN, 6);
        SELECT S.slim_id FROM solicitud_importacion S WHERE S.pref_pre = :PREF AND S.slim_numero = :NUMERO INTO :IDORD;
        SELECT max(SD.slde_prunit) FROM solicitud_importacion_det SD WHERE SD.slim_id = :idord AND SD.arti_cod = :articulo INTO :COSTO;
        END
    ELSE
        COSTO = 0;
ITEM = 0;
SELECT MAX(diwd_item+1) FROM doc_inventario_det_web DD WHERE DD.dinw_id = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into DOC_INVENTARIO_DET_WEB (DINW_ID, DIWD_ITEM, DIWD_ARTICULO, DIWD_CODBAR, DIWD_CANT, DIWD_UNIDAD, DIWD_COSTO, DIWD_LOTE, DIWD_VENCELOTE, DIWD_REF, DIWD_ANULADO, DIWD_OBS)
    values (:ID, :ITEM, :ARTICULO, :BARRAS, :CANT, :UNIDAD, :COSTO, :LOTE, :LOTEVEN, :REFER, 'N', :OBS);
/* DEVUELVA EL TOTAL */
SELECT SUM(DD.diwd_cant * DD.diwd_costo) FROM DOC_INVENTARIO_DET_WEB DD WHERE DD.dinw_id = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_REMICLIE_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    LOTE varchar(50),
    LOTEVEN date,
    REFER varchar(60),
    OBS varchar(1024))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO varchar(20);
declare variable UNIART varchar(8);
declare variable ORDEN varchar(12);
declare variable IDORD integer;
declare variable TIPO integer;
declare variable PREF varchar(4);
declare variable NUMERO varchar(8);
declare variable LON integer;
declare variable COSTO numeric(18,2);
declare variable ITEMO integer;
declare variable DTOP numeric(18,2);
begin
ARTICULO = NULL;
SELECT FIRST 1 B.ARTI_COD, COBA_UNIDAD
    from BARRAS_ARTICULO B, ARTICULO A, TARIFA_IVA T
    WHERE B.ARTI_COD = A.ARTI_COD AND COBA_COD = :BARRAS AND COBA_ACTIVO = 'S' and a.esar_cod <> 'I' AND A.taiv_cod = T.taiv_cod 
    INTO :ARTICULO, :uniart;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    SELECT FIRST 1 A.ARTI_COD, ARTI_UNIDAD
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.arti_cod = :barras AND A.taiv_cod = T.taiv_cod AND (a.esar_cod <> 'I')
        INTO :ARTICULO, :UNIART;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    exception articulo_no_existe 'NO SE ENCONTRO EL ARTICULO ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIART;

select d.dinw_tiporef, d.dinw_numref from doc_inventario_web d where d.dinw_id = :id into :tipo, :orden;
LON = STRLEN(ORDEN);
PREF = LEFT(ORDEN, LON - 6);
NUMERO = right(ORDEN, 6);
SELECT P.pedi_id FROM PEDIDOS P WHERE P.pref_pre = :PREF AND P.pedi_numero = :NUMERO INTO :IDORD;
SELECT FIRST 1 PD.pede_item, PD.pede_prunit, PD.pede_dtoporc FROM pedidos_detalle PD WHERE PD.pedi_id = :idord AND PD.arti_cod = :articulo
    INTO :ITEMO, :COSTO, :DTOP;
if (COSTO IS NULL) then
    COSTO = 0;
if (DTOP IS NULL) then
    DTOP = 0;
if (ITEMO = 0) then
    exception articulo_no_orden 'El articulo ' || articulo || ' no pertenece al pedido ' || :orden;
ITEM = 0;
SELECT MAX(diwd_item+1) FROM doc_inventario_det_web DD WHERE DD.dinw_id = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into DOC_INVENTARIO_DET_WEB (DINW_ID, DIWD_ITEM, DIWD_ARTICULO, DIWD_CODBAR, DIWD_CANT, DIWD_UNIDAD, DIWD_COSTO, DIWD_DTOPORC, DIWD_LOTE, DIWD_VENCELOTE, DIWD_REF, DIWD_ANULADO, DIWD_OBS)
    values (:ID, :ITEM, :ARTICULO, :BARRAS, :CANT, :UNIDAD, :COSTO, :DTOP, :LOTE, :LOTEVEN, :REFER, 'N', :OBS);
/* DEVUELVA EL TOTAL */
SELECT SUM(DD.diwd_cant * (DD.diwd_costo * (1 - :DTOP/100))) FROM DOC_INVENTARIO_DET_WEB DD WHERE DD.dinw_id = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_PEDIDO_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    PRUNIT numeric(18,2),
    DTOP numeric(9,2),
    REFER varchar(60),
    PROMO integer)
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO VARCHAR(20);
declare variable DESCRIP VARCHAR(300);
declare variable UNIART VARCHAR(8);
declare variable UNIBAR VARCHAR(8);
declare variable BOD VARCHAR(2);
declare variable LISTA INTEGER;
declare variable IVAP NUMERIC(9,2);
declare variable FACTOR NUMERIC(18,4);
begin
SELECT FIRST 1 A.ARTI_COD, ARTI_DES, TAIV_PORC, ARTI_UNIDAD, B.coba_unidad
    FROM ARTICULO A, TARIFA_IVA T, BARRAS_ARTICULO B
    WHERE B.coba_cod = :barras AND B.arti_cod = A.arti_cod AND A.taiv_cod = T.taiv_cod AND B.coba_activo = 'S' and ((a.esar_cod = 'A') or (a.esar_cod = 'B') or (a.esar_cod = 'K'))
    INTO :ARTICULO, :descrip, :IVAP, :UNIART, :UNIBAR;
if (ARTICULO = '') then
    exception articulo_no_existe 'NO SE ENCONTRO EL CODIGO DE BARRAS ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIBAR;
EXECUTE PROCEDURE factor_unidad_cant(:ARTICULO, :unidad) returning_values (:FACTOR);
SELECT BODE_COD FROM PUNTO_VENTA P, PEDIDO_WEB F
    WHERE F.ptvt_id = P.ptvt_id AND F.pewe_id = :ID
    INTO :BOD;
if (PRUNIT = 0) then
    BEGIN
    if ((BARRAS <> '') AND (BARRAS IS NOT NULL)) then
        BEGIN
        EXECUTE PROCEDURE factor_unidad_cant(:ARTICULO, :unidad) returning_values (:FACTOR);
        SELECT FIRST 1 PRAR_FIJO * :FACTOR FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :ARTICULO AND PRAR_CANTMIN <= :FACTOR
            ORDER BY PRAR_CANTMIN DESC
            INTO :PRUNIT;
        END
    END
LISTA = 0;
SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA
    WHERE PA.arti_cod = :articulo AND PA.prar_fijo = :prunit INTO :LISTA;
if (LISTA = 0) then
    BEGIN
    if (UNIDAD = UNIART) then
        BEGIN
        SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA
            WHERE PA.arti_cod = :articulo AND PA.prar_cantmin <= 1
            ORDER BY PA.prar_cantmin DESC
            INTO :LISTA;
        END
    SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA, UNIDAD_ARTICULO U
        WHERE PA.arti_cod = :articulo AND U.arti_cod = :articulo AND U.unar_unidad = :unidad AND U.unar_faccan >= PA.prar_cantmin
        ORDER BY PA.prar_cantmin DESC
        INTO :LISTA;
    END
ITEM = 0;
SELECT MAX(PEWD_ITEM+1) FROM pedido_web_detalle WHERE PEWE_ID = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
if (PROMO <> 0) then
    BOD = '99';
insert into PEDIDO_WEB_DETALLE (PEWE_ID, PEWD_ITEM, ARTI_COD, PEWD_CODBAR, BODE_COD, PEWD_CANT, PEWD_UNIDAD,
                                PEWD_FACTOR, LIPR_COD, PEWD_PRUNIT, PEWD_DTOP, PEWD_DTO1, PEWD_DTO2, PEWD_DTO3,
                                PEWD_IVAP, PEWD_IVAMONTO, PEWD_CONSUMO, PEWD_TOTAL, PEWD_REFERENCIA, PEWD_DTOM,
                                PEWD_DTO1M, PEWD_DTO2M, PEWD_DTO3M, PEWD_DESC, PEWD_ANULADO)
values (:ID, :ITEM, :articulo, :barras, :bod, :CANT, :UNIDAD, :FACTOR, :lista,
        :PRUNIT, :DTOP, 0, 0, 0, :IVAP, 0, 0, 0, :refer, 0, 0, 0, 0, :descrip, 'N');
/* DEVUELVA EL TOTAL */
SELECT SUM(pewd_total) FROM pedido_web_detalle WHERE PEWE_ID = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_DEVOLUCION_APP (
    ID integer,
    BARRAS varchar(20),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    LOTE varchar(20),
    LOTEVEN date,
    REFER varchar(60),
    OBS varchar(1024))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO varchar(20);
declare variable UNIART varchar(8);
declare variable ORDEN varchar(12);
declare variable IDORD integer;
declare variable TIPO integer;
declare variable PREF varchar(4);
declare variable NUMERO varchar(8);
declare variable LON integer;
declare variable COSTO numeric(18,2);
declare variable ITEMO integer;
begin
ARTICULO = NULL;
SELECT FIRST 1 B.ARTI_COD, COBA_UNIDAD
    from BARRAS_ARTICULO B, ARTICULO A
    WHERE B.ARTI_COD = A.ARTI_COD AND COBA_COD = :BARRAS AND COBA_ACTIVO = 'S' and a.esar_cod <> 'I'
    INTO :ARTICULO, :uniart;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    SELECT FIRST 1 A.ARTI_COD, ARTI_UNIDAD
        FROM ARTICULO A, TARIFA_IVA T
        WHERE A.arti_cod = :barras AND (a.esar_cod <> 'I')
        INTO :ARTICULO, :UNIART;
if ((ARTICULO IS NULL) or (ARTICULO = '')) then
    exception articulo_no_existe 'NO SE ENCONTRO EL ARTICULO ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIART;

select d.dinw_tiporef, d.dinw_numref from doc_inventario_web d where d.dinw_id = :id into :tipo, :orden;
ITEMO = 0;
if (TIPO = 31) then
    BEGIN
    LON = STRLEN(ORDEN);
    PREF = LEFT(ORDEN, LON - 8);
    NUMERO = right(ORDEN, 8);
    SELECT F.fact_id FROM FACTURAS F WHERE F.pref_pre = :PREF AND F.fact_numero = :NUMERO INTO :IDORD;
    SELECT FD.fade_item, FD.fade_prunit FROM FACTURAS_detalle FD WHERE FD.fact_id = :idord AND FD.arti_cod = :articulo
        INTO :ITEMO, :COSTO;
    if (ITEMO = 0) then
        exception articulo_no_orden 'El articulo ' || articulo || ' no pertenece a la factura ' || :orden;
    END
ITEM = 0;
SELECT MAX(diwd_item+1) FROM doc_inventario_det_web DD WHERE DD.dinw_id = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into DOC_INVENTARIO_DET_WEB (DINW_ID, DIWD_ITEM, DIWD_ARTICULO, DIWD_CODBAR, DIWD_CANT, DIWD_UNIDAD, DIWD_COSTO, DIWD_LOTE, DIWD_VENCELOTE, DIWD_REF, DIWD_ANULADO, DIWD_OBS)
    values (:ID, :ITEM, :ARTICULO, :BARRAS, :CANT, :UNIDAD, :COSTO, :LOTE, :LOTEVEN, :REFER, 'N', :OBS);
/* DEVUELVA EL TOTAL */
SELECT SUM(DD.diwd_cant * DD.diwd_costo) FROM DOC_INVENTARIO_DET_WEB DD WHERE DD.dinw_id = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure REGISTRE_ITEM_COTIZACION_APP (
    ID integer,
    BARRAS varchar(50),
    CANT numeric(18,4),
    UNIDAD varchar(8),
    PRUNIT numeric(18,2),
    DTOP numeric(9,2),
    REFER varchar(60))
returns (
    ITEM integer,
    TOTALF numeric(18,2))
as
declare variable ARTICULO VARCHAR(20);
declare variable DESCRIP VARCHAR(300);
declare variable UNIART VARCHAR(8);
declare variable UNIBAR VARCHAR(8);
declare variable BOD VARCHAR(2);
declare variable LISTA INTEGER;
declare variable IVAP NUMERIC(9,2);
declare variable FACTOR NUMERIC(18,4);
declare variable PTVT INTEGER;
begin
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'PEDIDOS', 'CODIGO PUNTO DE VENTA PARA PEDIDOS REGISTRADOS POR LA APP') returning_values (:PTVT);
SELECT FIRST 1 A.ARTI_COD, ARTI_DES, TAIV_PORC, ARTI_UNIDAD, B.coba_unidad
    FROM ARTICULO A, TARIFA_IVA T, BARRAS_ARTICULO B
    WHERE B.coba_cod = :barras AND B.arti_cod = A.arti_cod AND A.taiv_cod = T.taiv_cod AND B.coba_activo = 'S' and ((a.esar_cod = 'A') or (a.esar_cod = 'B') or (a.esar_cod = 'K'))
    INTO :ARTICULO, :descrip, :IVAP, :UNIART, :UNIBAR;
if (ARTICULO = '') then
    exception articulo_no_existe 'NO SE ENCONTRO EL CODIGO DE BARRAS ' || :BARRAS;

if ((UNIDAD = '') or (UNIDAD IS NULL)) then
    UNIDAD = UNIBAR;

SELECT BODE_COD FROM PUNTO_VENTA P WHERE ptvt_id = :PTVT INTO :BOD;
if (PRUNIT = 0) then
    BEGIN
    if ((BARRAS <> '') AND (BARRAS IS NOT NULL)) then
        BEGIN
        EXECUTE PROCEDURE factor_unidad_cant(:ARTICULO, :unidad) returning_values (:FACTOR);
        SELECT FIRST 1 PRAR_FIJO FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :ARTICULO AND PRAR_CANTMIN <= :FACTOR
            ORDER BY PRAR_CANTMIN DESC
            INTO :PRUNIT;
        END
    END
LISTA = 0;
SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA WHERE PA.arti_cod = :articulo AND PA.prar_fijo = :prunit INTO :LISTA;
if (LISTA = 0) then
    BEGIN
    if (UNIDAD = UNIART) then
        BEGIN
        SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA WHERE PA.arti_cod = :articulo AND PA.prar_cantmin <= 1
            ORDER BY PA.prar_cantmin DESC INTO :LISTA;
        END
    SELECT FIRST 1 LIPR_COD FROM PRECIOS_ARTICULO PA, UNIDAD_ARTICULO U
        WHERE PA.arti_cod = :articulo AND U.arti_cod = :articulo AND U.unar_unidad = :unidad AND U.unar_faccan >= PA.prar_cantmin
        ORDER BY PA.prar_cantmin DESC INTO :LISTA;
    END
ITEM = 0;
SELECT MAX(COWD_ITEM+1) FROM cotizacion_web_detalle WHERE COWE_ID = :ID INTO :ITEM;
if ((ITEM = 0) or (ITEM IS NULL)) then
    ITEM = 1;
insert into COTIZACION_WEB_DETALLE (COWE_ID, COWD_ITEM, ARTI_COD, COWD_CODBAR, COWD_CANT, COWD_UNIDAD, COWD_FACTOR,
                                    LIPR_COD, COWD_PRUNIT, COWD_DTOP, COWD_IVAP, COWD_IVAMONTO, COWD_CONSUMO,
                                    COWD_TOTAL, COWD_REFERENCIA, COWD_DTOM, COWD_DESC)
    values (:ID, :ITEM, :articulo, :barras, :CANT, :UNIDAD, :FACTOR, :lista, :PRUNIT, :DTOP, :IVAP, 0, 0, 0, :refer, 0, :descrip);
/* DEVUELVA EL TOTAL */
SELECT SUM(cowd_total) FROM cotizacion_web_detalle WHERE COWE_ID = :id INTO :TOTALF;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure PRESENTACIONES_APP
returns (
    ARTICULO varchar(20),
    BARRAS varchar(50),
    DESCRIPCION varchar(60),
    UNIDAD varchar(8),
    FACTOR numeric(18,4),
    IVA numeric(9,2),
    GRUPO varchar(2),
    SUBGRUPO varchar(3),
    MARCA varchar(3),
    CANT numeric(18,4),
    PRECIO numeric(18,2),
    ACTUALIZADO varchar(5))
as
declare variable FECHA date;
declare variable HORA time;
declare variable FECHOY date;
declare variable HORHOY time;
declare variable SALDO numeric(18,4);
declare variable OPER char(1);
declare variable CODBOD VARCHAR(2);
declare variable EXISTOT varchar(6);
begin
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
SELECT LOGP_FECHA, LOGP_HORA FROM log_presentaciones INTO :FECHA, :HORA;
FECHOY = CAST('NOW' AS DATE);
HORHOY = CAST('NOW' AS TIME);
UPDATE log_presentaciones SET FECAHORA = :FECHOY, HORAHORA = :HORHOY;
/* CAMBIO DE ARTICULOS */
FOR SELECT DISTINCT ARTI_COD, SUBSTRING(ARTI_DES FROM 1 FOR 60), ARTI_UNIDAD, GRUP_COD, IIF(SUBG_COD IS null,  '', SUBG_COD), IIF(MARC_COD IS NULL, '', MARC_COD), TAIV_PORC
    FROM ARTICULO A, TARIFA_IVA T, AUDITORIA AU
    WHERE A.taiv_cod = T.taiv_cod AND ((AU.tido_cod = 101) or (AU.tido_cod = 125) or (AU.tido_cod = 126)) AND AU.audi_cod = A.arti_cod
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))) AND ((A.esar_cod = 'A') or (A.esar_cod = 'B') or (A.esar_cod = 'K'))
    ORDER BY AUDI_ID
    INTO :ARTICULO, :DESCRIPCION, :UNIDAD, :GRUPO, :SUBGRUPO, :MARCA, :IVA
    DO
    BEGIN
    EXECUTE PROCEDURE NOMBRE_ASCII(descripcion) returning_values (descripcion);
    EXECUTE PROCEDURE NOMBRE_ASCII(unidad) returning_values (unidad);
    EXECUTE PROCEDURE NOMBRE_ASCII(SUBGRUPO) returning_values (SUBGRUPO);
    EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
    BARRAS = '';
    FACTOR = 1;
    execute procedure lee_configuracion('FACTURACION','PEDIDOS', 'CODIGO BODEGA A USAR EN PEDIDOS APP') returning_values (CODBOD);

    CANT = 0;
    if (EXISTOT = 'TOTAL') then
        EXECUTE PROCEDURE saldo_total_inventario (:articulo, :fechoy) returning_values (:SALDO);
    ELSE
        EXECUTE PROCEDURE saldo_inventario (:articulo, :CODBOD, :fechoy) returning_values (:SALDO);
    CANT = SALDO;
--    if (CANT > 0) then
        BEGIN
        SELECT FIRST 1 COBA_COD FROM BARRAS_ARTICULO B WHERE B.ARTI_COD = :ARTICULO AND B.coba_unidad = :unidad AND B.coba_activo = 'S'
            INTO :BARRAS;
        if ((BARRAS <> '') AND (BARRAS IS NOT NULL)) then
            BEGIN
            ACTUALIZADO = 'True';
            OPER = 'U';
            if (exists (select au.audi_oper from auditoria au where au.tido_cod = 125 and au.audi_cod = :articulo and
                AUDI_OPER = 'I' AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))))) then
                ACTUALIZADO = 'False';
            SELECT FIRST 1 PRAR_FIJO FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :ARTICULO AND PRAR_CANTMIN <= 1
                ORDER BY PRAR_CANTMIN DESC
                INTO :PRECIO;
    EXECUTE PROCEDURE NOMBRE_ASCII(BARRAS) returning_values (BARRAS);
            suspend;
            END
        /* BUSQUE LAS PRESENTACIONES */
        FOR SELECT COBA_COD, COBA_UNIDAD, UNAR_FACCAN FROM BARRAS_ARTICULO B, UNIDAD_ARTICULO U
            WHERE B.ARTI_COD = :ARTICULO AND U.arti_cod = :ARTICULO AND B.coba_unidad = U.unar_unidad
            AND B.coba_activo = 'S' AND U.unar_activa = 'S' AND UNAR_FACCAN <> 0
            INTO :BARRAS, :UNIDAD, :FACTOR
            DO
            BEGIN
            ACTUALIZADO = 'True';
            if (exists (select au.audi_oper from auditoria au where au.tido_cod = 125 and au.audi_cod = :articulo and
                AUDI_OPER = 'I' AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))))) then
                ACTUALIZADO = 'False';
            SELECT FIRST 1 (PRAR_FIJO * :FACTOR) FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :ARTICULO AND PRAR_CANTMIN <= :FACTOR
                ORDER BY PRAR_CANTMIN DESC
                INTO :PRECIO;
            CANT = SALDO / FACTOR;
    EXECUTE PROCEDURE NOMBRE_ASCII(BARRAS) returning_values (BARRAS);
            suspend;
            END
        END
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure LISTA_PRECIOS_CON_ESCALA (
    FECINI date,
    FECFIN date,
    AGENCIA integer,
    LISTA integer,
    GRUPO varchar(2))
returns (
    ARTICULO varchar(20),
    DESCRIPCION varchar(300),
    PRECIO numeric(18,2),
    PRECIOESCALA1 numeric(18,2),
    ESCALA1 numeric(18,4),
    PRECIOESCALA2 numeric(18,2),
    ESCALA2 numeric(18,4),
    IVA numeric(9,2))
as
declare variable LISTA1 INTEGER;
begin
FOR SELECT P.ARTI_COD, ARTI_DES, TAIV_PORC, P.prar_fijo
    FROM ARTICULO A, TARIFA_IVA T, PRECIOS_ARTICULO P
    WHERE A.taiv_cod = T.taiv_cod AND ((A.esar_cod = 'A') or (A.esar_cod = 'B') or (A.esar_cod = 'K')) AND A.arti_cod = P.arti_cod AND P.lipr_cod = :lista
    AND ((GRUP_COD = :GRUPO) or (:GRUPO IS NULL) or (:GRUPO = ''))
    INTO :ARTICULO, :descripcion, :IVA, :PRECIO
    DO
    BEGIN
    PRECIOESCALA1 = 0;
    ESCALA1 = 0;
    PRECIOESCALA2 = 0;
    ESCALA2 = 0;
    SELECT FIRST 1 P.prar_cantmin, P.prar_fijo, l.lipr_cod FROM precios_articulo P, lista_precios L
        WHERE ARTI_COD = :ARTICULO AND P.LIPR_COD <> :LISTA AND P.lipr_cod = L.lipr_cod AND L.sucu_id = :AGENCIA
        ORDER BY P.prar_cantmin DESC
        INTO :ESCALA1, :precioescala1, :LISTA1;
    SELECT FIRST 1 P.prar_cantmin, P.prar_fijo FROM precios_articulo P, lista_precios L
        WHERE ARTI_COD = :ARTICULO AND P.LIPR_COD <> :LISTA AND P.lipr_cod = L.lipr_cod AND L.sucu_id = :AGENCIA AND P.lipr_cod <> :LISTA1
        ORDER BY P.prar_cantmin DESC
        INTO :ESCALA2, :precioescala2;
    suspend;
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_EXISTENCIAS_WEB (
    FECHA date)
returns (
    CODIGO varchar(20),
    CODBOD varchar(2),
    NOMBOD varchar(30),
    AGENCIA integer,
    EXISTENCIA numeric(18,2))
as
declare variable EXISTANT NUMERIC(18,4);
begin
FOR SELECT ARTI_COD FROM ARTICULO WHERE ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))  AND SUBSTRING(ARTI_COD FROM 1 FOR 2) <> '.t' ORDER BY ARTI_COD INTO :CODIGO
    DO
    BEGIN
    FOR SELECT bodega, EXISTENCIA FROM existencias_menos_reserva(:CODIGO, :FECHA) INTO :CODBOD, :EXISTENCIA
        DO
        BEGIN
        existant = null;
        SELECT EXISTENCIA FROM existencias_articulo_web WHERE ARTICULO = :codigo AND BODEGA = :codbod INTO :existant;
        if (existant is null) then
            existant = 0;
        if (existant <> EXISTENCIA) then
            BEGIN
            delete from EXISTENCIAS_ARTICULO_WEB WHERE ARTICULO = :codigo AND BODEGA = :codbod;
            SELECT BODE_NOM, SUCU_ID FROM BODEGA WHERE BODE_COD = :codbod INTO :nombod, :AGENCIA;
            insert into EXISTENCIAS_ARTICULO_WEB (ARTICULO, BODEGA, EXISTENCIA)
                values (:CODIGO, :CODBOD, :EXISTENCIA);
            suspend;
            END
        END
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS_WEB (
    FECHA date)
returns (
    CODIGO varchar(20),
    DESCRIPCION varchar(60),
    UNIDAD varchar(8),
    UNIALT1 varchar(8),
    FACTCN1 numeric(18,2),
    FACTPR1 numeric(18,2),
    UNIALT2 varchar(8),
    FACTCN2 numeric(18,2),
    FACTPR2 numeric(18,2),
    UNIALT3 varchar(8),
    FACTCN3 numeric(18,2),
    FACTPR3 numeric(18,2),
    CODGRP varchar(2),
    NOMGRP varchar(30),
    CODSUBG varchar(3),
    NOMSUBG varchar(30),
    CODMARCA varchar(3),
    NOMMARCA varchar(30),
    IVA numeric(9,2),
    ESTAMPILLA numeric(18,2),
    PRECIO numeric(18,2),
    PRECIO2 numeric(18,2),
    CANTMIN2 numeric(18,2),
    PRECIO3 numeric(18,2),
    CANTMIN3 numeric(18,2),
    PRECIO4 numeric(18,2),
    CANTMIN4 numeric(18,2),
    BARRAS smallint)
as
DECLARE VARIABLE LISTA INTEGER;
declare variable DIG INTEGER;
declare variable I INTEGER;
declare variable uni VARCHAR(8);
declare variable facc NUMERIC(18,4);
declare variable facp NUMERIC(18,4);
declare variable CANTM NUMERIC(18,4);
declare variable FECAUD DATE;
declare variable HORAUD TIME;
declare variable FECULT DATE;
declare variable HORULT TIME;
declare variable OK CHAR(1);
BEGIN
BARRAS = 1;
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U
    WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
FOR select arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), grup_cod, subg_cod, marc_cod, arti_unidad, taiv_porc, arti_consumo
    from articulo a, tarifa_iva t
    where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))
    ORDER BY ARTI_COD
    INTO :CODIGO, :descripcion, :codgrp, :codsubg, :codmarca, :UNIDAD, :IVA, :estampilla
    do
    begin
    OK = 'N';

    SELECT FIRST 1 AUDI_FECHA, AUDI_HORA FROM AUDITORIA
        WHERE AUDI_COD = :CODIGO AND ((TIDO_COD = 101) or (TIDO_COD = 124) or (TIDO_COD = 126))
        ORDER BY AUDI_ID DESC
        INTO :FECAUD, :HORAUD;
    if ((FECAUD >= fecha) or (FECHA < '2016/01/01'))  then
        OK = 'S';
    if (OK =  'S') then
        BEGIN
        /* unidades alternativas */
        I = 0;
        unialt1 = '';
        factcn1 = 0;
        factpr1 = 0;
        unialt2 = '';
        factcn2 = 0;
        factpr2 = 0;
        unialt3 = '';
        factcn3 = 0;
        factpr3 = 0;
        for select first 3 u.unar_unidad, u.unar_faccan, u.unar_facpre from unidad_articulo u
            where arti_cod = :codigo and u.unar_activa = 'S'
            into :uni, :facc, :facp
            DO
            BEGIN
            if (I = 0) then
                BEGIN
                unialt1 = uni;
                factcn1 = facc;
                factpr1 = facp;
                END
            if (I = 1) then
                BEGIN
                unialt2 = uni;
                factcn2 = facc;
                factpr2 = facp;
                END
            if (I = 2) then
                BEGIN
                unialt3 = uni;
                factcn3 = facc;
                factpr3 = facp;
                END
            I = I + 1;
            END
        /* PRECIOS */
        I = 0;
        precio2 = 0;
        cantmin2 = 0;
        precio3 = 0;
        cantmin3 = 0;
        precio4 = 0;
        cantmin4 = 0;
        FOR SELECT FIRST 3 PRAR_FIJO, PRAR_REDON, PRAR_CANTMIN FROM PRECIOS_ARTICULO P
            WHERE ARTI_COD = :codigo AND LIPR_COD <> :LISTA ORDER BY PRAR_CANTMIN DESC
            INTO :PRECIO, :DIG, :cantm
            DO
            BEGIN
            EXECUTE procedure redondee(precio, DIG) returning_values (PRECIO);
            if (I = 0) then
                BEGIN
                precio2 = precio;
                cantmin2 = cantm;
                END
            if (I = 1) then
                BEGIN
                precio3 = precio;
                cantmin3 = cantm;
                END
            if (I = 2) then
                BEGIN
                precio4 = precio;
                cantmin4 = cantm;
                END
            I = I + 1;
            END
        SELECT PRAR_FIJO, PRAR_REDON FROM PRECIOS_ARTICULO WHERE ARTI_COD = :codigo AND LIPR_COD = :LISTA INTO :precio, :dig;
        EXECUTE procedure redondee(precio, DIG) returning_values (PRECIO);
        NOMGRP = '';
        SELECT GRUP_NOM FROM GRUPO WHERE GRUP_COD = :codgrp INTO :nomgrp;
        nomsubg = '';
        SELECT SUBG_NOM FROM SUBGRUPO WHERE GRUP_COD = :codgrp AND SUBG_COD = :codsubg INTO :nomsubg;
        nommarca = '';
        SELECT MARC_NOM FROM marcas WHERE MARC_COD = :codmarca INTO :nommarca;
        SUSPEND;
        END
    end
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS_PRECIOS (
    CODIGO varchar(20),
    LISTA integer)
returns (
    ARTICULO varchar(20),
    DES varchar(300),
    GRUPO varchar(30),
    MARCA varchar(30),
    UNIDAD varchar(8),
    PRECIO numeric(18,2),
    IVA numeric(9,2),
    OBSERVACIONES blob sub_type TEXT segment size 80,
    FOTO blob sub_type BINARY segment size 80,
    PESO numeric(18,2),
    IVAMONTO numeric(18,2),
    CONSUMO numeric(18,2),
    TOTAL numeric(18,2),
    LARGO numeric(18,2),
    ALTO numeric(18,2),
    ANCHO numeric(18,2),
    UNIDAD1 varchar(8),
    PRECIO1 numeric(18,2),
    UNIDAD2 varchar(8),
    PRECIO2 numeric(18,2),
    UNIDAD3 varchar(8),
    PRECIO3 numeric(18,2),
    PUM numeric(18,2))
as
declare variable DIG INTEGER;
declare variable ITEMS INTEGER;
declare variable CODGRP VARCHAR(2);
declare variable CODMAR VARCHAR(3);
declare variable IVAINC VARCHAR(2);
declare variable UNI2 VARCHAR(8);
declare variable FAC2 NUMERIC(18,4);
declare variable FACTOR NUMERIC(18,6);
declare variable dtop NUMERIC(18,2);
declare variable preciodto NUMERIC(18,2);
declare variable CANTMIN NUMERIC(18,4);
declare variable PRMASIVA CHAR(2);
declare variable ICOINC VARCHAR(2);
BEGIN
EXECUTE PROCEDURE lee_configuracion('FACTURACION', 'ARTICULOS', 'IMPOCONSUMO INCLUIDO EN EL PRECIO BASE DE VENTA ANTES DE IVA') returning_values (:icoinc);

select count(arti_cod) from BARRAS_ARTICULO WHERE COBA_COD = :CODIGO AND COBA_ACTIVO = 'S' INTO :ITEMS;
if (ITEMS > 0) then
    SELECT first 1 ARTI_COD, COBA_DES, COBA_UNIDAD from BARRAS_ARTICULO
        WHERE COBA_COD = :CODIGO AND COBA_ACTIVO = 'S' INTO :ARTICULO, :DES, :UNIDAD;
ELSE
    SELECT ARTI_COD, ARTI_DES, ARTI_UNIDAD FROM ARTICULO
        WHERE ARTI_COD = :CODIGO INTO :ARTICULO, :DES, :UNIDAD;
EXECUTE PROCEDURE factor_unidad_cant (:articulo, :unidad) returning_values(:factor);

EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'POS', 'CONSULTA PRECIOS EN UNIDAD ALTERNATIVA CON IMPUESTOS INCLUIDOS') returning_values (PRMASIVA);
FOR select grup_cod, taiv_porc, marc_cod, ARTI_OBS, ARTI_PESO, ARTI_LARGO, ARTI_ALTO, ARTI_ANCHO, ARTI_FOTO, ARTI_CONSUMO
    from articulo a, tarifa_iva t
    where a.taiv_cod = t.taiv_cod AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K'))  AND A.arti_cod = :ARTICULO
    INTO :CODGRP, :IVA, :CODMAR, :observaciones, :peso, :largo, :alto, :ancho, :foto, :CONSUMO
    do
    begin
    SELECT GRUP_NOM FROM GRUPO WHERE GRUP_COD = :CODGRP INTO :GRUPO;
    SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :CODMAR INTO :MARCA;
    select first 1 ftar_imagen from fotos_articulo where arti_cod = :articulo and ftar_imagen is not null into :foto;
    PRECIO = 0;
    EXECUTE PROCEDURE precio_cantidad(:articulo, :lista, 0, 1, :UNIDAD) returning_values (:precio,  :CANTMIN);
/*    SELECT prar_fijo PRECIO, PRAR_CONSUMO FROM precios_articulo
        WHERE arti_cod = :ARTICULO and lipr_cod = :LISTA INTO :PRECIO, :CONSUMO;*/
    EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
    IF (PESO <> 0) THEN
        PUM = PRECIO / PESO;
    ELSE
        PUM = 0;
--    PRECIO = :precio * :FACTOR;
    select DTOP, PRECIO from VALIDE_DESCUENTO(:ARTICULO, '9876543210', 1, 1) where ok = 'S' into :DTOP, :preciodto;
    if ((preciodto <> 0) AND (preciodto IS NOT NULL)) then
        PRECIO = PRECIODTO;
    ELSE
        if (DTOP IS NOT NULL) then
            PRECIO = PRECIO * (100 - :DTOP) / 100;
    SELECT LIPR_MODIF FROM LISTA_PRECIOS WHERE LIPR_COD = :LISTA INTO :IVAINC;
    if (IVAINC = 'N') then
        BEGIN
        if (icoinc = 'SI') then
            begin
            IVAMONTO = (PRECIO - CONSUMO) * IVA / 100;
            TOTAL = PRECIO + IVAMONTO;
            end
        else
            begin
            IVAMONTO = PRECIO * IVA / 100;
            TOTAL = PRECIO + IVAMONTO + CONSUMO;
            end
        END
    ELSE
        BEGIN
        TOTAL = PRECIO;
        IVAMONTO = (PRECIO - CONSUMO) * IVA / (100 + IVA);
        PRECIO = (PRECIO - CONSUMO) / (1 + (IVA/100));
        END
    ITEMS = 0;
    PRECIO1 = 0;
    UNIDAD1 = '';
    PRECIO2 = 0;
    UNIDAD2 = '';
    PRECIO3 = 0;
    UNIDAD3 = '';
    for select unar_unidad, UNAR_FACCAN, unar_facpre from unidad_articulo where arti_cod = :articulo
        into :uni2, factor, :fac2
        do
        begin
        ITEMS = ITEMS + 1;
        if (ITEMS = 1) then
            BEGIN
            UNIDAD1 = UNI2;
            EXECUTE PROCEDURE precio_cantidad(:articulo, :lista, 0, :factor, :UNIDAD) returning_values (:precio1,  :CANTMIN);
            if (IVAINC <> 'N') then
                PRECIO1 = (PRECIO1 - CONSUMO) / (1 + (IVA/100));
            IF (prmasiva = 'SI') THEN
                BEGIN
                PRECIO1 = PRECIO1 * ( 1 + (IVA / 100)) + CONSUMO;
                END
            PRECIO1 = PRECIO1 * FAC2;
            END
        if (ITEMS = 2) then
            BEGIN
            UNIDAD2 = UNI2;
            EXECUTE PROCEDURE precio_cantidad(:articulo, :lista, 0, :factor, :UNIDAD) returning_values (:precio2,  :CANTMIN);
            if (IVAINC <> 'N') then
                PRECIO2 = (PRECIO2 - CONSUMO) / (1 + (IVA/100));
            IF (prmasiva = 'SI') THEN
                BEGIN
                PRECIO2 = PRECIO2 * ( 1 + (IVA / 100)) + CONSUMO;
                END
            PRECIO2 = PRECIO2 * FAC2;
            END
        if (ITEMS = 3) then
            BEGIN
            UNIDAD3 = UNI2;
            EXECUTE PROCEDURE precio_cantidad(:articulo, :lista, 0, :factor, :UNIDAD) returning_values (:precio3,  :CANTMIN);
            if (IVAINC <> 'N') then
                PRECIO3 = (PRECIO3 - CONSUMO) / (1 + (IVA/100));
            IF (prmasiva = 'SI') THEN
                BEGIN
                PRECIO3 = PRECIO3 * ( 1 + (IVA / 100)) + CONSUMO;
                END
            PRECIO3 = PRECIO3 * FAC2;
            END
        end
    SUSPEND;
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS_MOVILC (
    BUSCAR varchar(100))
returns (
    CODIGO varchar(20),
    DES varchar(60),
    DESCORTA varchar(30),
    GRUPO varchar(30),
    SUBGR varchar(3),
    MARCA varchar(30),
    UNIDAD varchar(8),
    ALTERNATIVA varchar(30),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    PRECIO numeric(18,2),
    FOTO blob sub_type BINARY segment size 80,
    OBS blob sub_type TEXT segment size 80)
as
DECLARE VARIABLE LISTA INTEGER;
DECLARE VARIABLE EXIST CHAR(2);
DECLARE VARIABLE SINEXIST CHAR(2);
declare variable DIG INTEGER;
declare variable OK CHAR(1);
declare variable FECHA DATE;
declare variable CODBOD VARCHAR(2);
declare variable EXISTOT VARCHAR(6);
BEGIN
EXISTEN = 0;
FECHA = cast('now' as DATE);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:EXIST);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (:sinexist);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
if (LISTA > 0) then
    BEGIN
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
        FOR select a.arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, ARTI_OBS, ARTI_FOTO
            from articulo a, tarifa_iva t
            where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
            ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))  AND A.ARTI_COD LIKE :BUSCAR
            INTO :CODIGO, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :OBS, :FOTO
            do                                                                                         
            begin
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :GRUPO INTO GRUPO;
            SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :MARCA INTO MARCA;
            SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :SUBGR AND GRUP_COD = :GRUPO INTO :SUBGR;
            EXECUTE PROCEDURE NOMBRE_ASCII(GRUPO) returning_values (GRUPO);
            EXECUTE PROCEDURE NOMBRE_ASCII(SUBGR) returning_values (SUBGR);
            EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
            ALTERNATIVA = '';
            select FIRST 1 unar_unidad || ' x ' || unar_faccan FROM unidad_articulo WHERE ARTI_COD = :codigo INTO :alternativa;
            OK = 'N';
            PRECIO = 0;
            SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
            EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
            if (EXIST = 'SI') then
                BEGIN
                if (EXISTOT = 'TOTAL') then
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                ELSE
                    BEGIN
                    select first 1 p.bode_cod from punto_venta p, usuario u where u.user_cod = USER and ((u.sucu_id = p.sucu_id) or (u.sucu_id = 0))  into :codbod;
                    EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
                    END
                if ((SINEXIST = 'SI')  or (existen <> 0)) then
                    OK = 'S';
                END
            ELSE
                OK = 'S';
            if (ok = 'S') then
                SUSPEND;
            end
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS_MOVIL (
    BUSCAR varchar(100))
returns (
    CODIGO varchar(20),
    DES varchar(60),
    DESCORTA varchar(30),
    GRUPO varchar(30),
    SUBGR varchar(3),
    MARCA varchar(30),
    UNIDAD varchar(8),
    ALTERNATIVA varchar(30),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    PRECIO numeric(18,2),
    FOTO blob sub_type BINARY segment size 80,
    OBS blob sub_type TEXT segment size 80)
as
DECLARE VARIABLE LISTA INTEGER;
DECLARE VARIABLE EXIST CHAR(2);
DECLARE VARIABLE SINEXIST CHAR(2);
declare variable DIG INTEGER;
declare variable OK CHAR(1);
declare variable FECHA DATE;
declare variable CODBOD VARCHAR(2);
declare variable EXISTOT VARCHAR(6);
BEGIN
EXISTEN = 0;
FECHA = cast('now' as DATE);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:EXIST);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (:sinexist);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
if (LISTA > 0) then
    BEGIN
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
        BEGIN
        insert into ARTICULOS_REPORTE (ARTI_COD, ARRE_CANT)
        values (:BUSCAR, 101);
        FOR select a.arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, grup_cod, subg_cod, arti_unidad, taiv_porc, marc_cod, ARTI_CONSUMO, ARTI_OBS, ARTI_FOTO
            from articulo a, tarifa_iva t
            where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t' and
            ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))  AND (upper(A.ARTI_DES) like upper(:buscar))
            INTO :CODIGO, :DES, :DESCORTA, :GRUPO, :SUBGR, :UNIDAD, :IVA, :MARCA, :CONSUMO, :OBS, :FOTO
            do                                                                                         
            begin
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            SELECT GRUP_NOM FROM GRUPO G WHERE GRUP_COD = :GRUPO INTO GRUPO;
            SELECT MARC_NOM FROM MARCAS WHERE MARC_COD = :MARCA INTO MARCA;
            SELECT SUBG_NOM FROM SUBGRUPO WHERE SUBG_COD = :SUBGR AND GRUP_COD = :GRUPO INTO :SUBGR;
            EXECUTE PROCEDURE NOMBRE_ASCII(GRUPO) returning_values (GRUPO);
            EXECUTE PROCEDURE NOMBRE_ASCII(SUBGR) returning_values (SUBGR);
            EXECUTE PROCEDURE NOMBRE_ASCII(MARCA) returning_values (MARCA);
            ALTERNATIVA = '';
            select FIRST 1 unar_unidad || ' x ' || unar_faccan FROM unidad_articulo WHERE ARTI_COD = :codigo INTO :alternativa;
            OK = 'N';
            PRECIO = 0;
            SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
            EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
            if (EXIST = 'SI') then
                BEGIN
                if (EXISTOT = 'TOTAL') then
                    EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
                ELSE
                    BEGIN
                    select first 1 p.bode_cod from punto_venta p, usuario u where u.user_cod = USER and ((u.sucu_id = p.sucu_id) or (u.sucu_id = 0))  into :codbod;
                    EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
                    END
                if ((SINEXIST = 'SI')  or (existen <> 0)) then
                    OK = 'S';
                END
            ELSE
                OK = 'S';
            if (ok = 'S') then
                SUSPEND;
            end
        END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CONSULTA_ARTICULOS (
    INACTIVOS char(1))
returns (
    CODIGO varchar(20),
    DES varchar(300),
    GRUPO varchar(30),
    MARCA varchar(30),
    UNIDAD varchar(8),
    CONSUMO numeric(18,2),
    ESTADO varchar(30),
    IVA numeric(9,2),
    CODIGO1 varchar(20),
    CODIGO2 varchar(20),
    CODIGO3 varchar(20),
    UNIDAD2 varchar(8),
    FACTOR2 numeric(18,4),
    UNIDAD3 varchar(8),
    FACTOR3 numeric(18,4))
as
declare variable I INTEGER;
declare variable BARRAS VARCHAR(8);
declare variable FACTOR NUMERIC(18,4);
BEGIN
FOR select a.arti_cod, arti_des, grup_cod, arti_unidad, arti_consumo, esar_cod, taiv_porc, marc_cod
    from articulo a, tarifa_iva t
    where a.taiv_cod = t.taiv_cod
    INTO :CODIGO, :DES, :GRUPO, :UNIDAD, :CONSUMO, :ESTADO, :IVA, :MARCA
    do
    BEGIN
    if ((INACTIVOS = 'S') or (ESTADO = 'A') or (ESTADO = 'B') or ((INACTIVOS = 'C') AND (ESTADO = 'N')) ) then
        begin
        I = 0;
        CODIGO1 = '';
        CODIGO2 = '';
        CODIGO3 = '';
        for SELECT COBA_COD FROM BARRAS_ARTICULO WHERE ARTI_COD = :CODIGO INTO :BARRAS
            DO
            BEGIN
            I = I + 1;
            if (I = 1) then
                CODIGO1 = BARRAS;
            if (I = 2) then
                CODIGO2 = BARRAS;
            if (I = 3) then
                CODIGO3 = BARRAS;
            END
        I = 0;
        UNIDAD2 = '';
        UNIDAD3 = '';
        for SELECT UNAR_UNIDAD, UNAR_FACCAN FROM UNIDAD_ARTICULO WHERE ARTI_COD = :CODIGO INTO :BARRAS, :FACTOR
            DO
            BEGIN
            I = I + 1;
            if (I = 1) then
                BEGIN
                UNIDAD2 = BARRAS;
                FACTOR2 = FACTOR;
                END
            if (I = 2) then
                BEGIN
                UNIDAD3 = BARRAS;
                FACTOR3 = FACTOR;
                END
            SUSPEND;
            end
        END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure CAMBIOS_APP
returns (
    ARTICULOS integer,
    EXISTENCIAS integer,
    CLIENTES integer)
as
declare variable FECHA DATE;
declare variable HORA TIME;
declare variable EXISPED INTEGER;
begin
SELECT LOGP_FECHA, LOGP_HORA FROM log_presentaciones INTO :FECHA, :HORA;
SELECT COUNT(DISTINCT ARTI_COD)
    FROM ARTICULO A, AUDITORIA AU
    WHERE ((AU.tido_cod = 101) or (AU.tido_cod = 126)) AND AU.audi_cod = A.arti_cod
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))) AND ((A.esar_cod = 'A') or (A.esar_cod = 'B') or (A.esar_cod = 'K'))
    INTO :ARTICULOS;

SELECT LOGE_FECHA, LOGE_HORA FROM log_existencias INTO :FECHA, :HORA;
SELECT COUNT(DISTINCT ARTI_COD)
    FROM MOVIMIENTO_ARTICULO M, AUDITORIA AU
    WHERE AU.tido_cod = M.mvar_tipodoc AND AU.audi_iddoc = M.mvar_idref
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA)))
    INTO :EXISTENCIAS;
SELECT COUNT(DISTINCT ARTI_COD)
    FROM PEDIDOS_DETALLE PD, PEDIDOS P, AUDITORIA AU
    WHERE AU.tido_cod = 34 AND AU.audi_iddoc = P.pedi_id AND P.pedi_id = PD.pedi_id AND P.pedi_anulado = 'N'
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA)))
    INTO :EXISPED;
if (EXISPED IS NULL) then
    EXISPED = 0;
EXISTENCIAS = EXISTENCIAS + EXISPED;

SELECT LOGC_FECHA, LOGC_HORA FROM LOG_CLIENTES INTO :FECHA, :HORA;
/* CAMBIO DE ARTICULOS */
SELECT COUNT(distinct T.TERC_NIT)
    FROM TERCEROS T, CLIENTES C, AUDITORIA AU
    WHERE (AU.tido_cod = 102) AND AU.audi_cod = T.terc_nit AND T.terc_nit = C.terc_nit
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))) AND C.clie_estado = 'A'
    INTO :CLIENTES;
suspend;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure BUSCAR_ARTICULOS_MOVIL_INV (
    BUSCAR varchar(100),
    CODBOD varchar(2),
    TIPOORD integer,
    NROORDEN varchar(12),
    TIPO integer)
returns (
    CODIGO varchar(20),
    DES varchar(60),
    DESCORTA varchar(30),
    UNIDAD varchar(8),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    CANT numeric(18,2),
    EXISTEN numeric(18,2),
    COSTO numeric(18,2),
    FACTORD numeric(18,4),
    INVIMA varchar(30),
    CUM varchar(30),
    IUM varchar(30),
    IMAGENES integer)
as
declare variable LISTA integer;
declare variable DIG integer;
declare variable FECHA date;
declare variable VEREXIST varchar(6);
declare variable IDORD integer;
declare variable ITEORD integer;
declare variable CANTPEND NUMERIC(18, 4);
BEGIN
EXISTEN = 0;
FECHA = cast('now' as DATE);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:VEREXIST);
if ((tipoord = 18) and (nroorden <> '') and (nroorden is not null)) then
    begin
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
        for select od.orin_id, od.orid_item, od.arti_cod, SUBSTRING(OD.orid_desc FROM 1 FOR 60), OD.orid_cant, OD.orid_unidad, OD.orin_costo from ordenes_inventario o, ordeninventario_detalle od
            where o.orin_id = od.orin_id and o.orin_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and o.orin_anulado = 'N' AND (upper(od.orid_desc) like upper('%'||:buscar||'%'))
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(18, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    else
        for select od.orin_id, od.orid_item, od.arti_cod, SUBSTRING(OD.orid_desc FROM 1 FOR 60), OD.orid_cant, OD.orid_unidad, OD.orin_costo
            from ordenes_inventario o, ordeninventario_detalle od
            where o.orin_id = od.orin_id and o.orin_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and o.orin_anulado = 'N'
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(18, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    end
if ((tipoord = 23) and (nroorden <> '') and (nroorden is not null)) then
    begin
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
        for select od.ordc_id, od.ocde_item, od.arti_cod, SUBSTRING(OD.ocde_desc FROM 1 FOR 60), OD.ocde_cant, OD.ocde_unidad, OD.ocde_prunit
            from ordenes_compra o, ordenes_compra_detalle od
            where o.ordc_id = od.ordc_id and o.ordc_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and o.ordc_anulado = 'N' AND (upper(od.ocde_desc) like upper('%'||:buscar||'%'))
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(23, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    else
        for select od.ordc_id, od.ocde_item, od.arti_cod, SUBSTRING(OD.ocde_desc FROM 1 FOR 60), OD.ocde_cant, OD.ocde_unidad, OD.ocde_prunit
            from ordenes_compra o, ordenes_compra_detalle od
            where o.ordc_id = od.ordc_id and o.ordc_numero = right(:nroorden, 6) and o.pref_pre = left(:nroorden, strlen(:nroorden)-6)
            and o.ordc_anulado = 'N'
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(23, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    end
if ((tipoord = 31) and (nroorden <> '') and (nroorden is not null)) then
    begin
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
        for select fd.fact_id, fd.fade_item, fd.arti_cod, SUBSTRING(FD.fade_desc FROM 1 FOR 60), FD.fade_cant, FD.fade_unidad, FD.fade_prunit from FACTURAS F, facturas_detalle Fd
            where F.fact_id = Fd.fact_id and f.fact_numero = right(:nroorden, 8) and f.pref_pre = left(:nroorden, strlen(:nroorden)-8)
            and f.fact_anulado = 'N' AND (upper(fd.fade_desc) like upper('%'||:buscar||'%'))
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(31, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    else
        for select fd.fact_id, fd.fade_item, fd.arti_cod, SUBSTRING(FD.fade_desc FROM 1 FOR 60), FD.fade_cant, FD.fade_unidad, FD.fade_prunit from FACTURAS F, facturas_detalle Fd
            where F.fact_id = Fd.fact_id and f.fact_numero = right(:nroorden, 8) and f.pref_pre = left(:nroorden, strlen(:nroorden)-8)
            and f.fact_anulado = 'N'
            into :idord, :iteord, :CODIGO, :DES, cant, :unidad, :costo
            do
            begin
            select arti_descorta, ARTI_INVIMA, ARTI_IUM, ARTI_CUM from articulo where arti_cod = :codigo into :descorta, :INVIMA, :IUM, :CUM;
            EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
            EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
            if (VEREXIST = 'SI') then
                EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            ELSE
                existen = 0;
            SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
            execute procedure faltante(31, :tipo, :idord, :iteord) returning_values (cant, unidad, factord);
            /* RESTE LOS DOCUMENTOS DE INVENTARIO SIN TERMINAR DE HOY */
            SELECT SUM(dd.diwd_cant * dd.diwd_factor) from doc_inventario_web DW, doc_inventario_det_web DD
                where DW.dinw_id = DD.dinw_id and DW.dinw_tiporef = :tipoord AND DW.dinw_numref = :nroorden and DD.diwd_articulo = :codigo and DD.diwd_anulado = 'N'
                and dw.dinw_iddoc = 0 and DW.dinw_tipo = :TIPO and dw.dinw_fecha = cast('now' as DATE)
                INTO :cantpend;
            if (cantpend is null) then
                cantpend = 0;
            CANT = CANT - CANTPEND;
            suspend;
            end
    end
if (tipoord = 0) then
  if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
    FOR select a.arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, arti_unidad, taiv_porc, ARTI_CONSUMO, ARTI_INVIMA, ARTI_IUM, ARTI_CUM
      from articulo a, tarifa_iva t where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t'
      AND ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K')) AND (upper(A.ARTI_DES) like upper('%'||:buscar||'%'))
      INTO :CODIGO, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO, :INVIMA, :IUM, :CUM
      do
      begin
      EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
      EXECUTE PROCEDURE NOMBRE_ASCII(DESCORTA) returning_values (DESCORTA);
      costo = 0;
      cant = 0;
      if (VEREXIST = 'SI') then
        EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
      ELSE
        existen = 0;
      SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
      SUSPEND;
      end
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure BUSCAR_ARTICULOS_MOVIL (
    BUSCAR varchar(100))
returns (
    CODIGO varchar(20),
    DES varchar(60),
    DESCORTA varchar(30),
    UNIDAD varchar(8),
    IVA numeric(9,2),
    CONSUMO numeric(18,2),
    EXISTEN numeric(18,2),
    PRECIO numeric(18,2),
    VEREXIST char(2),
    SINEXIST char(2),
    IMAGENES integer,
    MARCA varchar(30),
    BARRAS T_BARRAS)
as
declare variable LISTA integer;
declare variable DIG integer;
declare variable FECHA date;
declare variable CODBOD varchar(2);
declare variable EXISTOT varchar(6);
declare variable EXRESERV varchar(10);
declare variable RESERVADO numeric(18,2);
BEGIN
EXISTEN = 0;
FECHA = cast('now' as DATE);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS', 'VER EXISTENCIA EN CONSULTA ARTICULOS') returning_values (:VEREXIST);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION', 'PEDIDOS', 'VALIDAR EXISTENCIA TOTAL O SOLO EN LA BODEGA INDICADA EN EL PUNTO DE VENTA') returning_values (:EXISTOT);
EXECUTE PROCEDURE lee_configuracion ('FACTURACION','ARTICULOS','VER ARTICULOS SIN EXISTENCIA EN CONSULTA DE ARTICULOS') returning_values (:sinexist);
EXECUTE PROCEDURE LEE_CONFIGURACION ('FACTURACION', 'ARTICULOS', 'REDONDEO AL MULTIPLO DE DIEZ EN PRECIOS') returning_values (DIG);
execute procedure lee_configuracion('INVENTARIO','EXISTENCIAS','ACCION A TOMAR SI LA EXISTENCIA ESTA RESERVADA') returning_values(:exreserv);
SELECT FIRST 1 LIPR_COD FROM LISTA_PRECIOS L, USUARIO U WHERE USER_COD = USER AND ((L.SUCU_ID = U.sucu_id) or (L.SUCU_ID = 0) or (U.SUCU_ID = 0)) AND LIPR_PREDET = 'S'
    INTO :LISTA;
if (LISTA > 0) then
    BEGIN
    if ((BUSCAR IS NOT NULL) AND (BUSCAR <> '')) then
    --BUSCAR POR CODIGO
    FOR select a.arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, arti_unidad, taiv_porc, ARTI_CONSUMO
      from articulo a, tarifa_iva t where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t'
      AND ((esar_cod = 'A') or (esar_cod = 'B') or (esar_cod = 'K'))  AND (upper(A.ARTI_COD) like upper('%'||:buscar||'%'))
      INTO :CODIGO, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO
      do
      begin
      select first 1 coba_cod from articulo a, barras_articulo B where a.arti_cod = b.arti_cod and upper(a.arti_cod) = upper(:CODIGO) and COBA_ACTIVO = 'S' into :barras;
      EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
      EXECUTE PROCEDURE NOMBRE_ASCII(UNIDAD) returning_values (UNIDAD);
      PRECIO = 0;
      SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
      SELECT MARC_NOM FROM marcas m, articulo arti where m.marc_cod = arti.marc_cod AND arti.arti_cod = :CODIGO INTO :MARCA;
      execute PROCEDURE NOMBRE_ASCII(MARCA) returning_values (marca);
      EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
      if (VEREXIST = 'SI') then
        BEGIN
        if (EXISTOT = 'TOTAL') then
            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
        ELSE
            BEGIN
            select first 1 p.bode_cod from punto_venta p, usuario u where u.user_cod = USER and ((u.sucu_id = p.sucu_id) or (u.sucu_id = 0))  into :codbod;
            EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            END
        if (:exreserv = 'PROHIBIR') then
            BEGIN
            RESERVADO = 0;
            SELECT SUM(RESERVADO) FROM EXISTENCIAS_UNIDAD(:CODIGO, :FECHA, :UNIDAD) WHERE ((BODEGA = :CODBOD) or (:existot = 'TOTAL'))
                INTO :RESERVADO;
            if (reservado is null) then
                reservado = 0;
            EXISTEN = EXISTEN - RESERVADO;
            END
        END
      ELSE
        EXISTEN = 0;
      if ((sinexist = 'SI') or (EXISTEN > 0))  then
        BEGIN
        SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
        SUSPEND;
        END
      end
    --BUSCAR POR DESCRIPCION
    FOR select a.arti_cod, SUBSTRING(arti_des FROM 1 FOR 60), arti_descorta, arti_unidad, taiv_porc, ARTI_CONSUMO
      from articulo a, tarifa_iva t where a.taiv_cod = t.taiv_cod and substring(a.arti_cod from 1 FOR 2) <> '.t'
      AND ((esar_cod = 'A') or (esar_cod = 'K')) AND (upper(A.ARTI_DES) like upper('%'||:buscar||'%'))
      INTO :CODIGO, :DES, :DESCORTA, :UNIDAD, :IVA, :CONSUMO
      do
      begin
      select first 1 coba_cod from articulo a, barras_articulo B where a.arti_cod = b.arti_cod and upper(a.arti_cod) = upper(:CODIGO) and COBA_ACTIVO = 'S' into :barras;
      EXECUTE PROCEDURE NOMBRE_ASCII(DES) returning_values (DES);
      EXECUTE PROCEDURE NOMBRE_ASCII(UNIDAD) returning_values (UNIDAD);
      PRECIO = 0;
      SELECT prar_fijo PRECIO FROM precios_articulo WHERE arti_cod = :CODIGO and lipr_cod = :LISTA INTO :PRECIO;
      SELECT MARC_NOM FROM marcas m, articulo arti where m.marc_cod = arti.marc_cod AND arti.arti_cod = :CODIGO INTO :MARCA;
      execute PROCEDURE NOMBRE_ASCII(MARCA) returning_values (marca);
      EXECUTE PROCEDURE redondee(PRECIO, DIG) returning_values (PRECIO);
      if (VEREXIST = 'SI') then
        BEGIN
        if (EXISTOT = 'TOTAL') then
            EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
        ELSE
            BEGIN
            select first 1 p.bode_cod from punto_venta p, usuario u where u.user_cod = USER and ((u.sucu_id = p.sucu_id) or (u.sucu_id = 0))  into :codbod;
            EXECUTE PROCEDURE saldo_inventario (:CODIGO, :CODBOD, :FECHA) returning_values (:EXISTEN);
            END
        if (:exreserv = 'PROHIBIR') then
            BEGIN
            RESERVADO = 0;
            SELECT SUM(RESERVADO) FROM EXISTENCIAS_UNIDAD(:CODIGO, :FECHA, :UNIDAD) WHERE ((BODEGA = :CODBOD) or (:existot = 'TOTAL'))
                INTO :RESERVADO;
            if (reservado is null) then
                reservado = 0;
            EXISTEN = EXISTEN - RESERVADO;
            END
        END
      ELSE
        EXISTEN = 0;
      if ((sinexist = 'SI') or (EXISTEN > 0))  then
        BEGIN
        SELECT COUNT(F.ftar_item) FROM fotos_articulo F WHERE F.arti_cod = :CODIGO AND F.ftar_imagen IS NOT NULL INTO :imagenes;
        SUSPEND;
        END
      end
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure ART_INACTIVOS_CON_EXISTENCIA (
    FECHA date)
returns (
    CODIGO varchar(20),
    DES varchar(300),
    REF varchar(20),
    GRUPO varchar(30),
    MARCA varchar(30),
    UNIDAD varchar(8),
    EXISTEN numeric(18,2))
as
BEGIN
FOR select a.arti_cod, arti_des, grup_cod, arti_unidad, marc_cod
    from articulo a where esar_cod = 'I'
        INTO :CODIGO, :DES, :GRUPO, :UNIDAD, :MARCA
        do
        begin
        ref = '';
        select first 1 coba_cod from barras_articulo where arti_cod = :codigo into :ref;
        EXECUTE PROCEDURE saldo_total_inventario (:CODIGO, :FECHA) returning_values (:EXISTEN);
        if (existen <> 0) then
            SUSPEND;
        end
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure ARTICULOS_MILISTAPP (
    FECHA date,
    HORA time)
returns (
    ARTICOD varchar(20),
    CODIGO varchar(20),
    DESCRIPCION varchar(60),
    UNIDAD varchar(8),
    PRECIO numeric(18,2),
    CLASE char(1),
    EXISTEN numeric(18,2),
    GRUPCOD varchar(2),
    SUBGCOD varchar(3),
    CATEG integer,
    SUBCATEG integer,
    UNIALT varchar(8),
    FACTUNI numeric(18,4),
    FOTO blob sub_type BINARY segment size 80,
    FOTO_OK varchar(2),
    ACTIVO char(1),
    TIVA numeric(9,4))
as
declare variable LISTAP INTEGER;
declare variable LISTART INTEGER;
declare variable FECHAAU DATE;
declare variable HORAAU TIME;
declare variable USUARIO VARCHAR(10);
declare variable CLAVE VARCHAR(10);
declare variable SERVER VARCHAR(1024);
declare variable CADSQL VARCHAR(2048);
begin
execute procedure LEE_CONFIGURACION('MILISTAPP', 'GENERAL', 'CODIGO DE LA LISTA DE PRECIOS A PUBLICAR EN MILISTAPP') returning_values (:LISTAP);
execute procedure LEE_CONFIGURACION('MILISTAPP', 'GENERAL', 'CODIGO DE LA LISTA DE ARTICULOS A PUBLICAR EN MILISTAPP') returning_values (:LISTART);
FOR SELECT A.arti_cod, P.prar_fijo, grup_cod, subg_cod, ARTI_CLASE, ESAR_COD, TAIV_PORC FROM ARTICULO A, PRECIOS_ARTICULO P, TARIFA_IVA T
    WHERE P.arti_cod = A.arti_cod AND ((ESAR_COD = 'A') or (ESAR_COD = 'B') or (ESAR_COD = 'K')) and P.lipr_cod = :LISTAP and substring(a.arti_cod from 1 FOR 2) <> '.t'
    AND A.taiv_cod = T.taiv_cod AND EXISTS (SELECT ARTI_COD FROM LISTA_ARTICULOS_DET WHERE LIAR_ID = :listart AND ARTI_COD = A.arti_cod)
    INTO :ARTICOD, :PRECIO, :GRUPCOD, :SUBGCOD, :CLASE, :ACTIVO, :TIVA
    DO
    BEGIN
    foto = null;
    categ = NULL;
    subcateg = NULL;
    CODIGO = NULL;
    SELECT FIRST 1 COBA_COD, SUBSTRING(COBA_DES FROM 1 FOR 60), COBA_UNIDAD FROM BARRAS_ARTICULO WHERE ARTI_COD = :ARTICOD
    AND COBA_ACTIVO = 'S' INTO :CODIGO, :DESCRIPCION, :UNIDAD;
    if (CODIGO IS NULL) then
      BEGIN
      CODIGO = :ARTICOD;
      SELECT SUBSTRING(ARTI_DES FROM 1 FOR 60), ARTI_UNIDAD FROM ARTICULO WHERE ARTI_COD = :ARTICOD INTO :DESCRIPCION, :UNIDAD;
      END
    UNIALT = '';
    factuni = 0;
    SELECT FIRST 1 UNAR_UNIDAD, UNAR_FACCAN FROM UNIDAD_ARTICULO WHERE ARTI_COD = :ARTICOD
        AND UNAR_ACTIVA = 'S' AND UNAR_FACCAN > 1 INTO :unialt, :factuni;
    SELECT FIRST 1 FTAR_IMAGEN FROM FOTOS_ARTICULO WHERE ARTI_COD = :ARTICOD INTO :FOTO;
    select GRUP_CATLISTAPP from grupo where grup_cod = :GRUPCOD into :categ;
    if (:SUBGCOD IS NULL) then
      begin
      SUBGCOD = 'No';
      subcateg = 1;
      end
    ELSE
      select SUBG_SUBCLISTAPP from subgrupo where grup_cod = :GRUPCOD and SUBG_COD = :subgcod into :subcateg;
    if (:FOTO IS NULL) then
      FOTO_OK = 'No';
    ELSE
      FOTO_OK = 'Si';
    EXECUTE PROCEDURE saldo_total_inventario (:ARTICOD, cast('now' as date)) returning_values (:EXISTEN);
    if (existen >= 5) then
        suspend;
/*    CADSQL = '';
    USUARIO = 'CONSULTA';
    CLAVE = 'Consulta';
    SERVER = '50.21.179.229/3053:C:\PIDEYA\LISTAPP3.FDB';
    CADSQL = 'UPDATE ARTICULOS_COMPANIA SET ARTI_IVA = '||:TIVA||' WHERE COMP_ID = 28 AND ARTI_COD = '''||:ARTICOD||'''';
    EXECUTE STATEMENT :CADSQL ON EXTERNAL :SERVER as user :USUARIO PASSWORD :CLAVE;
    if (:PRECIO > 0 AND :PRECIO IS NOT null AND :existen >= 6) then
      BEGIN
      UPDATE or INSERT INTO LISTA_ARTICULOS_DET(LIAR_ID, ARTI_COD) VALUES(:LISTART,:ARTICOD);
      SUSPEND;
      END*/
    END
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure ARTICULOS_API
returns (
    ARTICULO varchar(20),
    BARRAS varchar(20),
    DESCRIPCION varchar(60),
    UNIDAD varchar(8),
    FACTOR numeric(18,4),
    IVA numeric(9,2),
    GRUPO varchar(2),
    SUBGRUPO varchar(3),
    MARCA varchar(3),
    CANT numeric(18,4),
    PRECIO numeric(18,2),
    PROMO char(1),
    DESTA char(1),
    MASVE char(1),
    NUEVO char(1))
as
declare variable FECHA DATE;
declare variable HORA TIME;
declare variable FECHOY DATE;
declare variable HORHOY TIME;
declare variable SALDO NUMERIC(18,4);
begin
SELECT LOGP_FECHA, LOGP_HORA FROM log_presentaciones INTO :FECHA, :HORA;
FECHOY = CAST('NOW' AS DATE);
HORHOY = CAST('NOW' AS TIME);
UPDATE log_presentaciones SET FECAHORA = :FECHOY, HORAHORA = :HORHOY;
/* CAMBIO DE ARTICULOS */
FOR SELECT DISTINCT ARTI_COD, SUBSTRING(ARTI_DES FROM 1 FOR 60), ARTI_UNIDAD, GRUP_COD, SUBG_COD, MARC_COD, TAIV_PORC
    FROM ARTICULO A, TARIFA_IVA T, AUDITORIA AU
    WHERE A.taiv_cod = T.taiv_cod AND ((AU.tido_cod = 101) or (AU.tido_cod = 126)) AND AU.audi_cod = A.arti_cod
    AND ((AU.audi_fecha > :FECHA) OR ((AU.audi_hora >= :HORA) AND (AU.audi_fecha = :FECHA))) AND ((A.esar_cod = 'A') or (A.esar_cod = 'B') or (A.esar_cod = 'K'))
    ORDER BY AUDI_ID
    INTO :ARTICULO, :DESCRIPCION, :UNIDAD, :GRUPO, :SUBGRUPO, :MARCA, :IVA
    DO
    BEGIN
    if (SUBGRUPO IS NULL) then
        SUBGRUPO = '';
    if (MARCA IS NULL) then
        MARCA = '';
    PROMO = 'N';
    DESTA = 'N';
    MASVE = 'N';
    NUEVO = 'N';
    if (EXISTS (SELECT LD.liar_id FROM lista_articulos_det LD, lista_articulos L
        WHERE L.liar_id = LD.liar_id AND L.liar_nombre LIKE '%PROMOCIONES%' AND  LD.arti_cod = :ARTICULO)) then
        PROMO = 'S';
    if (EXISTS (SELECT LD.liar_id FROM lista_articulos_det LD, lista_articulos L
        WHERE L.liar_id = LD.liar_id AND L.liar_nombre LIKE '%DESTACA%' AND  LD.arti_cod = :ARTICULO)) then
        DESTA = 'S';
    if (EXISTS (SELECT LD.liar_id FROM lista_articulos_det LD, lista_articulos L
        WHERE L.liar_id = LD.liar_id AND L.liar_nombre LIKE 'VENDIDOS%' AND  LD.arti_cod = :ARTICULO)) then
        MASVE = 'S';
    if (EXISTS (SELECT LD.liar_id FROM lista_articulos_det LD, lista_articulos L
        WHERE L.liar_id = LD.liar_id AND L.liar_nombre LIKE '%NUEVO%' AND  LD.arti_cod = :ARTICULO)) then
        NUEVO = 'S';
    EXECUTE PROCEDURE NOMBRE_ASCII(descripcion) returning_values (descripcion);
    BARRAS = '';
    FACTOR = 1;
    CANT = 0;
    execute procedure saldo_total_inventarioc(:articulo, :fechoy) returning_values(SALDO);
    CANT = SALDO;
    if (CANT > 0) then
        BEGIN
        SELECT FIRST 1 COBA_COD FROM BARRAS_ARTICULO B WHERE B.ARTI_COD = :ARTICULO AND B.coba_unidad = :unidad AND B.coba_activo = 'S'
            INTO :BARRAS;
        if ((BARRAS <> '') AND (BARRAS IS NOT NULL)) then
            BEGIN
            SELECT FIRST 1 PRAR_FIJO FROM PRECIOS_ARTICULO P WHERE ARTI_COD = :ARTICULO AND PRAR_CANTMIN <= 1
                ORDER BY PRAR_CANTMIN DESC
                INTO :PRECIO;
            suspend;
            END
        END
    END
end^

SET TERM ; ^



