function jsaSetFecha($recibo, $fecha, $nuevoperiodo)
{
    $xRec = new cReciboDeOperacion(false, true, $recibo);
    $xF = new cFecha();
    $fecha = $xF->getFechaISO($fecha);
    $xRec->init();
    if ($xF->getInt($fecha) != $xF->getInt($xRec->getFechaDeRecibo())) {
        $xRec->setFecha($fecha, true);
    }
    if ($xRec->getPeriodo() != $nuevoperiodo) {
        $xRec->setPeriodo($nuevoperiodo, true);
    }
    return $xRec->getMessages(OUT_HTML);
}
 $TipoDeResponsabilidad = isset($DTConv["SIC_TIPO_DE_RESPONSABILIDAD"]) ? $DTConv["SIC_TIPO_DE_RESPONSABILIDAD"] : "I";
 //individual
 $TipoDeCuenta = isset($DTConv["SIC_TIPO_DE_CUENTA"]) ? $DTConv["SIC_TIPO_DE_CUENTA"] : "F";
 //Pagos fijos
 $TipoDeContrato = strtoupper($xCred->getOProductoDeCredito()->getTipoDeContratoCR());
 // isset($DTConv["SIC_TIPO_DE_CONTRATO"]) ? $DTConv["SIC_TIPO_DE_CONTRATO"] : "DESCONOCIDO";
 $ClaveUnidadMonetaria = "MX";
 $ValorActivoValuacion = 0;
 $NumeroDePagos = $xCred->getPagosAutorizados();
 $FrecuenciaDePagos = $xCR->getEPeriocidad($xCred->getPeriocidadDePago());
 $MontoPagar = $xCR->getMonto($xCred->getSaldoActual($FechaFinal));
 //Acabar, valor de la letra actual o saldo?
 $FechaAperturaCuenta = $xCR->getDate($xCred->getFechaDeMinistracion());
 $FechaUltimoPago = $xCR->getDate($xCred->getFechaUltimoDePago());
 //setLog("1....$FechaUltimoPago");
 if ($xF->getInt($xCred->getFechaUltimoDePago()) >= $xF->getInt($xCred->getFechaDeMinistracion())) {
     //$FechaUltimoPago		= $FechaAperturaCuenta;
     $xF100 = new cFecha();
     $FechaAperturaCuenta = $xCR->getDate($xF100->setRestarDias(2, $xCred->getFechaDeMinistracion()));
     $FechaUltimoPago = $xCR->getDate($xF100->setRestarDias(1, $xCred->getFechaDeMinistracion()));
     //setLog("2....$FechaUltimoPago");
 }
 $FechaUltimaCompra = $xCR->getDate($xCred->getFechaDeMinistracion());
 $FechaCierreCuenta = "";
 $FechaCorte = $FechaExtraccion;
 $Garantia = "";
 //TODO: Acabar garantia
 $CreditoMaximo = $xCR->getMonto($xSoc->getCreditoMaximo());
 $SaldoActual = $xCR->getMonto($xCred->getSaldoActual($FechaFinal));
 $LimiteCredito = $xCR->getMonto($xSoc->getCreditoMaximo());
 $SaldoVencido = 0;
 /**
  * Genera un reinversion
  *
  * @param date $fecha		Fecha de Cierre se refiere a la fecha que que se efectua la Reinversion
  * @param boolean $cerrar	Cerrar, indica si se cierra la inversion.
  * @param float $tasa
  * @param int $dias
  * @return integer Numero de Recibo
  */
 function setReinversion($fecha = false, $cerrar = false, $tasa = false, $dias = false, $InversionParcial = false, $invertido = 0)
 {
     $recibo = false;
     $xF = new cFecha();
     //en Monto de la reinversion sera despues de los depositos (Saldo Actual)
     //si cerrar = false, no efectuar ninguno movimiento
     if ($cerrar == true) {
         $this->mPeriodoCuenta = setNoMenorQueCero($this->mPeriodoCuenta) + 1;
         $this->mDiasInvertidos = setNoMenorQueCero($dias) > 0 ? $dias : $this->mDiasInvertidos;
         //2012-01-09: correccion de dias menores a cero
         $this->mDiasInvertidos = $this->mDiasInvertidos < INVERSION_DIAS_MINIMOS ? INVERSION_DIAS_MINIMOS : $this->mDiasInvertidos;
         if ($tasa != false) {
             if ($tasa > $this->mTasaInteres) {
                 $this->mTasaInteres = $tasa;
                 $this->mMessages .= "WARN\tTASA\tSe respeta una Tasa Especial de {$tasa} sobre " . $this->mTasaInteres . " que tenia Anteriormente  \r\n";
             }
         }
         $grupo = $this->mGrupoAsociado;
         $observaciones = "REINVERSION AUTOMATICA # " . $this->mPeriodoCuenta;
         $recibo_fiscal = "NA";
         $tipo_de_pago = TESORERIA_COBRO_NINGUNO;
         $cheque = "NA";
         $tipo_de_recibo = 6;
         //OK: Verificar Monto de la Operacion
         $monto = ($InversionParcial == true and $invertido > 0) ? $invertido : $this->mNuevoSaldo;
         //verificar Nuevamente la Tasa
         $tasa = $this->mTasaInteres <= 0 ? $this->getTasaAplicable($this->mDiasInvertidos, 0, $monto) : $this->mTasaInteres;
         //algoritmo de tasa incremental
         eval($this->mModificadorTasa);
         $this->mTasaInteres = $tasa;
         if (setNoMenorQueCero($this->mSocioTitular) <= DEFAULT_SOCIO) {
             $this->initCuentaByCodigo();
         }
         //2014-09-09 .- validar si el recibo se inicia y tiene fecha de hoy
         if ($this->getOReciboInversion() == null) {
             //El recibo no existe
             $this->mMessages .= "WARN\tNo existe el Recibo de Inversion\r\n";
         } else {
             $dia_de_inversion = $this->getOReciboInversion()->getFechaDeRecibo();
             $recibo_anterior = $this->getOReciboInversion()->getCodigoDeRecibo();
             if ($xF->getInt($dia_de_inversion) == $xF->getInt($fecha)) {
                 $this->mMessages .= "WARN\tLa fecha de reinversion[{$fecha}] es igual al recibo anterior[{$recibo_anterior} - " . $dia_de_inversion . "] se Eliminara\r\n";
                 $this->getOReciboInversion()->setRevertir(true);
                 $this->mMessages .= $this->getOReciboInversion()->getMessages();
             }
         }
         if ($fecha == false) {
             if (isset($this->mFechaOperacion) and $this->mFechaOperacion != false) {
                 $fecha = $this->mFechaOperacion;
             } else {
                 $fecha = fechasys();
             }
         }
         //Corrige el Dia Inhabil
         //$this->mFechaVencimiento;
         //corrige la fecha de Vencimiento, si es menor a la actual
         if (strtotime($fecha) >= strtotime($this->mFechaVencimiento)) {
             $this->mMessages .= "WARN\tLa fecha de reinversion[{$fecha}] es mayor a la de vencimiento[" . $this->mFechaVencimiento . "]\r\n";
             if ($this->mDiasInvertidos > 0) {
                 $this->mFechaVencimiento = $xF->setSumarDias($this->mDiasInvertidos, $fecha);
             }
         }
         $this->mFechaVencimiento = $xF->getDiaHabil($this->mFechaVencimiento);
         $diasCalculados = $xF->setRestarFechas($this->mFechaVencimiento, $fecha);
         if ($diasCalculados > $this->mDiasInvertidos) {
             $this->mDiasInvertidos = $diasCalculados;
             $this->mMessages .= "WARN\tSe Actualizan los Dias de Inversion a {$diasCalculados}\r\n";
         }
         $socio = $this->mSocioTitular;
         //Inicializar el Recibo
         $CRecibo = new cReciboDeOperacion($tipo_de_recibo, true);
         //Agregar recibo si no hay
         if (setNoMenorQueCero($recibo) <= 0) {
             $recibo = $CRecibo->setNuevoRecibo($socio, $this->mNumeroCuenta, $this->mFechaOperacion, $this->mPeriodoCuenta, $tipo_de_recibo, $observaciones, $cheque, $tipo_de_pago, $recibo_fiscal, $grupo);
             //Checar si se agrego el recibo
             if (setNoMenorQueCero($recibo) > 0) {
                 $this->mMessages .= "SUCESS\tSe Agrego Exitosamente el Recibo {$recibo} de la Cuenta " . $this->mNumeroCuenta . " \r\n";
                 $this->mReciboDeReinversion = $recibo;
                 $this->mSucess = true;
             } else {
                 $this->mMessages .= "ERROR\tSe Fallo al Agregar el Recibo {$recibo} de la Cuenta " . $this->mNumeroCuenta . " \r\n";
                 $this->mSucess = false;
             }
         } else {
         }
         $this->mReciboDeReinversion = $recibo;
         //Calcular el Interes
         $interes = $monto * $this->mTasaInteres * $this->mDiasInvertidos / EACP_DIAS_INTERES;
         //OK: Ejecutar modificador de interes
         eval($this->mModificadorDeInteres);
         //si hay recibo, agregar
         if (setNoMenorQueCero($recibo) > 0) {
             //Agregar el Movimiento de Reinversion
             $CRecibo->setNuevoMvto($fecha, $monto, 223, $this->mPeriodoCuenta, $observaciones, 1, TM_ABONO, $socio, $this->mNumeroCuenta);
             $this->mMessages .= "OK\tEVENT\tAgregando la Reinversion por un Monto de {$monto} de la Cuenta " . $this->mNumeroCuenta . " con fecha {$fecha} \r\n";
             //Agregar el Movimiento de Interes
             $CRecibo->setNuevoMvto($this->mFechaVencimiento, $interes, 500, $this->mPeriodoCuenta, $observaciones, 1, TM_ABONO, $socio, $this->mNumeroCuenta);
             $CRecibo->setFinalizarRecibo(true);
             $this->mMessages .= $CRecibo->getMessages("txt");
             $this->mSucess = true;
             //Actualizar la Cuenta
             if ($InversionParcial == false and $invertido == 0) {
                 $this->setUpdateInversion();
             }
         } else {
             $this->mMessages .= "ERROR\tNo Existe Recibo con el cual trabajar({$recibo}) \r\n";
         }
         $this->mMessages .= $CRecibo->getMessages();
         return $recibo;
     }
 }
