<?php
error_reporting(0); //No mostrar mensajes de errores por version de PHP
ini_set('max_execution_time', 0);
date_default_timezone_set('America/Lima');
require_once 'excel/reader.php';
require("class.phpmailer.php");
///////////////////////////////////////////////
$username="lq_adm_gestion";//"gesvetco_4045"; 
$password="WINxp512...";//"4045";
$database="lq_2021db";//"gesvetco_Sistema";
$connect=mysql_connect("localhost",$username,$password);
///////////////////////////////////////
@mysql_select_db($database,$connect) or die("<b>Error al intentar conectarse con la Base de Datos</b>");
//grs("SET NAMES utf8");
/////////////////////////////////////////////////////////////////////////////
$PRO_SI=1;
$PRO_NO=0;
$StrHWND="" ;
function GetHW(){
	$Fecha=date("d-m-y");
	$Hora=time();
	$FechaYHora=$Fecha.$Hora;
	return $FechaYHora;
}
if(strlen($_SESSION['SYS_USER_ID'])>0){
	if(strlen($StrHWND)==0){
		$StrHWND=GetHW();
	}
}	
//
ob_end_clean();
require("fpdf.php");
class PDF extends FPDF
{
function Footer()
{// Posici�n: a 1,5 cm del final
$this->SetY(-15);
// Arial italic 8
$this->SetFont('Arial','',8);
// N�mero de p�gina
$this->Cell(0,10,'Pag '.$this->PageNo(),0,0,'C');
}
}
//
function AddJs(){
	echo "
	<script src=\"jquery-1.7.2.min.js\" type=\"text/javascript\"></script>
	<script src=\"jquery.maskedinput.min.js\" type=\"text/javascript\"></script>	
	";
}
//
function AD($StrItem,$Sel){
	if($Sel==1){
		echo "<option value=\"$StrItem\" selected=\"selected\">$StrItem</option>";
	}else{
		echo "<option value=\"$StrItem\" >$StrItem</option>";
	}		
}
//
function NF($Num,$Nd){
return number_format($Num,$Nd,'.','');
}
function NF2($Num,$Nd){
return number_format($Num,$Nd,'.',',');
}
function NF3($Num){
return number_format($Num,2,'.',',');
}
function NF4($Num){
return number_format($Num,0,'',',');
}
function NF5($Num){
return number_format($Num,3,'.',',');
}
function GetALM(){
$s="SELECT alm_obs FROM almacenes 
WHERE id_almacen>= 0 AND 
alm_obs LIKE '".$_SESSION['SYS_USER_ALM']."' ORDER BY alm_obs";
return $s;
}
//
function ListALM($StrAlm){
$ss="";
$s="SELECT alm_obs FROM almacenes 
WHERE id_almacen>= 0 AND 
alm_obs LIKE '".$_SESSION['SYS_USER_ALM']."' ORDER BY alm_obs";
$result = grs($s);
while ($row = $result->fetch_row()){
if($StrAlm==$row[0]){
$ss=$ss."<option value=\"$row[0]\" selected=\"selected\">$row[0]</option>";
}else{
$ss=$ss."<option value=\"$row[0]\" >$row[0]</option>";
}
}
return $ss;
}
//
include("n2l.php");
include("inicializar.php");
include("vbruntime.php");
include("pdf_runtime.php");
//
function PagGet($_StrPag,$StrCmd,$LStrTR,$VP_RegXPag){
$_RESTO=$LStrTR%$VP_RegXPag;
if($_RESTO!=0){
	$LStrTR=$LStrTR+($VP_RegXPag-$_RESTO);
}
if(strlen($_StrPag)==0 || $_StrPag==0 ){
	$_StrPag="1";	
}	
if($StrCmd=="MSig"){
	$_StrPag=$_StrPag +1;	
}
if($StrCmd=="MAnt"){
	$_StrPag=($_StrPag-1);
}
if($StrCmd=="MPri"){
	$_StrPag=1;
}
if($StrCmd=="MUlt"){
	$_StrPag=($LStrTR / $VP_RegXPag);
}
if($_StrPag>0){	
	if($LStrTR >$VP_RegXPag * $_StrPag){
		if(($_StrPag-1)*$VP_RegXPag==$LStrTR){
			$_StrPag=$_StrPag-1;
		}
	}
}
return $_StrPag;
}
//
function PagBtn($LStrTR,$VP_RegXPag,$LStrPag){	
$s="";
$_RESTO=$LStrTR%$VP_RegXPag;
if($_RESTO!=0){
	$LStrTR=$LStrTR+($VP_RegXPag-$_RESTO);
}
if($LStrTR>$VP_RegXPag){
if($LStrPag==1){
$s=$s."<input style=\"width:40px\" name=\"CmdNP\" type=\"button\" id=\"CmdNP\" value=\"|&lt;\"  onclick=\"fPrimero();\" disabled=\"disabled\"/>";
$s=$s."<input style=\"width:40px\" name=\"CmdNA\" type=\"button\" id=\"CmdNA\" value=\"<\"  onclick=\"fAnterior();\" disabled=\"disabled\" />";
}else{
$s=$s."<input style=\"width:40px\" name=\"CmdNP\" type=\"button\" id=\"CmdNP\" value=\"|&lt;\"  onclick=\"fPrimero();\"/>";
$s=$s."<input style=\"width:40px\" name=\"CmdNA\" type=\"button\" id=\"CmdNA\" value=\"<\"  onclick=\"fAnterior();\"/>";
}
if(($LStrPag==floor($LStrTR  /$VP_RegXPag)  ) ){
$s=$s."<input style=\"width:40px\" name=\"CmdNS\" type=\"button\" id=\"CmdNS\" value=\">\"  onclick=\"fSiguiente();\"  disabled=\"disabled\" />";
$s=$s."<input style=\"width:40px\" name=\"CmdNU\" type=\"button\" id=\"CmdNU\" value=\"&gt;|\"  onclick=\"fUltimo();\"  disabled=\"disabled\"/>";				
}else{
$s=$s."<input style=\"width:40px\" name=\"CmdNS\" type=\"button\" id=\"CmdNS\" value=\">\"  onclick=\"fSiguiente();\" />";
$s=$s."<input style=\"width:40px\" name=\"CmdNU\" type=\"button\" id=\"CmdNU\" value=\"&gt;|\"  onclick=\"fUltimo();\"/>";				
}
}
return $s;
}
//
function PagSql($s,$LStrPag,$VP_RegXPag,$LStrTR){	
if($LStrTR<=$VP_RegXPag){
	return $s;
}else{
	$LStrPag=$LStrPag-1;
	$StrTemp=$LStrPag * $VP_RegXPag;
	return $s." LIMIT $StrTemp,$VP_RegXPag";
}
}
//PRINTER FUNCTION
function Pxy($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;word-wrap:break-word;height:11px;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX\">".$Str."</div>";
return $s."\n";
}
//
function xy($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX\">".$Str."</div>";
echo $s."\n";
}
function xy2($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"left:$X"."cm;top:$Y"."cm;width:$A"."cm;";
if($iDER==0){
$s=$s."text-align:left\"";
}else{
$s=$s."text-align:right\"";
}
$s=$s." class=\"EX2\">".$Str."</div>";
echo $s."\n";
}

function xz($X,$Y,$Str,$A,$iDER){
if($iDER==1)$X=$X - $A;
$s="<div style=\"display:block;text-align:justify;left:$X"."cm;top:$Y"."cm;width:$A"."cm\"";
$s=$s." class=\"EX\">".$Str."</div>";
echo $s."\n";
}
//
function SER_NUM_EX($StrSerNum,&$STR_SER,&$STR_NUM){
$iHasta=0;
for($i=1;$i<=strlen($StrSerNum);$i++){
if(vbmid($StrSerNum,$i,1)=="-"){
$iHasta=$i;
break;
}
}
$STR_SER=trim(vbmid($StrSerNum,1,$iHasta -1));
$STR_NUM=trim(vbmid($StrSerNum,$iHasta+1,strlen($StrSerNum) - $iHasta));
}
//
function GenId($StrId,$sT){
$ss="Select Count(*) From $sT";
$rs = grs($ss);$row = $rs->fetch_row();		
if($row[0]==0){
$StrIdEx=1;
}else{
$ss="Select Max($StrId) From $sT";
$rs = grs($ss);$row = $rs->fetch_row();		
$StrIdEx=$row[0]+1;
}
return $StrIdEx;
}
//
function GetTC(){
if(GetC("tipocambio","")==0){
INSERT("tipocambio","'01-01-01',1");		
}
return gn("valor","tipocambio","");
}
//
function GetIGV(){return 18;}
//
function GenGI(){
$ss="Select Max(valor) From gindex";
$rs = grs($ss);$row = $rs->fetch_row();				
$StrIdEx=$row[0]+1;ejt("UPDATE gindex SET valor=valor+1");
return $StrIdEx;	
}
//
function V($StrVar){return ($StrVar==null) ? "" : $StrVar;}
//
//
function X($StrVar){
	if(strlen($StrVar)==0){
		return "xx";
	}else{
		$vowels = array(">", "<", "/","&");
		return trim(str_replace($vowels, "", $StrVar));
	}
}
//
function TODOS($StrCer){
if($StrCer=="TODOS"){
echo "<option value=\"TODOS\" 
selected=\"selected\">TODOS</option>";
}else{
echo "<option value=\"TODOS\" >TODOS</option>";
}
}
//
function LIKE($StrV){
	if($StrV=="TODOS" || $StrV=="TODAS" || $StrV=="AMBOS" || $StrV=="AMBAS" ){
		return "%";
	}else{
		return $StrV;
	}	
}
//
function VV($StrVar){if($StrVar==null)return "&nbsp;";if(strlen(trim($StrVar))==0)return "&nbsp;";return $StrVar;}
//
function Gss($sC,$sT,$sW)
{return (strlen($sW)>0) ? "Select $sC From $sT Where $sW" : "Select $sC From $sT";}

