function jsaAmortizarLetras($persona, $credito, $letra, $amortizable)
{
    $NLetra = $letra + 1;
    $xCred = new cCredito($credito);
    $xCred->init();
    if ($xCred->isAFinalDePlazo() == false) {
        $xPlan = new cPlanDePagos();
        $xPlan->initByCredito($credito);
        $msg = "";
        $DPlan = $xPlan->getLetrasInArray(OPERACION_CLAVE_PLAN_CAPITAL, $NLetra);
        $amortizable = setNoMenorQueCero($amortizable);
        for ($ixletra = $NLetra; $ixletra <= $xCred->getPagosAutorizados(); $ixletra++) {
            if (isset($DPlan[$ixletra])) {
                $monto = setNoMenorQueCero($DPlan[$ixletra]);
                if ($amortizable > 0) {
                    if ($amortizable >= $monto) {
                        //cancelar
                        $xPlan->setNeutralizarParcialidad($ixletra);
                    } else {
                        $xPlan->setActualizarParcialidad($ixletra, $monto - $amortizable, false, false);
                    }
                }
                $msg .= "WARN\t  {$ixletra} --- {$amortizable} {$monto};\r\n";
                $amortizable -= $monto;
            }
        }
        $msg .= $xPlan->getMessages();
        if (MODO_DEBUG == true) {
            setLog($msg);
        }
    }
}
function jsaCerrarCaja($oficial, $pwd, $caja)
{
    $xBtn = new cHButton();
    $xCaja = new cCaja($caja);
    $cUsr = new cSystemUser($oficial, false);
    $sucess = $cUsr->getCompareData("contrasenna", $pwd);
    $msg = "";
    if ($sucess == true) {
        $IOficial = $cUsr->getID();
        $xCaja->init($caja);
        if ($xCaja->setCloseBox($IOficial, 0) == true) {
            $url = $xCaja->getLinkDeCorte();
            $msg = $xBtn->getBasic("TR.Imprimir Corte", "var xG = new Gen(); xG.w({url:'{$url}'});", "imprimir", "printcorte", false);
        } else {
            //TODO: Checar el problema con esto
            if (MODO_DEBUG == true) {
                setLog($xCaja->getMessages(OUT_TXT));
            }
            $msg = "<p class='warn'>CLAVE DE ERROR " . $err . "</p>";
        }
    } else {
        $msg = "<p class='warn'>ERROR</p>";
    }
    return $msg;
}
Example #3
0
 function format_output($returnData = null, $return = array())
 {
     $return = array_merge($return, ['data' => $returnData]);
     $setlog = setLog($return, $_REQUEST ? $_REQUEST['_url'] : 'null');
     echo json_encode($return, JSON_UNESCAPED_UNICODE);
     exit;
     return;
 }
function jsaSetPago($Recibo, $cuentabancaria, $monto1, $diferencia, $fecha, $transaccion, $bancodeorigen)
{
    $xF = new cFecha();
    $fecha = $xF->getFechaISO($fecha);
    $xCaja = new cCaja();
    $op = $xCaja->setCobroTransferencia($Recibo, $cuentabancaria, $monto1, $diferencia, $fecha, "", false, false, $transaccion, $bancodeorigen);
    if (MODO_DEBUG == true) {
        setLog($xCaja->getMessages());
    }
}
Example #5
0
 public function _initialize()
 {
     $this->appid = C('WX_APPID');
     $this->appsecret = C('WX_APPSECRET');
     $this->access_token = S('wx_access_token');
     if (empty($this->access_token)) {
         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
         $res = $this->https_request($url);
         $result = json_decode($res, true);
         $this->access_token = $result["access_token"];
         S('wx_access_token', $this->access_token, 7200);
         $date = date("Ymd");
         $count = S("token_count_{$date}");
         if (!$count) {
             S("token_count_{$date}", '0', 60 * 60 * 24 * 2);
         } else {
             $count++;
             if ($count > 100) {
                 setLog("token_count_{$date}:{$count}");
             }
             S("token_count_{$date}", $count, 60 * 60 * 24 * 2);
         }
     }
 }
 function init($data = false)
 {
     $clave = $this->mClave;
     if (is_array($data)) {
     } else {
         $ql = new MQL();
         $data = $ql->getDataRecord("SELECT * FROM `general_estados` WHERE `clave_numerica` = {$clave} LIMIT 0,1");
     }
     setLog("SELECT * FROM `general_estados` WHERE `clave_numerica` = {$clave} LIMIT 0,1");
     $this->mObj = new cGeneral_estados();
     $this->mObj->setData($data);
     $this->mData = $data;
 }
Example #7
0
<?php