function jsaGetControlDias($mod, $Msolicitud)
{
    $txt = "";
    if (isset($mod) and isset($Msolicitud)) {
        $mod = intval($mod);
        $periocidad = 15;
        $p_quincena = PQ_DIA_PRIMERA_QUINCENA;
        $s_quincena = PQ_DIA_SEGUNDA_QUINCENA;
        $xF = new cFecha();
        $xT = new cTipos();
        //---------------------------------------------------------
        $xCred = new cCredito($Msolicitud);
        $xCred->init();
        $periocidad = $xCred->getPeriocidadDePago();
        //cargar si es Nomina
        $xPlanGen = new cPlanDePagosGenerador();
        $xPlanGen->initPorCredito($Msolicitud);
        switch ($mod) {
            case CREDITO_TIPO_DIAS_DE_PAGO_PERSONALIZADOS:
                if ($periocidad == CREDITO_TIPO_PERIOCIDAD_QUINCENAL) {
                    $p_quincena = $xPlanGen->getDiaAbono1();
                    $s_quincena = $xPlanGen->getDiaAbono2();
                    $txt = "\n\t\t\t\t\t\t<th>Primer Dia de Abono en el Mes</th>\n\t\t\t\t\t\t<td><input type=\"text\" name=\"dia_primer_abono\" id=\"iddia_primer_abono\" size=\"3\" class=\"mny\" value=\"{$p_quincena}\" /></td>\n\n\t\t\t\t\t\t<th>Segundo Dia de Abono en el Mes</th>\n\t\t\t\t\t\t<td><input type=\"text\" name=\"dia_segundo_abono\" id=\"iddia_segundo_abono\" size=\"3\" class=\"mny\" value=\"{$s_quincena}\" /></td>\n\t\t\t\t\t\t";
                } elseif ($periocidad == CREDITO_TIPO_PERIOCIDAD_SEMANAL) {
                    $txt = "\n\t\t\t\t\t\t<td>Primer Dia de Abono</td>\n\t\t\t\t\t\t<td><select name=\"dia_primer_abono\" id=\"iddia_primer_abono\" >\n\t\t\t\t\t\t\t<option value=\"1\">Lunes</option>\n\t\t\t\t\t\t\t<option value=\"2\">Martes</option>\n\t\t\t\t\t\t\t<option value=\"3\">Miercoles</option>\n\t\t\t\t\t\t\t<option value=\"4\">Jueves</option>\n\t\t\t\t\t\t\t<option value=\"5\">Viernes</option>\n\t\t\t\t\t\t\t<option value=\"6\">Sabado</option>\n\t\t\t\t\t\t</select> </td>";
                } elseif ($periocidad == CREDITO_TIPO_PERIOCIDAD_DECENAL) {
                    $txt = "<td>Dias de Abono(Decenal)</td>\n\t\t\t\t\t\t<td><input type=\"text\" name=\"dia_primer_abono\" onblur=\"jsCambiarDiaPago(this)\" id=\"iddia_primer_abono\" value=\"10,20,30\" /></td>";
                } else {
                    $pago_mensual = PM_DIA_DE_PAGO;
                    $xF->set($xCred->getFechaDeMinistracion());
                    $pago_mensual = date("j", $xF->getInt());
                    $pago_mensual = $xPlanGen->getDiaAbono1();
                    $txt = "<td>Dia de Abono</td>\n\t\t\t\t\t\t<td><input type=\"number\" name=\"dia_primer_abono\" onblur=\"jsCambiarDiaPago(this)\" id=\"iddia_primer_abono\" value=\"" . $pago_mensual . "\" /></td>";
                }
                break;
        }
    }
    return $txt;
}
$errors = $msg == "" ? false : true;
if ($preguntar == true) {
    header('Content-type: application/json');
    $arr = array("mensajes" => $msg, "registros" => $operaciones, "errores" => $totalerrores);
    echo json_encode($arr);
} else {
    if ($production == true and $errors == false and $operaciones > 0) {
        $archivo = $xLayout->getClave() . $xT->cSerial(6, $casfin) . $FechaTitulo . "." . $xT->cSerial(3, $supervisor);
        //header("Content-type: text/x-csv");
        header("Content-type: text/plain");
        //header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename={$archivo}");
        echo $rpt;
        if ($definitivo == true) {
            //Guardar
            $sqlUpdate = " UPDATE `aml_risk_register` SET `estado_de_envio` = 1, `fecha_de_envio`= " . $xF->getInt() . "\n\t\t\tWHERE (SELECT `tipo_de_riesgo` FROM `aml_risk_catalog` WHERE\n\t\t\t(`clave_de_control`= `aml_risk_register`.`tipo_de_riesgo`= " . AML_CLAVE_OPERACIONES_INTERNAS . "\n\t\t\t\tOR\n\t\t\t`clave_de_control`= `aml_risk_register`.`tipo_de_riesgo`= " . AML_CLAVE_OPERACIONES_INUSUALES . ")\n\t\t\tAND (getFechaByInt(`aml_risk_register`.`fecha_de_reporte`) <='{$FechaFinal}')\n\t\t\tAND (`aml_risk_register`.`estado_de_envio` =0)\n\t\t\tAND (`aml_risk_register`.`reporte_inmediato` =1)\t\t\t\n\t\t\t";
            $query->setRawQuery($sqlUpdate);
            //enviar por mail al administrador
            $xMail = new cNotificaciones();
            $xMail->sendMail($archivo, $rpt, ADMIN_MAIL);
        }
    } else {
        $xRPT = new cReportes();
        $xRPT->setOut(OUT_HTML);
        $xRPT->addContent($xRPT->getHInicial($xHP->getTitle(), $FechaInicial, $FechaFinal));
        $arrTitulos = array();
        foreach ($Estructura as $indice => $propiedades) {
            $xCampo = new cReportes_LayoutTipos($propiedades);
            $arrTitulos[] = $xCampo->getNombre();
        }
        $xHTable->addTitles($arrTitulos);
 function initPorCredito($idcredito, $dataCredito = false)
 {
     $xCred = new cCredito($idcredito);
     $xCred->init($dataCredito);
     $xF = new cFecha();
     if ($xCred->getTipoEnSistema() == CREDITO_PRODUCTO_NOMINA) {
         //cargar datos de la empresa
         $idemp = $xCred->getClaveDeEmpresa();
         $periocidad = $xCred->getPeriocidadDePago();
         $this->setPeriocidadDePago($periocidad);
         $this->mTipoCreditoSis = $xCred->getTipoEnSistema();
         $this->mClaveDePlan = setNoMenorQueCero($xCred->getNumeroDePlanDePagos());
         if ($this->mClaveDePlan > 0) {
             //TODO: validar fecha de primer pago en calculos automaticos
             $this->mFechaPrimerPago = $xCred->getFechaPrimeraParc();
         } else {
             $this->mFechaPrimerPago = $this->getFechaDePago($xCred->getFechaDeMinistracion(), 1);
         }
         if ($xCred->getFechaPrimeraParc() == $this->mFechaFail or $xF->getInt($xCred->getFechaPrimeraParc()) <= $xF->getInt($xCred->getFechaDeMinistracion())) {
             $this->mFechaPrimerPago = $this->getFechaDePago($xCred->getFechaDeMinistracion(), 1);
         }
         $xEmp = new cEmpresas($idemp);
         $xEmp->init();
         $DDias = $xEmp->getDiasDeNomina($periocidad);
         $this->mDiaDeAbono1 = isset($DDias[0]) ? setNoMenorQueCero($DDias[0]) : $this->mDiaDeAbono1;
         $this->mDiaDeAbono2 = isset($DDias[1]) ? setNoMenorQueCero($DDias[1]) : $this->mDiaDeAbono2;
         $this->mDiaDeAbono3 = isset($DDias[2]) ? setNoMenorQueCero($DDias[2]) : $this->mDiaDeAbono3;
     } else {
         $this->mFechaPrimerPago = $this->getFechaDePago($xCred->getFechaDeMinistracion(), 1);
     }
 }
 function setProcesarProgramacion($id, $arrVars = false, $data = false, $fecha = false)
 {
     $xF = new cFecha();
     $xT = new cTipos();
     $xLog = new cCoreLog();
     $arrVars = $arrVars == false ? $this->mArrVars : $arrVars;
     //idprograma, nombre_del_aviso, forma_de_creacion, programacion, destinatarios, microformato, tipo_de_medios, intent_check, intent_command
     $sql = "SELECT *\tFROM sistema_programacion_de_avisos WHERE idprograma={$id} LIMIT 0,1";
     $d = $data == false ? obten_filas($sql) : $data;
     $mOb = new cSistema_programacion_de_avisos();
     $mOb->setData($d);
     $emails = array();
     $tels = array();
     $enviar = false;
     $fecha = $fecha == false ? fechasys() : $fecha;
     $nombredia = $xF->getDayName();
     $diadelmes = date("j", $xF->getInt());
     $EnviarNota = true;
     $EnviarMail = true;
     $EnviarSMS = false;
     $xLoc = new cLocal();
     //procesar cuerpo del contenido
     $arrVars["fecha"] = !isset($arrVars["fecha"]) ? $fecha : $arrVars["fecha"];
     $arrVars["fecha_dia_siguiente"] = $xF->setSumarDias(1, $fecha);
     $arrVars["fecha_inicio_de_semana"] = $xF->getFechaDeInicioDeSemana($fecha);
     $arrVars["fecha_inicio_de_mes"] = $xF->getDiaInicial($fecha);
     //Dia de la semana inicial
     $arrVars["hora"] = date("H");
     $arrVars["usuario"] = $xLoc->getNombreUsuario();
     $arrVars["clave_de_usuario"] = !isset($arrVars["clave_de_usuario"]) ? getUsuarioActual() : $arrVars["clave_de_usuario"];
     //interpretar DIA
     if (strtoupper($mOb->forma_de_creacion()->v()) == SYS_ALERTA_POR_EVENTO) {
         $enviar = true;
     } else {
         //if($mOb->programacion())
         $programacion = strtoupper($mOb->programacion()->v());
         $periodo = explode(":", $programacion);
         //INTERPRETAR DIA
         if ($periodo[0] == "PROGRAMACION_SEMANAL") {
             if (strpos($nombredia, $programacion) !== false) {
                 $enviar = true;
             }
         } else {
             if ($periodo[0] == "PROGRAMACION_DIARIA") {
                 $enviar = true;
             } else {
                 if (isset($periodo[1])) {
                     $dias = explode(",", $periodo[1]);
                     foreach ($dias as $dias => $iddia) {
                         $mes = $xF->mes();
                         $anno = $xF->anno();
                         if (date("Y-m-d", strtotime("{$anno}-{$mes}-{$iddia}")) == $fecha) {
                             $enviar = true;
                         }
                     }
                 }
             }
         }
     }
     //1.- extraer emails
     $destinatarios = explode("|", $mOb->destinatarios()->v());
     foreach ($destinatarios as $key => $cnt) {
         if (trim($cnt) != "") {
             //1.1 Desfragmentar destinos
             $DS = explode(":", $cnt);
             $mdestino = isset($DS[0]) ? strtoupper($DS[0]) : "";
             switch ($mdestino) {
                 case "OFICIALES":
                     if (isset($DS[1])) {
                         $oficiales = explode(",", $DS[1]);
                         foreach ($oficiales as $ofc => $ofkey) {
                             $xOf = new cOficial($ofkey);
                             $xOf->init();
                             $mail = $xOf->getEmail();
                             $emails[] = $mail;
                             $xLog->add("OK\tOFICIAL\tAgregar mail {$mail}  \r\n", $xLog->DEVELOPER);
                         }
                     }
                     break;
                 case "EMPRESAS":
                     if (isset($DS[1])) {
                         $empresas = explode(",", $DS[1]);
                         foreach ($empresas as $emp => $empkey) {
                             $xEmp = new cEmpresas($empkey);
                             $xEmp->init();
                             //$mail		= $xEmp->getEmailsDeEnvio();
                             //$emails[]	= $mail;
                             $emails = array_merge($emails, $xEmp->getEmailsDeEnvio());
                             $xLog->add("OK\tEMPRESAS\tAgregar mail de la empresa {$empkey}  \r\n", $xLog->DEVELOPER);
                         }
                     }
                     break;
                 case "PERSONAS":
                     if (isset($DS[1])) {
                         $personas = explode(",", $DS[1]);
                         foreach ($personas as $ofc => $ofkey) {
                             $xSoc = new cSocio($ofkey);
                             $xSoc->init();
                             $mail = $xSoc->getCorreoElectronico();
                             $emails[] = $mail;
                             $xLog->add("OK\tPERSONA\tAgregar mail {$mail}  \r\n", $xLog->DEVELOPER);
                             if ($xT->cNumeroTelefonico($xSoc->getTelefonoPrincipal()) != false) {
                                 $EnviarSMS = true;
                                 $tels[] = $xT->cNumeroTelefonico($xSoc->getTelefonoPrincipal());
                             }
                         }
                     }
                     break;
                 case "CORREO":
                     if (isset($DS[1])) {
                         $personas = explode(",", $DS[1]);
                         foreach ($personas as $ofc => $ofkey) {
                             if (filter_var($ofkey, FILTER_VALIDATE_EMAIL)) {
                                 $emails[] = $ofkey;
                             }
                             $xLog->add("OK\tCORREO\tAgregar mail {$ofkey}  \r\n", $xLog->DEVELOPER);
                         }
                     }
                     break;
             }
             //1.1.1 Validar oficiales, empresas, personas
             //if(strpos("OFICIALES:", $needle))
         }
     }
     $this->mMessages .= $xLog->getMessages();
     $texto = $mOb->microformato()->v();
     foreach ($arrVars as $variable => $valor) {
         $texto = str_replace("{" . $variable . "}", $valor, $texto);
     }
     if ($enviar == true) {
         $url = $mOb->intent_command()->v(OUT_TXT);
         //2 procesado del comando
         if (trim($url) == "") {
             $titulo = strtoupper($mOb->nombre_del_aviso()->v());
             $xNot = new cNotificaciones();
             //enviar mail normal
             if ($EnviarSMS == true) {
                 foreach ($tels as $pitm => $ptel) {
                     $xNot->sendSMS($ptel, $texto);
                 }
             }
             if ($EnviarMail == true) {
                 foreach ($emails as $itm => $pmail) {
                     $xNot->sendMail($titulo, $texto, $pmail);
                 }
             }
         } else {
             //execute command
             //rpttesoreria/corte_de_caja.rpt.php?on=2014-5-3&off=2014-5-3&cajero=todas&dependencia=todas
             $smail = "";
             $xHO = new cHObject();
             foreach ($arrVars as $variable => $valor) {
                 $url = str_replace("{" . $variable . "}", $valor, $url);
             }
             foreach ($emails as $id => $rmail) {
                 //$smail	.= ($smail == "") ? "email$id=$rmail" : "&email$id=$rmail";
                 $smail .= "&email{$id}={$rmail}";
             }
             //Iniciar session en contexto &on=$fecha&off=$fecha
             $xSysUser = new cSystemUser();
             $xSysUser->init();
             $url = $url . $smail . "&ctx=" . $xSysUser->getCTX();
             if (MODO_DEBUG == true) {
                 setLog($url);
             }
             $xHO->navigate($url);
         }
     } else {
         $this->mMessages .= "OK\tNo e envia el reporte\r\n";
     }
     setLog($this->mMessages);
     $this->mObProgAv = $mOb;
     //return $this->mObProgAv;
 }
 function setDescartaAlerta($notas = "", $fecha = false)
 {
     $fecha = $fecha == false ? fechasys() : $fecha;
     $xF = new cFecha();
     $fecha = $xF->getInt($fecha);
     $clave = $this->mCodigo;
     //Actualizar la alerta
     $sql = "UPDATE aml_alerts SET fecha_de_checking={$fecha}, estado_en_sistema=" . SYS_CERO . ", notas_de_checking=\"{$notas}\" WHERE clave_de_control={$clave}";
     my_query($sql);
     $this->mMessages .= "WARN\tAlerta # {$clave} descartada\r\n";
 }
}
/**
 * Actualiza Recibos de Operaciones
 **/
$sqlS = "UPDATE operaciones_recibos SET tipo_pago = \"ninguno\" WHERE tipo_pago = \"\" OR IsNULL(tipo_pago) ";
my_query($sqlS);
/**
 * Actualiza los Periodos a Formatos Validos en el Caso que el sistema les haya asigando otro valor
 */
$sqlPeriodosCorrectos = "UPDATE operaciones_mvtos\r\n\t\t\t\t\t\t\t\tSET periodo_mensual = DATE_FORMAT(fecha_afectacion, '%c'),\r\n\t\t\t\t\t\t\t\tperiodo_anual = DATE_FORMAT(fecha_afectacion, '%Y'),\r\n\t\t\t\t\t\t\t\tperiodo_semanal = DATE_FORMAT(fecha_afectacion, '%w')\r\n\t\t\t\t\t\t\t\t";
$x1 = my_query($sqlPeriodosCorrectos);
$messages .= $x1[SYS_INFO];
$xSys = new cSystemTask();
$xDB = new cSAFEData();
//crear backup //
if ($xF->getDiaFinal() == $xF->get() or date("N", $xF->getInt()) == 5) {
    $messages .= "BACKUP\tRespaldo a la fecha " . $xF->getFechaDDMM() . "\r\n";
    $xDB->setCheckDatabase();
    $messages .= $xSys->setBackupDB_WithMail();
}
//cerrar el log
$xLog->setWrite($messages);
$xLog->setClose();
if (ENVIAR_MAIL_LOGS == true) {
    $xLog->setSendToMail("TR.Eventos del Cierre del Sistema");
}
//Stored procedures
$ql->setRawQuery("CALL `proc_listado_de_ingresos` ");
//$ql->setRawQuery("CALL `proc_historial_de_pagos` ");
$ql->setRawQuery("CALL `sp_clonar_actividades` ");
$ql->setRawQuery("CALL `proc_perfil_egresos_por_persona` ");
 function add($tipo, $pagina, $observaciones, $contrato = false, $persona = false, $documento = false, $fecha = false)
 {
     $xF = new cFecha();
     $fecha = $fecha == false ? fechasys() : $fecha;
     $documento = $documento == false ? $this->mNombreArchivo : $documento;
     $persona = $persona == false ? $this->mPersona : $persona;
     $contrato = $contrato == false ? DEFAULT_CREDITO : $contrato;
     $fecha = $xF->getInt($fecha);
     $user = getUsuarioActual();
     $suc = getSucursal();
     $ent = EACP_CLAVE;
     $sql = "INSERT INTO personas_documentacion(\n\t\t\tclave_de_persona, tipo_de_documento, fecha_de_carga, observaciones, archivo_de_documento, valor_de_comprobacion, \n\t\t\testado_en_sistema, fecha_de_verificacion, oficial_que_verifico, \n\t\t\tresultado_de_la_verificacion, notas, version_de_documento, numero_de_pagina, usuario, sucursal, entidad, documento_relacionado)\n\t\tVALUES({$persona}, {$tipo}, {$fecha}, '{$observaciones}', '{$documento}', '',\n\t\t 1, 0, 0, 0, '', '', {$pagina}, {$user}, '{$suc}', '{$ent}', {$contrato})";
     $rs = my_query($sql);
     if ($rs[SYS_ESTADO] == false) {
         $this->mMessages .= "ERROR\t \r\n";
     } else {
         $this->mMessages .= "OK\t \r\n";
     }
     return $rs[SYS_ESTADO];
 }
 function getDate($fecha)
 {
     $xF = new cFecha();
     return $this->mOut == OUT_CSV ? date("Ymd", $xF->getInt($fecha)) : "" . date("Ymd", $xF->getInt($fecha));
 }
$cajero = isset($_GET["f3"]) ? $_GET["f3"] : getUsuarioActual();
// Numero de Cajero
$cajero = parametro("cajero", $cajero, MQL_RAW);
$out = parametro("out", OUT_HTML, MQL_RAW);
$mails = getEmails($_REQUEST);
$ByCajero = "";
$ByAll = "";
$xCaja = new cCaja();
$xCaja->initByFechaUsuario($fecha_final, $cajero);
if (isset($_REQUEST["fechaMX"])) {
    $fecha_inicial = $xF->getFechaISO($_REQUEST["fechaMX"]);
    $fecha_final = $xF->getFechaISO($_REQUEST["fechaMX"]);
}
if (count($mails) <= 0) {
    if (MODULO_CAJA_ACTIVADO == true) {
        if ($xF->getInt($fecha_final) > $xF->getInt(fechasys())) {
            if ($xCaja->getEstatus() == TESORERIA_CAJA_ABIERTA) {
                $xHP->goToPageError(70102);
            }
        }
    }
}
$xUsr = new cSystemUser($cajero);
$xUsr->init();
$nombre = $xUsr->getNombreCompleto();
$ByDependencia = (isset($_GET["dependencia"]) and $_GET["dependencia"] != SYS_TODAS) ? " AND `socios`.`iddependencia`=" . $_GET["dependencia"] : "";
$xRPT = new cReportes();
$title = $xHP->getTitle();
$xRPT->setTitle($title);
$xRPT->setOut($out);
$xRPT->setSenders($mails);
 function setReestructurarSDPM($SoloConSaldos = false, $credito = false, $forzarTodos = false, $fechaCorte = false, $fechaInicial = false, $EliminarTodo = true)
 {
     //FIXME: probar con saldo anterior
     $fechaCorte = $fechaCorte == false ? fechasys() : $fechaCorte;
     $msg = "";
     $wCredito1 = $credito != false ? "  `creditos_mvtos_asdpm`.`documento` = {$credito}" : " `documento` > 0 ";
     $wCredito2 = $credito != false ? "  numero_de_credito = {$credito} " : " numero_de_credito > 0";
     $ByRTM = $credito != false ? " " : " SQL_CACHE ";
     $wFecha1 = " AND (fecha >='{$fechaInicial}' AND fecha <='{$fechaCorte}' ) ";
     $wFecha2 = " AND (`fecha_actual` >= '{$fechaInicial}' AND `fecha_actual`<='{$fechaCorte}' ) ";
     $ql = new MQL();
     $arrEstatusD = array(OPERACION_CLAVE_MINISTRACION, 111, 114, 115);
     $arrEstatus = array(OPERACION_CLAVE_MINISTRACION => CREDITO_ESTADO_VIGENTE, 111 => CREDITO_ESTADO_VENCIDO, 114 => CREDITO_ESTADO_VIGENTE, 115 => CREDITO_ESTADO_MOROSO);
     //Eliminar el SDPM
     if ($EliminarTodo == true) {
         $DAction = $ql->setRawQuery("DELETE FROM creditos_sdpm_historico WHERE {$wCredito2} {$wFecha2} ");
         if (MODO_DEBUG == true) {
             $msg .= "WARN\tEliminando SDPM\r\n";
         }
     }
     if ($credito != false) {
         $ql->setRawQuery("DELETE FROM operaciones_mvtos WHERE docto_afectado={$credito} AND tipo_operacion = 420");
         if (MODO_DEBUG == true) {
             $msg .= "WARN\tEliminando Operaciones 420 del credito {$credito}\r\n";
         }
     }
     $msg .= "Socio\tCredito\tFecha\tMonto\tSaldo\tDias\tOperacion\tEstatus\tInteres\tMoratorios\r\n";
     //Generar saldos de credito por mes
     $sql = "SELECT {$ByRTM}\n\t\t`creditos_mvtos_asdpm`.`socio`,\n\t\t`creditos_mvtos_asdpm`.`documento`,\n\t\t`creditos_mvtos_asdpm`.`recibo`,\n\t\t`creditos_mvtos_asdpm`.`fecha`,\n\t\t`creditos_mvtos_asdpm`.`operacion`,\n\t\t`creditos_mvtos_asdpm`.`monto`,\n\t\t`creditos_mvtos_asdpm`.`afectacion`\n\t\tFROM `creditos_mvtos_asdpm`\tWHERE {$wCredito1} {$wFecha1} ";
     //setLog($sql);
     $rsM = $ql->getDataRecord($sql);
     $saldo = 0;
     $creditoA = 0;
     $xT = new cTipos();
     $xF = new cFecha();
     $FECHA_DE_ULTIMO_PAGO = "1998-01-01";
     $CREDITO_SALDO_ANTERIOR = 0;
     $MvtoAnterior = OPERACION_CLAVE_MINISTRACION;
     $ESTADO_ACTUAL = CREDITO_ESTADO_VIGENTE;
     $DIVISOR_DE_INTERESES = EACP_DIAS_INTERES;
     $DCred = array();
     $IsCredNew = true;
     $xCred = null;
     foreach ($rsM as $rw) {
         $socio = $xT->cInt($rw["socio"]);
         $credito = $xT->cInt($rw["documento"]);
         $fecha = $rw["fecha"];
         $nota = "";
         //
         $IsCredNew = true;
         if ($creditoA != $credito) {
             $saldo = 0;
             $FECHA_DE_ULTIMO_PAGO = $fecha;
             $ESTADO_ACTUAL = CREDITO_ESTADO_VIGENTE;
             $xCred = new cCredito($credito, $socio);
             $xCred->init();
             $DCred = $xCred->getDatosDeCredito();
             $CREDITO_SALDO_ANTERIOR = 0;
             //si es Ministracion
             if ($MvtoAnterior == OPERACION_CLAVE_MINISTRACION) {
                 $FECHA_DE_ULTIMO_PAGO = $xCred->getFechaDeMinistracion();
             }
             $msg .= "------------------------\tNUEVO_CREDITO : {$credito}------------------------------\r\n";
             if ($EliminarTodo == false) {
                 my_query("DELETE FROM creditos_sdpm_historico WHERE numero_de_credito = {$credito} {$wFecha2}");
             }
         } else {
             $IsCredNew = false;
         }
         $OProd = $xCred->getOProductoDeCredito();
         $recibo = $rw["recibo"];
         $operacion = $rw["operacion"];
         $afectacion = $rw["afectacion"];
         $monto = $xT->cFloat($rw["monto"], 2);
         $periocidad = $xCred->getPeriocidadDePago();
         $FechaVencimiento = $xCred->getFechaDeVencimiento();
         //(!isset( $DCred["fecha_vencimiento_dinamico"])) ? $xCred->getFechaDeVencimiento() : $DCred["fecha_vencimiento_dinamico"];
         $DiaInteresMax = $xF->setSumarDias(INTERES_DIAS_MAXIMO_A_DEVENGAR, $FechaVencimiento);
         $dias_transcurridos = $xF->setRestarFechas($fecha, $FECHA_DE_ULTIMO_PAGO);
         $saldo_calculado = $dias_transcurridos * $saldo;
         //No poner la afectacion
         $saldo += $xT->cFloat($monto * $afectacion, 2);
         // si es normal, calcular normal, si es mora: Calcular mora y normal, si es vencido: calcular normal y mora
         $interes = 0;
         $moratorio = 0;
         $TASA_NORMAL = $xCred->getTasaDeInteres();
         $TASA_MORA = $xCred->getTasaDeMora();
         $TIPO_DE_PAGO = $xCred->getTipoDePago();
         $PAGOS_SIN_CAPITAL = $xCred->getPagosSinCapital();
         $MONTO_ORIGINAL_DE_CREDITO = $xCred->getMontoAutorizado();
         $saldoBase = $xT->cFloat($saldo, 2);
         if ($operacion == OPERACION_CLAVE_PAGO_CAPITAL and $saldo == 0) {
             $saldoBase = $CREDITO_SALDO_ANTERIOR;
         }
         if ($MvtoAnterior == OPERACION_CLAVE_MINISTRACION) {
             $saldoBase = $CREDITO_SALDO_ANTERIOR;
             $saldo_calculado = $dias_transcurridos * $CREDITO_SALDO_ANTERIOR;
         }
         $SALDO_ACTUAL = $xCred->getSaldoActual();
         $BASE_NORMAL = $saldo_calculado;
         $BASE_MORA = $saldo_calculado;
         eval($OProd->getPreModInteres());
         //considerar si es un maximo de x dias devengar en vencidos
         switch ($ESTADO_ACTUAL) {
             case CREDITO_ESTADO_VIGENTE:
                 $interes = $BASE_NORMAL * $TASA_NORMAL / $DIVISOR_DE_INTERESES;
                 break;
             case CREDITO_ESTADO_VENCIDO:
                 //validar si tiene un maximo de dias transcurridos de devengado
                 if ($xF->getInt($fecha) <= $xF->getInt($DiaInteresMax)) {
                     $interes = $BASE_NORMAL * $TASA_NORMAL / $DIVISOR_DE_INTERESES;
                     $moratorio = $BASE_MORA * $TASA_MORA / $DIVISOR_DE_INTERESES;
                 } else {
                     $interes = 0;
                     $moratorio = 0;
                     $nota = "Despues del {$DiaInteresMax} no se acumula Interes, Vencimiento : {$FechaVencimiento}";
                 }
                 break;
             case CREDITO_ESTADO_MOROSO:
                 $interes = $BASE_NORMAL * $TASA_NORMAL / $DIVISOR_DE_INTERESES;
                 $moratorio = $BASE_MORA * $TASA_MORA / $DIVISOR_DE_INTERESES;
                 break;
         }
         //END_SWITCH
         $interes = $xT->cFloat($interes, 2);
         if ($periocidad == CREDITO_TIPO_PERIOCIDAD_FINAL_DE_PLAZO) {
             $moratorio = $xT->cFloat($moratorio, 2);
             //0; //2012-04-10
         } else {
             //$moratorio			= 0;
         }
         eval($OProd->getPosModInteres());
         $msg .= "{$socio}\t{$credito}\t{$fecha}\t{$monto}\t{$saldo}\t{$dias_transcurridos}\t{$operacion}\t{$ESTADO_ACTUAL}\t{$interes}\t{$moratorio}\t{$nota}\r\n";
         if ($xF->getInt($fecha) <= $xF->getInt(SYS_FECHA_DE_MIGRACION)) {
             $interes = 0;
             $moratorio = 0;
             if (MODO_DEBUG == true) {
                 $msg .= "WARN\tOMITIR Interes {$interes} y MORA por {$moratorio} por estar antes de la migracion {$fecha}\r\n";
             }
         }
         if ($xF->getInt($fecha) <= $xF->getInt($fechaCorte)) {
             $msgSDPM = $xCred->addSDPM($interes, $moratorio, $FECHA_DE_ULTIMO_PAGO, $saldo, $ESTADO_ACTUAL, $fecha, $operacion, $saldo_calculado);
             //if(MODO_DEBUG == true){ $msg	.= $msgSDPM;	}
         }
         if ($saldo <= TOLERANCIA_SALDOS) {
             $msg .= "------------------------------------------------------\r\n";
         }
         $creditoA = $credito;
         $FECHA_DE_ULTIMO_PAGO = $fecha;
         $CREDITO_SALDO_ANTERIOR = $saldo;
         $MvtoAnterior = $operacion;
         /*
          * si existe la operacion de cambio de estatus, validar en el array, y actualizar el valor
          * Este estatus se aplicara en el siguiente
          */
         if (in_array($operacion, $arrEstatusD)) {
             $ESTADO_ACTUAL = $arrEstatus[$operacion];
         }
     }
     return $msg;
 }
 */
$rsm = $ql->getDataRecord($SQLBody);
foreach ($rsm as $rwm) {
    $pendiente = 0;
    $title = $rwm["descripcion_operacion"];
    $monto = $xT->cFloat($rwm["total_operacion"], 2);
    $MTipo = $rwm["tipo_operacion"];
    $cls = "";
    $xLog->add("WARN\tIX\tEl Movimiento es {$MTipo}\r\n", $xLog->DEVELOPER);
    //Omite los Intereses Pactados y tod lo concerniente al credito segun la base
    if (in_array($MTipo, $arrINTS)) {
        $xLog->add("WARN\t{$MTipo}\tINTERES\tEl Monto por {$monto} Del Movimiento {$MTipo} se lleva a CERO\r\n", $xLog->DEVELOPER);
        $monto = 0;
    }
    if ($MTipo == OPERACION_CLAVE_PLAN_INTERES) {
        if ($xCred->getPagosSinCapital() == true and $xF->getInt($fecha_operacion) < $xF->getInt($fecha_de_pago)) {
            $interes_calculado = $interes_normal_devengado - $interes_normal_pagado + $interes_normal_calculado;
            if ($monto > $interes_calculado) {
                $xLog->add("WARN\t{$MTipo}\tINT.DEV\tInteres de la Letra Ajustado de {$monto} a {$interes_calculado} por ser menos\r\n", $xLog->COMMON);
                $monto = $interes_calculado > 0 ? $interes_calculado : 0;
                $cls = " class='warn' ";
            }
        } else {
            if ($pago_total == false) {
                $xLog->add("WARN\tSin cambios en Intereses {$MTipo}\r\n", $xLog->DEVELOPER);
            } else {
                $interes_normal = setNoMenorQueCero($interes_normal - $monto);
            }
        }
    }
    if (in_array($MTipo, $aActosDeIva)) {
 function check5Cierres($fecha_final, $alCerrar = false)
 {
     $xF = new cFecha();
     $fecha_inicio_sistema = FECHA_INICIO_OPERACIONES_SISTEMA;
     $dias_a_revisar = REVISAR_DIAS_DE_CIERRE;
     $fecha_inicial = $xF->setRestarDias($dias_a_revisar, $fecha_final);
     $res = array();
     $ok = false;
     $xSuc = new cSucursal();
     for ($i = 0; $i <= $dias_a_revisar; $i++) {
         $fecha = $xF->setSumarDias($i, $fecha_inicial);
         if ($xF->getInt($fecha_inicio_sistema) >= $xF->getInt($fecha)) {
             $this->mMessages .= "WARN\tFecha {$fecha} OMITIDO por ser menor al inicio de operaciones\r\n";
             $res[$fecha] = true;
             $ok = true;
         } elseif ($xF->getInt($fecha) == $xF->getInt(fechasys())) {
             $this->mMessages .= "WARN\tFecha {$fecha} OMITIDO por ser Fecha Actual\r\n";
             $res[$fecha] = true;
             $ok = true;
             if ($alCerrar == true) {
                 if ((int) date("H") < (int) $xSuc->getHorarioDeCierre()) {
                     //considerar si es dia festivo
                     $this->mMessages .= "ERROR\tNO ES EL HORARIO MINIMO DE CIERRE PARA LA FECHA {$fecha} SON LAS " . date("H") . " HRS. DE " . $xSuc->getHorarioDeCierre() . ", MINIMO DE CIERRE\r";
                     $res[$fecha] = false;
                     $ok = false;
                 }
             }
         } else {
             //$this->mMessages	.= "WARN\tFecha $fecha OMITIDO por ser menor al inicio de operaciones\r\n";
             if ($this->checkCierre($fecha) == false) {
                 $res[$fecha] = false;
                 $ok = false;
                 $this->mMessages .= "ERROR\tFecha {$fecha} No existe en el sistema\r\n";
                 if ($xF->getInt($fecha) == $xF->getInt($fecha_final)) {
                     $this->mMessages .= "ERROR\tPROCESAR LA FECHA {$fecha_final}|{$fecha} LAS FECHAS SON LAS MISMAS A " . fechasys() . "\r\n";
                     $res[$fecha] = true;
                     $ok = true;
                 }
             } else {
                 $res[$fecha] = true;
                 $ok = true;
                 $this->mMessages .= "OK\tFecha {$fecha} existente\r\n";
             }
         }
         $xCaja = new cCaja();
         if ($alCerrar == true) {
             if ($xCaja->getCajasAbiertas($fecha) > 0) {
                 $ok = false;
                 $res[$fecha] = false;
                 $this->mMessages .= "OK\tFecha {$fecha} tiene cortes pendientes\r\n";
             }
         }
     }
     unset($res[fechasys()]);
     foreach ($res as $dateme => $rs) {
         if ($dateme != SYS_ESTADO) {
             if ($rs == false) {
                 $this->mMessages .= "ERROR\tFecha {$dateme} tiene cortes pendientes.-2\r\n";
                 $ok = false;
             }
         }
     }
     if (MODO_DEBUG == true) {
         setLog($this->mMessages);
     }
     $res[SYS_ESTADO] = $ok;
     return $res;
 }
$xSoc = new cSocio($persona);
$xSoc->init();
$xT = new cTabla($sql, 2);
$xT->setTipoSalida($out);
$xT->setFootSum(array(4 => "monto", 9 => "unidades", 10 => "equivalencia"));
$body = $xRPT->getEncabezado($xHP->getTitle(), $FechaInicial, $FechaFinal);
$xRPT->setBodyMail($body);
$xRPT->addContent($body);
$xRPT->addContent($xSoc->getFicha(true));
//$xT->setEventKey("jsGoPanel");
//$xT->setKeyField("creditos_solicitud");
$xRPT->addContent($xT->Show($xHP->getTitle()));
$xT = new cTabla($xL->getListadoDePerfil($persona));
$xRPT->addContent($xT->Show());
if (MODO_DEBUG == true) {
    $periodo_inicial = date("Ym", $xF->getInt($FechaInicial));
    $periodo_final = date("Ym", $xF->getInt($FechaFinal));
    $xT2 = new cTabla($xL->getAMLAcumuladoDeEgresos($periodo_inicial, $periodo_final, $persona));
    $xRPT->addContent($xT2->Show());
}
$xRPT->addContent("<h3>" . $xHP->lang("Mensaje") . "</h3>");
//============ Agregar HTML
//$xRPT->addContent( $xHP->init($jsEvent) );
//$xRPT->addContent( $xHP->end() );
$xAml = new cAMLPersonas($persona);
$xAml->init();
$validar = false;
//(MODO_DEBUG == true) ? true : false;
$xAml->setVerificarPerfilTransaccional(false, $validar);
$xAml->setVerificarOperacionesSemestrales();
$xRPT->addContent($xAml->getMessages(OUT_HTML));
 function calcular($fecha_inicial = false, $PrimerPago = false, $SegundoPago = false, $TercerPago = false)
 {
     $xCred = new cCredito($this->mClaveDeCredito);
     $xCred->init();
     $xF = new cFecha();
     $msg = "";
     $FORMA_DE_PAGO = $xCred->getFormaDePago();
     $PAGOS_AUTORIZADOS = $xCred->getPagosAutorizados();
     $PERIOCIDAD_DE_PAGO = $xCred->getPeriocidadDePago();
     $MONTO_AUTORIZADO = $xCred->getMontoAutorizado();
     $SALDO_ACTUAL = $xCred->getSaldoActual();
     $INTERES_PAGADO = $xCred->getInteresNormalPagado();
     $MORA_PAGADO = $xCred->getInteresMoratorioPagado();
     $xCred->initPagosEfectuados();
     $CAPITAL_PAGADO = setNoMenorQueCero($MONTO_AUTORIZADO - $SALDO_ACTUAL);
     $SALDO_DE_PLAN = $xCred->getMontoAutorizado();
     $TASA_NORMAL = $xCred->getTasaDeInteres();
     $TASA_MORA = $xCred->getTasaDeMora();
     $TASA_IVA = $xCred->getTasaIVA();
     $DIVISOR_DE_INTS = EACP_DIAS_INTERES;
     $FECHA_DE_PAGO = $xCred->getFechaPrimeraParc();
     $FECHA_INICIAL = $xCred->getFechaDeMinistracion();
     $opciondia_1 = $PrimerPago;
     $opciondia_2 = $SegundoPago;
     $opciondia_3 = $TercerPago;
     //sanitiza la fecha de pago
     if ($FECHA_DE_PAGO == false) {
         $FECHA_DE_PAGO = $xF->setSumarDias($PERIOCIDAD_DE_PAGO, $FECHA_INICIAL);
     }
     if (($PERIOCIDAD_DE_PAGO > CREDITO_TIPO_PERIOCIDAD_CATORCENAL or $PERIOCIDAD_DE_PAGO == CREDITO_TIPO_PERIOCIDAD_CATORCENAL) and ($opciondia_1 == false or $opciondia_2 == false or $opciondia_3 == false)) {
         if ($PERIOCIDAD_DE_PAGO == CREDITO_TIPO_PERIOCIDAD_QUINCENAL) {
             $opciondia_1 = $opciondia_1 == false ? PQ_DIA_PRIMERA_QUINCENA : $opciondia_1;
             $opciondia_2 = $opciondia_2 == false ? PQ_DIA_SEGUNDA_QUINCENA : $opciondia_2;
         } elseif ($PERIOCIDAD_DE_PAGO == CREDITO_TIPO_PERIOCIDAD_DECENAL) {
             $opciondia_1 = $opciondia_1 == false ? 10 : $opciondia_1;
             $opciondia_2 = $opciondia_2 == false ? 20 : $opciondia_2;
             $opciondia_3 = $opciondia_3 == false ? 30 : $opciondia_3;
         } else {
             $opciondia_1 = $opciondia_1 == false ? PM_DIA_DE_PAGO : $opciondia_1;
         }
     }
     //pagos decenales entre el mes
     $arrPagos = array();
     //obtener los dias de pago en el mes por tipo de pago
     $dia_de_pago = $xCred->getFechaDeMinistracion();
     for ($i = 1; $i <= $PAGOS_AUTORIZADOS; $i++) {
         $letra = $i;
         switch ($PERIOCIDAD_DE_PAGO) {
             case CREDITO_TIPO_PERIOCIDAD_DIARIO:
                 $dia_de_pago = $xF->getDiaHabil($xF->setSumarDias(1, $dia_de_pago));
                 $arrPagos[$letra][SYS_FECHA] = $dia_de_pago;
                 $msg .= "OK\t{$letra}\tDIARIO\tFecha de pago a {$dia_de_pago}\r\n";
                 break;
             case CREDITO_TIPO_PERIOCIDAD_SEMANAL:
                 break;
             case CREDITO_TIPO_PERIOCIDAD_DECENAL:
                 break;
             case CREDITO_TIPO_PERIOCIDAD_CATORCENAL:
                 //dias naturales, cada dos semanas?
                 break;
             case CREDITO_TIPO_PERIOCIDAD_QUINCENAL:
                 $dia_de_pago = $xF->setSumarDias(CREDITO_TIPO_PERIOCIDAD_QUINCENAL, $dia_de_pago);
                 $dia_de_pago = $xF->getDiaAbonoQuincenal($opciondia_1, $opciondia_2, $dia_de_pago);
                 $arrPagos[$letra][SYS_FECHA] = $dia_de_pago;
                 $msg .= "OK\t{$letra}\tQUINCENAL\tFecha de pago a {$dia_de_pago}, opcion {$opciondia_1}, {$opciondia_2}\r\n";
                 break;
             case CREDITO_TIPO_PERIOCIDAD_MENSUAL:
                 $dia_de_pago = date("Y-m-", $xF->getInt($dia_de_pago)) . $opciondia_1;
                 $dia_de_pago = $xF->setSumarMeses(1, $dia_de_pago);
                 $dia_de_pago = $xF->getDiaHabil($dia_de_pago);
                 $arrPagos[$letra][SYS_FECHA] = $dia_de_pago;
                 $msg .= "OK\t{$letra}\tMENSUAL\tFecha de pago a {$dia_de_pago}, opcion {$opciondia_1}\r\n";
                 break;
             case CREDITO_TIPO_PERIOCIDAD_BIMESTRAL:
                 break;
             case CREDITO_TIPO_PERIOCIDAD_TRIMESTRAL:
                 break;
         }
     }
     //$FORMULA_INT			= new cFormula("interes_normal");
     //dias de pago
     //si es empresa, tomar la fecha de la empresa semanal, quincenal, mensual, decenal
     //Iniciar los Pagos Actuales
     //$this->initParcsPendientes();
     $DatosDePagados = $xCred->getListadoDePagos();
     /* interes capital impuestos */
     switch ($FORMA_DE_PAGO) {
         case CREDITO_TIPO_PAGO_PERIODICO:
             //parcialidad interes + capital
             break;
         case CREDITO_TIPO_PAGO_FLAT_PARCIAL:
             for ($i = 1; $i <= $PAGOS_AUTORIZADOS; $i++) {
                 $letra = $i;
                 $letraAnterior = setNoMenorQueCero($letra - 1);
                 $PagoAnterior = isset($DatosDePagados[$letra]) ? $DatosDePagados[$letra] : array();
                 $capital_pagado = isset($DPago[SYS_CAPITAL]) ? $DPago[SYS_CAPITAL] : 0;
                 $SALDO_DE_PLAN = $SALDO_DE_PLAN - $capital_pagado;
                 $interes_normal = $MONTO_AUTORIZADO * $PERIOCIDAD_DE_PAGO * $TASA_NORMAL / $DIVISOR_DE_INTS;
                 $capital = $MONTO_AUTORIZADO / $PAGOS_AUTORIZADOS;
                 $capital = setNoMenorQueCero($capital - $capital_pagado);
                 $interes_pagado = isset($DPago[SYS_INTERES_NORMAL]) ? $DPago[SYS_INTERES_NORMAL] : 0;
                 $interes_normal = setNoMenorQueCero($interes_normal - $interes_pagado);
                 $arrPagos[$letra][SYS_INTERES_NORMAL] = $interes_normal;
                 if ($letra == $PAGOS_AUTORIZADOS) {
                     if ($SALDO_DE_PLAN > 0) {
                         $arrPagos[$letra][SYS_CAPITAL] = $SALDO_DE_PLAN;
                         $msg .= "WARN\t{$letra}\tCapital a ultimo pago {$SALDO_DE_PLAN} \r\n";
                     }
                 }
                 //determinar proxima fecha de pago
                 $msg .= "OK\t{$letra}\tInteres Normal en {$interes_normal}, Pagado {$interes_pagado} \r\n";
             }
             break;
         case CREDITO_TIPO_PAGO_INTERES_PERIODICO:
             for ($i = 1; $i <= $PAGOS_AUTORIZADOS; $i++) {
                 $letra = $i;
                 $letraAnterior = setNoMenorQueCero($letra - 1);
                 $DAnterior = isset($DatosDePagados[$letraAnterior]) ? $DatosDePagados[$letraAnterior] : array();
                 $capital_pagado = isset($DAnterior[SYS_CAPITAL]) ? $DAnterior[SYS_CAPITAL] : 0;
                 $SALDO_DE_PLAN = $SALDO_DE_PLAN - $capital_pagado;
                 $DPago = isset($DatosDePagados[$letra]) ? $DatosDePagados[$letra] : array();
                 $interes_pagado = isset($DPago[SYS_INTERES_NORMAL]) ? $DPago[SYS_INTERES_NORMAL] : 0;
                 //datos del pago anterior
                 $DLetraAnterior = isset($arrPagos[$letraAnterior]) ? $arrPagos[$letraAnterior] : array();
                 $DLetra = isset($arrPagos[$letra]) ? $arrPagos[$letra] : array();
                 $FechaAnterior = isset($DLetraAnterior[SYS_FECHA]) ? $DLetraAnterior[SYS_FECHA] : $xCred->getFechaDeMinistracion();
                 $FechaActual = isset($DLetra[SYS_FECHA]) ? $DLetra[SYS_FECHA] : false;
                 $DIAS_TRANSCURRIDOS = $xF->setRestarFechas($FechaActual, $FechaAnterior);
                 //INTERES NORMAL
                 $interes_normal = $SALDO_DE_PLAN * $DIAS_TRANSCURRIDOS * $TASA_NORMAL / $DIVISOR_DE_INTS;
                 $interes_normal = setNoMenorQueCero($interes_normal - $interes_pagado);
                 $arrPagos[$letra][SYS_INTERES_NORMAL] = $interes_normal;
                 if ($capital_pagado > 0) {
                     $msg .= "WARN\t{$letra}\tCapital en pago {$letraAnterior} de {$capital_pagado} \r\n";
                 }
                 if ($letra == $PAGOS_AUTORIZADOS) {
                     if ($SALDO_DE_PLAN > 0) {
                         $arrPagos[$letra][SYS_CAPITAL] = $SALDO_DE_PLAN;
                         $msg .= "WARN\t{$letra}\tCapital a ultimo pago {$SALDO_DE_PLAN} \r\n";
                     }
                 }
                 $msg .= "OK\t{$letra}\tInteres Normal en {$interes_normal}, Pagado {$interes_pagado}, Dias {$DIAS_TRANSCURRIDOS},Fecha : Actual {$FechaActual} Anterior {$FechaAnterior}\r\n";
             }
             break;
         case CREDITO_TIPO_PAGO_INTERES_COMERCIAL:
             for ($i = 1; $i <= $PAGOS_AUTORIZADOS; $i++) {
                 $letra = $i;
                 $letraAnterior = setNoMenorQueCero($letra - 1);
                 $DAnterior = isset($DatosDePagados[$letraAnterior]) ? $DatosDePagados[$letraAnterior] : array();
                 $capital_pagado = isset($DAnterior[SYS_CAPITAL]) ? $DAnterior[SYS_CAPITAL] : 0;
                 $SALDO_DE_PLAN = $SALDO_DE_PLAN - $capital_pagado;
                 $DPago = isset($DatosDePagados[$letra]) ? $DatosDePagados[$letra] : array();
                 $interes_pagado = isset($DPago[SYS_INTERES_NORMAL]) ? $DPago[SYS_INTERES_NORMAL] : 0;
                 //INTERES NORMAL
                 $interes_normal = $SALDO_DE_PLAN * $PERIOCIDAD_DE_PAGO * $TASA_NORMAL / $DIVISOR_DE_INTS;
                 $interes_normal = setNoMenorQueCero($interes_normal - $interes_pagado);
                 $arrPagos[$letra][SYS_INTERES_NORMAL] = $interes_normal;
                 if ($capital_pagado > 0) {
                     $msg .= "WARN\t{$letra}\tCapital en pago {$letraAnterior} de {$capital_pagado} \r\n";
                 }
                 if ($letra == $PAGOS_AUTORIZADOS) {
                     if ($SALDO_DE_PLAN > 0) {
                         $arrPagos[$letra][SYS_CAPITAL] = $SALDO_DE_PLAN;
                         $msg .= "WARN\t{$letra}\tCapital a ultimo pago {$SALDO_DE_PLAN} \r\n";
                     }
                 }
                 $msg .= "OK\t{$letra}\tInteres Normal en {$interes_normal}, Pagado {$interes_pagado} \r\n";
             }
             break;
     }
     $NumeroPlan = $this->mNumeroDePlan;
     //$this->setEliminar();
     //eliminar plan de pagos
     foreach ($arrPagos as $periodo) {
     }
     $this->mMessages .= $msg;
     return $msg;
 }
            $xTabla->setData($_REQUEST);
            $xTabla->query()->update()->save($clave);
            $xFRM->addAvisoRegistroOK();
        }
    }
}
$xHP->init();
$msg = "";
$xAlert = new cAMLAlertas($codigo);
$xAlert->init();
$xFRM->addAviso($xAlert->getDescripcion());
$xFRM->OTextArea("razones_de_reporte", $xTabla->razones_de_reporte()->v(), "TR.AML_TEXTO_A");
$xFRM->OTextArea("acciones_tomadas", $xTabla->acciones_tomadas()->v(), "TR.AML_TEXTO_B");
$xFRM->OTextArea("notas_de_checking", $xTabla->notas_de_checking()->v(), "TR.Observaciones de la operacion");
$xFRM->OHidden("clave_de_riesgo", $xTabla->clave_de_riesgo()->v(), "");
$xFRM->OHidden("fecha_de_checking", $xF->getInt(), "");
echo $xFRM->get();
?>
<script>
var xG		= new Gen();
//function jsDescartaRiesgo(){ xG.confirmar({ msg : "Desea Descartar la Alerta como Riesgo?", callback : "jsaDescartaRiesgo()", evaluador : jsRazonNoVacia(), alert : "La observacion no puede quedar vacia"}); }
//function jsConfirmaRiesgo(){ xG.confirmar({ msg : "Desea Confirmar la Alerta como Riesgo?", callback : "jsaConfirmaRiesgo()", evaluador : jsRazonNoVacia(), alert : "La observacion no puede quedar vacia" }); }
function jsRazonNoVacia(){
	var valid	= new ValidGen();
	return valid.NoVacio( $("#notas_de_checking").val() );
}