function gn($sC,$sT,$sW)
{	
	$ss=Gss($sC,$sT,$sW);	
	$rs = grs($ss);
	$row = $rs->fetch_row();
	return (is_null($row[0])) ? "0" : $row[0];
}
function gnx($sql){
	$ss=$sql;
	$rs = grs($ss);
	$row = $rs->fetch_row();
	return (is_null($row[0])) ? 0 : $row[0];
}
function gnw($sC,$sT,$sW)
{
	$ss="SELECT ".$sC." FROM ".$sT." WHERE ".$sW;
	$rs = grs($ss);
	$row = $rs->fetch_row();
	return (is_null($row[0])) ? "0" : $row[0];
}

function y($s){
	if(strlen(trim($s))==0){
		return "<";
	}else{
		return $s;
	}
}
function gs($sC,$sT,$sW)
{$ss=Gss($sC,$sT,$sW);$rs = grs($ss);$row = $rs->fetch_row();return (is_null($row[0])) ? "" : $row[0];}
function GetC($sT,$sW)
{$ss=Gss("count(*)",$sT,$sW);$rs = grs($ss);$row = $rs->fetch_row();return (is_null($row[0])) ? "0" : $row[0];}
//
function GetSO($sC,$sT,$sW,$StrOrden){
$ss="Select $sC From $sT ";
if(strlen($sW)>0)
$ss=$ss." WHERE $sW ORDER BY $StrOrden";		
else
$ss=$ss." ORDER BY $StrOrden";		
$rs = grs($ss);$row = $rs->fetch_row();		
return (is_null($row[0])) ? "" : $row[0];
}
//
function ejt($ss){$rs = grs($ss);}
function DelAll($sT){$rs = grs("DELETE FROM $sT ");}
function INSERT($sT,$StrValues){$rs = grs("INSERT INTO $sT VALUES ($StrValues)");}
function DELETE($sT,$sW){$rs = grs("DELETE From $sT WHERE $sW");}
function UPDATE($sT,$StrValues,$sW){$rs = grs("UPDATE $sT SET $StrValues WHERE $sW");}
//
function JsMsg($StrMsg,$StrUrl){
echo "
<script language='javascript'> 
alert('$StrMsg'); 
location.href='$StrUrl';
</script>
";
}
//
function JsDir($StrUrl){
echo "
<script language='javascript'> 				
location.href='$StrUrl';
</script>
";
}
function JsDirN($StrUrl){
echo "
<script language='javascript'> 				
window.location='$StrUrl';
</script>
";
}
//
function SetVar($StrVar,$StrVal){
if(gn("count(*)","variables","variable='$StrVar'")==0){
ejt("INSERT INTO variables VALUES ('$StrVar','$StrVal')");
}else{
ejt("UPDATE variables SET valor='$StrVal' WHERE variable='$StrVar'");
}
}
//
function GetVar($StrVar){
return gs("valor","variables","variable='$StrVar'");
}
//
function IsNumber($StrNum){
if(is_numeric($StrNum))
return true;
else
return false;
}
//
function IsDate($StrFecha){
$StrAnio="20".substr($StrFecha,6,2);
$StrMes=substr($StrFecha,3,2);
$StrDia=substr($StrFecha,0,2);	
if(!is_numeric($StrDia)) return false;
if(!is_numeric($StrMes)) return false;
if(!is_numeric($StrAnio)) return false;	
if (checkdate((int) $StrMes,(int) $StrDia, (int)$StrAnio)){
return true;
}else{
return false;
}
}
//
function ToDate($StrFecha){
if(strlen($StrFecha)==0){
return "1900-01-01";
}else{
$StrAnio="20".substr($StrFecha,6,2);
$StrMes=substr($StrFecha,3,2);
$StrDia=substr($StrFecha,0,2);	
return $StrAnio."-".$StrMes."-".$StrDia;
}
}
//
function GetHoraServer(){
$StrDate=date("r");
return $StrDate;}
function GetHora(){
$StrDate=date("H:i:s");
$StrHor=substr($StrDate,0,2);$StrMin=substr($StrDate,3,2);
$StrSeg=substr($StrDate,6,2);$StrHor=$StrHor;
if(strlen($StrHor)==1){
$StrHor="0".$StrHor;
}
return $StrHor.":".$StrMin.":".$StrSeg;
}
//
function GetHoraAP(){
$StrDate=GetHora();
$StrHor=substr($StrDate,0,2);$StrMin=substr($StrDate,3,2);
$StrSeg=substr($StrDate,6,2);$StrAP="AM";
if($StrHor>=13){
$StrAP="PM";$StrHor=$StrHor - 12;
}
if(strlen($StrHor)==1){
$StrHor="0".$StrHor;
}
return $StrHor.":".$StrMin.":".$StrSeg." ".$StrAP;
}
//
function EnviarEmail($StrTit,$StrAsunto,$StrCliente,$StrEmail,$StrTexto,$StrF1,$StrF2){
$mail = new PHPMailer();	
$mail->Host = "localhost";
$mail->From = "remite@email.com";//Correo de quien esta enviando.
$mail->FromName = $StrTit; //Quien esta enviando esto aparece en la bandeja
$mail->Subject = $StrAsunto; //Titulo del correo aparecen en la bandeja
$mail->AddAddress($StrEmail,$StrCliente);//Nombre 01->cliente ejt. Marco sayas
//$mail->AddAddress("destino2@correo.com","Nombre 02");	
$mail->Body =$StrTexto;
$mail->AltBody = "***";
if(strlen($StrF1)>0 && strlen($StrF2)>0){
$mail->AddAttachment($StrF1,$StrF2);
}
if(strlen($StrF1)>0 && strlen($StrF2)==0){
$mail->AddAttachment($StrF1);
}
if(strlen($StrF1)==0 && strlen($StrF2)>0){
$mail->AddAttachment($StrF2);
}
$mail->Send();
}
//
function VENTAS_GEN_SER_NUM($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$IdVen=gn("MAX(id_venta)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
$StrS=gs("ser","ventas","id_venta=$IdVen");$StrN=gs("num","ventas","id_venta=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function VENTAS_GEN_SER_NUM_MAX($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID");
$MAX_N=gn("max(inum)","ventas","id_alm=$ALM_ID AND id_com=$COM_ID AND iser=$MAX_S");
//
$IdVen=gn("id_venta","ventas","id_alm=$ALM_ID AND 
id_com=$COM_ID AND iser=$MAX_S AND inum=$MAX_N");
$StrS=gs("ser","ventas","id_venta=$IdVen");
$StrN=gs("num","ventas","id_venta=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function GUIAS_GEN_SER_NUM_MAX($ALM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","guias","id_almacen=$ALM_ID ");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","guias","id_almacen=$ALM_ID ");
$MAX_N=gn("max(inum)","guias","id_almacen=$ALM_ID AND iser=$MAX_S");
$IdVen=gn("id_guia","guias","id_almacen=$ALM_ID AND iser=$MAX_S AND inum=$MAX_N");
$StrS=gs("ser","guias","id_guia=$IdVen");$StrN=gs("num","guias","id_guia=$IdVen");
$STR_SER=$StrS;$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function COTI_GEN_SER_NUM_MAX($ALM_ID,$COM_ID,&$STR_SER,&$STR_NUM){
$IdVen=gn("count(*)","cotizaciones","id_alm=$ALM_ID AND id_com=$COM_ID");
if($IdVen==0){
$STR_SER="001";$STR_NUM="00001";
}else{
$MAX_S=gn("max(iser)","cotizaciones","id_alm=$ALM_ID AND id_com=$COM_ID");
$MAX_N=gn("max(inum)","cotizaciones","id_alm=$ALM_ID AND iser=$MAX_S AND id_com=$COM_ID");
$IdVen=gn("id_cotizacion","cotizaciones","id_alm=$ALM_ID AND 
iser=$MAX_S AND inum=$MAX_N AND id_com=$COM_ID");
$StrS=gs("ser","cotizaciones","id_cotizacion=$IdVen");
$StrN=gs("num","cotizaciones","id_cotizacion=$IdVen");
$STR_SER=$StrS;
$StrNN=$StrN+1;
if(strlen($StrNN)>strlen($StrN)){
$STR_NUM=$StrNN;
}else{
$i=strlen($StrN);
$STR_NUM=vbr("000000000000".$StrNN,$i);
}}}
function GetMES($i){
if($i==1) return "Enero";		if($i==2) return "Febrero";if($i==3) return "Marzo";
if($i==4) return "Abril";		if($i==5) return "Mayo";if($i==6) return "Junio";
if($i==7) return "Julio";		if($i==8) return "Agosto";if($i==9) return "Septiembre";
if($i==10) return "Octubre";	if($i==11) return "Noviembre";if($i==12) return "Diciembre";
return "****";}
function FECHA_ADD($lpDias,$lpMeses,$lpAnios){
$Fecha = mktime(0, 0, 0, date("m")+$lpMeses, date("d")+$lpDias, date("Y")+$lpAnios);
$StrFechaA= date("d-m-y", $Fecha);return $StrFechaA;}
function FECHA_DIASEM(){
$fecha= date("Y-m-d");$i = strtotime($fecha);
return jddayofweek(cal_to_jd(CAL_GREGORIAN, date("m",$i),date("d",$i), date("Y",$i)) , 0 );
}
function FECHA_SEM_PD(){
	$DS=0;
	$ds=FECHA_DIASEM();
	if($ds==0){
		$DS=7;
	}else{
		$DS=$ds;
	}
	$iDia=($DS-1)* -1;
	$StrFec=FECHA_ADD($iDia,0,0);
	return $StrFec;
}
function FECHA_HOY(){return date("d-m-y");}

function STOCK_ADD($IdAlm,$IdPro,$Cant){
if(gn("count(*)","stocks","id_almacen=$IdAlm AND id_producto=$IdPro")==0){
	ejt("INSERT INTO stocks VALUES ($IdAlm,$IdPro,$Cant)");
}else{
	ejt("UPDATE stocks SET stock=stock + $Cant WHERE id_almacen=$IdAlm AND id_producto=$IdPro");
}}

function STOCK_SUB($IdAlm,$IdPro,$Cant){
if(gn("count(*)","stocks","id_almacen=$IdAlm AND id_producto=$IdPro")==0){
$Cant=$Cant * -1;ejt("INSERT INTO stocks VALUES ($IdAlm,$IdPro,$Cant)");
}else{
ejt("UPDATE stocks SET stock=stock - $Cant WHERE id_almacen=$IdAlm AND id_producto=$IdPro");
}}
function ZTOCK_ADD($IdAlm,$IdPro,$Cant,$Uni){
	if($Uni>0){
		if(gn("count(*)","stocks_presentaciones",
			  "sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND ".
			  "sp_presentacion=$Uni")==0){
			$s="INSERT INTO stocks_presentaciones VALUES ($IdAlm,$IdPro,$Uni,$Cant,0)";	
			ejt($s);
		}else{
			ejt("UPDATE stocks_presentaciones ".
				"SET sp_cantidad=sp_cantidad + $Cant ".
				"WHERE sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND sp_presentacion=$Uni");
		}
	}
}

function ZTOCK_SUB($IdAlm,$IdPro,$Cant,$Uni){
	if($Uni>0){
		if(gn("count(*)","stocks_presentaciones",
			  "sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND ".
			  "sp_presentacion=$Uni")==0){
			$Cant=$Cant * -1;
			ejt("INSERT INTO stocks_presentaciones VALUES ($IdAlm,$IdPro,$Uni,$Cant,0)");
		}else{
			ejt("UPDATE stocks_presentaciones ".
				"SET sp_cantidad=sp_cantidad - $Cant ".
				"WHERE sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND sp_presentacion=$Uni");
		}
	}
}
function ZTOCK_SUB_P($IdAlm,$IdPro,$Cant,$Uni){
	if($Uni>0){	
		if(gn("count(*)","stocks_presentaciones",
			  "sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND ".
			  "sp_presentacion=$Uni")==0){
			$Cant=$Cant * -1;
			ejt("INSERT INTO stocks_presentaciones VALUES ($IdAlm,$IdPro,$Uni,$Cant,1)");
		}else{
			ejt("UPDATE stocks_presentaciones ".
				"SET sp_cantidad=sp_cantidad - $Cant ".
				"WHERE sp_id_almacen=$IdAlm AND sp_id_producto=$IdPro AND sp_presentacion=$Uni");
		}
	}
}

//
function PDF_COTI($Id){
$_CxL=90;
$_S=10;
	

$pdf = new PDF('P','mm',A4);
$pdf->AddPage();$pdf->SetFont('courier','B',16);

$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"LQ IMPORT EXPORT",0,1);	
$pdf->SetFont('courier','',10);

$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,vbl("PROFORMA".vbfill(" ",$_S),$_S)." : ".gs("CONCAT(SER,'-',NUM)","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("FECHA".vbfill(" ",$_S),$_S)." : ".gs("DATE_FORMAT(FEC,'%d-%m-%Y')","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("CLIENTE".vbfill(" ",$_S),$_S)." : ".gs("CLI","vcotizaciones","ID=$Id"),0,1);	
$pdf->Cell(0,4,vbl("RUC".vbfill(" ",$_S),$_S)." : ".gs("RUC","vcotizaciones","ID=$Id"),0,1);
$_MON=gs("MON","vcotizaciones","ID=$Id");
if($_MON=="S"){
	$_MON="Soles   (S/.) ";
}else{
	$_MON="Dolares ($) ";
}
$_IIG=gs("IIG","vcotizaciones","ID=$Id");
if($_IIG=="0"){
	$_IIG="Los precios NO incluyen IGV";
}else{
	$_IIG="Los precios incluyen IGV";
}

$pdf->Cell(0,4,vbl("MONEDA".vbfill(" ",$_S),$_S)." : ".$_MON,0,1);	
$pdf->Cell(0,4,vbl("NOTA".vbfill(" ",$_S),$_S)." : ".$_IIG,0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
$_ENC="CODIGO".vbfill(" ",15)." "."DESCRIPCION".vbfill(" ",30)." "."PRECIO"." "."DSCTO"." "."CANT"."  "."IMPORTE";
$pdf->Cell(0,4,$_ENC,0,1);	
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
//
$s="SELECT COD,DES,ROUND(PR,1),ROUND(DT,1),KA,ROUND(IMP,1) FROM vcotizaciones_det WHERE ID=$Id";
$result = grs($s);
while ($row = $result->fetch_row()){
	$_COD=vbl($row[0].vbfill(" ",21),21);
	$_DES=vbl($row[1].vbfill(" ",41),41);
	$_PRE=vbr(vbfill(" ",6).$row[2],6);
	$_DST=vbr(vbfill(" ",5).$row[3],5);
	$_KAN=vbr(vbfill(" ",4).$row[4],4);
	$_IMP=vbr(vbfill(" ",7).$row[5],7);
	$pdf->Cell(0,4,$_COD." ".$_DES." ".$_PRE." ".$_DST." ".$_KAN."  ".$_IMP,0,1);	
}
$pdf->Cell(0,4,vbfill("-",$_CxL),0,1);	
$_TOT="TOTAL : ".gs("FORMAT(TOT,1)","vcotizaciones","ID=$Id");
$pdf->Cell(0,4,vbfill(" ",$_CxL-strlen($_TOT)).$_TOT,0,1);	
//
$_S=20;
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	

$_FDP=vbl("FORMA DE PAGO".vbfill(" ",$_S),$_S)." : ".gs("fdp","cotizaciones_con","");	
$_TDE=vbl("TIEMPO DE ENTREGA".vbfill(" ",$_S),$_S)." : ".gs("tde","cotizaciones_con","");	
$_GAR=vbl("GARANTIA".vbfill(" ",$_S),$_S)." : ".gs("gar","cotizaciones_con","");	
$_VAL=vbl("VALIDES DE OFERTA".vbfill(" ",$_S),$_S)." : ".gs("val","cotizaciones_con","");	
$_STO=vbl("STOCK".vbfill(" ",$_S),$_S)." : ".gs("stock","cotizaciones_con","");	
$pdf->Cell(0,4,$_FDP,0,1);	
$pdf->Cell(0,4,$_TDE,0,1);	
$pdf->Cell(0,4,$_GAR,0,1);	
$pdf->Cell(0,4,$_VAL,0,1);	
$pdf->Cell(0,4,$_STO,0,1);	
$pdf->Cell(0,4,"",0,1);	
$pdf->Cell(0,4,"",0,1);	

//
$PDF_NAME="Cotizacion".gs("CONCAT(SER,'-',NUM)","vcotizaciones","ID=$Id").".pdf";
$pdf->Output($PDF_NAME);		
return $PDF_NAME;
}
//
//
function XLS_STOCK(){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('Stock2003.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$COD=trim(V($data->sheets[0]['cells'][$i][1])); 		
		$PIE=trim(V($data->sheets[0]['cells'][$i][2])); 		
		$STO=trim(V($data->sheets[0]['cells'][$i][3])); 		
		$PRE=vbval(trim(V($data->sheets[0]['cells'][$i][4])));
		$TOT=$PIE * $STO;
		if(strlen($COD)==0) break;
		
		//
		if(gn("count(*)","productos","pro_codigo='$COD'")==0){
			$IDP=GenId("id_producto","productos");
			$s="INSERT INTO productos VALUES ".
			   "($IDP,'$COD',0,'$COD',0,0,0,$PRE,$PRE,'',0,0,0,'S',0,0)";
			ejt($s);
			$s="INSERT INTO stocks VALUES (1,$IDP,$TOT)";
			ejt($s);
			if($PIE>0){
				$s="INSERT INTO stocks_presentaciones VALUES (1,$IDP,$PIE,$STO,0)";
				ejt($s);
			}
		}else{
			echo "$COD .ya registrado <br>";
		}
	}
}
//
function PROV_GET_ID($StrProv){
	if(strlen($StrProv)>0){
		$ID=gn("id_distrito","distritos","dis_nombre='$StrProv'");
		if($ID==0){
			$ID=GenId("id_distrito","distritos");
			$s="INSERT INTO distritos VALUES ($ID,'$StrProv')";
			ejt($s);
		}
	}else{
		$ID=0;
	}
	return $ID;
}
//
function IMP_CLIENTES(){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_clientes.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$NOM=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$CON=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][2]))); 		
		$DIR=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][3])));
		$PRO=trim(str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][4]))));
		$RUC=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][5])));
		$DNI=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][6])));
		$TEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][7])));
		$CEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][8])));
		$FAX=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][9])));
		$EMA=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][10])));
		//
		if(strlen($NOM)==0) break;
		//
		$PRO=PROV_GET_ID($PRO);				
		//
		$CLI=0;
		if(strlen($RUC)>0){
			$CLI=gn("id_cliente","clientes","cli_ruc='$RUC'");
		}
		if($CLI==0 && strlen($DNI)>0){
			$CLI=gn("id_cliente","clientes","cli_dni='$DNI'");
		}
		if($CLI==0){
			$CLI=gn("id_cliente","clientes","cli_nombre='$NOM'");		
		}
		if($CLI==0){
			$CLI=GenId("id_cliente","clientes");
			$s="INSERT INTO clientes VALUES ".
			   "($CLI,'$NOM','$CON','$DIR',$PRO,'$DNI',".
			   "'$RUC','$TEL','$CEL','$FAX','$EMA',0)";
			ejt($s);
		}else{
			$s="UPDATE clientes SET ".
			   "cli_nombre='$NOM',cli_contacto='$CON',".
			   "cli_dir='$DIR',cli_id_distrito=$PRO,".
			   "cli_dni='$DNI',".
			   "cli_ruc='$RUC',cli_tel='$TEL',".
			   "cli_cel='$CEL',cli_fax='$FAX',cli_email='$EMA' ".
			   "WHERE id_cliente=$CLI";			
			ejt($s);			
		}
		//
	}
}