require_once __LIB__ . '/common.php';
//Implement your code
setLog('Hello World!');
 function analizarOperacion($persona, $monto_operado, $moneda, $tipo_de_pago, $fecha = false, $recibo = false, $perfil = false)
 {
     $moneda = strtoupper($moneda);
     $sql = "SELECT * FROM `aml_risk_catalog` \n\t\t\t\t\tWHERE (`aml_risk_catalog`.`tipo_de_riesgo` = 912)\n\t\t\t\t\tAND (`aml_risk_catalog`.`clave_de_control` != " . AML_CLAVE_RIESGO_OPS_INDIVIDUALES . ")\n\t\t\t\t\tORDER BY \n\t\t\t\t\t`aml_risk_catalog`.`unidad_de_medida`,\t`aml_risk_catalog`.`unidades_ponderadas` DESC ";
     $ql = new MQL();
     $risk = new cAml_risk_catalog();
     $raised = false;
     $xAML = new cAML();
     $rs = $ql->getDataRecord($sql);
     //Datos de Operaciones Mensuales
     $xAMLP = new cAMLPersonas($persona);
     $xAMLP->init();
     $OMens = $xAMLP->getOAcumuladoDeOperaciones($fecha, $fecha, $moneda, $tipo_de_pago);
     $monto_original = $OMens->getMonto() + $monto_operado;
     $this->mMessages .= "WARN\tOperaciones acumuladas por " . $OMens->getMonto() . "\r\n";
     if ($perfil == false) {
         $this->mMessages .= "ERROR\tNo existe el perfil tipo de pago {$tipo_de_pago} en Moneda {$moneda} \r\n";
         //agregar perfil a cero
     } else {
         $perfil = setNoMenorQueCero($perfil);
         $sql = "SELECT * FROM `personas_perfil_transaccional_tipos` WHERE `idpersonas_perfil_transaccional_tipos` = {$perfil} LIMIT 0,1";
         $d = $ql->getDataRow($sql);
         if (isset($d["tipo_de_exhibicion"])) {
             $tipo_de_pago = strtolower($d["tipo_de_exhibicion"]);
         }
         $this->mMessages .= "OK\tCarga del perfil {$perfil}  con tipo de pago {$tipo_de_pago}\r\n";
     }
     //verificar operaciones con reglas
     foreach ($rs as $rows) {
         $risk->setData($rows);
         $reporteMoneda = strtoupper($risk->unidad_de_medida()->v());
         if ($reporteMoneda == $moneda) {
             if ($raised == false) {
                 $reporteMoneda = strtoupper($risk->unidad_de_medida()->v());
                 $xMon = new cMonedas($reporteMoneda);
                 $valor_local = $xMon->getValor();
                 $clave = $risk->clave_de_control()->v();
                 if ($xAML->isTransaccionVigilada($tipo_de_pago) != false) {
                     $unidadesReportadas = $risk->unidades_ponderadas()->v();
                     $unidadesOperadas = 0;
                     if ($reporteMoneda == AML_CLAVE_MONEDA_LOCAL) {
                         $unidadesOperadas = $monto_original;
                     } else {
                         $this->mMessages .= "WARN\tUnidades reportadas {$unidadesOperadas} en Moneda {$moneda} con valor local de {$valor_local}\r\n";
                         $unidadesReportadas = $valor_local * $unidadesReportadas / VALOR_ACTUAL_DOLAR;
                         $unidadesOperadas = $monto_original * $valor_local / VALOR_ACTUAL_DOLAR;
                     }
                     if ($unidadesOperadas >= $unidadesReportadas) {
                         $this->mMsgAlert = "ERROR\tUnidades excedidas de {$unidadesReportadas} operados {$unidadesOperadas} en la Moneda {$reporteMoneda}\r\n";
                         $this->mMessages .= $this->mMsgAlert;
                         $raised = true;
                         $this->mTipoDeAlerta = $clave;
                         $this->mTipoDeReporte = $risk->forma_de_reportar()->v();
                     } else {
                         $this->mMessages .= "OK\tOperacion Normal de {$unidadesOperadas} no sobrepasan {$unidadesReportadas}\r\n";
                     }
                     //Validar sivienen de paises con alto riesgo
                     $xP = new cDomiciliosPaises();
                     $xP->getPaisPorMoneda($reporteMoneda);
                     $nombrepais = $xP->getNombre();
                     if ($xP->getRiesgoAMLAsociado() >= SYS_RIESGO_MEDIO) {
                         //Agregar alerta por operaciones en paises de  alto y medio riesgo
                         $this->mMsgAlert .= "ERROR\tFondos provenientes de paises con Riesgo Elevado {$nombrepais}\r\n";
                         $this->mMessages .= "ERROR\tFondos provenientes de paises con Riesgo Elevado {$nombrepais}\r\n";
                     }
                 } else {
                     $this->mMessages .= "OK\tOperacion Omitida por ser tipo de pago {$tipo_de_pago} ({$reporteMoneda} )\r\n";
                 }
             }
         } else {
             $this->mMessages .= "OK\tOperacion Omitida por ser Moneda {$moneda} de {$reporteMoneda}\r\n";
         }
     }
     //setLog($this->mMessages);
     if (MODO_DEBUG == true) {
         setLog($this->getMessages());
     }
     return $raised;
 }
 function addValorArqueado($valor_arqueado, $numero_arqueado, $documento, $notas = "", $fecha = false, $hora = false)
 {
     //eliminar valor anterior
     $fecha = $fecha == false ? fechasys() : $fecha;
     $hora = $hora == false ? time() : $hora;
     $monto = $valor_arqueado * $numero_arqueado;
     $xArq = new cTesoreria_caja_arqueos();
     $id = $xArq->query()->getLastID();
     $xArq->codigo_de_arqueo($id);
     $xArq->codigo_de_caja($this->mClaveDecaja);
     $xArq->documento($documento);
     $xArq->eacp(EACP_CLAVE);
     $xArq->fecha_de_arqueo($fecha);
     $xArq->hora_de_arqueo($hora);
     $xArq->idusuario(getUsuarioActual());
     $xArq->monto_total_arqueado($monto);
     $xArq->observaciones($notas);
     $xArq->sucursal(getSucursal());
     $xArq->valor_arqueado($valor_arqueado);
     $xArq->numero_arqueado($numero_arqueado);
     $cmd = $xArq->query()->insert();
     $cmd->save();
     if (MODO_DEBUG == true) {
         setLog($cmd->getMessages());
     }
     return $id;
 }
 public function cancel()
 {
     M()->validation(array(array('aid', 'require', '活动ID不能为空', Model::MUST_VALIDATE, 'regex')));
     $aid = I('aid');
     $activity = D('Activity')->field('anumber,floor,astatus')->find($aid);
     if ($activity['anumber'] < $activity['floor'] && ($activity['astatus'] == 0 || $activity['astatus'] == 2)) {
     } else {
         $this->retError('活动状态不允许取消');
     }
     $flg = D('Activity')->where("id = '{$aid}'")->setField('astatus', '-2');
     if (!$flg) {
         $this->retError('取消活动出错,请稍候再试');
     }
     $list = D('Order')->field("orderno,uid,orderprice")->where("aid = '{$aid}' and paystatus = 1")->select();
     if (count($list) > 0) {
         //修改所有账单状态为取消
         $orderValues = '';
         array_walk($list, function ($a) use(&$orderValues) {
             $orderValues .= "('" . $a['orderno'] . "', '-1'),";
         });
         $orderValues = substr($orderValues, 0, strlen($orderValues) - 1);
         $sql = "insert into t_order (orderno,paystatus) values {$orderValues} on duplicate key update paystatus=values(paystatus)";
         setLog('schedule5:modify_order:' . $sql);
         $flg = M()->execute($sql);
         //给已付款的账户增加对应金额
         $userValues = '';
         array_walk($list, function ($a) use(&$userValues) {
             $userValues .= '(' . $a['uid'] . ', ' . $a['orderprice'] . '),';
         });
         $userValues = substr($userValues, 0, strlen($userValues) - 1);
         $sql = "insert into t_user (id,amount) values {$userValues} on duplicate key update amount=amount+values(amount)";
         setLog('schedule5:modify_amount:' . $sql);
         $flg = M()->execute($sql);
     }
     $this->retSuccess();
 }
Example #11
0
                            }
                            if ($resultLanguage->rowCount() == 1) {
                                $rowLanguage = $resultLanguage->fetch();
                                setLanguageSession($guid, $rowLanguage);
                            }
                        }
                    }
                    //Make best effort to set IP address and other details, but no need to error check etc.
                    try {
                        $data = array("lastIPAddress" => $_SERVER["REMOTE_ADDR"], "lastTimestamp" => date("Y-m-d H:i:s"), "failCount" => 0, "username" => $username);
                        $sql = "UPDATE gibbonPerson SET lastIPAddress=:lastIPAddress, lastTimestamp=:lastTimestamp, failCount=:failCount WHERE username=:username";
                        $result = $connection2->prepare($sql);
                        $result->execute($data);
                    } catch (PDOException $e) {
                    }
                    if (isset($_GET["q"])) {
                        if ($_GET["q"] == "/publicRegistration.php") {
                            $URL = "./index.php";
                        } else {
                            $URL = "./index.php?q=" . $_GET["q"];
                        }
                    } else {
                        $URL = "./index.php";
                    }
                    setLog($connection2, $_SESSION[$guid]["gibbonSchoolYearIDCurrent"], NULL, $row["gibbonPersonID"], "Login - Success", array("username" => $username), $_SERVER["REMOTE_ADDR"]);
                    header("Location: {$URL}");
                }
            }
        }
    }
}
 function getFechaISO($fecha_ES_MX = false)
 {
     $fecha_ES_MX = $fecha_ES_MX == false ? $this->mFecha : $fecha_ES_MX;
     $fecha_ES_MX = str_replace("/", "-", $fecha_ES_MX);
     $D = explode("-", $fecha_ES_MX, 3);
     $anno = $this->anno();
     $mes = $this->mes();
     $dia = $this->dia();
     if (setNoMenorQueCero($D[0]) > 31) {
         $anno = setNoMenorQueCero($D[0]);
         $mes = setNoMenorQueCero($D[1]);
         $dia = setNoMenorQueCero($D[2]);
         //setLog($fecha_ES_MX);
     } else {
         if (isset($D[2])) {
             $panno = setNoMenorQueCero($D[2]);
             if ($panno > 31) {
                 $anno = $panno;
             }
         }
         if (!isset($D[1])) {
             if (MODO_DEBUG == true) {
                 setLog("Fecha fallida {$fecha_ES_MX}");
             }
         }
         $mes = setNoMenorQueCero($D[1]);
         $dia = setNoMenorQueCero($D[0]);
     }
     $anno = ($anno > 2099 or $anno < 1900) ? $this->anno() : $anno;
     $mes = ($mes < 1 or $mes > 12) ? $this->mes() : $mes;
     $dia = ($dia < 1 or $dia > 31) ? $this->dia() : $dia;
     $fecha_ES_MX = mktime(0, 0, 0, $mes, $dia, $anno);
     $this->mFecha = date("Y-m-d", $fecha_ES_MX);
     return $this->mFecha;
 }
Example #13
0
<?php