//function jsSalir(){ xG.close(); }
</script>
<?php 
//$jxc ->drawJavaScript(false, true);
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, El Mes Anterior==" . $xF->getFechaMesAnterior() . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, dos meses atras==" . $xF->getFechaMesAnterior(false, 2) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}  - 30 Dias==" . $xF->setRestarDias(30) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}  + 30 Dias==" . $xF->setSumarDias(30) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}  + 2 meses==" . $xF->setSumarMeses(2) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}  - 2 meses==" . $xF->setRestarMeses(2) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Nombre del Dia==" . $xF->getDayName() . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Dia Inicial del mes==" . $xF->getDiaInicial() . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Obtener Dia Habil==" . $xF->getDiaHabil() . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Dias desde el 31Dic2013==" . $xF->setRestarFechas($xF->get(), "2013-12-31") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Buscar Sabado(D6) para el dia de hoy==" . $xF->getDiaAbonoSemanal(6) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Buscar NOMBRE Sabado(D6) para el dia de hoy==" . $xF->getDayName($xF->getDiaAbonoSemanal(6)) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-02") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-11") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-18") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-20") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-24") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-29") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Fecha de Pago Decenal 1==" . $xF->getDiaAbonoDecenal(10, 20, 30, "2014-03-31") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Obtener dias Loborales en el mes==" . $xF->getDiasHabilesEnRango("2014-03-31", "2014-03-01") . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, Obtener entero del mes==" . $xF->getInt(fechasys()) . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, DIAS CORRIENTES DE MES" . $xF->getDiasCorrientesDeMes() . "</p>");
$xHFrm->addHElem("<p class='aviso'>La {$miFecha}, sumar  7 dias time stamp 84600==" . $xF->getFechaByInt($xF->getInt(fechasys()) + (7 + 1) * 84600) . "</p>");
$xHFrm->addHElem("<p class='aviso'>" . $xF->getMessages(OUT_HTML) . "</p>");
//$xHFrm->addHTML("<p>Esto es un parrafo de prueba</p>");
echo $xHFrm->get();
echo $xP->setBodyEnd();
echo $xP->end();
//=====================================================================================================
?>
 
 function getFechaDeAviso($periocidad = false, $fecha = false, $periodoInit = false, $periodoEnd = false)
 {
     $xF = new cFecha();
     $dias = explode(",", strtoupper($this->mDiasDeAviso));
     $diasSem = $xF->getDiasDeSemanaInArray();
     $periocidad = $periocidad == false ? $this->getPeriocidadPref() : $periocidad;
     $fecha = $fecha == false ? fechasys() : $fecha;
     $result = null;
     $items = 1;
     foreach ($diasSem as $numero => $nombre) {
         /*if(isset($dias[$nombre]) ){
         			unset($dias[$nombre]);
         			$dias[$numero]
         		}*/
     }
     foreach ($dias as $id => $dia) {
     }
     foreach ($dias as $id => $dia) {
         //limpiar
         if ($periocidad != CREDITO_TIPO_PERIOCIDAD_SEMANAL) {
             foreach ($diasSem as $numero => $nombre) {
                 if ($dia == $nombre) {
                     unset($dias[$id]);
                 }
             }
             if (setNoMenorQueCero($dia) > $xF->getDiasDelMes() or setNoMenorQueCero($dia) == 0) {
                 unset($dias[$id]);
             }
             switch ($periocidad) {
                 case CREDITO_TIPO_PERIOCIDAD_DECENAL:
                     if ($id > 3) {
                         unset($dias[$id]);
                     }
                     break;
                 case CREDITO_TIPO_PERIOCIDAD_CATORCENAL:
                     if ($id > 2) {
                         unset($dias[$id]);
                     }
                     break;
                 case CREDITO_TIPO_PERIOCIDAD_QUINCENAL:
                     if ($id > 2) {
                         unset($dias[$id]);
                     }
                     break;
                 case CREDITO_TIPO_PERIOCIDAD_MENSUAL:
                     if ($id > 1) {
                         unset($dias[$id]);
                     }
                     break;
             }
         } else {
             //convertir dias
             foreach ($diasSem as $numero => $nombre) {
                 if ($dia == $nombre) {
                     $dias[$id] = $numero;
                 }
             }
             if (setNoMenorQueCero($dia) > 7 or setNoMenorQueCero($dia) == 0) {
                 unset($dias[$id]);
             }
             if ($id > 1) {
                 unset($dias[$id]);
             }
         }
     }
     //$items		= count($dias);
     //encontrar el periodo cero
     switch ($periocidad) {
         case CREDITO_TIPO_PERIOCIDAD_DECENAL:
             break;
         case CREDITO_TIPO_PERIOCIDAD_CATORCENAL:
             break;
         case CREDITO_TIPO_PERIOCIDAD_QUINCENAL:
             break;
         case CREDITO_TIPO_PERIOCIDAD_MENSUAL:
             $xF1 = new cFecha(0, $fecha);
             $result = $xF1->anno() . "-" . $xF1->mes() . "-" . $dias[0];
             break;
         case CREDITO_TIPO_PERIOCIDAD_SEMANAL:
             //$fechaInicial	= $xF->setFechaPorSemana();
             $xF1 = new cFecha(0, $fecha);
             $buscar = 1;
             foreach ($dias as $id => $cnt) {
                 $buscar = $cnt;
             }
             $semana = date("W", $xF1->getInt());
             $result = $xF1->setFechaPorSemana($semana, $buscar);
             /*
              $first_day_of_week = date('m-d-Y', strtotime('Last Monday', time()));
             $last_day_of_week = date('m-d-Y', strtotime('Next Sunday', time()));
             */
             break;
     }
     return $result;
 }