//
function IMP_PROVEEDORES(){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_proveedores.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$NOM=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$CON=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][2]))); 		
		$DIR=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][3])));
		$PRO=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][4])));
		$RUC=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][5])));
		$DNI=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][6])));
		$TEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][7])));
		$CEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][8])));
		$FAX=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][9])));
		$EMA=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][10])));
		//
		if(strlen($NOM)==0) break;
		//
		$PRO=PROV_GET_ID($PRO);				
		//
		$CLI=gn("id_proveedor","proveedores","pro_nombre='$NOM'");
		if($CLI==0){
			$CLI=GenId("id_proveedor","proveedores");
			$s="INSERT INTO proveedores VALUES ".
			   "($CLI,'$NOM','$CON','$DIR',$PRO,'$DNI',".
			   "'$RUC','$TEL','$CEL','$FAX','$EMA')";
			ejt($s);
		}else{
			$s="UPDATE proveedores SET ".
			   "pro_nombre='$NOM',pro_contacto='$CON',".
			   "pro_dir='$DIR',pro_id_distrito=$PRO,".
			   "pro_dni='$DNI',".
			   "pro_ruc='$RUC',pro_tel='$TEL',".
			   "pro_cel='$CEL',pro_fax='$FAX',pro_email='$EMA' ".
			   "WHERE id_proveedor=$CLI";
			ejt($s);			
		}
		//
	}
}
//
function LIN_GET_ID($StrLinea){
    $StrLinea=trim($StrLinea);
	if(strlen($StrLinea)==0){
		return 0;
	}
	$ID=gn("id_linea","lineas","lin_nombre='$StrLinea'");
	if($ID==0){
		$ID=GenId("id_linea","lineas");
		$s="INSERT INTO lineas VALUES ($ID,'$StrLinea','')";
		ejt($s);
	}
	return $ID;
}
function PROVEEDOR_GET_ID($StrProveedor){
	$ID=gn("id_proveedor","proveedores","pro_nombre='$StrProveedor'");
	if($ID==0){
		$ID=GenId("id_proveedor","proveedores");
		$s="INSERT INTO proveedores VALUES ($ID,'$StrProveedor','','',0,'','','','','','')";
		ejt($s);
	}
	return $ID;
}
//
function IMP_PRODUCTOZ(){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_productos.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$COD=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$LIN=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][2]))); 		
		$DES=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][3])));
		$PCO=vbval(str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][4]))));
		$PVm=vbval(str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][5]))));
		$PVM=vbval(str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][6]))));
		$PRO=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][7])));
		//
		if(strlen($COD)==0) break;
		//
		$LIN=LIN_GET_ID($LIN);	
		$PRO=0;			
		//
		if(strlen($COD)>0){
			$CLI=gn("id_producto","productos","pro_codigo='$COD'");
		}else{
			$CLI=gn("id_producto","productos","pro_des='$DES' AND pro_id_linea=$LIN");
		}
		if($CLI==0){
			$CLI=GenId("id_producto","productos");
			$s="INSERT INTO productos VALUES ".
			   "($CLI,'$COD',$LIN,'$DES',0,0,$PCO,$PVm,$PVM,'',$PRO,0,0,'S',0,0)";
			ejt($s);
		}else{
			$s="UPDATE productos SET ".
			   "pro_codigo='$COD',pro_id_linea=$LIN,".
			   "pro_des='$DES',pro_pc_sol=$PCO,".
			   "pro_pv_min=$PVm,pro_pv_max=$PVM,".
			   "pro_id_proveedor=$PRO WHERE id_producto=$CLI";
			ejt($s);
			//
			$s="UPDATE t_productos SET pro_cod='$COD',pro_des='$DES',pro_pmi=$PVm,pro_pma=$PVM,pro_lin='$LIN' WHERE pro_id=$CLI";
			ejt($s);			
		}		
	}
}
//
function IMP_STOCKS_ADD($ALM){
	$ID=0;
	$cx=0;
	$ACC="A";
	$FEC=date("Y-m-d");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_stocks.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$COD=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$PIE=vbval(V($data->sheets[0]['cells'][$i][2])); 		
		$STO=vbval(V($data->sheets[0]['cells'][$i][3])); 	
		//		
		if(strlen($COD)==0) break;
		$PRO=gn("id_producto","productos","pro_codigo='$COD'");
		if($PRO>0){				
			ZTOCK_ADD($ALM,$PRO,$STO,$PIE);
			STOCK_ADD($ALM,$PRO,$PIE * $STO);
			$GII=GenGI();
			$ID=GenId("id_ajuste","ajustex");
			$s="INSERT INTO ajustex ".
			"VALUES ($ID,'$FEC',$ALM,$PRO,'$ACC',$STO,$PIE,$GII,'IMP. EXCEL',0)";
			ejt($s);
			T_P_ACT($PRO);
		}
		//
		
	}
}
//
function IMP_STOCKS($ALM){
	$ID=0;
	$cx=0;
	$ACC="";
	$FEC=date("Y-m-d");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_stocks.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$COD=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$PIE=vbval(V($data->sheets[0]['cells'][$i][2])); 		
		$STO=vbval(V($data->sheets[0]['cells'][$i][3])); 	
		//		
		if(strlen($COD)==0) break;
		$PRO=gn("id_producto","productos","pro_codigo='$COD'");
		//echo $COD."@".$PRO."<br>";
		if($PRO>0){
			$STA=gn("sp_cantidad",
					"stocks_presentaciones",
					"sp_id_almacen=$ALM AND sp_id_producto=$PRO AND sp_presentacion=$PIE");			
			$DIF=$STA - $STO;
			if($DIF!=0){
				$ACC="A";
				if($DIF>0)$ACC="Q";
				$STO=abs($DIF);	
				if($ACC=="A"){
					ZTOCK_ADD($ALM,$PRO,$STO,$PIE);
					STOCK_ADD($ALM,$PRO,$PIE * $STO);
				}else{
					ZTOCK_SUB($ALM,$PRO,$STO,$PIE);
					STOCK_SUB($ALM,$PRO,$PIE * $STO);
				}
				$GII=GenGI();
				$ID=GenId("id_ajuste","ajustex");
				$s="INSERT INTO ajustex ".
				"VALUES ($ID,'$FEC',$ALM,$PRO,'$ACC',$STO,$PIE,$GII,'IMP. EXCEL',0)";
				ejt($s);
				T_P_ACT($PRO);
			}			
		}
		//
	}
}
//
function extension($filename){
    return substr(strrchr($filename, '.'), 1);
}
function USU_SET_GI($StrId){
	$StrId=vbval($StrId);
	$StrGI=GenGI();
	ejt("UPDATE usuarios SET gi=$StrGI WHERE id_usuario=$StrId");
	return $StrGI;
}
function USU_GET_GI($StrId){
	$StrId=vbval($StrId);
	return gn("gi","usuarios","id_usuario=$StrId");
}