session_start();
require_once dirname(__FILE__) . "/lib/header.php";
if (isset($_SESSION['loginID'])) {
    locate($URLPv . "index.php");
} else {
    if (isset($_POST['stuID']) && isset($_POST['stuPW'])) {
        if (CheckPOP3($_POST['mailserver'] . ".ndhu.edu.tw", $_POST['stuID'], $_POST['stuPW'])) {
            $_SESSION['loginID'] = $_POST['stuID'];
            $_SESSION['loginToken'] = genToken($DBmain, $_SESSION['loginID']);
            setLogin($DBmain, $_SESSION['loginID'], $_SESSION['loginToken']);
            if (checkAdmin($DBmain, $_SESSION['loginID'])) {
                setLog($DBmain, "info", "Admin Login", $_SESSION['loginID']);
            }
            if (checkReg($DBmain, $_SESSION['loginID'])) {
                locate($URLPv . "index.php");
            } else {
                locate($URLPv . "regist.php");
            }
        } else {
            alert("Login Failed! Please try again. ");
            locate($URLPv . "login.php");
        }
    } else {
        ?>
	<div class="login">
		<form action="login.php" method="post">
			<div class="form-horizontal">
				<div class="form-group">
					<label class="control-label col-sm-2">Email: </label>
    //Definir bien los PWD
    $cUsr = new cSystemUser($oficial_s, false);
    $sucess = $cUsr->getCompareData("contrasenna", $pwd);
    $cUsr->init();
    if ($sucess == true) {
        $IOficial = $cUsr->getID();
        if ($fondos <= 0) {
            $msg .= "ERROR\tFondos menores a los establecido {$fondos} \r\n";
        } else {
            $cCj = new cCaja();
            $ropen = $cCj->setOpenBox($IOficial, $fondos);
            if ($ropen == true) {
                $msg .= "OK\tLa Caja esta abierta\r\n";
            } else {
                if (MODO_DEBUG == true) {
                    setLog($cCj->getMessages());
                }
                $msg .= "ERROR\tProblemas al iniciar la Caja\r\n";
            }
            if (MODO_DEBUG == true) {
                $msg .= $cCj->getMessages(OUT_TXT);
            }
        }
    } else {
        if (MODO_DEBUG == true) {
            $msg .= $cUsr->getMessages(OUT_TXT);
        }
        $msg .= "WARN\tERROR AL INICIAR LA SESSION DE CAJA\r\n";
    }
}
$xFRM = new cHForm("frmabrir", "abrir_caja.frm.php?action=1");
 function getCuentaContable($socio, $documento, $formula, $cajero = false, $cheque = false, $cuenta_bancaria = false)
 {
     $language = strpos($formula, "\$");
     // SI hay $ el Lenguaje es PHP
     $cuenta = CUENTA_DE_CUADRE;
     $numero_de_socio = $socio;
     $cheque = setNoMenorQueCero($cheque);
     $cajero = setNoMenorQueCero($cajero);
     $cuenta_bancaria = setNoMenorQueCero($cuenta_bancaria);
     //getCuentaContablePorBanco($cuenta_bancaria)
     $QL = new MQL();
     //FIXME: Verificar movimientos de variables no existentes, ejemplo $cheque
     //Verificar validez y funcionamiento - verificado. dic 2011
     if ($language !== false) {
         //Obtiene si el documento es de Captacion
         $esCredito = strpos($formula, "cartera");
         $esCaptacion = strpos($formula, "captacion");
         if (isset($esCredito) and $esCredito !== false) {
             /**
              * Obtiene Informacion para Cartera de credito
              */
             $sqliCartera = "SELECT * FROM creditos_datos_contables WHERE numero_solicitud={$documento} LIMIT 0,1";
             /*AND numero_socio=$socio*/
             $cartera = obten_filas($sqliCartera);
             $this->mMessages .= "{$socio}\t{$documento}\tCREDITOS\tLos Datos Contables se cargan\r\n";
         }
         if (isset($esCaptacion) and $esCaptacion !== false) {
             /**
              * Obtiene Informacion para Cuentas Captacion
              */
             $sqliCaptacion = "SELECT * FROM captacion_datos_contables WHERE numero_cuenta={$documento} LIMIT 0,1";
             /*AND numero_socio=$socio*/
             $captacion = obten_filas($sqliCaptacion);
             $this->mMessages .= "{$socio}\t{$documento}\tCAPTACION\tLos Datos Contables se cargan\r\n";
         }
         //setLog($formula);
         eval($formula);
         $this->mReturn = $cuenta;
         $this->mMessages .= "{$socio}\t{$documento}\tEVALUAR\tLa Cuenta se EVALUA y queda en {$cuenta}\r\n";
     } else {
         $cartera = array();
         $captacion = array();
         /**
          * Busca si es credito o Captacion
          */
         $esCredito = strpos($formula, "APLICA_CREDITO");
         $esCaptacion = strpos($formula, "APLICA_CAPTACION");
         if (isset($esCredito) and $esCredito !== 0) {
             $formula = str_replace("APLICA_CREDITO", "", $formula);
             /**
              * Obtiene Informacion para Cartera de credito
              */
             $sqliCartera = "SELECT * FROM creditos_datos_contables WHERE numero_solicitud={$documento} AND numero_socio={$socio} LIMIT 0,1";
             setLog($sqliCartera);
             $creditos = obten_filas($sqliCartera);
             $sustituir["CREDITOS_CARTERA_VIGENTE"] = isset($creditos["contable_cartera_vigente"]) ? $creditos["contable_cartera_vigente"] : CUENTA_DE_CUADRE;
             $sustituir["CREDITOS_CARTERA_VENCIDA"] = isset($creditos["contable_cartera_vencida"]) ? $creditos["contable_cartera_vencida"] : CUENTA_DE_CUADRE;
             $sustituir["CREDITOS_INTERESES_DEVENGADOS"] = isset($creditos["contable_intereses_devengados"]) ? $creditos["contable_intereses_devengados"] : CUENTA_DE_CUADRE;
             $sustituir["CREDITOS_INTERESES_ANTICIPADOS"] = isset($creditos["contable_intereses_anticipados"]) ? $creditos["contable_intereses_anticipados"] : CUENTA_DE_CUADRE;
             $sustituir["CREDITOS_INTERESES_COBRADOS"] = isset($creditos["contable_intereses_cobrados"]) ? $creditos["contable_intereses_cobrados"] : CUENTA_DE_CUADRE;
             $sustituir["CREDITOS_INTERESES_MORATORIOS"] = $creditos["contable_intereses_moratorios"];
             $sustituir["CREDITOS_CARTERA_CASTIGADA"] = $creditos["contable_catera_castigada"];
         } elseif (isset($esCaptacion) and $esCaptacion !== 0) {
             $formula = str_replace("APLICA_CAPTACION", "", $formula);
             /**
              * Obtiene Informacion para Cuentas Captacion
              */
             $sqliCaptacion = "SELECT * FROM captacion_datos_contables WHERE numero_cuenta={$documento} AND numero_socio={$socio} LIMIT 0,1";
             $captacion = obten_filas($sqliCaptacion);
             $sustituir["CAPTACION_MOVIMIENTOS"] = $captacion["contable_movimientos"];
             $sustituir["CAPTACION_INTERESES_POR_PAGAR"] = $captacion["contable_intereses_por_pagar"];
             $sustituir["CAPTACION_GASTOS_POR_INTERESES"] = $captacion["contable_gastos_por_intereses"];
             $sustituir["CAPTACION_CUENTAS_CASTIGADAS"] = $captacion["contable_cuentas_castigadas"];
         }
         /**
          *  Cambios generales
          */
         $formula = str_replace(";", "", $formula);
         $formula = str_replace("#", "", $formula);
         $formula = str_replace("\t", "", $formula);
         $formula = str_replace("+", "", $formula);
         foreach ($sustituir as $key => $value) {
             $formula = str_replace($key, $value, $formula);
         }
         $formula = str_replace(" ", "", $formula);
         $cuenta = $formula;
         //Retorna un String para valorar
         $this->mReturn = $cuenta;
     }
     return $this->mReturn;
 }
 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;
 }
