public function listarAction() { $collection = \FacturaQuery::create()->orderByIdfactura('DESC')->filterByFacturaStatus('cancelada')->find(); $arr = array(); foreach ($collection->toArray(null, false, \BasePeer::TYPE_FIELDNAME) as $entity) { $fecha = new \DateTime($entity['factura_fecha']); $tmp['id'] = $entity['idfactura']; $tmp['fecha'] = $fecha->format('d-m-Y H:s'); if (!is_null($entity['idadmision'])) { $tmp['movimiento'] = 'ADM-' . $entity['idadmision']; } else { if (!is_null($entity['idconsulta'])) { $tmp['movimiento'] = 'CON-' . $entity['idconsulta']; } else { $tmp['movimiento'] = 'VP-' . $entity['idventa']; } } $tmp['uuid'] = $entity['factura_cfdi']; $arr[] = $tmp; } return new ViewModel(array('collection' => $arr, 'flashMessages' => $this->flashMessenger()->getSuccessMessages())); }
/** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this Cliente is new, it will return * an empty collection; or if this Cliente has previously * been saved, it will retrieve related Facturas from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in Cliente. * * @param Criteria $criteria optional Criteria object to narrow the query * @param PropelPDO $con optional connection object * @param string $join_behavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return PropelObjectCollection|Factura[] List of Factura objects */ public function getFacturasJoinTipoPago($criteria = null, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $query = FacturaQuery::create(null, $criteria); $query->joinWith('TipoPago', $join_behavior); return $this->getFacturas($query, $con); }
/** * Get the associated Factura object * * @param PropelPDO $con Optional Connection object. * @return Factura The associated Factura object. * @throws PropelException */ public function getFactura(PropelPDO $con = null) { if ($this->aFactura === null && $this->factura_id !== null) { $this->aFactura = FacturaQuery::create()->findPk($this->factura_id, $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->aFactura->addFacturaDetalles($this); */ } return $this->aFactura; }
/** * 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; }
/** * Executes index action * * @param sfRequest $request A request object */ public function executeIndex(sfWebRequest $request) { $this->facturas = FacturaQuery::create()->findByActivo(true); }
/** * 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(FacturaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = FacturaQuery::create()->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); // symfony_behaviors behavior foreach (sfMixer::getCallables('BaseFactura: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('BaseFactura: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 enviarAction() { $request = $this->getRequest(); if ($request->isPost()) { $post_data = $request->getPost(); $factura = \FacturaQuery::create()->findPk($post_data['id']); $file = $factura->getFacturaUrlXml(); $file = explode('/tmp/xml/', $file); $file = explode('.', $file[1]); $file = $file[0]; $xml = $file . '.xml'; $pdf = $file . '.pdf'; $mail = new \PHPMailer(); $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = '******'; $mail->Password = '******'; $mail->Port = 25; $mail->From = '*****@*****.**'; $mail->FromName = 'HOSPITAL DEL VALLE DE ATEMAJAC'; $mail->addAddress($post_data['email']); // Add a recipient $mail->addAttachment($_SERVER['DOCUMENT_ROOT'] . "/tmp/xml/" . $xml); $mail->addAttachment($_SERVER['DOCUMENT_ROOT'] . "/tmp/pdf/" . $pdf); $mail->isHTML(true); $mail->Subject = 'FACTURA ELECTRONICA'; $mail->Body = 'Buen dia, Le enviamos adjunto su factura elctronica. Saludos!'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if (!$mail->send()) { return $this->getResponse()->setContent(\Zend\Json\Json::encode(array('response' => false, 'msg' => 'Existio un error durante el envio, por favor intentelo mas tarde'))); } else { return $this->getResponse()->setContent(\Zend\Json\Json::encode(array('response' => true, 'msg' => 'Correo electronico enviado satisfactoriamente!'))); } $my_file = $pdf; // puede ser cualquier formato $my_path = $_SERVER['DOCUMENT_ROOT'] . "/tmp/pdf/"; $my_name = "HOSPITAL DEL VALLE DE ATEMAJAC"; $my_mail = "*****@*****.**"; $my_replyto = "*****@*****.**"; $my_subject = "FACTURA ELECTRONICA"; $my_message = ""; $envio = $this->mail_attachment($my_file, $my_path, $post_data['email'], $my_mail, $my_name, $my_replyto, $my_subject, $my_message); if ($envio) { return $this->getResponse()->setContent(\Zend\Json\Json::encode(array('response' => true, 'msg' => 'Correo electronico enviado satisfactoriamente!'))); } else { return $this->getResponse()->setContent(\Zend\Json\Json::encode(array('response' => false, 'msg' => 'Existio un error durante el envio, por favor intentelo mas tarde'))); } } if ($this->params()->fromQuery('id')) { $id = $this->params()->fromQuery('id'); $factura = \FacturaQuery::create()->findPk($id); $idpaciente = $factura->getPacientefacturacion()->getPaciente()->getIdpaciente(); $facturacion = \PacientefacturacionQuery::create()->filterByIdpaciente($idpaciente)->find(); $emails = array(); foreach ($facturacion as $data) { $email = $data->getPacientefacturacionEmail(); if (!is_null($email) && !empty($email)) { $emails[$data->getIdpacientefacturacion()] = $email; } } $viewModel = new ViewModel(); $viewModel->setTerminal(true); $viewModel->setVariable('id', $id); $viewModel->setVariable('emails', $emails); return $viewModel; } $this->getResponse()->setStatusCode(404); return; }
public function indexAction() { //Hacemos una peticion a todas nuestras admisiones $admisiones = \AdmisionQuery::create()->orderByIdadmision('asc')->find(); $general_array = array(); //Comenzamos a itinerar para darl el formato que necesitamos foreach ($admisiones as $admision) { $tmp['fecha'] = new \DateTime($admision->getAdmisionFechaadmision()); $tmp['fecha'] = $tmp['fecha']->format('d-m-Y'); $tmp['movimiento'] = 'ADM-' . $admision->getIdadmision(); $tmp['paciente'] = $admision->getPaciente()->getPacienteNombre() . ' ' . $admision->getPaciente()->getPacienteAp() . ' ' . $admision->getPaciente()->getPacienteAm(); $tmp['medico'] = $admision->getMedico()->getMedicoNombre() . ' ' . $admision->getMedico()->getMedicoApellidopaterno() . ' ' . $admision->getMedico()->getMedicoApellidomaterno(); $tmp['diagnostico'] = $admision->getAdmisionDiagnostico(); $tmp['status_pago'] = $admision->getAdmisionStatus(); //Verificar con George $rs = \FacturaQuery::create()->findOneByIdadmision($admision->getIdadmision()); $tmp['razon_social'] = $rs; if (!is_null($rs) && $rs->getAdmision()->getAdmisionFacturada(true)) { $tmp['razon_social'] = $rs->getPacientefacturacion()->getPacientefacturacionRazonsocial(); } else { $tmp['razon_social'] = NULL; } //Pagos $tmp['total'] = $admision->getAdmisionTotal(); $tmp['efectivo'] = \AdmisionanticipoQuery::create()->filterByIdadmision($admision->getIdadmision())->filterByAdmisionanticipoTipo('Efectivo')->withColumn('SUM(admisionanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['efectivo'] = $tmp['efectivo']['total']; $tmp['tarjeta'] = \AdmisionanticipoQuery::create()->filterByIdadmision($admision->getIdadmision())->filterByAdmisionanticipoTipo(array('Tarjeta de debito', 'Tarjeta de credito'))->withColumn('SUM(admisionanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['tarjeta'] = $tmp['tarjeta']['total']; $tmp['cheque'] = \AdmisionanticipoQuery::create()->filterByIdadmision($admision->getIdadmision())->filterByAdmisionanticipoTipo('Cheque')->withColumn('SUM(admisionanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['cheque'] = $tmp['cheque']['total']; $tmp['spei'] = \AdmisionanticipoQuery::create()->filterByIdadmision($admision->getIdadmision())->filterByAdmisionanticipoTipo('SPEI')->withColumn('SUM(admisionanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['spei'] = $tmp['spei']['total']; //Verificar con George (status alta/admision) $admision_salida = $admision->getAdmisionFechasalida(); if (is_null($admision_salida)) { $tmp['status'] = 'Admisión'; } else { $tmp['status'] = 'Alta'; } $general_array[] = $tmp; } $consultas = \ConsultaQuery::create()->orderByIdconsulta('asc')->find(); //Comenzamos a itinerar para darl el formato que necesitamos foreach ($consultas as $consulta) { $tmp['fecha'] = new \DateTime($consulta->getConsultaFecha()); $tmp['fecha'] = $tmp['fecha']->format('d-m-Y'); $tmp['movimiento'] = 'CON-' . $consulta->getIdconsulta(); $tmp['paciente'] = $consulta->getPaciente()->getPacienteNombre() . ' ' . $consulta->getPaciente()->getPacienteAp() . ' ' . $consulta->getPaciente()->getPacienteAm(); $tmp['medico'] = $consulta->getMedico()->getMedicoNombre() . ' ' . $consulta->getMedico()->getMedicoApellidopaterno() . ' ' . $consulta->getMedico()->getMedicoApellidomaterno(); $tmp['diagnostico'] = $consulta->getConsultaDiagnostico(); $tmp['status_pago'] = $consulta->getConsultaStatus(); //Verificar con George $rs = \FacturaQuery::create()->findOneByIdconsulta($consulta->getIdconsulta()); if (!is_null($rs) && $rs->getConsulta()->getConsultaFacturada(true)) { $tmp['razon_social'] = $rs->getPacientefacturacion()->getPacientefacturacionRazonsocial(); } else { $tmp['razon_social'] = NULL; } //Pagos $tmp['total'] = $consulta->getConsultaTotal(); $tmp['efectivo'] = \ConsultaanticipoQuery::create()->filterByIdconsulta($consulta->getIdconsulta())->filterByConsultaanticipoTipo('Efectivo')->withColumn('SUM(consultaanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['efectivo'] = $tmp['efectivo']['total']; $tmp['tarjeta'] = \ConsultaanticipoQuery::create()->filterByIdconsulta($consulta->getIdconsulta())->filterByConsultaanticipoTipo(array('Tarjeta de debito', 'Tarjeta de credito'))->withColumn('SUM(consultaanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['tarjeta'] = $tmp['tarjeta']['total']; $tmp['cheque'] = \ConsultaanticipoQuery::create()->filterByIdconsulta($consulta->getIdconsulta())->filterByConsultaanticipoTipo('Cheque')->withColumn('SUM(consultaanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['cheque'] = $tmp['cheque']['total']; $tmp['spei'] = \ConsultaanticipoQuery::create()->filterByIdconsulta($consulta->getIdconsulta())->filterByConsultaanticipoTipo('SPEI')->withColumn('SUM(consultaanticipo_cantidad)', 'total')->findOne()->toArray(); $tmp['spei'] = $tmp['spei']['total']; //Verificar con George (status alta/admision) $consulta_status = $consulta->getConsultaStatus(); if ($consulta_status != 'pagada') { $tmp['status'] = 'En Consulta'; } else { $tmp['status'] = 'Consultado'; } $general_array[] = $tmp; } return new ViewModel(array('reportes' => $general_array)); }
public function cancelarAction() { if ($this->params()->fromRoute('id')) { $id = $this->params()->fromRoute('id'); $factura = \FacturaQuery::create()->findPk($id); //Verificamos si la factura esta dentros del rango permitido $current_date = new \DateTime(); $current_month = $current_date->format('m'); $factura_month = $factura->getFacturaFecha('m'); if ($current_month != $factura_month) { $this->flashMessenger()->addErrorMessage('Lo sentimos pero no es posible cancelar esta factura ya que no fue emitida en el mes en curso'); return $this->redirect()->toUrl('/facturacion/emitidas'); } # Read the x509 certificate file on PEM format and encode it on base64 $cerpem = file_get_contents(__DIR__ . '/../Certificados/aad990814bp7_1210261233s.cer.pem'); # Read the Encrypted Private Key (des3) file on PEM format and encode it on base64 $keypem = file_get_contents(__DIR__ . '/../Certificados/aad990814bp7_1210261233s.key.pem'); $taxpayer_id = $this->emisorArr['rfc']; # The RFC of the Emisor $invoices = array($factura->getFacturaCfdi()); # A list of UUIDs $url = "http://demo-facturacion.finkok.com/servicios/soap/cancel.wsdl"; $client = new \SoapClient($url); $params = array("UUIDS" => array('uuids' => $invoices), "username" => '*****@*****.**', "password" => 'Hva2015#', "taxpayer_id" => $taxpayer_id, "cer" => $cerpem, "key" => $keypem); $response = $client->__soapCall("cancel", array($params)); if ($response->cancelResult->Folios->Folio->EstatusUUID == 202) { $this->flashMessenger()->addErrorMessage('Se produjo un error al intentar cancelar la factura, por favor refresque e intente nuevamente'); } else { //Si no hubo problema al cancelar $factura->setFacturaStatus('cancelada'); $factura->setFacturaFecha($response->cancelResult->Fecha); $factura->save(); //Cambiamos el status de la admision/venta/consutla if (!is_null($factura->getIdadmision())) { $admision = $factura->getAdmision(); $admision->setAdmisionFacturada(0); $admision->save(); } elseif (!is_null($factura->getIdconsulta())) { $consulta = $factura->getConsulta(); $consulta->setConsultaFacturada(0); $consulta->save(); } else { $venta = $factura->getVenta(); $venta->setVentaFacturada(0); $venta->save(); } $this->flashMessenger()->addSuccessMessage('Factura cancelada exitosamente!'); return $this->redirect()->toUrl('/facturacion/canceladas'); } } $this->getResponse()->setStatusCode(404); return; }
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'); }
/** * 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(FacturaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE); } $con->beginTransaction(); try { $deleteQuery = FacturaQuery::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; } }