public function indexAction() { $request = $this->getRequest(); $message = ""; /* $user = '******'; $pass = md5('qwerty'); $entity = new \Empleado(); $entity->setEmpleadoEmail($user); //SETIAMOS LA CONTRASEÑA EN MD5 $entity->setEmpleadoPassword($pass); $entity->save(); */ if ($request->isPost()) { $success = false; $post_data = $request->getPost(); $user = $post_data['txtUser']; $pass = md5($post_data['txtPass']); $entity = \ClienteQuery::create()->filterByClienteEmail($user)->find(); //Crear un usuario /* $entity = new \Cliente(); $entity->setClienteEmail($user); //SETIAMOS LA CONTRASEÑA EN MD5 $entity->setClientePassword($pass); $entity->save(); */ if (count($entity) != 0) { foreach ($entity as $client) { if ($client->getClienteEmail() == $user && $client->getClientePassword() == $pass) { //Nuesta session $session = new \Shared\Session\ClientSession(); $session->Create(array('idcliente' => $client->getIdCliente(), 'cliente_nombre' => $client->getClienteNombrecontacto(), 'cliente_email' => $client->getClienteEmail())); //var_dump($session->getData()); return $this->redirect()->toUrl('http://itrade/'); //return $this->redirect()->toRoute('client'); } } } $message = "Correo electrónico o contraseña incorrecta"; } //Romper la sesion $session = new \Shared\Session\ClientSession(); $session->Close(); $layout = $this->layout(); $layout->setTemplate('website/layout/layout_login'); $viewModel = new ViewModel(array("mensaje" => $message)); return $viewModel; }
public function iniciarSesion($nombre_usuario, $pass) { $empleado = empleadoQuery::create(); $empleado->filterByUser($nombre_usuario)->filterByPass(md5($pass))->joinWith('Privilegios'); if ($this->login = $empleado->findOne()) { $this->setAttribute('nombre_usuario', $nombre_usuario); $this->setAttribute('nivel', $this->login->getPrivilegios()->getDescripcion()); $this->setAuthenticated(true); } else { $cliente = ClienteQuery::create(); $cliente->filterByUser($nombre_usuario)->filterByPass($pass); if ($this->login = $cliente->findOne()) { $this->setAttribute('nombre_usuario', $this->login->getUser()); $this->setAttribute('nivel', 'cliente'); $this->setAttribute('codCliente', $this->login->getIdClie()); $this->setAuthenticated(true); } else { $this->cerrarSesion(); } // $this->cerrarSesion(); } }
/** * Get the associated Cliente object * * @param PropelPDO Optional Connection object. * @return Cliente The associated Cliente object. * @throws PropelException */ public function getCliente(PropelPDO $con = null) { if ($this->aCliente === null && $this->idcliente !== null) { $this->aCliente = ClienteQuery::create()->findPk($this->idcliente, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aCliente->addVentas($this); */ } return $this->aCliente; }
/** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @throws Exception * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(ClientePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = ClienteQuery::create()->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BaseCliente:delete:pre') as $callable) { if (call_user_func($callable, $this, $con)) { $con->commit(); return; } } if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BaseCliente:delete:post') as $callable) { call_user_func($callable, $this, $con); } $con->commit(); $this->setDeleted(true); } else { $con->commit(); } } catch (Exception $e) { $con->rollBack(); throw $e; } }
public function indexAction() { $session = new \Shared\Session\ClientSession(); //if(!$session->isActive()) //return $this->redirect()->toUrl('http://itrade/login'); $request = $this->getRequest(); //echo $request; $message = "success"; //$id = $session->getData()['idcliente']; $id = 1; $entity = \ClienteQuery::create()->findPk($id); if ($request->isPost()) { $success = false; $post_data = $request->getPost(); $post_files = $request->getFiles(); //Campos de datos generales $entity->setClienteRazonsocial($post_data['cliente_razon_social']); $entity->setClienteRfc($post_data['cliente_rfc']); $entity->setClienteCalle($post_data['cliente_calle']); $entity->setClienteNumero($post_data['cliente_numero_exterior']); $entity->setClienteInterior($post_data['cliente_numero_interior']); $entity->setClienteColonia($post_data['cliente_colonia']); $entity->setClienteCiudad($post_data['cliente_ciudad']); $entity->setClienteCodigopostal($post_data['cliente_cp']); if ($post_data['cliente_estado'] != 'Seleccione un estado') { } $entity->setClienteEstado($post_data['cliente_estado']); if ($post_data['cliente_pais'] != 'Seleccione un país') { } $entity->setClientePais($post_data['cliente_pais']); $entity->setClienteEmail($post_data['cliente_email']); $entity->setClienteTelefono($post_data['cliente_telefono']); $entity->setClienteRfc($post_data['cliente_rfc']); $entity->setClienteNombrecontacto($post_data['cliente_nombre']); //Terminan campos generales //Campos Fiscales //$entity->setClienteRazonsocial($post_data['cliente_f_razon_social']); //$entity->setClienteRfc($post_data['cliente_f_rfc']); $entity->setClienteCallefiscal($post_data['cliente_f_calle']); $entity->setClienteNumerofiscal($post_data['cliente_f_numero_exterior']); $entity->setClienteInteriorfiscal($post_data['cliente_f_numero_interior']); $entity->setClienteColoniafiscal($post_data['cliente_f_colonia']); $entity->setClienteCiudadfiscal($post_data['cliente_f_ciudad']); $entity->setClienteCodigopostalfiscal($post_data['cliente_f_cp']); if ($post_data['cliente_f_estado'] != 'Seleccione un estado') { } $entity->setClienteEstadofiscal($post_data['cliente_f_estado']); if ($post_data['cliente_f_pais'] != 'Seleccione un país') { } $entity->setClientePaisfiscal($post_data['cliente_f_pais']); //Terminan campos fiscales //Ruta donde se guardaran los archivos $upload_folder = $_SERVER['DOCUMENT_ROOT'] . "/files/clientes/" . $id . "/"; //Clase auxiliar para validar y guardar archivos $fileClass = new \Client\Files\SaveFiles(); //Creamos el directorio del cliente si no existe if (!file_exists($upload_folder)) { mkdir($upload_folder); } $names = array('cliente_padron', 'cliente_encargoconferido'); /* foreach ($post_files as $file ) { $i = 0; //Verificamos si el no archivo es valido, si lo es proseguimos con el else if( !$fileClass->validateFile($file) == "") $message = $message.$fileClass->validateFile($file); else { $newName = $names[$i]; $fileClass->saveFile($upload_folder,$file,$newName); $debug = $names[$i]; } $i++; } */ //Verificamos que el usuario haya subido algún archivo $file = $post_files['cliente_padron']; if ($file['name'] != "") { $debug = $file; if (!$fileClass->validateFile($file) == "") { //Si el archivo que se quiso subir tiene error $message = $message . $fileClass->validateFile($file); } else { //Si se valido que el archivo sea correcto $fileClass->saveFile($upload_folder, $file, 'cliente_padron'); //Insertamos a la base de datos $entity->setClientePadronimportador("/files/clientes/" . $id . "/cliente_padron." . $fileClass->getType($file)); } } //copy($post_files['cliente_padron']['tmp_name'], $upload_folder); if ($message == "success") { $entity->save(); } /* $entity->setClienteNombrecontacto('Victor'); $entity->save(); /* $cliente = \ClienteQuery::create() ->filterByEmpleadoEmail($user) ->find(); */ } else { $message = ""; } $mexico_states = \Shared\GeneralFunction\Geolocation::getMexicoStates(); $form = new \Client\Form\ClienteForm($mexico_states, $entity); //$form = new \Catalogo\Form\ClienteForm(); $layout = $this->layout(); $layout->setTemplate('client/layout/layout'); //RETORNAMOS A NUESTRA VISTA return new ViewModel(array('form' => $form, 'message' => $message, 'session' => $session, 'debug' => $debug)); }
public function proveedoreditarAction() { $idcliente = $this->params()->fromRoute('id'); $idproveedor = $this->params()->fromRoute('idproveedor'); $request = $this->getRequest(); if ($request->isPost()) { $post_data = $request->getPost(); $entity = \ProveedorclienteQuery::create()->findPk($idproveedor); foreach ($post_data as $key => $value) { if (\ProveedorclientePeer::getTableMap()->hasColumn($key) && !empty($value) && $key != 'cliente_cumpleanios') { $entity->setByName($key, $value, \BasePeer::TYPE_FIELDNAME); } } $entity->save(); $this->flashMessenger()->addSuccessMessage('Registro guardado exitosamente!'); //REDIRECCIONAMOS A LA ENTIDAD QUE ACABAMOS DE CREAR return $this->redirect()->toUrl('/clientes/ver/' . $idcliente . '?active=proveedores'); } $exist = \ProveedorclienteQuery::create()->filterByIdproveedorcliente($idproveedor)->exists(); if ($exist) { $entity = \ProveedorclienteQuery::create()->findPk($idproveedor); $cliente = \ClienteQuery::create()->findPk($idcliente); $form = new \Admin\Clientes\Form\ProveedorForm($idcliente); $form->setData($entity->toArray(\BasePeer::TYPE_FIELDNAME)); $view_model = new ViewModel(); $view_model->setTemplate('admin/clientes/proveedor/editar'); $view_model->setVariables(array('entity' => $entity, 'successMessages' => json_encode($this->flashMessenger()->getSuccessMessages()), 'form' => $form, 'cliente' => $cliente)); return $view_model; } else { return $this->redirect()->toUrl('/clientes/ver/' . $idcliente . '?active=proveedores'); } }
/** * Executes index action * * @param sfRequest $request A request object */ public function executeIndex(sfWebRequest $request) { $defaults = array('Inicio' => date('d/m/Y'), 'Fin' => date('d/m/Y')); $this->form = new ReporteForm($defaults); $html = ''; $datos = array(); if ($request->isMethod('POST')) { $this->form->bind($request->getParameter('reporte')); if ($this->form->isValid()) { $valores = $this->form->getValues(); $inicio = $valores['Inicio']; $inicio = explode('/', $inicio); $inicio = $inicio[2] . '-' . $inicio[1] . '-' . $inicio[0]; $fin = $valores['Fin']; $fin = explode('/', $fin); $fin = $fin[2] . '-' . $fin[1] . '-' . $fin[0]; switch ($valores['Tipo']) { case '0': $string = 'Estado Actual de Producto'; $datos = ProductoQuery::create()->find(); $html = $this->getPartial('reporte/reporteCero', array('datos' => $datos)); break; case '1': $string = 'Productos por Debajo de Minimo'; $productos = ProductoQuery::create()->find(); $datos = new PropelArrayCollection(); foreach ($productos as $fila) { if ($fila->getCantidadMinima() >= Producto::obtenerExistencia($fila->getId())) { $datos[] = $fila; } } $html = $this->getPartial('reporte/reporteUno', array('datos' => $datos)); break; case '2': $string = '5 Maximos Clientes'; $listadoUno = array(); $listadoDos = array(); $listadoTres = array(); $MasCompras = FacturaDetalleQuery::create()->useFacturaQuery()->where("created_at <= '{$fin} 23:59:59' and created_at >= '{$inicio} 00:00:00'")->groupByClienteId()->endUse()->withColumn('Count(*)', 'Contador')->orderBy('Contador', 'Desc')->limit(5)->find(); foreach ($MasCompras as $mc) { if ($mc->getFactura()) { $Cliente = ClienteQuery::create()->findOneById($mc->getFactura()->getClienteId()); $fila = array(); $fila['Maximo'] = $mc->getContador(); $fila['Cliente'] = $Cliente->getNombre(); $listadoUno[] = $fila; } } // $masFacturas = FacturaQuery::create()->where("created_at <= '{$fin} 23:59:59' and created_at >= '{$inicio} 00:00:00'")->groupByClienteId()->withColumn('Count(*)', 'Contador')->orderBy('Contador', 'Desc')->limit(5)->find(); foreach ($masFacturas as $mc) { $fila = array(); $fila['Maximo'] = $mc->getContador(); $fila['Cliente'] = $mc->getCliente()->getNombre(); $listadoDos[] = $fila; } // $monto = FacturaDetalleQuery::create()->withColumn('SUM(cantidad * precio_unitario)', 'Total')->useFacturaQuery()->groupByClienteId()->where("created_at <= '{$fin} 23:59:59' and created_at >= '{$inicio} 00:00:00'")->endUse()->orderBy('Total', 'Desc')->limit(5)->find(); foreach ($monto as $mc) { $fila = array(); $Cliente = ClienteQuery::create()->findOneById($mc->getFactura()->getClienteId()); $fila['Monto'] = $mc->getTotal(); $fila['Cliente'] = $Cliente->getNombre(); $listadoTres[] = $fila; } $datos['listadoUno'] = $listadoUno; $datos['listadoDos'] = $listadoDos; $datos['listadoTres'] = $listadoTres; $html = $this->getPartial('reporte/reporteDos', array('listadoUno' => $listadoUno, 'listadoDos' => $listadoDos, 'listadoTres' => $listadoTres)); break; case '3': $Proveedores = MovimientoQuery::create()->where("fecha <= '{$fin}' and fecha >= '{$inicio}'")->filterByTipoMovimiento('+')->groupByProveedorId()->withColumn('count(id)', 'Total')->orderBy('Total')->limit(5)->find(); $string = 'Reporte de Proveedores'; $html = $this->getPartial('reporte/reporteTres', array('datos' => $Proveedores)); break; case '4': $movimientos = MovimientoQuery::create()->where("fecha <= '{$fin}' and fecha >= '{$inicio}'")->filterByTipoMovimiento('-')->groupByProductoId()->withColumn('count(cantidad)', 'Total')->orderBy('Total')->limit(5)->find(); $string = 'Reporte de Productos mas Vendidos'; $html = $this->getPartial('reporte/reporteCuatro', array('datos' => $movimientos)); break; case '5': $movimientos = MovimientoQuery::create()->where("fecha <= '{$fin}' and fecha >= '{$inicio}'")->filterByTipoMovimiento('-')->groupByProductoId()->withColumn('count(cantidad)', 'Total')->orderBy('Total', 'desc')->limit(5)->find(); $string = 'Reporte de Productos menos Vendidos'; $html = $this->getPartial('reporte/reporteCinco', array('datos' => $movimientos)); break; case '6': $Facturas = FacturaQuery::create()->where("created_at <= '{$fin} 23:59:59' and created_at >= '{$inicio} 00:00:00'")->groupByCreatedBy()->withColumn('count(id)', 'Suma')->orderBy('Suma')->limit(1)->find(); $string = 'Empleado con mas Venta'; $html = $this->getPartial('reporte/reporteSeis', array('datos' => $Facturas)); break; case '7': $Facturas = FacturaQuery::create()->where("created_at <= '{$fin} 23:59:59' and created_at >= '{$inicio} 00:00:00'")->groupByCreatedBy()->withColumn('count(id)', 'Suma')->orderBy('Suma')->find(); $string = 'Empleados con mas Ventas'; $html = $this->getPartial('reporte/reporteSeis', array('datos' => $Facturas)); break; case '8': $Producto = MovimientoQuery::create()->where("fecha <= '{$fin}' and fecha >= '{$inicio}'")->groupByProductoId()->withColumn('count(id)', 'Suma')->find(); $Marca = MovimientoQuery::create()->joinWith('Producto')->joinWith('Producto.Marca')->where("movimiento.fecha <= '{$fin}' and movimiento.fecha >= '{$inicio}'")->withColumn('count(marca.id)', 'Suma')->find(); $tipo = MovimientoQuery::create()->joinWith('Producto')->joinWith('Producto.TipoProducto')->where("movimiento.fecha <= '{$fin}' and movimiento.fecha >= '{$inicio}'")->withColumn('count(TipoProducto.id)', 'Suma')->find(); $presentacion = MovimientoQuery::create()->joinWith('Producto')->joinWith('Producto.TipoPresentacion')->where("movimiento.fecha <= '{$fin}' and movimiento.fecha >= '{$inicio}'")->withColumn('count(TipoPresentacion.id)', 'Suma')->find(); $string = 'Resumen de Ventas'; $html = $this->getPartial('reporte/reporteOcho', array('productos' => $Producto, 'marcas' => $Marca, 'tipos' => $tipo, 'presentacion' => $presentacion)); break; case '9': $Pedido = PedidoProveedorQuery::create()->where("estado <> 'Entregado' ")->find(); $string = 'Pedidos en Transito'; $html = $this->getPartial('reporte/reporteNueve', array('datos' => $Pedido)); break; } if ($request->hasParameter('pdf')) { $htmlBase = '<img src="/vendor/dist/img/logo_farmacia.png" style="width:150px"/><br/><h3>' . $string . '</h3><br/>'; $html = $htmlBase . $html; $pdf = new TCPDF("P", "mm", "Letter"); $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('SALUD_INTEGRAL'); $pdf->SetTitle('Reporte'); $pdf->SetSubject('Reporte'); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $pdf->SetHeaderMargin(0.1); $pdf->SetFooterMargin(0.1); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); $pdf->SetFont('dejavusans', '', 7); $pdf->AddPage(); $pdf->writeHTML($html); $pdf->Output('Reporte.pdf', 'D'); die; } } } $this->html = $html; }
/** * Returns the number of related Cliente objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Cliente objects. * @throws PropelException */ public function countClientesRelatedByIdempleadooperaciones(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { $partial = $this->collClientesRelatedByIdempleadooperacionesPartial && !$this->isNew(); if (null === $this->collClientesRelatedByIdempleadooperaciones || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collClientesRelatedByIdempleadooperaciones) { return 0; } if ($partial && !$criteria) { return count($this->getClientesRelatedByIdempleadooperaciones()); } $query = ClienteQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query->filterByEmpleadoRelatedByIdempleadooperaciones($this)->count($con); } return count($this->collClientesRelatedByIdempleadooperaciones); }
public function eliminarAction() { $request = $this->getRequest(); if ($request->isPost()) { $id = $request->getPost('id'); $entity = \EmpleadoQuery::create()->findPk($id); $entity->delete(); //Agregamos un mensaje $this->flashMessenger()->addSuccessMessage('Registro eliminado exitosamente!'); if ($entity->isDeleted()) { return $this->getResponse()->setContent(json_encode(true)); } } $id = $this->params()->fromQuery('id'); /* * VALIDACIONES */ //VALIDAMOS QUE EL EMPLEADO QUE SE QUIERE ELIMINAR NO TENGA ASIGNADO UN CLIENTE/EXPEDIENTE ASIGNADO $valid = true; if (\ClienteQuery::create()->filterByIdempleadocomercial($id)->exists()) { $valid = false; } elseif (\ClienteQuery::create()->filterByIdempleadooperaciones($id)->exists()) { $valid = false; } $viewModel = new ViewModel(); $viewModel->setTerminal(true); $viewModel->setTemplate('admin/catalogo/empleado/eliminar'); if (!$valid) { $viewModel->setTemplate('admin/catalogo/empleado/eliminar_error'); } return $viewModel; }
public function nuevoAction() { $request = $this->getRequest(); $idcliente = $this->params()->fromRoute('id'); $cliente = \ClienteQuery::create()->findPk($idcliente); if ($request->isPost()) { $post_data = $request->getPost(); $entity = new \Expediente(); foreach ($post_data as $key => $value) { if (\ExpedientePeer::getTableMap()->hasColumn($key) && !empty($value) && $key != 'cliente_cumpleanios') { $entity->setByName($key, $value, \BasePeer::TYPE_FIELDNAME); } } //LA FECHA DE APERTURA $entity->setExpedienteFechainicio(new \DateTime()); //EL ESTATUS $entity->setExpedienteEstatus('abierto'); $date = new \DateTime(); $entity->save(); //CREAMOS EL FOLIO $folio = 'ITR' . $date->format('m') . $date->format('y'); if ((int) $entity->getIdexpediente() < 10) { $folio .= '0'; } $folio .= $entity->getIdexpediente(); $entity->setExpedienteFolio($folio); $entity->save(); $mailer = new \Shared\GeneralFunction\Itrademailer(); if ($mailer->newExpedienteEmail($cliente, $folio)) { $this->flashMessenger()->addSuccessMessage('Correo electronico enviado exitosamente!'); } $this->flashMessenger()->addSuccessMessage('Registro guardado exitosamente!'); //REDIRECCIONAMOS A LA ENTIDAD QUE ACABAMOS DE CREAR return $this->redirect()->toUrl('/clientes/ver/' . $idcliente . '/expedientes/ver/' . $entity->getIdexpediente()); } $form = new \Admin\Clientes\Form\ExpedienteForm($idcliente); $view_model = new ViewModel(); $view_model->setTemplate('admin/clientes/expedientes/nuevo'); $view_model->setVariable('form', $form); $view_model->setVariable('cliente', $cliente); return $view_model; }
/** * Returns the number of related Cliente objects. * * @param Criteria $criteria * @param boolean $distinct * @param PropelPDO $con * @return int Count of related Cliente objects. * @throws PropelException */ public function countClientesRelatedByIdCiudad(Criteria $criteria = null, $distinct = false, PropelPDO $con = null) { if (null === $this->collClientesRelatedByIdCiudad || null !== $criteria) { if ($this->isNew() && null === $this->collClientesRelatedByIdCiudad) { return 0; } else { $query = ClienteQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query->filterByCiudadRelatedByIdCiudad($this)->count($con); } } else { return count($this->collClientesRelatedByIdCiudad); } }
/** * Removes this object from datastore and sets delete attribute. * * @param PropelPDO $con * @return void * @throws PropelException * @throws Exception * @see BaseObject::setDeleted() * @see BaseObject::isDeleted() */ public function delete(PropelPDO $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(ClientePeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = ClienteQuery::create()->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); $con->commit(); $this->setDeleted(true); } else { $con->commit(); } } catch (Exception $e) { $con->rollBack(); throw $e; } }
public function executeConfirmar(sfWebRequest $request) { $Factura = FacturaQuery::create()->findOneById($request->getParameter('id')); $Detalles = FacturaDetalleQuery::create()->findByFacturaId($request->getParameter('id')); if (sizeof($Detalles) == 0) { $this->getUser()->setFlash('error', 'No existen productos ingresados en esta factura.'); $this->redirect('venta/detalle?id=' . $request->getParameter('id')); } if ($Factura->getActivo()) { foreach ($Detalles as $detalle) { $fecha = date("d/m/Y"); $Promocion = PromocionQuery::create()->filterByProductoId($detalle->getProductoId())->where("fecha_inicio <= '{$fecha}' and fecha_fin >= '{$fecha}'")->findOne(); $descuento = 1; if ($Promocion) { $descuento = 1 - $Promocion->getDescuento() / 100; } $Movimiento = new Movimiento(); $Movimiento->setTipoMovimiento('-'); $Movimiento->setClienteId($Factura->getClienteId()); $Movimiento->setProductoId($detalle->getProductoId()); $Movimiento->setCantidad($detalle->getCantidad()); $Movimiento->setProveedorId($detalle->getProveedorId()); $Movimiento->setPrecio($detalle->getPrecioUnitario() * $descuento); $Movimiento->setFecha(date('Y-m-d')); $Movimiento->save(); } $BitacoraCambios = new BitacoraCambios(); $BitacoraCambios->setModelo('Factura'); $BitacoraCambios->setIp(sfContext::getInstance()->getRequest()->getRemoteAddress()); $BitacoraCambios->setDescripcion('Creacion de Factura con id: ' . sprintf("%05d", $Factura->getId())); $Usuario = UsuarioQuery::create()->findOneById(sfContext::getInstance()->getUser()->getAttribute('usuario', null, 'seguridad')); if ($Usuario) { $Factura->setCreatedBy($Usuario->getUsuario()); $BitacoraCambios->setCreatedBy($Usuario->getUsuario()); } $BitacoraCambios->save(); $Cliente = ClienteQuery::create()->findOneById($Factura->getClienteId()); if (Factura::obtenerTotal($request->getParameter('id')) >= 200) { $Cliente->setPuntos($Cliente->getPuntos() + 10); $Cliente->save(); } } $Factura->setActivo(false); $Factura->save(); $pdf = new sfTCPDF("P", "mm", "Letter"); $this->id = $request->getParameter("id"); $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('SALUD_INTEGRAL'); $pdf->SetTitle('Factura'); $pdf->SetSubject('Factura'); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); $pdf->SetHeaderMargin(0.1); $pdf->SetFooterMargin(0.1); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); $pdf->SetFont('dejavusans', '', 7); $pdf->AddPage(); $html = ''; $detalles = FacturaDetalleQuery::create()->findByFacturaId($Factura->getId()); $html = $this->getPartial('venta/soporteTabla', array("factura" => $Factura, "detalles" => $detalles)); $pdf->writeHTML($html); $pdf->Output('Factura.pdf', 'D'); }