//--------------------------------------Verifica las tareas Comunes.------------------------------------------------
//
****************************************************************************************************************** */
if (MODO_DEBUG == true) {
} else {
    //checar cierre del dia
    $xCierre = new cCierreDelDia();
    $aCierres = $xCierre->check5Cierres($fecha_de_sesion);
    if ($aCierres[SYS_ESTADO] == false) {
        setLog($xCierre->getMessages(), 300);
        header("location:utils/frmcierredeldia.php");
        exit;
    }
    $xPerCred = new cPeriodoDeCredito();
    if ($xPerCred->checkPeriodoVigente($fecha_de_sesion) == false) {
        setLog($xPerCred->getMessages(), 300);
        header("location:frmcreditos/cambiarperiodo.frm.php?a=1");
    }
}
$PATHIMG = "images/common/";
$xHP->setNoCache();
$xHP->setNoDefaultCSS();
$xHP->addCSS("css/general.css");
$xHP->addCSS("css/jmenu.css");
$xHP->addJsFile("js/jquery/jquery.ui.js");
$xHP->addJsFile("js/jmenu/jMenu.jquery.js");
$xHP->addJsFile("js/tinybox.js");
echo $xHP->getHeader();
?>
<style>
	html, body, object  {
 /**
  * 登录
  */
 public function login()
 {
     $User = D("User");
     // 实例化User对象
     $userData = null;
     if (I("token") != null) {
         $User->validation(array(array('token', 'require', '令牌不能为空', Model::MUST_VALIDATE, 'regex'), array('token', '10,50', '令牌长度不正确', Model::MUST_VALIDATE, 'length')));
         $userData = $User->relation('privacy')->where("id = (select uid from t_thirdaccount where token = '%s')", I("token"))->field("id,token")->find();
         if (empty($userData)) {
             $this->retError(403, '没有对应的token');
         }
     } else {
         $User->validation(array(array('phonenumber', 'require', '手机号不能为空', Model::MUST_VALIDATE, 'regex'), array('password', 'require', '密码不能为空', Model::MUST_VALIDATE, 'regex'), array('password', '6,50', '密码长度不正确', Model::MUST_VALIDATE, 'length'), array('phonenumber', 'phonenumber', '手机号格式不正确', Model::MUST_VALIDATE, 'regex')));
         \Think\Log::record(I("phonenumber"));
         \Think\Log::record(md5(I('password')));
         \Think\Log::save();
         setLog(I("phonenumber"));
         $userData = $User->where("phonenumber='%s' and password = '******'", I("phonenumber"), md5(I('password')))->field("id,token")->find();
         if (empty($userData)) {
             $this->retError(201, "帐号或密码错误");
         }
     }
     $this->retSuccess($userData);
 }
Example #19
0
}
//end if
if (!$module) {
    die('No Module Appointed!');
}
$pid_file = '/var/run/' . $module . '.pid';
//multi process
for ($i = 0; $i < $process_num; $i++) {
    $pid[$i] = pcntl_fork();
    if ($pid[$i] == -1) {
        setLog("Error: could not daemonize process.");
        return 1;
        //error
    } else {
        if ($pid[$i]) {
            setLog('Process: ' . $i . ' PID: ' . $pid[$i]);
            if ($i > 0) {
                $pid_str = file_get_contents($pid_file) . ' ' . $pid[$i];
            } else {
                $pid_str = $pid[$i];
            }
            file_put_contents($pid_file, $pid_str);
        } else {
            //the main process
            while (true) {
                require __SCRIPT__ . '/' . $module . '.php';
                sleep(1);
            }
        }
    }
}
 function modify_activity_status()
 {
     $activityList = D('Activity')->field('id,astatus,last_modify_time,anumber,floor,starttime,endtime')->where("astatus >= 1 and astatus <= 5 and atype = 0")->select();
     $map = array(array('conditions' => function ($activity) {
         return $activity['astatus'] == 1 && time() >= $activity['last_modify_time'] + 3600 / 2;
     }, 'status' => '0'), array('conditions' => function ($activity) {
         return ($activity['astatus'] == 2 || $activity['astatus'] == 3) && $activity['anumber'] >= $activity['floor'] && time() >= $activity['starttime'];
     }, 'status' => '4'), array('conditions' => function ($activity) {
         return $activity['astatus'] == 2 && $activity['anumber'] < $activity['floor'] && time() >= $activity['starttime'];
     }, 'status' => '-3', 'do' => function ($activity) {
         $aid = $activity['id'];
         $list = D('Order')->field("orderno,uid,orderprice")->where("aid = '{$aid}' and paystatus = 1")->select();
         if (count($list) > 0) {
             //修改所有账单状态为取消
             $orderValues = '';
             array_walk($list, function ($a) use(&$orderValues) {
                 $orderValues .= "('" . $a['orderno'] . "', '-1'),";
             });
             $orderValues = substr($orderValues, 0, strlen($orderValues) - 1);
             $sql = "INSERT into t_order (orderno,paystatus) values {$orderValues} on duplicate key update paystatus=values(paystatus)";
             setLog('schedule5:modify_order:' . $sql);
             $flg = M()->execute($sql);
             //给已付款的账户增加对应金额
             $userValues = '';
             array_walk($list, function ($a) use(&$userValues) {
                 $userValues .= '(' . $a['uid'] . ', ' . $a['orderprice'] . '),';
             });
             $userValues = substr($userValues, 0, strlen($userValues) - 1);
             $sql = "INSERT into t_user (id,amount) values {$userValues} on duplicate key update amount=amount+values(amount)";
             setLog('schedule5:modify_amount:' . $sql);
             $flg = M()->execute($sql);
         }
     }), array('conditions' => function ($activity) {
         return ($activity['astatus'] == 0 || $activity['astatus'] == 1) && time() >= $activity['starttime'];
     }, 'status' => '-3'), array('conditions' => function ($activity) {
         return $activity['astatus'] == 4 && time() >= $activity['endtime'];
     }, 'status' => '5', 'do' => function ($activity) {
     }), array('conditions' => function ($activity) {
         return $activity['astatus'] == 5 && time() >= $activity['endtime'] + 3600 * 48;
     }, 'status' => '6', 'do' => function ($activity) {
     }), array('conditions' => function ($activity) {
         return ($activity['astatus'] == 2 || $activity['astatus'] == 3) && $activity['anumber'] >= $activity['floor'] && $activity['isreminder'] == '1' && time() >= $activity['starttime'] - 3600 * 24;
     }, 'do' => function ($activity) {
         D('Push', 'Logic')->reminderUser($activity['uid'], 5, '你发起的[' . $activity['title'] . ']活动还有一天就要开始');
         $aid = $activity['id'];
         $list = M()->query("SELECT t1.deviceid as cid from t_device t1, t_activity_user t2 where t1.uid = t2.uid and t2.aid = {$aid}");
         $cids = array();
         foreach ($list as $value) {
             $cids[] = $value['uid'];
         }
         $sendData = array();
         $sendData['t'] = 2;
         $sendData['v'] = 5;
         $sendData['d'] = array('content' => '你参与的[' . $activity['title'] . ']活动还有一天就要开始', 'sendtime' => time());
         D('Push', 'Logic')->pushMessageToList($cids, '', json_encode($sendData));
         D('Activity')->where('id = %d', $aid)->setField('isreminder', '0');
     }));
     array_walk($map, function ($matche) use($activityList) {
         $conditions = $matche['conditions'];
         $status = $matche['status'];
         $do = $matche['do'];
         $activityList_filter = array_filter($activityList, $conditions);
         if (count($activityList_filter) > 0) {
             if ($status) {
                 $values = '';
                 array_walk($activityList_filter, function ($a) use(&$values, $status) {
                     $values .= '(' . $a['id'] . ', ' . $status . '),';
                 });
                 $values = substr($values, 0, strlen($values) - 1);
                 $sql = "INSERT into t_activity (id,astatus) values {$values} on duplicate key update astatus=values(astatus)";
                 setLog('schedule5:modify_status:' . $sql);
                 $flg = M()->execute($sql);
                 S('activity_status', null);
             }
             if ($do) {
                 array_walk($activityList_filter, function ($a) use($do) {
                     $do($a);
                 });
             }
         }
     });
 }
 function FTPGetFile($documento = false, $persona = false)
 {
     if ($this->mCnnFTP == null) {
         $this->FTPConnect();
     }
     $documento = $documento == false ? $this->mNombreArchivo : $documento;
     if ($persona != false) {
         ftp_chdir($this->mCnnFTP, $persona);
     }
     $mark = $persona == false ? "" : "{$persona}-";
     $ruta_completa = PATH_TMP . "/{$mark}" . $documento;
     //TODO: 01/01/2015 Modificar 2014Nov19 mejorar en cache.- validar mejoras
     if (is_file($ruta_completa)) {
     } else {
         $flocal = fopen($ruta_completa, 'w');
         if (ftp_fget($this->mCnnFTP, $flocal, $documento, FTP_BINARY, 0)) {
             //setLog( "Se ha escrito satisfactoriamente sobre $flocal");
         } else {
             setLog("Ha habido un problema durante la descarga de {$documento} en {$flocal}");
         }
     }
     $data = file_get_contents($ruta_completa);
     return $data;
 }
 public function notify()
 {
     /*
     *
     <xml> <appid><![CDATA[wx4e81aacd38a27424]]></appid> <attach><![CDATA[{"uid":"74","openid":"oVe75s2v_gh8E_ed5-MS57NVVXhg","aid":"1"}]]></attach> <bank_type><![CDATA[CFT]]></bank_type> <cash_fee><![CDATA[1]]></cash_fee> <fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe> <mch_id><![CDATA[1247136201]]></mch_id> <nonce_str><![CDATA[z616xlvfxant9iej7xx7cxnxhw7l4bl1]]></nonce_str> <openid><![CDATA[oVe75s2v_gh8E_ed5-MS57NVVXhg]]></openid> <out_trade_no><![CDATA[2015092150101971]]></out_trade_no> <result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code> <sign><![CDATA[181D406FF7A8D2F23F78EEF46DD46FF7]]></sign> <time_end><![CDATA[20150921212944]]></time_end> <total_fee>1</total_fee> <trade_type><![CDATA[JSAPI]]></trade_type> <transaction_id><![CDATA[1000040089201509210951012566]]></transaction_id> </xml>
     */
     //使用通用通知接口
     $notify = D('Server', 'Pay');
     //存储微信的回调
     $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
     setLog($xml);
     $notify->saveData($xml);
     //验证签名,并回应微信。
     //对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,
     //微信会通过一定的策略(如30分钟共8次)定期重新发起通知,
     //尽可能提高通知的成功率,但微信不保证通知最终能成功。
     if ($notify->checkSign() == FALSE) {
         $notify->setReturnParameter("return_code", "FAIL");
         //返回状态码
         $notify->setReturnParameter("return_msg", "签名失败");
         //返回信息
     } else {
         $notify->setReturnParameter("return_code", "SUCCESS");
         //设置返回码
     }
     if ($notify->checkSign() == TRUE) {
         if ($notify->data["return_code"] == "FAIL") {
             //通信出错
         } elseif ($notify->data["result_code"] == "FAIL") {
             //业务出错
         } else {
             //支付成功
             $data = $notify->getData();
             $attach = $data['attach'];
             $attach = json_decode($attach, true);
             $aid = $attach['aid'];
             $uid = $attach['uid'];
             if (!$aid || !$uid) {
                 $notify->setReturnParameter("return_code", "FAIL");
                 //返回状态码
                 $notify->setReturnParameter("return_msg", "parameter error");
                 //返回信息
                 $returnXml = $notify->returnXml();
                 echo $returnXml;
                 exit;
             }
             $activity = D('Activity')->find($aid);
             $user = D('User')->cache('user_base_' . $uid, 3600 * 24)->find($uid);
             $sid = $activity['sid'];
             $site = D('Site')->cache('site_base_' . $sid, 3600 * 24)->find($sid);
             if (!$user || !$site || $activity['money'] != $data['total_fee']) {
                 $notify->setReturnParameter("return_code", "FAIL");
                 //返回状态码
                 $notify->setReturnParameter("return_msg", "user or site or money error");
                 //返回信息
                 $returnXml = $notify->returnXml();
                 echo $returnXml;
                 exit;
             }
             $orderno = $data['out_trade_no'];
             $order = D('Order');
             $cnt = $order->where("orderno = '{$orderno}'")->count();
             if ($cnt) {
                 $notify->setReturnParameter("return_code", "FAIL");
                 //返回状态码
                 $notify->setReturnParameter("return_msg", "order exists");
                 //返回信息
                 $returnXml = $notify->returnXml();
                 echo $returnXml;
                 exit;
             }
             $orderData = array('orderno' => $orderno, 'aid' => $aid, 'uid' => $uid, 'ordertime' => time(), 'paytime' => tounix($data['time_end']), 'paymethod' => '__weixin__', 'orderprice' => $data['total_fee'], 'quantity' => 1, 'paystatus' => 1);
             if ($order->create($orderData)) {
                 $order->add();
             }
             D("ActivityUser")->addJoin($uid, $aid);
             $openid = $data['openid'];
             //捉影万圣节活动
             if ($activity['uid'] != '10012') {
                 $res = D('Template')->new_enroll($openid, $user['nickname'], $activity['title'], $orderno, $activity['starttime'], $site['address']);
             }
             $returnXml = $notify->returnXml();
             echo $returnXml;
             exit;
         }
         //商户自行增加处理流程,
         //例如:更新订单状态
         //例如:数据库操作
         //例如:推送支付完成信息
     }
     $returnXml = $notify->returnXml();
     echo $returnXml;
 }
 function setPersona($clave_de_persona)
 {
     $this->mPersona = $clave_de_persona;
     $cSoc = new cSocio($clave_de_persona);
     $fichas_de_respsolidarios = "";
     $firmas_de_respsolidarios = "";
     if ($cSoc->init() == true) {
         $domicilio_del_socio = $cSoc->getDomicilio();
         $ficha_socio = $cSoc->getFicha(true, true);
         $xODom = $cSoc->getODomicilio();
         $xOAE = $cSoc->getOActividadEconomica();
         //Caja local por SQL
         $SQLCL = "SELECT idsocios_cajalocal, descripcion_cajalocal, ultimosocio, region, sucursal FROM socios_cajalocal WHERE idsocios_cajalocal=" . $cSoc->getNumeroDeCajaLocal();
         $caja_local = mifila($SQLCL, "descripcion_cajalocal");
         $xFecha = new cFecha();
         $this->mArr["variable_domicilio_del_socio"] = $domicilio_del_socio;
         $this->mArr["variable_rfc_del_socio"] = $cSoc->getRFC();
         $this->mArr["variable_curp_del_socio"] = $cSoc->getCURP();
         $this->mArr["variable_numero_de_socio"] = $cSoc->getCodigo();
         $this->mArr["variable_nombre_caja_local"] = $caja_local;
         $this->mArr["variable_informacion_del_socio"] = $ficha_socio;
         $this->mArr["variable_fecha_de_nacimiento_del_socio"] = $xFecha->getFechaMediana($cSoc->getFechaDeNacimiento());
         $this->mArr["variable_ciudad_de_nacimiento_del_socio"] = $cSoc->getLugarDeNacimiento();
         if ($xODom != null) {
             $this->mArr["variable_sin_ciudad_domicilio_del_socio"] = $xODom->getDireccionBasica();
             $this->mArr["variable_ciudad_del_socio"] = $xODom->getCiudad();
             $this->mArr["variable_persona_domicilio_municipio"] = $xODom->getMunicipio();
         }
         if ($xOAE != null) {
             $this->mArr["variable_actividad_economica_del_socio"] = $xOAE->getPuesto();
             $this->mArr["variable_estado_de_actividad_economica"] = $xOAE->getNombreEstado();
             $this->mArr["variable_municipio_de_actividad_economica"] = $xOAE->getNombreMunicipio();
             $this->mArr["variable_nombre_de_la_empresa"] = $xOAE->getNombreEmpresa();
             $this->mArr["variable_socio_actividad_ciudad"] = $xOAE->getLocalidad();
             $this->mArr["variable_socio_actividad_telefono"] = $xOAE->getTelefono();
         }
         $this->mArr["variable_nombre_del_socio"] = $cSoc->getNombreCompleto();
         $this->mArr["variable_persona_nombre_completo"] = $cSoc->getNombreCompleto();
         $idestadocivil = $cSoc->getEstadoCivil();
         $DEstadoCivil = new cSocios_estadocivil();
         $DEstadoCivil->setData($DEstadoCivil->query()->initByID($idestadocivil));
         $nombre_estadocivil = $DEstadoCivil->descripcion_estadocivil()->v();
         $this->mArr["variable_estado_civil_del_socio"] = $nombre_estadocivil;
         $firmas_de_respsolidarios = $cSoc->getCoResponsables("firmas");
     } else {
         if (MODO_DEBUG == true) {
             setLog($cSoc->getMessages());
         }
     }
     $this->mArr["variable_responsable_solidario_en_fichas"] = $fichas_de_respsolidarios;
     $this->mArr["variable_firmas_de_obligados_solidarios"] = $firmas_de_respsolidarios;
 }
 function setGenerarInteresSobreSDPM($recibo = false, $fecha_de_corte = false)
 {
     $sucursal = getSucursal();
     $xQL = new MQL();
     $xErC = new cErrorCodes();
     $xLog = new cCoreLog();
     $xDTb = new cSAFETabla(TCAPTACION_CUENTAS);
     //(`captacion_cuentas`.`sucursal` ='$sucursal') AND
     $txtlog = "";
     $txtlog .= "==========================================================================================\r\n";
     $txtlog .= "==========\tCALCULO DE INTERESES SOBRE SDPM DE CUENTAS A LA VISTA EN LA SUCURSAL {$sucursal}\r\n";
     $txtlog .= "==========\tRECIBO DE CALCULO {$recibo}\r\n";
     $txtlog .= "==========================================================================================\r\n";
     $xF0 = new cFecha(0, $fecha_de_corte);
     $fecha_de_corte = $fecha_de_corte == false ? fechasys() : $fecha_de_corte;
     $dias_del_mes = $xF0->getDiasDelMes();
     $fecha_de_inicio = $xF0->getDiaInicial();
     $fecha_de_termino = $xF0->getDiaFinal();
     $ejer = $xF0->anno();
     $peri = $xF0->mes();
     //(`captacion_cuentas`.`sucursal` ='$sucursal') AND
     /**
      * Reestructurar los Dias SDPM para los Creditos que no han tenido Movimiento
      */
     //Generando el SDPM de los Credito sin movimiento o ultimo SDPM del mes
     $SQL_LST = $xDTb->getQueryInicial() . "\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t(`captacion_cuentas`.`estatus_cuenta` ='10') AND\n\t\t\t\t\t\t\t(`captacion_subproductos`.`metodo_de_abono_de_interes` ='AL_FIN_DE_MES')\n\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t(`captacion_cuentas`.`saldo_cuenta`>= " . A_LA_VISTA_MONTO_MINIMO . " )\n\t\t\t\t\t\t";
     $txtlog .= date("H:i:s") . "\t=========Cerrando las cuentas a su ultimo SDPM\r\n";
     $txtlog .= date("H:i:s") . "\tLas Cuentas con Saldo Menor a " . A_LA_VISTA_MONTO_MINIMO . " no se Incluyen\r\n";
     $rsUSDPM = $xQL->getDataRecord($SQL_LST);
     foreach ($rsUSDPM as $rwUSDPM) {
         $cuenta = $rwUSDPM["numero_cuenta"];
         $socio = $rwUSDPM["numero_socio"];
         $fecha_ultimo_mvto = $rwUSDPM["fecha_afectacion"];
         $saldo_actual = $rwUSDPM["saldo_cuenta"];
         $dias_de_sdpm = restarfechas($fecha_de_corte, $fecha_ultimo_mvto);
         $xCta = new cCuentaALaVista($cuenta);
         $xCta->init($rwUSDPM);
         if ($dias_de_sdpm > $dias_del_mes) {
             $txtlog .= date("H:i:s") . "\t{$socio}\t{$cuenta}\tLos dias del SDPM son de {$dias_de_sdpm} Mayores al del Mes {$dias_del_mes}, se ajustan\r\n";
             $xFMes = new cFecha(0, $fecha_de_corte);
             $dias_de_sdpm = $xF0->setRestarFechas($fecha_de_corte, $xF0->getDiaInicial());
         }
         $sdpm = $saldo_actual * $dias_de_sdpm;
         //Obtiene la Tasa
         $tasa = $xCta->getTasaAplicable(0, 0, $saldo_actual);
         //Inserta el SDPM
         $sqlUS = "INSERT INTO captacion_sdpm_historico\n\t\t\t\t\t\t(ejercicio, periodo, cuenta, fecha, dias, tasa, monto, recibo)\n\t    \t\t\t\tVALUES( {$ejer}, {$peri}, {$cuenta}, '{$fecha_de_corte}', {$dias_de_sdpm}, {$tasa},{$sdpm}, {$recibo})";
         my_query($sqlUS);
         //Actualiza la Cuenta
         $sqlUI = "UPDATE captacion_cuentas\n\t    \t\t\t\t\t\tSET fecha_afectacion='{$fecha_de_corte}', ultimo_sdpm={$sdpm}\n\t    \t\t\t\t\t\tWHERE numero_cuenta={$cuenta}";
         my_query($sqlUI);
         $txtlog .= date("H:i:s") . "\t{$socio}\t{$cuenta}\tAgregando y Actualizando el SDPM por {$sdpm} del {$fecha_ultimo_mvto} al {$fecha_de_corte} por {$saldo_actual}\r\n";
     }
     //considerar fecha de Apertura
     //agregar al Recibo
     //TODO: Actualizar esta linea
     $SQL_Captacion = "\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t`captacion_cuentas`.*,\n\t\t\t\t\t\t\t`captacion_subproductos`.*,\n\t\t\t\t\n\t\t\t\t\t`captacion_cuentas`.`numero_cuenta`                 AS `cuenta`,\n\t\t\t\t\t`captacion_cuentas`.`fecha_afectacion`              AS `apertura`,\n\t\t\t\t\t`captacion_cuentas`.`inversion_fecha_vcto`          AS `vencimiento`,\n\t\t\t\t\t`captacion_cuentas`.`tasa_otorgada`                 AS `tasa`,\n\t\t\t\t\t`captacion_cuentas`.`dias_invertidos`               AS `dias`,\n\t\t\t\t\t`captacion_cuentas`.`observacion_cuenta`            AS `observaciones`,\n\t\t\t\t\t`captacion_cuentas`.`saldo_cuenta` \t\t\t        AS `saldo`,\n\t\t\t\t\t`captacion_subproductos`.`descripcion_subproductos` AS `subproducto`,\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tSUM(`captacion_sdpm_historico`.`monto`) AS 'suma_sdpm'\n\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t`captacion_cuentas` `captacion_cuentas`\n\t\t\t\t\t\t\t\tINNER JOIN `captacion_subproductos` `captacion_subproductos`\n\t\t\t\t\t\t\t\tON `captacion_cuentas`.`tipo_subproducto` = `captacion_subproductos`.\n\t\t\t\t\t\t\t\t`idcaptacion_subproductos`\n\t\t\t\t\t\t\t\t\tINNER JOIN `captacion_sdpm_historico` `captacion_sdpm_historico`\n\t\t\t\t\t\t\t\t\tON `captacion_cuentas`.`numero_cuenta` = `captacion_sdpm_historico`.\n\t\t\t\t\t\t\t\t\t`cuenta`\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t(`captacion_cuentas`.`estatus_cuenta` ='10') AND\n\t\t\t\t\t\t\t(`captacion_subproductos`.`metodo_de_abono_de_interes` ='AL_FIN_DE_MES')\n\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t(`captacion_sdpm_historico`.`fecha` >='{$fecha_de_inicio}')\n\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t(`captacion_sdpm_historico`.`fecha` <='{$fecha_de_termino}')\n\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t(`captacion_cuentas`.`saldo_cuenta`>=" . A_LA_VISTA_MONTO_MINIMO . ")\n\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t`captacion_sdpm_historico`.`cuenta`\n\t\t\t\t\t\t\t";
     setLog($SQL_Captacion);
     $rsCAP = $xQL->getDataRecord($SQL_Captacion);
     if (!$rsCAP) {
         if (MODO_DEBUG == true) {
             $txtlog .= $xQL->getMessages();
             //date("H:i:s") . "\tERROR (" . mysql_errno() . ") AL EJECUTAR LA CONSULTA";
         }
     } else {
         $txtlog .= "==========================================================================================\r\n";
         //$xT1	= new cTipos();
         foreach ($rsCAP as $rwC) {
             $cuenta = $rwC["numero_cuenta"];
             $socio = $rwC["numero_socio"];
             $apertura = $rwC["fecha_apertura"];
             $sumaSDPM = $rwC["suma_sdpm"];
             $dias_de_calc = $dias_del_mes;
             $promedio = $rwC["saldo_cuenta"];
             $modificadorDeInteres = $rwC["algoritmo_modificador_del_interes"];
             $modificadorDeTasa = $rwC["algoritmo_de_tasa_incremental"];
             $interes = 0;
             $producto = $rwC["tipo_subproducto"];
             //Si la Fecha de Apertura es Menor al Inicio de mes
             if (strtotime($apertura) > strtotime($fecha_de_inicio)) {
                 $dias_de_calc = restarfechas($fecha_de_termino, $apertura);
                 //Corrige el TIMESTAMP de Interes, la rotacion debe ser de al menos 24 Horas
                 if ($dias_de_calc == 0) {
                     $dias_de_calc = 1;
                 } elseif ($dias_de_calc < 0) {
                     $txtlog .= date("H:i:s") . "\t{$socio}\t{$cuenta}\tEROR_DIAS\t SDPM {$sumaSDPM}, Dias {$dias_de_calc}\r\n";
                     $dias_de_calc = 1;
                     $sumaSDPM = $promedio;
                 }
             }
             $xCta = new cCuentaALaVista($cuenta);
             $xCta->init($rwC);
             $promedio = round($sumaSDPM / $dias_de_calc, 2);
             $tasa_nueva = $xCta->getTasaAplicable(0, 0, $promedio);
             $tasa = $tasa_nueva;
             //OK: Ejecutar Modificador de Tasa
             eval($modificadorDeTasa);
             //setLog("$modificadorDeTasa");
             $interes = $sumaSDPM * $tasa / EACP_DIAS_INTERES;
             //OK: Ejecutar Consulta de Modificador de Interes
             eval($modificadorDeInteres);
             $interes = round($interes, 2);
             //$txtlog		.= $modificadorDeInteres;
             if ($interes > 0) {
                 $rsx = setNuevoMvto($socio, $cuenta, $recibo, $fecha_de_corte, $interes, 222, 1, "CALCULO_AUTOMATICO");
                 if ($rsx == false) {
                     $txtlog .= "ERROR\t{$socio}\t{$cuenta}\tInteres por {$interes}, tasa {$tasa_nueva}, Promedio {$promedio}, SDPM {$sumaSDPM}, Dias {$dias_de_calc}\r\n";
                 } else {
                     $txtlog .= "OK\t{$socio}\t{$cuenta}\tInteres por {$interes}, tasa {$tasa_nueva}, Promedio {$promedio}, SDPM {$sumaSDPM}, Dias {$dias_de_calc} en Rec {$recibo}\r\n";
                 }
                 $sqlUI = "UPDATE captacion_cuentas\n\t\t    \t\t\t\t\t\tSET saldo_cuenta = (saldo_cuenta + {$interes})\n\t\t    \t\t\t\t\t\tWHERE numero_cuenta={$cuenta} AND numero_socio={$socio}";
                 $x = my_query($sqlUI);
             } else {
                 $txtlog .= "WARN\t{$socio}\t{$cuenta}\tNOINT\t({$interes} / {$tasa_nueva}) Promedio {$promedio}, SDPM {$sumaSDPM}, Dias {$dias_de_calc}\r\n";
             }
         }
     }
     return $txtlog;
 }
 function getService($url)
 {
     $obj = null;
     $req = $this->getRequest($url);
     // file_get_contents($url);
     if (!$req) {
         setLog("Error al procesar la url : {$url}");
     } else {
         $req = $this->getDecryptData($req);
         $obj = json_decode($req, true);
         /*if(!$obj){
         			
         		} else {
         			
         		}*/
         /*	str	= base64.decode(str);
         			str	= Aes.Ctr.decrypt(str, CloudConfig.apiKey, 256)
         			*/
         /*
         $data		= (isset($_REQUEST["data"])) ? $svc->getDecryptData($_REQUEST["data"]) : null;
         $command	= (isset($_REQUEST["cmd"])) ? $svc->getDecryptData($_REQUEST["cmd"]) : null;
         $context	= (isset($_REQUEST["ctx"])) ? $svc->getDecryptData($_REQUEST["ctx"]) : null;
         $obj		= json_decode($data, true);
         */
     }
     return $obj;
 }
 function setActualizarParcialidad($NumeroDeParcialidad, $capital = false, $interes = false, $ahorro = false, $OtroClave = false, $OtroMonto = false)
 {
     $msg = "";
     $BWhere = "(recibo_afectado = " . $this->mNumeroDePlan . ") AND ( periodo_socio= {$NumeroDeParcialidad} ) AND ";
     //AND ( socio_afectado=" . $this->mSocio . ") AND ( docto_afectado=" . $this->mCredito . ")
     if (setNoMenorQueCero($NumeroDeParcialidad) > 0) {
         if ($capital !== false) {
             $sql1 = "UPDATE operaciones_mvtos SET afectacion_real={$capital}\n\t\t\t\t    WHERE {$BWhere}  (tipo_operacion=" . OPERACION_CLAVE_PLAN_CAPITAL . ") ";
             setLog($sql1);
             $xEs = my_query($sql1);
             $msg .= $xEs[SYS_INFO];
             //Actualizar credito
             //TODO: Actualizar a tolerancia de Saldos
             if ($interes <= 0.01 && $capital <= 0.01) {
                 //Obtener datos de la parcialidad
                 $fechaV = $this->getParcialidadFechaDePago($NumeroDeParcialidad);
                 $sqlMA = "UPDATE creditos_solicitud SET ultimo_periodo_afectado={$NumeroDeParcialidad},\n\t\t\t\t\tfecha_ultimo_mvto = '{$fechaV}'\n\t\t\t\t\tWHERE numero_solicitud=" . $this->mCredito . "\n\t\t\t\t\t\tAND\n\t\t\t\t\t\tnumero_socio = " . $this->mSocio . "\n\t\t\t\t\t";
                 my_query($sqlMA);
             }
         }
         if ($interes !== false) {
             $tasa_iva = $this->mTasaDeIVA;
             $iva = $interes * $tasa_iva;
             $sql1 = "UPDATE operaciones_mvtos SET afectacion_real={$interes}  WHERE {$BWhere} (tipo_operacion=" . OPERACION_CLAVE_PLAN_INTERES . ") ";
             $xEs = my_query($sql1);
             $msg .= $xEs[SYS_INFO];
             //if($iva > 0.001){
             //actualizar IVA
             $sql1 = "UPDATE operaciones_mvtos  SET afectacion_real={$iva}  WHERE {$BWhere} (tipo_operacion=" . OPERACION_CLAVE_PLAN_IVA . ") ";
             $xEs = my_query($sql1);
             $msg .= $xEs[SYS_INFO];
             //}
         }
         if ($ahorro !== false) {
             $sql1 = "UPDATE operaciones_mvtos SET afectacion_real={$ahorro} WHERE {$BWhere} (tipo_operacion=" . OPERACION_CLAVE_PLAN_AHORRO . ") ";
             $xEs = my_query($sql1);
             $msg .= $xEs[SYS_INFO];
         }
         if ($OtroClave !== false and $OtroMonto !== false) {
             $sql1 = "UPDATE operaciones_mvtos SET afectacion_real={$OtroMonto} WHERE {$BWhere} (tipo_operacion={$OtroClave}) ";
             $xEs = my_query($sql1);
             $msg .= $xEs[SYS_INFO];
         }
     }
     $this->mMessages .= $msg . "\r\n";
     return $msg;
 }
                 $msg .= "OK\tSE HA ACTUALIZADO LAS CUENTAS TIPO {$tipocuenta}  DE CANTIDADES MAYORES A {$minimo} Y MENORES A {$maximo}\r\n";
             } else {
                 $msg .= $x[SYS_MSG];
             }
         } else {
             if (setNoMenorQueCero($subproducto) == 0) {
             } else {
                 $sql_cap = "UPDATE captacion_cuentas  \n\t\t\t\t\t\t\tSET tasa_otorgada={$tasa}\n\t\t\t\t\t\t\tWHERE tipo_cuenta={$tipocuenta} \n\t\t\t\t\t\t\tAND  saldo_cuenta>={$minimo}\n\t\t\t\t\t\t\tAND saldo_cuenta<={$maximo}\n\t\t\t\t\t\t\tAND tipo_subproducto={$subproducto}";
                 $x = my_query($sql_cap);
                 if ($x[SYS_ESTADO] == true) {
                     $msg .= "OK\tSE HA ACTUALIZADO LAS CUENTAS TIPO {$tipocuenta}/{$subproducto}  DE CANTIDADES MAYORES A {$minimo} Y MENORES A {$maximo}\r\n";
                 } else {
                     $msg .= $x[SYS_MSG];
                 }
             }
             setLog($sql_cap);
         }
     }
     break;
     //========================================================================================================================
 //========================================================================================================================
 case 203:
     $msg .= "============== DEPURANDO LA CUENTA GLOBAL CORRIENTE ========\r\n";
     $cuenta = $id == "NO_APLICA" ? CTA_GLOBAL_CORRIENTE : $id;
     $sqlDM = "DELETE FROM operaciones_mvtos WHERE docto_afectado={$cuenta}";
     $xDM = my_query($sqlDM);
     $msg .= $xDM[SYS_MSG];
     $sqlDS = "DELETE FROM `captacion_sdpm_historico` WHERE cuenta={$cuenta}";
     $xDS = my_query($sqlDS);
     $msg .= $xDS[SYS_MSG];
     //obtiene la cuenta con mas antiguedad
