Me apunto con MarcosZorrilla, si mantienes un acumulado en la ficha del articulo, no podras validar ese numero, es mejor tener un registro de los movimientos que te permita reconstruir ese numero, obtener precios medios y demas.
En el ultimo que monte deje la posibilidad de introducir inventarios en cualquier momento, el problema para conocer el stock de un articulo es localizar el apunte de inventario mas cercano y acumular a partir de el, aqui os pongo el storeproc que uso para automatizarlo, a ver si le veis pegas o mejoras, por supuesto se aceptan criticas y comentarios ;-D
Código:
ALTER PROCEDURE "STOCKARTICULO"
(
"ARTICULO" VARCHAR(6) CHARACTER SET ISO8859_1,
"FECHA" DATE
)
RETURNS
(
"INVENTARIO" INTEGER,
"ENTRA" INTEGER,
"SALE" INTEGER,
"MERMA" INTEGER,
"VENTA" INTEGER,
"STOCK" INTEGER,
"PRECIOMEDIO" DOUBLE PRECISION
)
AS
declare variable Inicio Date;
declare variable flag integer;
declare variable tmp integer;
declare variable pvp double precision;
declare variable tipo char(1);
BEGIN
Entra= 0;
Sale= 0;
merma= 0;
Venta= 0;
preciomedio= 0;
Stock= 0;
flag= 0;
/* Buscamos el primer inventario, no nos queda mas remedio que usar un for */
for select Fecha, Unidades, Precio from ArtMueve
where Articulo=:Articulo and TipoMueve='I' and Fecha <=:Fecha
order by Fecha desc into :Inicio, :tmp, :pvp do begin
/* Hay fecha inicial, la primera vez sumamos, el resto se desechan*/
if (flag=0) then begin
Inventario= tmp;
PrecioMedio= pvp*tmp;
/* Acumulamos por tipo de movimiento */
for select TipoMueve, sum(Unidades), sum(Unidades*Precio) from ArtMueve
where Articulo=:Articulo and Fecha>:Inicio and Fecha <=:Fecha
group by TipoMueve into :tipo, :tmp, :pvp do begin
if (tipo='E') then begin
Entra= Entra+tmp;
PrecioMedio= PrecioMedio+pvp;
end
if (tipo='S') then Sale = Sale +tmp;
if (tipo='M') then Merma = Merma +tmp;
end
/* Sumamos las ventas producidas */
select sum(Unidades) from ArticuloGasto
where Articulo=:Articulo and Fecha>:Inicio and Fecha<=:Fecha
into :tmp;
if (tmp is not null) then Venta= Venta;
flag= 1;
end
end
/* No hay inventario inicial, asi que actuamos sin fechas */
if (flag=0) then begin
for select TipoMueve, sum(Unidades) from ArtMueve
where Articulo=:Articulo and Fecha<=:Fecha
group by TipoMueve into :tipo, :tmp do
if (tipo='E') then begin
Entra= Entra+tmp;
PrecioMedio= PrecioMedio+pvp;
end
if (tipo='S') then Sale = Sale +tmp;
if (tipo='M') then Merma = Merma +tmp;
select sum(Unidades) from ArticuloGasto
where Articulo=:Articulo and Fecha<=:Fecha into tmp;
if (tmp is not null) then Venta= tmp;
end
Stock= Inventario+Entra-Sale-Merma-Venta;
if ((Inventario+Entra)<> 0) then
PrecioMedio= PrecioMedio/(Inventario+Entra);
else
PrecioMedio= 0;
suspend;
END