function FCBO_($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N"){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	//
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrCam";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrCam";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function FCBOOD_($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	//
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd DESC";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd DESC";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
function FCBOO_($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	//
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd";
	}	
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function GetIR($StrComR_,$Ser_,$Num_){
	$Ser_=vbval($Ser_);
	$Num_=vbval($Num_);
	if($StrComR_==-1){//TRANSFERENCIA
		$IdL=gn("id_trans","transferencias","id_trans=$Num_");
		return $IdL;
	}
	if($StrComR_==-3){//PROFORMA
		$IdL=gn("id_cotizacion","cotizaciones","iser=$Ser_ AND inum=$Num_");
		return $IdL;
	}
	if($StrComR_==-2){//GUIA INTERNA
		$IdL=gn("id_gi","ginterna","gi_inum=$Num_");
		return $IdL;
	}
	$IdL=gn("id_venta","ventas","id_com=$StrComR_ AND iser=$Ser_ AND inum=$Num_");
	return $IdL;
}
//

//
function CONTROL($StrComR_,$_IR,$_IDP,$_CAN,$_UNI){
	if($StrComR_==-1){//TRANSFERENCIA
		$s="UPDATE transferencias_det ".
		   "SET cant_control=cant_control - $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_trans=$_IR";
		 ejt($s);
	}
	if($StrComR_==-3){//PROFORMA
		$s="UPDATE cotizaciones_det ".
		   "SET ca_control=ca_control - $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_cotizacion=$_IR";
		 ejt($s);
	}
	if($StrComR_==-2){//GUIA INTERNA
		$s="UPDATE ginterna_det ".
		   "SET ca_control=ca_control - $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_gi=$_IR";
		 ejt($s);
	}	
	if($StrComR_>0){//VENTA
		$s="UPDATE ventas_det ".
		   "SET ca_control=ca_control - $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_venta=$_IR";
		 ejt($s);
	}
		
}
function CONTROLZ($StrComR_,$_IR,$_IDP,$_CAN,$_UNI){
	if($StrComR_==-1){//TRANSFERENCIA
		$s="UPDATE transferencias_det ".
		   "SET cant_control=cant_control + $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_trans=$_IR";
		 ejt($s);
	}
	if($StrComR_==-3){//PROFORMA
		$s="UPDATE cotizaciones_det ".
		   "SET ca_control=ca_control + $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_cotizacion=$_IR";
		 ejt($s);
	}
	if($StrComR_==-2){//GUIA INTERNA
		$s="UPDATE ginterna_det ".
		   "SET ca_control=ca_control + $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_gi=$_IR";
		 ejt($s);
	}	
	if($StrComR_>0){//VENTAS
		$s="UPDATE ventas_det ".
		   "SET ca_control=ca_control + $_CAN ".
		   "WHERE ".
		   "id_producto=$_IDP AND can_uni=$_UNI AND id_venta=$_IR";
		 ejt($s);
	}

}
//
function DEV_GEN_NUM_MAX(&$STR_NUM,$TIP,$EMP){
$IdVen=gn("count(*)","z_vis_devoluciones","TIP='$TIP' AND ID_EMP=$EMP");
if($IdVen==0){
	$STR_NUM="00001";
}else{
	$MAX_N=gn("max(NRO_)","z_vis_devoluciones","TIP='$TIP' AND ID_EMP=$EMP");
	$IdVen=gn("ID","z_vis_devoluciones","NRO_=$MAX_N AND TIP='$TIP' AND ID_EMP=$EMP");	
	$StrN=$MAX_N + 1;
	$StrNN=gs("dev_nro","devoluciones","id_devolucion=$IdVen");
	if(strlen($StrN)>strlen($StrNN)){
		$STR_NUM=$StrNN;
	}else{
		$i=strlen($StrNN);
		$STR_NUM=vbr("000000000000".$StrN,$i);
	}
}}
//
function GI_GEN_NUM_MAX($ALM_ID,&$STR_NUM,&$STR_SER){
$IdVen=gn("count(*)","ginterna","gi_id_alm=$ALM_ID");
if($IdVen==0){
	$STR_SER="000";
	$STR_NUM="00001";
}else{
	$MAX_S=gn("max(gi_iserie)","ginterna","gi_id_alm=$ALM_ID");		
	$MAX_N=gn("max(gi_inum)","ginterna","gi_id_alm=$ALM_ID AND gi_iserie=$MAX_S");
	//	
	$IdVen=gn("id_gi","ginterna","gi_id_alm=$ALM_ID AND gi_inum=$MAX_N AND gi_iserie=$MAX_S");	
	$STR_SER=gs("gi_serie","ginterna","id_gi=$IdVen");	
	if(strlen($STR_SER)==0)$STR_SER="000";
	$StrN=$MAX_N + 1;
	$StrNN=gs("gi_num","ginterna","id_gi=$IdVen");
	if(strlen($StrN)>strlen($StrNN)){
		$STR_NUM=$StrNN;
	}else{
		$i=strlen($StrNN);
		$STR_NUM=vbr("000000000000".$StrN,$i);
	}
	
}}
//
function val_dex($StrDex){
	if(strlen($StrDex)==0){
		$StrDexT="1900-01-01";
	}else{
		if(IsDate($StrDex)==false){
			$StrDexT="1900-01-01";
		}else{
			$StrDexT=ToDate($StrDex);
		}
	}
	return $StrDexT;
}

function val_hax($StrHax){
	if(strlen($StrHax)==0){
		$StrHaxT="2100-01-01";
	}else{
		if(IsDate($StrHax)==false){
			$StrHaxT="2100-01-01";
		}else{
			$StrHaxT=ToDate($StrHax);
		}
	}
	return $StrHaxT;	
}
function val_vac($Str){
	if(strlen(trim($Str))==0){
		return "%";
	}else{
		return trim($Str);
	}
}
//
function VEN_V_MEA($ID){
	$SER=gn("iser","ventas","id_venta=$ID");
	$NUM=gn("inum","ventas","id_venta=$ID");	
	$CX=gn("COUNT(*)","guias","id_comr>0 AND id_ref=$ID AND anu='N'");
	if($CX>0){
		return "GR";
	}
	$CX=gn("COUNT(*)","devoluciones","dev_id_comprobante>0 AND dev_id_ref=$ID AND dev_anu='N'");
	if($CX>0){
		return "DE";
	}
	$CX=gn("COUNT(*)","cobroz","cob_id_com>0 AND cob_icser=$SER AND cob_icnum=$NUM AND cob_anu='N'");
	if($CX>0){
		return "CO";
	}
	$CX=gn("COUNT(*)","cobrox","cx_id_com>0 AND cx_iser=$SER AND cx_inum=$NUM AND cx_anu='NO'");
	if($CX>0){
		return "CT";
	}
	return "OK";
}
//
function COT_V_MEA($ID){
	$SER=gn("iser","cotizaciones","id_cotizacion=$ID");
	$NUM=gn("inum","cotizaciones","id_cotizacion=$ID");
	$CX=gn("COUNT(*)","ventas","ven_id_com=-3 AND ven_id_ven=$ID AND anu='N'");
	if($CX>0){
		return "VE";
	}	
	$CX=gn("COUNT(*)","guias","id_comr=-3 AND id_ref=$ID AND anu='N'");
	if($CX>0){
		return "GR";
	}
	$CX=gn("COUNT(*)","ginterna","gi_id_cotizacion=$ID AND gi_anu='N'");
	if($CX>0){
		return "GI";
	}
	$CX=gn("COUNT(*)","devoluciones","dev_id_comprobante=-3 AND dev_id_ref=$ID AND dev_anu='N'");
	if($CX>0){
		return "DE";
	}
	$CX=gn("COUNT(*)","cobroz","cob_id_com=-3 AND cob_icser=$SER AND cob_icnum=$NUM AND cob_anu='N'");
	if($CX>0){
		return "CO";
	}
	$CX=gn("COUNT(*)","cobrox","cx_id_com=-3 AND cx_iser=$SER AND cx_inum=$NUM AND cx_anu='NO'");
	if($CX>0){
		return "CT";
	}
	return "OK";
}
//
function COB_GC($StrCom,$StrSer,$StrNum){
	$P1=$StrCom;
	$P2=vbval($StrSer);
	$P3=vbval($StrNum);
	if($P1=="BOLETA" || $P1=="FACTURA"){
		$D=gn("id_comprobante","comprobantes","com_nombre='$P1'");
		$S=vbval($P2);
		$N=vbval($P3);
		$I=gn("id_venta","ventas","id_com=$D AND iser=$S AND inum=$N");
		return vbval(gn("id_cliente","ventas","id_venta=$I"));
	}
	if($P1=="PROFORMA"){
		$S=vbval($P2);
		$N=vbval($P3);
		$I=gn("id_cotizacion","cotizaciones","iser=$S AND inum=$N");
		return vbval(gn("id_cliente","cotizaciones","id_cotizacion=$I"));
	}	
}
//
function GetIDU(){
	return vbval($_SESSION['SYS_USER_ID']);
}
//
function COBROS_ADD($COM_,$SER_,$NUM_,$TOT_,$COB_,$CLI_){
	$ID=GenId("id_cobro","cobroz");
	$StrFEC=date("Y-m-d");
	$GII=GenGI();
	$StrNUM=vbr("000000".$Id,6);
	$SAL=round($TOT - $COB_);
	$iSER=vbval($SER_);
	$iNUM=vbval($NUM_);
	$s="INSERT INTO cobroz VALUES ".
	   "($ID,'$StrNUM',$COM_,'$SER_',".
	   "'$NUM_','$StrFEC',$GII,'CO',".
	   "$COB_,$SAL,'SI','NO',$iSER,".
	   "$iNUM,'',$TOT_,$SAL,0,$CLI_,".GetIDU().")";
	ejt($s);
}
//
function IMP_PERSONAL(){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('imp_personal.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$NOM=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][1]))); 		
		$DIR=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][2]))); 		
		$DIS=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][3])));
		$DNI=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][4])));
		$TEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][5])));
		$CEL=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][6])));
		$EMA=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][7])));
		$CAR=str_replace("'"," ",trim(V($data->sheets[0]['cells'][$i][8])));
		//
		if(strlen($NOM)==0) break;
		if(strlen($DNI)==0) break;
		//
		if(strlen($DIS)>0){
			if(GetC("distritos","dis_nombre='$DIS'")==0){
				$ID_DIS=GenId("id_distrito","distritos");
				$s="INSERT INTO distritos VALUES ($ID_DIS,'$DIS')";
				ejt($s);
			}else{
				$ID_DIS=gn("id_distrito","distritos","dis_nombre='$DIS'");
			}
		}else{
			$ID_DIS=0;
		}
		//
		if(strlen($CAR)>0){
			if(GetC("cargos","car_nombre='$CAR'")==0){
				$ID_CAR=GenId("id_cargo","cargos");
				$s="INSERT INTO cargos VALUES ($ID_CAR,'$CAR')";
				ejt($s);
			}else{
				$ID_CAR=gn("id_cargo","cargos","car_nombre='$CAR'");
			}
		}else{
			$ID_CAR=0;
		}
		$ID_PER=gn("id_personal","personal","per_dni='$DNI'");

		if($ID_PER==0){
			$ID_PER=GenId("id_personal","personal");
			$s="INSERT INTO personal VALUES ".
			   "($ID_PER,'$NOM','$DIR',$ID_DIS,'1900-01-01','$DNI','$TEL','$CEL','1900-01-01','$EMA',$ID_CAR,'')";
			ejt($s);
		}else{
			$s="UPDATE personal SET 
				per_nombre='$NOM',
				per_direccion='$DIR',
				per_id_distrito=$ID_DIS,
				per_dni='$DNI',
				per_tel='$TEL',
				per_cel='$CEL',
				per_email='$EMA',
				per_id_cargo=$ID_CAR
			WHERE id_personal=$ID_PER";
			ejt($s);		
		}
		//
	}
}
//
function IMP_PROD_XLS($ALM_){
	$cx=0;
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('Inventario.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {
		$COD=trim(V($data->sheets[0]['cells'][$i][1])); 		
		$DES=trim(V($data->sheets[0]['cells'][$i][2])); 		
		$PIE=vbval(V($data->sheets[0]['cells'][$i][3])); 
		$STO=vbval(V($data->sheets[0]['cells'][$i][4])); 				
		//
		$IDP=gn("id_producto","productos","pro_codigo='$COD'");
		if($IDP>0){
			$SA=gn("sp_cantidad","stocks_presentaciones",
				   "sp_id_producto=$IDP AND sp_id_almacen=$ALM_ AND ");
		}
		//
	}
}
function CREDITOS_DEJA($ID_CLI,$TOTAL){
	$ID=gn("id_credito","creditos","cre_id_cliente=$ID_CLI");
	if($ID!=0){
		ejt("UPDATE creditos SET cre_deja=cre_deja + $TOTAL WHERE id_credito=$ID");
	}else{
		$ID=GenId("id_credito","creditos");
		ejt("INSERT INTO creditos VALUES ($ID,$ID_CLI,0,$TOTAL)");
	}
}
function CREDITOS_DEVO($ID_CLI,$TOTAL){
	$ID=gn("id_credito","creditos","cre_id_cliente=$ID_CLI");
	if($ID!=0){
		ejt("UPDATE creditos SET cre_devo=cre_devo + $TOTAL WHERE id_credito=$ID");
	}else{
		$ID=GenId("id_credito","creditos");
		ejt("INSERT INTO creditos VALUES ($ID,$ID_CLI,$TOTAL,0)");
	}
}