function listar_cuentas($idcta)
{
    //$idcta = substr($idcta, 1, -1);
    $sucess = true;
    $tds = "";
    $i = 1;
    $xCta = new cCuentaContableEsquema($idcta);
    $sql = "SELECT numero, nombre FROM contable_catalogo WHERE numero LIKE '" . $xCta->CUENTARAW . "%' AND afectable=1  ORDER BY numero LIMIT 0,10";
    if (MODO_DEBUG == true) {
        setLog($sql);
    }
    if (trim($idcta) == "" or (int) $idcta == 0) {
        $sucess = false;
    }
    if ($sucess == true) {
        $rs = getRecordset($sql);
        while ($row = mysql_fetch_array($rs)) {
            $ctaformateada = $row[0];
            $nombrecuenta = substr(htmlentities($row[1]), 0, 20);
            if ($i == 2) {
                $i = 1;
            } else {
                $i++;
            }
            //
            $tds .= " \n\n\t\t\t<option value=\"{$row['0']}\" >{$ctaformateada} - {$nombrecuenta}</option>";
        }
    } else {
        $tds .= " \n<option >NO HAY CUENTAS PARA ({$idcta})</option>";
    }
    if ($sucess = true) {
        return "<select name=\"underCuenta\" id=\"idUnderCuenta\" size=\"10\"\n\t\t\tonclick=\"setNumeroCuenta(this.value);\"\n\t\t\tonblur=\"setNoSearchCatalog();\"\n\t\t\tonkeyup=\"setActionByKey(event);\" >\n\t\t\t\t{$tds}\n\t\t\t</select>";
    }
}
 function sendMail($subject = "", $body = "", $to = "", $arrFile = false)
 {
     $omsg = "";
     if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
         //Create a new PHPMailer instance
         $mail = new PHPMailer();
         //Tell PHPMailer to use SMTP
         $mail->IsSMTP();
         //Enable SMTP debugging
         // 0 = off (for production use)
         // 1 = client messages
         // 2 = client and server messages
         $mail->SMTPDebug = 0;
         $mail->Timeout = 10;
         if (MODO_DEBUG == true) {
             /*$mail->SMTPDebug  = 2;*/
         }
         //Ask for HTML-friendly debug output
         $mail->Debugoutput = 'html';
         //Set the hostname of the mail server
         $mail->Host = ADMIN_MAIL_SMTP_SERVER;
         //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
         $mail->Port = ADMIN_MAIL_SMTP_PORT;
         //Set the encryption system to use - ssl (deprecated) or tls
         if (ADMIN_MAIL_SMTP_TLS != "") {
             $mail->SMTPSecure = ADMIN_MAIL_SMTP_TLS;
             //'tls';
         }
         //Whether to use SMTP authentication
         $mail->SMTPAuth = true;
         //Username to use for SMTP authentication - use full email address for gmail
         $mail->Username = ADMIN_MAIL;
         //EACP_MAIL;
         //Password to use for SMTP authentication
         $mail->Password = ADMIN_MAIL_PWD;
         //Set who the message is to be sent from
         $mail->SetFrom(ADMIN_MAIL, 'S.A.F.E. OSMS System Alert');
         //Set an alternative reply-to address
         //$mail->AddReplyTo('*****@*****.**','First Last');
         //Set who the message is to be sent to
         $mail->AddAddress($to, 'SAFE-OSMS');
         //Set the subject line
         $mail->Subject = $subject;
         //Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
         //$mail->MsgHTML(file_get_contents('contents.html'), dirname(__FILE__));
         $mxMsg = "";
         $mxMsg .= $body;
         $mail->MsgHTML($mxMsg);
         //Replace the plain text body with one created manually
         //$mail->AltBody = 'This is a plain-text message body';
         //Attach an image file
         if ($arrFile != false and is_array($arrFile)) {
             if (isset($arrFile["archivo1"])) {
                 if (is_array($arrFile["archivo1"])) {
                     foreach ($arrFile as $archivos) {
                         $mail->AddAttachment($archivos["path"]);
                     }
                 }
                 $mail->Timeout = 80;
             } else {
                 //$m->Attach($arrFile["path"], $arrFile["mime"], "inline");
                 $mail->AddAttachment($arrFile["path"]);
                 $mail->Timeout = 60;
             }
         }
         //$mail->AddAttachment('images/phpmailer-mini.gif');
         //Send the message, check for errors
         if (!$mail->Send()) {
             $omsg .= "ERROR\t{$to}\t" . $mail->ErrorInfo . "\r\n";
         } else {
             $omsg .= "OK\tMensaje Enviado a {$to} con exito.\r\n";
         }
     } else {
         $omsg .= "ERROR\tInvalid email {$to}\r\n";
     }
     if (MODO_DEBUG == true) {
         setLog($omsg);
     }
     return $omsg;
 }