function VCbo($Cbo){
	if(strlen($Cbo)==0)$Cbo="TODOS";
	if($Cbo=="TODOS"){$CboT="%";}else{$CboT=$Cbo;}
	return $CboT;
}
//
function CLI_VE($ID){
	$CX=0;
	$CX=gn("count(*)","cotizaciones","id_cliente=$ID");
	if($CX>0)return "COT";
	$CX=gn("count(*)","ventas","id_cliente=$ID");
	if($CX>0)return "VEN";	
	return "OK";
}
//
function XERIFICAR($IDP,$PIE){
	$EXI=0;
	if(GetC("ajustes_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("ajustes_presentacion_det","id_producto=$IDP AND piezas=$PIE")>0){
		$EXI=1;
	}
	if(GetC("ajustes_presentacion_det","id_producto=$IDP AND (piezas - piezas_ajuste)=$PIE")>0){
		$EXI=1;
	}
	if(GetC("compras_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("cotizaciones_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("devoluciones_det","dd_id_producto=$IDP AND dd_pie=$PIE")>0){
		$EXI=1;
	}
	if(GetC("devoluciones_det","dd_id_producto=$IDP AND dd_pie=$PIE")>0){
		$EXI=1;
	}
	if(GetC("ginterna_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("guias_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("guias_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("transferencias_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	if(GetC("transformaciones","id_producto=$IDP AND de_uxc=$PIE")>0){
		$EXI=1;
	}
	if(GetC("transformaciones","id_producto=$IDP AND (((cant * de_caja)/a_caja)+a_uxc)=$PIE")>0){
		$EXI=1;
	}
	if(GetC("ventas_det","id_producto=$IDP AND can_uni=$PIE")>0){
		$EXI=1;
	}
	return $EXI;
}
//
function YERIFICAR($IDP){
	$EXI=0;
	if(GetC("ajustes_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("ajustes_presentacion_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("ajustes_presentacion_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("compras_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("cotizaciones_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("devoluciones_det","dd_id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("devoluciones_det","dd_id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("ginterna_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("guias_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("guias_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("transferencias_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("transformaciones","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("transformaciones","id_producto=$IDP")>0){
		$EXI=1;
	}
	if(GetC("ventas_det","id_producto=$IDP")>0){
		$EXI=1;
	}
	return $EXI;
}
//
function XLS_PRECIOS($ALM_){	
	$AX_FEC=date("Y-m-d");
	$data = new Spreadsheet_Excel_Reader();
	$data->setOutputEncoding('CP1251');
	$data->read('inv_precios.xls');
	error_reporting(E_ALL ^ E_NOTICE);
	$Fil=$data->sheets[0]['numRows'];
	$Col=$data->sheets[0]['numCols'];	
	for ($i = 2; $i <= $Fil; $i++) {		
		$COD=V($data->sheets[0]['cells'][$i][1]);					
		$PM=trim(V($data->sheets[0]['cells'][$i][6])); 
		$PW=trim(V($data->sheets[0]['cells'][$i][7])); 
		if(strlen($COD)==0) break;		
		$IDP=gn("id_producto","productos","pro_codigo='$COD'");
		if($IDP>0){
			if(strlen($PM)>0){	
				$INV=str_replace(",","",$PM);
				$INV=round(vbval($INV),3);	
				$INV=str_replace(",","",$INV);
				ejt("UPDATE productos SET pro_pv_min=$INV WHERE id_producto=$IDP");	
				ejt("UPDATE t_productos SET pro_pmi=$INV WHERE pro_id=$IDP");	
							
			}
			if(strlen($PW)>0){	
				$INV=str_replace(",","",$PW);
				$INV=round(vbval($INV),3);	
				$INV=str_replace(",","",$INV);
				ejt("UPDATE productos SET pro_pv_max=$INV WHERE id_producto=$IDP");	
				ejt("UPDATE t_productos SET pro_pma=$INV WHERE pro_id=$IDP");				
			}
		}
	}
}
function _D($ID){
	if($ID==1){
		return " disabled=\"disabled\" ";
	}else{
		return "";
	}
}
//
function APK_VAL($APK_ID){
	$_USU=gn("apk_id_usuario","apk","id_apk=$APK_ID");
	$_HAB=gs("hab","usuarios","id_usuario=$_USU");
	if($_HAB=="NO"){
		return "USU_NH";
	}
	$_COT=gn("valor","usuarios_menus","id_usuario=$_USU AND id_sm=27");
	if($_COT==0){
		return "USU_NP";
	}
	return "";		
}
//
function LA($lpE,$A,$T="N",$V="N"){
	AA($lpE."OK");
	$c="";
	$IDU=vbval(V($_SESSION['SYS_USER_ID']));		
	$ALM=gn("id_alm","usuarios","id_usuario=".$IDU);	
	//
	if($ALM!=0)$T="N";
	//
	if($T=="S")$V="N";
	//
	if($T=="S"){
		if(strlen($lpE)==0 || $lpE=="TODOS"){			
			$c=$c. "<option value=\"TODOS\" selected>TODOS</option>";
		}else{
			$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($V=="S"){
		if(strlen($lpE)==0){
			$c=$c. "<option value=\"\" selected></option>";
		}else{
			$c=$c. "<option value=\"\" ></option>";
		}
	}
	if($lpE=="TODOS"){
		if($ALM==0){
			$s="SELECT ANC FROM vis_almacenes 
				WHERE IDA>0 
				GROUP BY ANC 
				ORDER BY ANC ";
		}else{
			$s="SELECT ANC FROM vis_almacenes 
				WHERE IDA=$ALM 
				GROUP BY ANC 
				ORDER BY ANC ";
		}
	}else{
		if($ALM==0){
			$s="SELECT ANC FROM vis_almacenes ".
			   "WHERE IDA>0 AND ENC='$lpE' ".
			   "GROUP BY ANC ORDER BY ANC ";			
		}else{
			$s="SELECT ANC FROM vis_almacenes ".
			   "WHERE IDA=$ALM ".
			   "GROUP BY ANC ORDER BY ANC ";
		}
	}
	//AA($s);
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($A==$row[0]){
			$c=$c. "<option value=\"$row[0]\" selected>$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}		
	return $c;	
}
//
function GA($E,$T){
	$IDU=vbval(V($_SESSION['SYS_USER_ID']));
	$EMP=gn("id_emp","usuarios","id_usuario=".$IDU);
	$ALM=gn("id_alm","usuarios","id_usuario=".$IDU);
	//
	if($EMP==0){
		if($T=="S"){
			return "TODOS";
		}else{
			return "TODOS";
		}
	}else{
		if($ALM==0){
			if($T=="S"){
				return "TODOS";
			}else{
				return GetSO("alm_obs","almacenes","alm_id_empresa=$EMP","alm_obs");
			}
		}else{
			return GetSO("alm_obs","almacenes","id_almacen=$ALM","alm_obs");
		}
	}
}
//
function GE($T){	
	$IDU=vbval(V($_SESSION['SYS_USER_ID']));
	if($IDU==0){
		if($T=="S"){
			return "TODOS";
		}else{
			return GetSO("emp_nomc","empresas","id_emp>0","emp_nomc");
		}
	}else{
		$EMP=gn("id_emp","usuarios","id_usuario=".$IDU);
		if($EMP==0){
			if($T=="S"){
				return "TODOS";
			}else{
				return GetSO("emp_nomc","empresas","id_emp>0","emp_nomc");
			}
		}else{
			return gs("emp_nomc","empresas","id_emp=$EMP");
		}
	}
}
//
function LE($E,$T="N",$V="N"){
	$c="";
	$IDU=vbval(V($_SESSION['SYS_USER_ID']));
	$EMP=gn("id_emp","usuarios","id_usuario=".$IDU);
	//
	if($EMP==0){
		$s="SELECT emp_nomc 
			FROM empresas 
			WHERE id_emp>0";			
	}else{
		$s="SELECT emp_nomc 
			FROM empresas 
			WHERE id_emp=$EMP";			
		$T="N";
	}
	if($T=="S" || $EMP>0){
		$V="N";
	}
	if($T=="S"){
		if(strlen($E)==0 || $E=="TODOS"){
			$c=$c. "<option value=\"TODOS\" selected>TODOS</option>";
		}else{
			$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($V=="S"){
		if(strlen($E)==0){
			$c=$c. "<option value=\"\" selected></option>";
		}else{
			$c=$c. "<option value=\"\" ></option>";
		}
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($E==$row[0]){
			$c=$c. "<option value=\"$row[0]\" selected>$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}		
	return $c;	
}
function LAX($EA,$T="N",$V="N"){
	$c="";
	$IDU=vbval(V($_SESSION['SYS_USER_ID']));
	$EMP=gn("id_emp","usuarios","id_usuario=".$IDU);
	$ALM=gn("id_alm","usuarios","id_usuario=".$IDU);
	//
}
function AA($s){
	ejt("DELETE FROM a");
	$s=str_replace("'","@",$s);
	ejt("INSERT INTO a VALUES (1,'$s')");
	
}
//
function TRANS_GET_ID_REF($C,$S,$N,$IA){
	$ID=0;
	$S=vbval($S);
	$N=vbval($N);
	if($C=="PROFORMA"){
		$ID=gn("id_cotizacion","cotizaciones","iser=$S AND inum=$N AND id_alm=$IA");
	}else{
		$ID=gn("ID","vcompras","COM='$C' AND SER_=$S AND NUM_=$N AND ID_ALM=$IA");
	}
	return $ID;
}
function VEN_GET_ID_REF($C,$S,$N,$IE){
	$ID=0;
	$S=vbval($S);
	$N=vbval($N);
	if($C=="PROFORMA"){
		$ID=gn("ID","vcotizaciones","ISER=$S AND INUM=$N AND ID_EMP=$IE");
	}else{
		$ID=gn("ID","vcompras","COM='$C' AND SER_=$S AND NUM_=$N AND ID_EMP=$IE");
	}
	return $ID;
}
function COT_GET_ID_COMPRA($D,$E,$SN){
	$SN=explode("-",$SN);
	$SE=vbval($SN[0]);
	$NU=vbval($SN[1]);
	$ID=gn("ID","vcompras","EMPC='$E' AND COM='$D' AND SER_=$SE AND NUM_=$NU");
	return $ID;
}
function VF($FEC){
	if($FEC=="00-00-00" || $FEC=="01-01-00"){
		return "";
	}else{
		return $FEC;
	}
}
function PGT($StrGT,$LStrFoc,$LStrMsg){
	if($StrGT=="S"){
		if(strlen($LStrMsg)>0){
			if(strlen($LStrFoc)==0){
				$LStrMsg="onload=\"alert('$LStrMsg');\"";
			}else{
				$LStrMsg="onload=\"alert('$LStrMsg');jF('$LStrFoc');\"";
			}
		}else{
			if(strlen($LStrFoc)>0){
				$LStrMsg="onload=\"jF('$LStrFoc');\"";
			}
		}
	}else{	
		$LStrFoc="document.getElementById('$P_C').focus();";
		$LStrMsg="onload=\"$LStrFoc;\"";
	}
	return $LStrMsg;
}
function BL($StrGT,$LStrMsg,$LStrFoc,$P_C){
	if($StrGT=="S"){
		if(strlen($LStrMsg)>0){
			if(strlen($LStrFoc)==0){
				$LStrMsg="onload=\"alert('$LStrMsg');\"";
			}else{
				$LStrMsg="onload=\"alert('$LStrMsg');$LStrFoc;\"";
			}
		}else{
			if(strlen($LStrFoc)>0){
				$LStrMsg="onload=\"$LStrFoc;\"";
			}
		}
	}else{	
		if(strlen($LStrFoc)==0){
			$LStrFoc="jF('$P_C');";	
		}
		$LStrMsg="onload=\"$LStrFoc;\"";
	}
	return $LStrMsg;
}
function PID(&$StrId,$GET_ID,&$StrCmd,&$LStrPag,$GET_PAG){
	if(strlen($StrId)==0){
		$StrId=$GET_ID;
		if(is_numeric($StrId)==false){
			$StrId="";		
		}else{
			$StrCmd="AR";
			$LStrPag=$GET_PAG;
			if(!is_numeric($LStrPag)){
				$LStrPag="";
			}
		}
	}
}
//
function FCBOO($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}

function FCBOOD($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N",$StrOrd){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrOrd DESC ";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrOrd DESC ";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}

function FCBO($StrCam,$StrTab,$StrCon,$StrSel,$StrTod,$StrVac="N"){
	$c="";
	if($StrTod=="S"){
		if(strlen($StrSel)==0 || $StrSel=="TODOS"){
		$c=$c."<option value=\"TODOS\" selected=\"selected\">TODOS</option>";
		}else{
		$c=$c. "<option value=\"TODOS\" >TODOS</option>";
		}
	}
	if($StrVac=="S"){
		if(strlen($StrSel)==0 ){
		$c=$c. "<option value=\"\" selected=\"selected\"></option>";
		}else{
		$c=$c. "<option value=\"\" ></option>";
		}
	}
	
	if(strlen($StrCon)==0){
		$s="SELECT $StrCam FROM $StrTab ORDER BY $StrCam";
	}else{
		$s="SELECT $StrCam FROM $StrTab WHERE $StrCon ORDER BY $StrCam";
	}
	$result = grs($s);
	while ($row = $result->fetch_row()){
		if($StrSel==$row[0]){
			$c=$c. "<option value=\"$row[0]\" ".
			"selected=\"selected\">$row[0]</option>";
		}else{
			$c=$c. "<option value=\"$row[0]\" >$row[0]</option>";
		}
	}
	return $c;
}
//
function gr($t,$w){
	if(strlen($w)==0){
		$ss="SELECT * FROM ".$t;
	}else{
		$ss="SELECT * FROM ".$t." WHERE ".$w;
	}
	$rs = grs($ss);
	$row = $rs->fetch_assoc;			
	return $row;
}
//AL MOMENTO DE COMPRAR O DE GENERAR ALGUN STOCK
function T_P_ACT($PRO_ID){
	 $s="SELECT sp_presentacion as PIE 
		 FROM stocks_presentaciones 
		 WHERE sp_id_producto=$PRO_ID AND sp_provicional=0 ORDER BY sp_presentacion";			  
	 $rs=grs($s);
	 while ($r=$rs->fetch_assoc()){
		$PIE=$r['PIE'];
		T_P_ADD($PRO_ID,$PIE,0);
	 }
	 //
	 $s="SELECT sp_presentacion as PIE 
		 FROM stocks_presentaciones 
		 WHERE sp_id_producto=$PRO_ID AND sp_provicional=1 ORDER BY sp_presentacion";			  
	 $rs=grs($s);
	 while ($r=$rs->fetch_assoc()){
		$PIE=$r['PIE'];
		T_P_ADD($PRO_ID,$PIE,1);
	 }
	 //
	 $s="SELECT PIE FROM vcot_control WHERE IDP=$PRO_ID AND (CA_CONTROL - DEJ)>0 AND ANU='N' AND PRI='1' GROUP BY PIE ";
	 $rs=grs($s);
	 while ($r=$rs->fetch_assoc()){
		$PIE=$r['PIE'];
		T_P_ADD($PRO_ID,$PIE,0);		
	 }
	 //
	 $s="SELECT PIE FROM vven_control WHERE IDP=$PRO_ID AND (CA_CONTROL - DEJ)>0 AND ANU='N' AND PRI=1 GROUP BY PIE ";
	 $rs = grs($s);
	 while ($r=$rs->fetch_assoc()){
		 $PIE=$r['PIE'];
		 T_P_ADD($PRO_ID,$PIE,0);
	 }
	 //
	 $s="SELECT pro_pie as PIE FROM t_productos WHERE pro_id=$PRO_ID GROUP BY pro_pie";	   
	 $rss = grs($s);
	 while ($r=$rss->fetch_assoc()){		
		 $PIE=$r['PIE'];
		 //
		 $ss="SELECT SUM(CA_CONTROL - DEJ) FROM vcot_control WHERE IDP=$PRO_ID AND PIE=$PIE AND ANU='N' AND PRI='1'";
		 $rs = grs($ss);
		 $row = $rs->fetch_row();
		 $RES= (is_null($row[0])) ? 0 : $row[0];
		 //
		 $_SEP=$RES;
		 $ss="SELECT SUM(CA_CONTROL - DEJ) FROM vven_control WHERE IDP=$PRO_ID AND PIE=$PIE AND ANU='N' AND PRI=1";
		 $rs = grs($ss);
		 $row = $rs->fetch_row();
		 $RES= (is_null($row[0])) ? 0 : $row[0];
		 //
		 $_SEP=$_SEP + $RES;
		 $ss="SELECT SUM(CA) FROM vcom_control WHERE IDP=$PRO_ID AND PIE=$PIE AND ANU='N' AND ET='SI'";
		 $rs = grs($ss);
		 $row = $rs->fetch_row();
		 $RES= (is_null($row[0])) ? 0 : $row[0];
		 //
		 $_TRA=$RES;//gn("SUM(CA)","vcom_control","IDP=$PRO_ID AND PIE=$PIE AND ANU='N' AND ET='SI'") ;
		 //
		 $ss="SELECT SUM(sp_cantidad) FROM stocks_presentaciones WHERE sp_id_producto=$PRO_ID AND sp_presentacion=$PIE";
		 //echo $ss."<br>";
		 $rs = grs($ss);
		 $row = $rs->fetch_row();
		 $STO= (is_null($row[0])) ? 0 : $row[0];
		 //
		 $s="UPDATE t_productos SET pro_sep=$_SEP,pro_etr=$_TRA,pro_sto=$STO WHERE pro_id=$PRO_ID AND pro_pie=$PIE";
		 //echo $s."<br>";
		 grs($s);
	 }
}
//
function T_P_ADD($PRO_ID,$PIE,$PRV){
	if(gn("count(*)","t_productos","pro_id=$PRO_ID AND pro_pie=$PIE")==0){
		$rs = grs("SELECT * FROM vproductos WHERE ID=$PRO_ID");
	    $r = $rs->fetch_assoc;	
		$COD=$r['COD'];
		$DES=$r['DESCRIPCION'];
		$PMI=$r['PV_MIN'];
		$PMA=$r['PV_MAX'];
		$LIN=$r['LINEA'];
		$PIE=$PIE;
		$CAN=0;
		$PRV=$PRV;
		$SEP=0;
		$ETR=0;
		$ROJ=$r['ROJ'];
		$AMA=$r['AMA'];
		$USO=gs("pro_uso","productos","id_producto=$PRO_ID");
		$CX=GenId("id_pro","t_productos");
		$s="INSERT INTO t_productos VALUES ($CX,$PRO_ID,'$COD','$DES',$PMI,$PMA,'$LIN',$PIE,$CAN,$PRV,$SEP,$ETR,'$USO',$AMA,$ROJ)";		
		grs($s);
	}	
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++
function USU_PER_SET($USU,$MOD,$PER){
	ejt("DELETE FROM usuarios_permisos WHERE usu=$USU AND modulo='$MOD'");
	ejt("INSERT INTO usuarios_permisos VALUES ($USU,'$MOD',$PER)");
}
function USU_PER_GET($USU,$MOD){
	$PER=gn("per","usuarios_permisos","usu=$USU AND modulo='$MOD'");
	return $PER;
}
function USU_PER_GET_EX($MOD){
	$USU=vbval(V($_SESSION['SYS_USER_ID']));
	$PER=gn("per","usuarios_permisos","usu=$USU AND modulo='$MOD'");
	return $PER;
}
function USU_PER_GET_ES_CAJERO(){
	$USU=vbval(V($_SESSION['SYS_USER_ID']));
	$VEN=gn("id_vendedor","usuarios","id_usuario=$USU");
	$CAR=gs("CARGO","vpersonal","ID=$VEN");
	if($CAR=="CAJERO"){
		return true;
	}else{
		return false;
	}
}
//A=10/B=15 = 5 DIAS(TAMBIEN SALE NEGATIVOS)
function DATE_DIF($FEC_A,$FEC_B){
	$s="SELECT DATEDIFF('".$FEC_B."','".$FEC_A."')";
	$rs = grs($s);
	$r = $rs->fetch_row();
	return $r[0];
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
function FxCOT_SUM_DET($COT_KOD){
	$X_IMPORTE=0;
	$s="SELECT * FROM cotizaciones_det 
		WHERE id_cotizacion=$COT_KOD";
	$rs=grs($s);
	while($r=$rs->fetch_assoc()){
		$X_IM=NF($r['im'],3);	
		$X_IMPORTE=$X_IMPORTE+$X_IM;
	}
	$N=round($X_IMPORTE,2);
	$M=round($X_IMPORTE,1);
	if($N>$M){
		$X_IMPORTE=$M+0.1;	
	}else{
		$X_IMPORTE=$M;	
	}
	return $X_IMPORTE;
}
function LQ_COT_ERR_TOT_LOG($cot,$cot_fec,$cot_tot,$tot_rea,$tot_des,$tot_det,$tipo,$dif,$acc){
	$FEC=date("Y-m-d");
	$s="INSERT INTO lq_cot_err_tot (fec,cot,cot_fec,cot_tot,cot_tot_rea,cot_tot_des,cot_tot_det,cot_err_tip,cot_dif,acc) 
		VALUES ('$FEC',$cot,'$cot_fec',$cot_tot,$tot_rea,$tot_des,$tot_det,'$tipo',$dif,'$acc')";
	ejt($s);
	//echo $s."<br>";
}
function FxCOT_PARSE_TOT($COT_KOD,$ACC){
	$r=gr("cotizaciones","id_cotizacion=".$COT_KOD);
	$COT_FEC=$r['fec'];
	$TOTAL=round($r['tot'],1);
	$TOTAL_REA=round($r['tot_real'],1);
	$TOTAL_DES=round($r['tot_des'],1);
	$DET_SUM_TOT=round(FxCOT_SUM_DET($COT_KOD),1);
	//
	if($TOTAL!=round($TOTAL_REA + $TOTAL_DES,1)){
		LQ_COT_ERR_TOT_LOG($COT_KOD,$COT_FEC,$TOTAL,$TOTAL_REA,$TOTAL_DES,$DET_SUM_TOT,"INCOHERENCIA",0,$ACC);
		return false;
	}	
	$DIF=round($TOTAL - $DET_SUM_TOT,1);
	if($DIF==0){
		return true;
	}else{
		if(abs($DIF)==0.1){
			LQ_COT_ERR_TOT_LOG($COT_KOD,$COT_FEC,$TOTAL,$TOTAL_REA,$TOTAL_DES,$DET_SUM_TOT,"OX",0,$ACC);
			return true;
		}else{
			if(abs($DIF)==0.2){
				LQ_COT_ERR_TOT_LOG($COT_KOD,$COT_FEC,$TOTAL,$TOTAL_REA,$TOTAL_DES,$DET_SUM_TOT,"OZ",0,$ACC);
				return true;
			}else{
				LQ_COT_ERR_TOT_LOG($COT_KOD,$COT_FEC,$TOTAL,$TOTAL_REA,$TOTAL_DES,$DET_SUM_TOT,"OBS",$DIF,$ACC);
				return false;
			}
		}
	}
	return false;
}
?>