public function postStore() { if (Input::has('porcentaje_especial')) { $porcentaje_vendedor = Input::get('porcentaje_especial'); } else { $porcentaje_comision = ComisionEsquemaVendedor::leftJoin('esquema_comision', 'comision_esquema_vendedor.esquema_comision_id', '=', 'esquema_comision.id')->where('asesor_id', Input::get('asesor_id'))->where('comision_esquema_vendedor.activo', 1)->firstOrFail(); $porcentaje_vendedor = $porcentaje_comision->porcentaje; } $venta = new Venta(); $venta->id = Input::get('venta_id'); $venta->cliente_id = Input::get('cliente_id'); $venta->folio_solicitud = Input::get('folio_solicitud'); $venta->descuento = Input::get('descuento'); $venta->asesor_id = Input::get('asesor_id'); $venta->fecha = Carbon\Carbon::now(); $venta->comentarios = Input::get('comentarios'); $cart = Session::pull('productos', array()); $products = array(); $total = 0; $total_comision = 0; foreach ($cart as $item) { $servicio = VistaServicioFuneral::find($item['producto_id']); if (count($servicio) > 0) { $serv = VistaServicioFuneral::find($item['producto_id']); $total_comision = $serv->monto_comisionable * ($porcentaje_vendedor / 100); } else { $total_comision += ($item['precio'] * $item['cantidad'] - Input::get('descuento') / 1.16) * ($porcentaje_vendedor / 100); } $venta_producto = new VentaProducto(); $venta_producto->venta_id = Input::get('venta_id'); $venta_producto->producto_id = $item['producto_id']; $venta_producto->cantidad = $item['cantidad']; $venta_producto->precio_unitario = $item['precio']; $venta_producto->iva = 16; $venta_producto->total = $item['precio'] * $item['cantidad'] * 1.16; $total += $venta_producto->total; array_push($products, $venta_producto); } $venta->total = $total - $venta->descuento; $plan_pago = PlanPago::find(Input::get('plan_pago')); $plan_pago_venta = new PlanPagoVenta(); $plan_pago_venta->venta_id = Input::get('venta_id'); $plan_pago_venta->plan_pago_id = $plan_pago->id; $plan_pago_venta->fecha_aplicado = Carbon\Carbon::now(); $plan_pago_venta->pago_regular = ($venta->total - $venta->total * $plan_pago->porcentaje_anticipo / 100) / $plan_pago->numero_pagos; $venta->save(); $venta->ventaproducto()->saveMany($products); $venta->planpagoventa()->save($plan_pago_venta); if (!Input::has('directa') && $total_comision > 0) { $comision = new Comision(); $comision->id = Input::get('venta_id'); $comision->asesor_id = Input::get('asesor_id'); $comision->total = $total_comision; $comision->total_comisionable = $total_comision; $comision->numero_pagos = $plan_pago->numero_comisiones; $comision->porcentaje = $porcentaje_vendedor; $venta->comision()->save($comision); } return Redirect::action('CotizacionControlador@getIndex'); }
public function saveVenta() { $this->load->model(array('Venta', 'DetalleVenta')); header("Content-type: application/json"); $postdata = file_get_contents("php://input"); $request = json_decode($postdata); $venta = new Venta(); if (isset($request->folio)) { $venta->load($request->folio); } $venta->fecha = $request->fecha; $venta->cliente = $request->cliente->id; if ($venta->save()) { foreach ($request->deletedRows as $id) { $detalle = new DetalleVenta($id); $detalle->delete(); } foreach ($request->rows as $row) { $detalle = new DetalleVenta(); if (isset($row->id)) { $detalle->load($row->id); } $detalle->venta = $venta->folio; $detalle->cantidad = $row->cantidad; $detalle->producto = $row->producto->codigo; $detalle->iepsUnidad = isset($row->iepsUnidad) && $row->iepsUnidad ? 1 : 0; $detalle->save(); } $venta->loadObjectAttributes(); $response = $this->setDocumentoVenta($venta); echo json_encode(array("success" => true, "ws" => $response)); } else { echo json_encode(array("success" => true)); } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Venta(); if (isset($_POST['Venta'])) { $model->attributes = $_POST['Venta']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->NumVenta)); } } $this->render('create', array('model' => $model)); }
public function vender() { if (Input::has('_token')) { $cliente = Cliente::find(Input::get('cliente_id')); if ($cliente->bloqueado == 1 && $cliente->vip == 0) { return "No se puede vender porque el cliente esta bloqueado..!"; } if ($cliente->saldo + Input::get('monto') > 1000 && $cliente->vip == 0) { return 'No se puede vender porque su deuda pasaria los mil con la venta....'; } $venta = new Venta(); $venta->user_id = Auth::user()->id; $venta->cliente_id = Input::get('cliente_id'); $venta->monto = Input::get('monto'); $venta->descripcion = Input::get('descripcion'); DB::connection('bazar')->table('ventas')->whereId(Input::get('venta_id'))->update(array('total' => Input::get('monto'), 'completed' => 1, 'dpi' => $cliente->dpi, 'dpi_id' => $cliente->id)); if ($cliente->saldo <= 0.0) { $pago = new Pago(); $pago->user_id = Auth::user()->id; $pago->cliente_id = Input::get('cliente_id'); $pago->saldo_anterior = 0; $pago->monto = 0; $pago->saldo_actual = 0; $pago->save(); } if ($venta->save()) { $cliente->saldo = $cliente->saldo + Input::get('monto'); $cliente->bloqueado = 1; if ($cliente->save()) { return Response::json(array('success' => true, 'id' => $venta->id, 'venta_id' => Input::get('venta_id'))); } } return Response::json(array('success' => true)); } $cliente = Cliente::find(Input::get('id')); if ($cliente->inactivo) { return 'no se le puede vender a este cliente porque esta bloquado Permanentemente'; } if ($cliente->estado == 0) { return 'no se le puede vender a este cliente porque esta Inactivo'; } else { if ($cliente->bloqueado == 1 && $cliente->vip == 0) { return 'no se le puede vender a este cliente porque esta Bloqueado'; } } $dias = DB::table('pagos')->select(DB::raw("monto ,DATEDIFF(current_date,max(created_at)) as dias"))->where('cliente_id', '=', Input::get('id'))->first(); $dias_v = DB::table('ventas')->select(DB::raw("monto ,DATEDIFF(current_date,max(created_at)) as dias"))->where('cliente_id', '=', Input::get('id'))->first(); $dia = $dias->dias; $dias_v = $dias->dias; if ($cliente->saldo <= 0) { $dia = 0; } return Response::json(array('success' => true, 'view' => View::make('cliente.vender', compact('cliente', 'dia', 'dias_v'))->render())); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Venta(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Venta'])) { $model->attributes = $_POST['Venta']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their corresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aLugarinventario !== null) { if ($this->aLugarinventario->isModified() || $this->aLugarinventario->isNew()) { $affectedRows += $this->aLugarinventario->save($con); } $this->setLugarinventario($this->aLugarinventario); } if ($this->aServicio !== null) { if ($this->aServicio->isModified() || $this->aServicio->isNew()) { $affectedRows += $this->aServicio->save($con); } $this->setServicio($this->aServicio); } if ($this->aVenta !== null) { if ($this->aVenta->isModified() || $this->aVenta->isNew()) { $affectedRows += $this->aVenta->save($con); } $this->setVenta($this->aVenta); } if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { $this->doInsert($con); } else { $this->doUpdate($con); } $affectedRows += 1; $this->resetModified(); } $this->alreadyInSave = false; } return $affectedRows; }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { date_default_timezone_set('America/Caracas'); // Creamos un nuevo objeto para nuestro nuevo agente $ventas = new Venta(); // Obtenemos la data enviada por el usuario $data = Input::all(); // Revisamos si la data es válido if ($ventas->isValid($data)) { // Si la data es valida se la asignamos al agente $ventas->fill($data); // Guardamos el agente $ventas->save(); // Y Devolvemos una redirección a la acción show para mostrar el agente return Redirect::route('ventas.show', array($ventas->id))->with('create', 'La venta del <b>' . date('d/m/Y', strtotime($ventas->fecha_z)) . '</b> ha sido agregada correctamente.'); } else { // En caso de error regresa a la acción create con los datos y los errores encontrados return Redirect::route('ventas.create')->withInput()->withErrors($ventas->errors); } }
public function actionCreate() { Yii::import('ext.multimodelform.MultiModelForm'); $model = new Venta(); $member = new Detalleventa(); $producto = new Producto(); $cliente = new Cliente(); $validatedMembers = array(); //ensure an empty array if (isset($_POST['Venta'])) { $model->attributes = $_POST['Venta']; if (MultiModelForm::validate($member, $validatedMembers, $deleteItems) && $model->save()) { //the value for the foreign key 'groupid' $masterValues = array('NumVenta' => $model->NumVenta); if (MultiModelForm::save($member, $validatedMembers, $deleteMembers, $masterValues)) { $usuario = Yii::app()->user->name; $numdocumento = $_POST['Venta']['NumVenta']; $forpago = $_POST['Venta']['ForPago']; $rut = $_POST['Venta']['CodCliente']; $descripcion = $_POST['Detalleventa']['Descripcion']; $codigo = $_POST['Detalleventa']['CodProducto']; $cantidad = $_POST['Detalleventa']['Cantidad']; $saldoanterior = $_POST['Detalleventa']['Saldo']; $precio = $_POST['Detalleventa']['Precio']; $subtotal = $_POST['Detalleventa']['Subtotal']; $iva = $_POST['Detalleventa']['Iva']; $unidad = $_POST['Detalleventa']['UniMedida']; for ($i = 0; $i < count($codigo); $i++) { $saldoactual[$i] = $saldoanterior[$i] - $cantidad[$i]; Yii::app()->db->createCommand('update productos set CanExistencia = (CanExistencia - ' . $cantidad[$i] . '),PreCompra=' . $precio[$i] . ',Iva=' . $iva[$i] . ' where CodProducto = "' . $codigo[$i] . '"')->query(); Yii::app()->db->createCommand('insert into kardex (Rut,ForPago,NumDocumento, Descripcion, CodProducto, UniMedida, TipoMovimiento, Cantidad, SaldoAnterior, SaldoActual, Precio,Iva, Subtotal,Usuario)' . ' Values("' . $rut . '",' . $forpago . ',' . $numdocumento . ',"' . $descripcion[$i] . '","' . $codigo[$i] . '","' . $unidad[$i] . '","Venta",' . $cantidad[$i] . ',' . $saldoanterior[$i] . ',' . $saldoactual[$i] . ',' . $precio[$i] . ',' . $iva[$i] . ',' . $subtotal[$i] . ',"' . $usuario . '")')->query(); // } $this->redirect(array('view', 'id' => $model->Id)); } } } $this->render('create', array('model' => $model, 'member' => $member, 'validatedMembers' => $validatedMembers, 'cliente' => $cliente)); }
protected function realizarCompra($producto, $cliente) { $actualizar = ProductoPeer::retrieveByPK($producto); $stock = $actualizar->getStock() - 1; $actualizar->setStock($stock); $actualizar->save(); $fecha = date('Y-m-d'); $nuevo = new Venta(); $nuevo->setIdcliente($cliente); $nuevo->setIdproducto($producto); $nuevo->setFecha($fecha); $nuevo->save(); }
public function asignarAction() { $pacienteQuery = \PacienteQuery::create()->filterByPacienteNombre('Publico')->filterByPacienteAp('en')->filterByPacienteAm('general')->findOne(); $id = $pacienteQuery->getIdpaciente(); $request = $this->getRequest(); // Start Actualizar consulta_status = pagada if ($request->getPost()->subTotalVenta == "0") { if (\VentaQuery::create()->filterByIdventa($request->getPost()->idventa)->exists()) { $ventaActualizarStatus = \VentaQuery::create()->filterByIdventa($request->getPost()->idventa)->findOne(); $ventaActualizarStatus->setVentaStatus($request->getPost()->venta_status)->setVentaReferenciapago($request->getPost()->venta_referenciapago)->setVentaTipodepago($request->getPost()->venta_tipodepago)->setVentaFacturada(0)->setVentaTotal($request->getPost()->venta_total)->save(); $ventaArray = $ventaActualizarStatus->toArray(BasePeer::TYPE_FIELDNAME); return new JsonModel(array('ventaArray' => $ventaArray)); } } // End Actualizar consulta_status = pagada // Start Cancelar Venta if ($request->getPost()->ecancelar == "true") { if (\VentaQuery::create()->filterByIdventa($request->getPost()->idventa)->exists()) { \VentaQuery::create()->filterByIdventa($request->getPost()->idventa)->delete(); return new JsonModel(array('ventaEliminada' => true)); } } // End Cancelar Venta // Start Eliminar cargoventa if ($request->getPost()->idcargoventa) { if ($request->getPost()->eliminar_cargoventa_tipo == 'articulo') { if (\CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->exists()) { $cargoventaEliminado = \CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->findOne(); $lugarinventarioEntity = $cargoventaEliminado->getLugarinventario(); $cantidad = $lugarinventarioEntity->getLugarinventarioCantidad(); $lugarinventarioEntity->setLugarinventarioCantidad($cantidad + $request->getPost()->cantidad); $lugarinventarioEntity->save(); $cargoventaEliminadoArray = array(); if ($cargoventaEliminado->getIdlugarinventario() != null) { $articulovarianteEliminado = $cargoventaEliminado->getLugarinventario()->getOrdencompradetalle()->getArticulovariante(); $propiedadvalorNombreEliminado = null; foreach ($articulovarianteEliminado->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEliminado) { $propiedadEliminadoQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEliminado->getIdpropiedad())->findOne(); $propiedadvalorEliminadoQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEliminado->getIdpropiedadvalor())->findOne(); $propiedadvalorNombreEliminado .= $propiedadEliminadoQuery->getPropiedadNombre() . " " . $propiedadvalorEliminadoQuery->getPropiedadvalorNombre() . " "; } $cargoventaEliminado = array('idcargoventa' => $cargoventaEliminado->getIdcargoventa(), 'idventa' => $cargoventaEliminado->getIdventa(), 'status' => $cargoventaEliminado->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEliminado->getCantidad(), 'articulo' => $cargoventaEliminado->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulo()->getArticuloNombre(), 'descripcion' => utf8_encode($propiedadvalorNombreEliminado), 'salida' => $cargoventaEliminado->getLugarinventario()->getLugar()->getLugarNombre(), 'fechahora' => $cargoventaEliminado->getCargoventaFecha(), 'precio' => $cargoventaEliminado->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulovariantePrecio(), 'subtotal' => $cargoventaEliminado->getMonto()); array_push($cargoventaEliminadoArray, $cargoventaEliminado); } \CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->delete(); $cargoventaQuery = \CargoventaQuery::create()->filterByIdventa($request->getPost()->idventa)->find(); if ($cargoventaQuery->getArrayCopy()) { $cargoventaArray = array(); foreach ($cargoventaQuery as $cargoventaEntity) { if ($cargoventaEntity->getIdlugarinventario() != null) { $articulovarianteEntity = $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante(); $propiedadvalorNombre = null; foreach ($articulovarianteEntity->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity) { $propiedadQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEntity->getIdpropiedad())->findOne(); $propiedadvalorQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEntity->getIdpropiedadvalor())->findOne(); $propiedadvalorNombre .= $propiedadQuery->getPropiedadNombre() . " " . $propiedadvalorQuery->getPropiedadvalorNombre() . " "; } $cargoventa = array('idcargoventa' => $cargoventaEntity->getIdcargoventa(), 'idventa' => $cargoventaEntity->getIdventa(), 'status' => $cargoventaEntity->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEntity->getCantidad(), 'articulo' => $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulo()->getArticuloNombre(), 'descripcion' => utf8_encode($propiedadvalorNombre), 'salida' => $cargoventaEntity->getLugarinventario()->getLugar()->getLugarNombre(), 'fechahora' => $cargoventaEntity->getCargoventaFecha(), 'precio' => $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulovariantePrecio(), 'subtotal' => $cargoventaEntity->getMonto()); array_push($cargoventaArray, $cargoventa); } } } return new JsonModel(array('cargoventaArray' => $cargoventaArray, 'cargoventaEliminadoArray' => $cargoventaEliminadoArray)); } } if ($request->getPost()->eliminar_cargoventa_tipo == 'servicio') { if (\CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->exists()) { $cargoventaEliminado = \CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->findOne(); $cargoventaEliminadoArray = array(); if ($cargoventaEliminado->getIdservicio() != null) { $cargoventaEliminado = array('idcargoventa' => $cargoventaEliminado->getIdcargoventa(), 'idventa' => $cargoventaEliminado->getIdventa(), 'status' => $cargoventaEliminado->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEliminado->getCantidad(), 'servicio' => $cargoventaEliminado->getServicio()->getServicioNombre(), 'descripcion' => $cargoventaEliminado->getServicio()->getServicioDescripcion(), 'precio' => $cargoventaEliminado->getServicio()->getServicioPrecio(), 'subtotal' => $cargoventaEliminado->getMonto(), 'fechahora' => $cargoventaEliminado->getCargoventaFecha()); array_push($cargoventaEliminadoArray, $cargoventaEliminado); } \CargoventaQuery::create()->filterByIdcargoventa($request->getPost()->idcargoventa)->delete(); $cargoventaQuery = \CargoventaQuery::create()->filterByIdventa($request->getPost()->idventa)->find(); if ($cargoventaQuery->getArrayCopy()) { $cargoventaArray = array(); foreach ($cargoventaQuery as $cargoventaEntity) { if ($cargoventaEntity->getIdservicio() != null) { $cargoventa = array('idcargoventa' => $cargoventaEntity->getIdcargoventa(), 'idventa' => $cargoventaEntity->getIdventa(), 'status' => $cargoventaEntity->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEntity->getCantidad(), 'servicio' => $cargoventaEntity->getServicio()->getServicioNombre(), 'descripcion' => $cargoventaEntity->getServicio()->getServicioDescripcion(), 'precio' => $cargoventaEntity->getServicio()->getServicioPrecio(), 'subtotal' => $cargoventaEntity->getMonto(), 'fechahora' => date('Y-m-d H:i:s')); array_push($cargoventaArray, $cargoventa); } } } return new JsonModel(array('cargoventaArray' => $cargoventaArray, 'cargoventaEliminadoArray' => $cargoventaEliminadoArray)); } } } // End Eliminar cargoventa if ($id) { $paciente = PacienteQuery::create()->filterByIdpaciente($id)->findOne(); //Intanciamos nuestro formulario venta $ventaForm = new VentaForm(); //Instanciamos un nuevo objeto de nuestro objeto Paciente $venta = new \Venta(); //Intanciamos nuestro formulario cargoventa "SIN PARAMETROS" $cargoventaForm = new CargoventaForm(); if ($request->getPost()->cargoventaarticulo_by != null) { if ($request->getPost()->cargoventaarticulo_by == 'nombre') { if ($request->getPost()->busquedaArticulo != null) { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->useArticulovarianteQuery()->useArticuloQuery()->filterBy(BasePeer::translateFieldname('articulo', 'articulo_nombre', BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), '%' . $request->getPost()->busquedaArticulo . '%', \Criteria::LIKE)->endUse()->endUse()->find(); } else { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->find(); } } if ($request->getPost()->cargoventaarticulo_by == 'código de barras') { if ($request->getPost()->busquedaArticulo != null) { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->useArticulovarianteQuery()->filterBy(BasePeer::translateFieldname('articulovariante', 'articulovariante_codigobarras', BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), '%' . $request->getPost()->busquedaArticulo . '%', \Criteria::LIKE)->endUse()->find(); } else { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->find(); } } if ($request->getPost()->cargoventaarticulo_by == 'proveedor') { if ($request->getPost()->busquedaArticulo != null) { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->useOrdencompraQuery()->useProveedorQuery()->filterBy(BasePeer::translateFieldname('proveedor', 'proveedor_nombre', BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), '%' . $request->getPost()->busquedaArticulo . '%', \Criteria::LIKE)->endUse()->endUse()->find(); } else { $ordencompradetalleQuery = \OrdencompradetalleQuery::create()->find(); } } if ($ordencompradetalleQuery->getArrayCopy()) { $ordencompradetalleArray = array(); $lugarNombre = null; foreach ($ordencompradetalleQuery as $ordencompradetalleEntity) { /* foreach($ordencompradetalleEntity->getLugarinventarios()->getArrayCopy() as $lugarinventarioEntity){ $idlugarinventario = $lugarinventarioEntity->getIdlugarinventario(); $lugarNombre = $lugarinventarioEntity->getLugar()->getLugarNombre(); $lugarinventarioCantidad = $lugarinventarioEntity->getLugarinventarioCantidad(); $articuloNombre = $ordencompradetalleEntity->getArticulovariante()->getArticulo()->getArticuloNombre(); foreach($ordencompradetalleEntity->getArticulovariante()->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity){ $propiedadQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEntity->getIdpropiedad())->findOne(); $propiedadNombre = $propiedadQuery->getPropiedadNombre(); } foreach($ordencompradetalleEntity->getArticulovariante()->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity){ $propiedadvalorQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEntity->getIdpropiedadvalor())->findOne(); $propiedadvalorNombre = $propiedadvalorQuery->getPropiedadvalorNombre(); } } */ foreach ($ordencompradetalleEntity->getLugarinventarios()->getArrayCopy() as $lugarinventarioEntity) { $idlugarinventario = $lugarinventarioEntity->getIdlugarinventario(); $lugarNombre = $lugarinventarioEntity->getLugar()->getLugarNombre(); $lugarinventarioCantidad = $lugarinventarioEntity->getLugarinventarioCantidad(); $articuloNombre = $ordencompradetalleEntity->getArticulovariante()->getArticulo()->getArticuloNombre(); /* foreach($ordencompradetalleEntity->getArticulovariante()->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity){ $propiedadQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEntity->getIdpropiedad())->findOne(); $propiedadNombre = $propiedadQuery->getPropiedadNombre(); array_push($propiedadArray, $propiedadNombre); } foreach($ordencompradetalleEntity->getArticulovariante()->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity){ $propiedadvalorQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEntity->getIdpropiedadvalor())->findOne(); $propiedadvalorNombre = $propiedadvalorQuery->getPropiedadvalorNombre(); array_push($propiedadValorArray, $propiedadvalorNombre); } */ $propiedadvalorNombre = null; foreach ($ordencompradetalleEntity->getArticulovariante()->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity) { $propiedadQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEntity->getIdpropiedad())->findOne(); $propiedadvalorQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEntity->getIdpropiedadvalor())->findOne(); $propiedadvalorNombre .= $propiedadQuery->getPropiedadNombre() . " " . $propiedadvalorQuery->getPropiedadvalorNombre() . " "; } } $ordencompradetalle = array('idordencompradetalle' => $ordencompradetalleEntity->getIdordencompradetalle(), 'idlugarinventario' => $idlugarinventario, 'cargoventa_tipo' => 'articulo', 'cargoventa_fecha' => date('Y-m-d H:i:s'), 'ordencompradetalle_caducidad' => $ordencompradetalleEntity->getOrdencompradetalleCaducidad(), 'existencia' => $lugarinventarioCantidad, 'articulo' => $articuloNombre, 'descripcion' => utf8_encode($propiedadvalorNombre), 'precio' => $ordencompradetalleEntity->getArticulovariante()->getArticulovariantePrecio(), 'salida' => $lugarNombre); array_push($ordencompradetalleArray, $ordencompradetalle); } } return new JsonModel(array('ordencompradetalleArray' => $ordencompradetalleArray)); } if ($request->getPost()->cargoventaservicio_by != null) { if ($request->getPost()->cargoventaservicio_by == 'nombre') { if ($request->getPost()->busquedaServicio != null) { $servicioQuery = \ServicioQuery::create()->filterBy(BasePeer::translateFieldname('servicio', 'servicio_nombre', BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME), '%' . $request->getPost()->busquedaServicio . '%', \Criteria::LIKE)->find(); } else { $servicioQuery = \ServicioQuery::create()->find(); } } if ($servicioQuery->getArrayCopy()) { $servicioArray = array(); foreach ($servicioQuery as $servicioEntity) { $servicio = array('idservicio' => $servicioEntity->getIdservicio(), 'cargoventa_tipo' => 'servicio', 'cargoventa_fecha' => date('Y-m-d H:i:s'), 'servicio_nombre' => $servicioEntity->getServicioNombre(), 'servicio_descripcion' => $servicioEntity->getServicioDescripcion(), 'servicio_precio' => $servicioEntity->getServicioPrecio()); array_push($servicioArray, $servicio); } } return new JsonModel(array('servicioArray' => $servicioArray)); } // Fin Preparando Form Cargoventa if ($request->isPost()) { //Si hicieron POST //Instanciamos nuestro filtro $ventaFilter = new VentaFilter(); //Le ponemos nuestro filtro a nuesto fromulario $ventaForm->setInputFilter($ventaFilter->getInputFilter()); //Le ponemos los datos a nuestro formulario $ventaForm->setData($request->getPost()); //Validamos nuestro formulario if ($ventaForm->isValid()) { //Recorremos nuestro formulario y seteamos los valores a nuestro objeto Venta foreach ($ventaForm->getData() as $ventaKey => $ventaValue) { if ($ventaKey == 'venta_fecha') { $venta->setVentaFecha($ventaValue . date('H:i:s')); } else { $venta->setByName($ventaKey, $ventaValue, \BasePeer::TYPE_FIELDNAME); } $venta->setVentaStatus('no pagada'); } //Guardamos en nuestra base de datos $venta->save(); $ventaArray = \VentaQuery::create()->filterByIdventa($venta->getIdventa())->findOne()->toArray(BasePeer::TYPE_FIELDNAME); return new JsonModel(array('ventaArray' => $ventaArray)); //Redireccionamos a nuestro list //return $this->redirect()->toRoute('pacientes'); } //Instanciamos nuestro filtro $cargoventaFilter = new CargoventaFilter(); //Le ponemos nuestro filtro a nuesto fromulario $cargoventaForm->setInputFilter($cargoventaFilter->getInputFilter()); //Le ponemos los datos a nuestro formulario $cargoventaForm->setData($request->getPost()); //Validamos nuestro formulario if ($cargoventaForm->isValid()) { $cargoventaArray = array(); if ($request->getPost()->cargoventa_tipo == 'articulo') { //Instanciamos un nuevo objeto de nuestro objeto Paciente $cargoventa = new \Cargoventa(); //Recorremos nuestro formulario y seteamos los valores a nuestro objeto Venta foreach ($cargoventaForm->getData() as $cargoventaKey => $cargoventaValue) { if ($cargoventaKey != 'cargoventaarticulo_by' && $cargoventaKey != 'cargoventaservicio_by' && $cargoventaKey != 'busquedaArticulo' && $cargoventaKey != 'busquedaServicio') { $cargoventa->setByName($cargoventaKey, $cargoventaValue, \BasePeer::TYPE_FIELDNAME); } } // Validar precio, caducidad y existencia de ordencompradetalle $existencia = $cargoventa->getLugarinventario()->getLugarinventarioCantidad(); $caducidad = $cargoventa->getLugarinventario()->getOrdencompradetalle()->getOrdencompradetalleCaducidad(); $precio = $cargoventa->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulovariantePrecio(); if ($existencia > 0) { if ($caducidad < date('Y-m-d')) { $cargoventa->setMonto($request->getPost()->cantidad * $precio); } } //Guardamos en nuestra base de datos $cargoventa->save(); $lugarinventarioQuery = $cargoventa->getLugarinventario(); $lugarinventarioQuery->setLugarinventarioCantidad($lugarinventarioQuery->getLugarinventarioCantidad() - $cargoventa->getCantidad()); $lugarinventarioQuery->save(); $cargoventaQuery = \CargoventaQuery::create()->filterByIdventa($cargoventa->getIdventa())->find(); if ($cargoventaQuery->getArrayCopy()) { foreach ($cargoventaQuery as $cargoventaEntity) { if ($cargoventaEntity->getIdlugarinventario() != null) { $articulovarianteEntity = $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante(); $propiedadvalorNombre = null; foreach ($articulovarianteEntity->getArticulovariantevalors()->getArrayCopy() as $articulovariantevalorEntity) { $propiedadQuery = \PropiedadQuery::create()->filterByIdpropiedad($articulovariantevalorEntity->getIdpropiedad())->findOne(); $propiedadvalorQuery = \PropiedadvalorQuery::create()->filterByIdpropiedadvalor($articulovariantevalorEntity->getIdpropiedadvalor())->findOne(); $propiedadvalorNombre .= $propiedadQuery->getPropiedadNombre() . " " . $propiedadvalorQuery->getPropiedadvalorNombre() . " "; } $cargoventa = array('idcargoventa' => $cargoventaEntity->getIdcargoventa(), 'idventa' => $cargoventaEntity->getIdventa(), 'venta_status' => $cargoventaEntity->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEntity->getCantidad(), 'articulo' => $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulo()->getArticuloNombre(), 'descripcion' => utf8_encode($propiedadvalorNombre), 'salida' => $cargoventaEntity->getLugarinventario()->getLugar()->getLugarNombre(), 'fechahora' => $cargoventaEntity->getCargoventaFecha(), 'precio' => $cargoventaEntity->getLugarinventario()->getOrdencompradetalle()->getArticulovariante()->getArticulovariantePrecio(), 'subtotal' => $cargoventaEntity->getMonto()); array_push($cargoventaArray, $cargoventa); } } } } if ($request->getPost()->cargoventa_tipo == 'servicio') { //Instanciamos un nuevo objeto de nuestro objeto Paciente $cargoventa = new \Cargoventa(); //Recorremos nuestro formulario y seteamos los valores a nuestro objeto Venta foreach ($cargoventaForm->getData() as $cargoventaKey => $cargoventaValue) { if ($cargoventaKey != 'cargoventaarticulo_by' && $cargoventaKey != 'cargoventaservicio_by' && $cargoventaKey != 'busquedaArticulo' && $cargoventaKey != 'busquedaServicio') { $cargoventa->setByName($cargoventaKey, $cargoventaValue, \BasePeer::TYPE_FIELDNAME); } } $precio = $cargoventa->getServicio()->getServicioPrecio(); $cargoventa->setMonto($request->getPost()->cantidad * $precio); //Guardamos en nuestra base de datos $cargoventa->save(); $cargoventaQuery = \CargoventaQuery::create()->filterByIdventa($cargoventa->getIdventa())->find(); if ($cargoventaQuery->getArrayCopy()) { foreach ($cargoventaQuery as $cargoventaEntity) { if ($cargoventaEntity->getIdservicio() != null) { $cargoventa = array('idcargoventa' => $cargoventaEntity->getIdcargoventa(), 'idventa' => $cargoventaEntity->getIdventa(), 'venta_status' => $cargoventaEntity->getVenta()->getVentaStatus(), 'cantidad' => $cargoventaEntity->getCantidad(), 'servicio' => $cargoventaEntity->getServicio()->getServicioNombre(), 'descripcion' => $cargoventaEntity->getServicio()->getServicioDescripcion(), 'precio' => $cargoventaEntity->getServicio()->getServicioPrecio(), 'subtotal' => $cargoventaEntity->getMonto(), 'fechahora' => $cargoventaEntity->getCargoventaFecha()); array_push($cargoventaArray, $cargoventa); } } } } return new JsonModel(array('cargoventaArray' => $cargoventaArray)); } /* else { $messageArray = array(); foreach ($cargoventaForm->getMessages() as $key => $value){ foreach($value as $val){ //Obtenemos el valor de la columna con error $message = $key.' '.$val; array_push($messageArray, $message); } } var_dump($messageArray); return new ViewModel(array( 'input_error' => $messageArray )); }*/ } return new ViewModel(array('pacienteEntity' => $paciente, 'ventaForm' => $ventaForm, 'cargoventaForm' => $cargoventaForm)); } else { return $this->redirect()->toRoute('pacientes'); } }
function agregarDireccion($idDireccion) { $mdb2 = conectar(); $ventas = new Venta($mdb2['dsn']); $ventas->setSelect('idVenta'); $ventas->setWhere("idUsuario = " . $_SESSION['usuario']['idUsuario']); $ventas = $ventas->getAll(); for ($i = 0; $i < sizeof($ventas); $i++) { $arrayData = array("idVenta" => $ventas[$i]['idVenta'], "idDireccion" => $idDireccion); $venta = new Venta($mdb2['dsn']); $venta->save($arrayData); } }
public function postRenovacion() { $precio = Precio::where('producto_id', Input::get('producto_id'))->where('activo', 1)->firstorfail(); $mtto_detalle = VistaDetalleMantenimiento::find(Input::get('id')); $mtto_catalogo = Mantenimiento::where('producto_id', Input::get('producto_id'))->firstorfail(); //para obtener los meses a sumar en el mantenimiento renovado $vencimiento_actual = $mtto_detalle->fecha_fin; $vencimiento_actual_carbon = Carbon::parse($vencimiento_actual); //validar formulario $rules = array('forma_pago' => 'required'); if (Input::get('valor_efectivo') == 1 and Input::has('efectivo')) { $rules['efectivo'] = 'required|numeric|integer'; } if (Input::get('valor_credito') == 1 and Input::has('credito')) { $rules['credito'] = 'required|numeric|integer'; } if (Input::get('valor_debito') == 1 and Input::has('debito')) { $rules['debito'] = 'required|numeric|integer'; } $messages = array('required' => 'Capture :attribute', 'numeric' => 'solo números', 'integer' => 'solo se aceptan valores enteros'); $validator = Validator::make(Input::all(), $rules, $messages); if ($validator->fails()) { return Redirect::back()->withInput()->withErrors($validator); } //mantenimiento vencido toma la fecha de hoy if ($mtto_detalle->vencido == 1 and $mtto_detalle->venta_mantenimiento_activo == 1) { $inicio_renovacion_carbon = Carbon::now()->toDateString(); $vencimiento_renovacion_carbon = Carbon::parse($inicio_renovacion_carbon)->addMonths($mtto_catalogo->meses)->toDateString(); } elseif ($mtto_detalle->vencido == 0 and $mtto_detalle->venta_mantenimiento_activo == 1) { $inicio_renovacion_carbon = $vencimiento_actual_carbon->addDays(1)->toDateString(); $vencimiento_renovacion_carbon = Carbon::parse($inicio_renovacion_carbon)->addMonths($mtto_catalogo->meses)->toDateString(); } /*"precio"." ".$precio->monto*1.16." "."vencimiento actual "." ".$vencimiento_actual." ". "vencimiento contratado "." ". $vencimiento_renovacion_carbon ." "."meses"." ".$mtto_catalogo->meses." "."inicio del nuevo mantenimiento "." ". $inicio_renovacion_carbon;*/ //registrar venta $venta = new Venta(); $venta->cliente_id = Input::get('cliente_id'); $venta->folio_solicitud = Input::get('folio_solicitud'); $venta->total = $precio->monto * Input::get('iva'); if (Input::get('comentarios')) { $venta->comentarios = Input::get('comentarios'); } $venta->save(); //registrar detalle de venta $venta_producto = new VentaProducto(); $venta_producto->venta_id = $venta->id; $venta_producto->producto_id = Input::get('producto_id'); $venta_producto->cantidad = 1; $venta_producto->total = $precio->monto * Input::get('iva'); $venta_producto->precio_unitario = $precio->monto; $venta_producto->iva = (Input::get('iva') - 1) * 100; $venta_producto->save(); //registra venta de mantenimiento $venta_mantenimiento = new VentaMantenimiento(); $venta_mantenimiento->venta_producto_id = $venta_producto->id; $venta_mantenimiento->empleado_id = 4; $venta_mantenimiento->lote_id = Input::get('lote_id'); $venta_mantenimiento->fecha_inicio = $inicio_renovacion_carbon; $venta_mantenimiento->fecha_fin = $vencimiento_renovacion_carbon; $venta_mantenimiento->nuevo = 0; $venta_mantenimiento->activo = 1; $venta_mantenimiento->save(); //genera recibo $recibo = new Recibo(); $recibo->venta_id = $venta->id; $recibo->fecha_limite = $inicio_renovacion_carbon; $recibo->monto = $venta_producto->total; $recibo->cancelado = 0; $recibo->pagado = 1; $recibo->mensajero = 0; $recibo->save(); //registra pago(s) if (Input::has('efectivo')) { $efectivo = Input::get('efectivo'); $pago_efectivo = new Pago(); $pago_efectivo->recibo_id = $recibo->id; $pago_efectivo->forma_pago_id = 1; $pago_efectivo->monto = $efectivo; $pago_efectivo->usuario_id = Auth::user()->id; $pago_efectivo->save(); } if (Input::has('credito')) { $efectivo = Input::get('credito'); $pago_efectivo = new Pago(); $pago_efectivo->recibo_id = $recibo->id; $pago_efectivo->forma_pago_id = 2; $pago_efectivo->monto = $efectivo; $pago_efectivo->usuario_id = Auth::user()->id; $pago_efectivo->save(); } if (Input::has('debito')) { $efectivo = Input::get('debito'); $pago_efectivo = new Pago(); $pago_efectivo->recibo_id = $recibo->id; $pago_efectivo->forma_pago_id = 5; $pago_efectivo->monto = $efectivo; $pago_efectivo->usuario_id = Auth::user()->id; $pago_efectivo->save(); } //actualiza registro anterior de venta de mantenimiento ya que dejará de ser "nuevo" $venta_mantenimiento_actualiza = VentaMantenimiento::find($mtto_detalle->id); $venta_mantenimiento_actualiza->nuevo = 0; $venta_mantenimiento_actualiza->activo = 0; $venta_mantenimiento_actualiza->save(); //actualiza el ultimo consecutivo de folios de mantenimiento en tabla de configuracion general $config_gral = ConfiguracionGeneral::find(Input::get('config_gral_id')); $config_gral->folio_mtto = Input::get('folio_solicitud'); $config_gral->save(); return Redirect::to('mantenimiento'); }
public function actionProcesa_pago() { $varSession = Yii::app()->GenericFunctions->getVariableSession(); // inicializamos la variable de session de acuerdo al idioma $idioma = Yii::app()->language; $email_test = array("*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"); $txtIp = Yii::app()->GenericFunctions->obtenerIP(); $monedaCobro = $varSession['booking']['moneda']; $numAdults = $varSession['booking']['adult']; $numChilds = $varSession['booking']['child']; /* datos del solicitante */ $txtNombre = $_POST['nombre']; $txtApellido = $_POST['apellido']; $txtEmail = $_POST['email']; $txtPais = $_POST['pais']; $txtEstado = $_POST['estado']; $txtTel = $_POST['phone']; $txtComentarios = $_POST['comments']; $txtDireccion = $_POST['address']; if (Yii::app()->params['Moneda'] == 'MXN' && Yii::app()->language == 'es') { $GatewayMethod = explode("_", $_POST['cant_pagos']); print_r($GatewayMethod); if ($GatewayMethod[1] == 1) { Yii::app()->Santander->setVars("4018", "001", "MEX", "4018WEUS0", "4018WEUS0", "15365", "3", "MXN", "A7BEC7D1", "prod"); } else { if ($GatewayMethod[1] == 3) { Yii::app()->Santander->setVars("4018", "001", "MEX", "4018WEUS0", "4018WEUS0", "15531", "3", "MXN", "A7BEC7D1", "prod"); } else { if ($GatewayMethod[1] == 6) { Yii::app()->Santander->setVars("4018", "001", "MEX", "4018WEUS0", "4018WEUS0", "15532", "3", "MXN", "A7BEC7D1", "prod"); } } } if (in_array($txtEmail, $email_test)) { Yii::app()->Santander->setVars("1141", "002", "MEX", "1141SIUS0", "1141SIUS0", "52863", "3", "MXN", "114AF671", "dev"); } } else { if (in_array($txtEmail, $email_test)) { Yii::app()->Santander->setVars("1141", "002", "MEX", "1141SIUS0", "1141SIUS0", "52868", "3", "USD", "114AF671", "dev"); } } //insertar el cliente en la bd de lomas $_Cliente = new Cliente(); $_Cliente->cliente_nombre = $txtNombre; $_Cliente->cliente_apellido = $txtApellido; $_Cliente->cliente_email = $txtEmail; $_Cliente->cliente_pais_n = $txtPais; $_Cliente->cliente_domicilio = $txtDireccion; $_Cliente->cliente_estado = $txtEstado; $_Cliente->cliente_ciudad = ''; $_Cliente->cliente_postal_code = ''; $_Cliente->cliente_telefono = $txtTel; $_Cliente->cliente_comentario = $txtComentarios; if ($_Cliente->save()) { $clientId = $_Cliente->cliente_id; } else { $_SESSION['error']['Tabla'] = "Cliente"; $_SESSION['error'] = "Cliente no Guardado, Imposible continuar .."; ////////////////////////////// error si el cliente no se guarda //Para que no se recarge la pagina y realize los cobros //Yii::app()->GenericFunctions->setNullVariableSession(); header("Location: /transaction_error"); } $nombres_adultos = ""; $nombres_ninios = ""; $detalles_adultos = ""; $detalles_ninios = ""; for ($i = 1; $i <= $numAdults; $i++) { $nombres_adultos .= ucwords(trim($_POST['adult_adult_' . $i])); $nombres_adultos .= ";"; $detalles_adultos .= ucwords(trim($_POST['adult_adult_' . $i])) . "," . ucwords(trim($_POST['weight_adult_' . $i])) . ',' . ucwords(trim($_POST['medida_adult_' . $i])) . ',' . ucwords(trim($_POST['height_adult_' . $i])) . ',' . ucwords(trim($_POST['edad_adult_' . $i])); $detalles_adultos .= ";"; } for ($i = 1; $i <= $numChilds; $i++) { $nombres_ninios .= ucwords(trim($_POST['child_' . $i])); $nombres_ninios .= ";"; $detalles_ninios .= ucwords(trim($_POST['child_' . $i])) . "," . ucwords(trim($_POST['weight_child_' . $i])) . ',' . ucwords(trim($_POST['medida_child_' . $i])) . ',' . ucwords(trim($_POST['height_child_' . $i])) . ',' . ucwords(trim($_POST['edad_child_' . $i])); $detalles_ninios .= ";"; } $_Venta = new Venta(); $_Venta->venta_session_id = 's/n'; $_Venta->venta_moneda = $varSession['booking']['moneda']; /* Para colocar el sitio en la venta 23= ingles y 22= español*/ if (Yii::app()->language != 'es') { $_Venta->venta_site_id = 23; } else { $_Venta->venta_site_id = 22; } /* */ $_Venta->venta_user_id = $clientId; $_Venta->venta_estt = 1; $_Venta->venta_total = $varSession['booking']['total']; // total de la venta $_Venta->venta_fecha = date("Y-m-d H:i:s"); $_Venta->venta_hotel = $varSession['booking']['salida']; // $_Venta->venta_ip = $txtIp; // la ip actual $_Venta->venta_authcode = 'Santander'; // el tipo de tarjeta santander,amex .. etc $_Venta->venta_observacion = $txtComentarios; $_Venta->tipo_pago = 2; $_Venta->tipo_cambio = $varSession['booking']['tipoCambio']; if ($_Venta->save()) { $Venta = $_Venta->venta_id; // id de la venta } else { $_SESSION['error']['Tabla'] = "Venta"; $_SESSION['error'] = $_Venta->getErrors(); //Para que no se recarge la pagina y realize los cobros //Yii::app()->GenericFunctions->setNullVariableSession(); header("Location: /transaction_error"); } if ($idioma != 'es') { $txtFolioReserva = "BNZ-" . $Venta; // Folio de la venta } else { $txtFolioReserva = "BNX-" . $Venta; // Folio de la venta } $date_ = explode("/", $varSession['booking']['date']); if (Yii::app()->language != 'es') { $date = $date_[2] . $date_[0] . $date_[1]; // convertir de formato ingles } else { $date = $date_[2] . $date_[1] . $date_[0]; // convertir de formato español } $descripciones_tarifa = array(8 => "Cancun", 9 => "Puerto Morelos", 11 => "Riviera Maya", 20 => "Tulum", 10 => "Playa del Carmen"); $descripcion = "Departing from " . $descripciones_tarifa[$varSession['booking']['zona']] . ", Time: " . $varSession['booking']['departureTime']; if (Yii::app()->language == 'es') { $descripcion = "Saliendo de " . $descripciones_tarifa[$varSession['booking']['zona']] . ", Hora: " . $varSession['booking']['departureTime']; } $hotel = new VentaDescripcion(); // venta del hotel $hotel->descripcion_producto = $varSession['booking']['txtTour']; // $hotel->descripcion_destino = 0; // $hotel->descripcion_brief = "n/a"; $hotel->descripcion_tarifa = $descripcion; $hotel->descripcion_venta = $Venta; //Id de la venta $hotel->descripcion_fecha = date("Y-m-d H:i:s"); // $hotel->descripcion_fecha1 = $date; // $hotel->descripcion_fecha2 = $date; // $hotel->descripcion_adultos = intval($varSession['booking']['adult']); // $hotel->descripcion_menores = intval($varSession['booking']['child']); // $hotel->descripcion_infantes = 0; $hotel->descripcion_cuartos = 0; // $hotel->descripcion_precio = $varSession['booking']['tarifas']['tar_adult']; // if (intval($varSession['booking']['child']) != 0) { $hotel->descripcion_precio_nino = $varSession['booking']['tarifas']['tar_adult']; $hotel->descripcion_total_nino = $varSession['booking']['tarifas']['tar_child'] * intval($varSession['booking']['child']); } $hotel->descripcion_total = $varSession['booking']['total']; // $hotel->hotel_huesped = $varSession['booking']['salida']; $hotel->descripcion_hotel2 = "n/a"; $hotel->descripcion_tipo_producto = 2; // tipo de producto 1 porque es hotel $hotel->descripcion_servicio_ini = 1; $hotel->descripcion_servicio_id = $txtFolioReserva; $hotel->descripcion_reservable = 1; $hotel->descripcion_pagado = 0; $hotel->tipo_translado = 1; $hotel->detalles_adultos = $detalles_adultos; $hotel->detalles_ninos = $detalles_ninios; $hotel->observaciones = $txtComentarios; $hotel->descripcion_thumb = "http://lomastravel.com.mx/carta_confirmacion/bonanza_new.png"; $hotel->descripcion_producto_id = 1005; if ($hotel->save()) { $id_venta_hotel = $hotel->descripcion_id; } else { $_SESSION['error']['Tabla'] = "Descripcion"; $_SESSION['error'] = $hotel->getErrors(); //Para que no se recarge la pagina y realize los cobros //Yii::app()->GenericFunctions->setNullVariableSession(); header("Location: /transaction_error"); } /*print_r("<pre>"); print_r($detalles_adultos); print_r($_REQUEST); exit();*/ $granTotal = $varSession['booking']['total']; // se aplica cargo en santander $xml = Yii::app()->Santander->makeXML($txtFolioReserva, $clientId, $granTotal, $_REQUEST["card_name"], trim($_REQUEST["card_number"]), trim($_REQUEST["card_month"]), trim($_REQUEST["card_year"]), trim($_REQUEST["card_code"])); $iService = Yii::app()->Santander->callService($xml); $answerSantander = get_object_vars($iService); foreach ($answerSantander as $k => $v) { if (is_object($v)) { $answerSantander[$k] = get_object_vars($v); } } $tmpTns = array_merge($answerSantander, $_POST); /* Se guardan el resultado de la transferencia sea cual sea */ $_tns = new VentaTns(); $_tns->venta_id = $Venta; $_tns->venta_fecha = date("Y-m-d H:i:s"); $_tns->venta_data = serialize($tmpTns); if ($_tns->save()) { $venta_tns = $_tns->venta_data_id; } else { $_SESSION['error']['Tabla'] = "Transferencia"; $_SESSION['error'] = $_tns->getErrors(); header("Location: /transaction_error"); } if ($iService->response == "approved") { $authCode = $iService->auth; $auth = "Santander"; $sucess = true; $ventaUserid = Venta::model()->findByPk($Venta); $ventaUserid->venta_estt = "2"; $ventaUserid->venta_autorizador = $authCode; $ventaUserid->venta_total = $granTotal; $ventaUserid->save(); $_Tarjeta = new Tarjeta(); $_Tarjeta->tarjeta_cliente = $clientId; $_Tarjeta->tarjeta_venta = $Venta; $_Tarjeta->Ecom_Payment_Name = $_REQUEST["card_name"]; $_Tarjeta->Ecom_Payment_Card_Number = $_REQUEST["card_number"]; $_Tarjeta->Ecom_Payment_Card_Month = "0"; $_Tarjeta->Ecom_Payment_Card_Year = "0"; $_Tarjeta->save(); /* si la pagina esta en ingles se cambia la url de donde se toman las cartas confirma */ $link_papeleta = "http://www.lomastravel.com/voucher.html?id=" . Yii::app()->GenericFunctions->ProtectVar($id_venta_hotel); /* si la pagina esta en español se cambia la url de donde se toman las cartas confirma */ if (Yii::app()->language == 'es') { $link_papeleta = "http://www.lomastravel.com.mx/cupon.html?id=" . Yii::app()->GenericFunctions->ProtectVar($id_venta_hotel); } /* si es un test se cambia la peticion de la papeleta a local */ if (in_array($txtEmail, $email_test)) { $link_papeleta = "http://lomasbeta.dev/voucher.html?id=" . Yii::app()->GenericFunctions->ProtectVar($id_venta_hotel); /*si la pagina esta en español se cambia la url de donde se toman las cartas confirma */ if (Yii::app()->language == 'es') { $link_papeleta = "http://lomasmx.dev/cupon.html?id=" . Yii::app()->GenericFunctions->ProtectVar($id_venta_hotel); } } //print_r(Yii::app()->GenericFunctions->ProtectVar($Hotel->descripcion_id)); $info = file_get_contents($link_papeleta); if ($info == "") { $info = "No cargo ningun datos del link proporcionado"; } if ($idioma == 'es') { $varsession = $_SESSION['bookin_ES']; } else { $varsession = $_SESSION['bookin']; } require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/phpmailer_v5_1/class.phpmailer.php"; $m["mail_titulo"] = "Lomas Travel | Carta de Servicio | #" . $id_venta_hotel; // Titulo del email $email_carrusel = "*****@*****.**"; $email_webmaster = "*****@*****.**"; //Correo que se le va a enviar al cliente $correoC = new PHPMailer(true); $correoC->isSMTP(); $correoC->Host = "smtp.gmail.com"; $correoC->SMTPAuth = true; $correoC->Username = "******"; $correoC->Password = "******"; $correoC->SMTPSecure = "tls"; $correoC->Port = 587; $correoC->From = "*****@*****.**"; $correoC->FromName = "Rancho Bonanza"; $correoC->Subject = $m["mail_titulo"]; $correoC->MsgHTML($info); $correoC->AddAddress($txtEmail, "Cliente Lomas Travel"); $correoC->AddCC($email_carrusel, "Lomas Travel"); $correoC->IsHTML(true); $correoC->Send(); $correoC->ClearAddresses(); //Correos que se van a enviar a ventas y respaldo $correoA->isSMTP(); $correoA->Host = "smtp.gmail.com"; $correoA->SMTPAuth = true; $correoA->Username = "******"; $correoA->Password = "******"; $correoA->SMTPSecure = "tls"; $correoA->Port = 587; $correoA->From = "*****@*****.**"; $correoA->FromName = "Rancho Bonanza"; $correoA->AddAddress("*****@*****.**"); $correoA->AddAddress($email_webmaster); $correoA->AddCC($email_webmaster); $correoA->AddCC("*****@*****.**"); $correoA->Subject = $m["mail_titulo"]; $correoA->MsgHTML($info); $correoA->IsHTML(true); $correoA->Send(); $correoA->ClearAddresses(); Yii::app()->GenericFunctions->setNullVariableSession(); // BORRAMOS LA VARIABLE DE SESSION header("Location: /transaction_aproved?ref=" . Yii::app()->GenericFunctions->ProtectVar($id_venta_hotel)); } else { if ($iService->response == "denied") { //Insertar Estado de la venta $ventaUserid = Venta::model()->findByPk($Venta); $ventaUserid->venta_estt = "7"; $ventaUserid->venta_total = $granTotal; $ventaUserid->save(); $_SESSION['error'] = $_tns->getErrors(); //Para que no se recarge la pagina y realize los cobros // Yii::app()->GenericFunctions->setNullVariableSession(); header("Location: /transaction_denied?ref=" . $iService->friendly_response); exit; } else { //Insertar Estado de la venta $ventaUserid = Venta::model()->findByPk($Venta); $ventaUserid->venta_estt = "6"; $ventaUserid->venta_total = $granTotal; $ventaUserid->save(); // Insertar Estado de la venta //Para que no se recarge la pagina y realize los cobros // Yii::app()->GenericFunctions->setNullVariableSession(); header("Location: /transaction_error?ref=" . $iService->nb_error); exit; } } }
function compraCarrito() { $mdb2 = conectar(); $ventas = new Venta($mdb2['dsn']); $ventas->setSelect('idVenta'); $ventas->addSelect(TABLA_PRODUCTO . '.idProducto AS idProducto'); $ventas->addSelect(TABLA_PRODUCTO . '.vecesComprado AS vecesComprado'); $ventas->setWhere("idUsuario = " . $_SESSION['usuario']['idUsuario']); $ventas->addWhere("carrito = 1"); $ventas->setJoin(TABLA_PRODUCTO, "venta.idProducto = " . TABLA_PRODUCTO . ".idProducto", inner); $ventas = $ventas->getAll(); for ($i = 0; $i < sizeof($ventas); $i++) { $arrayData = array("idProducto" => $ventas[$i]["idProducto"], "vecesComprado" => $ventas[$i]["vecesComprado"] + 1); $producto = new Producto($mdb2['dsn']); $producto->save($arrayData); $arrayData = array("idVenta" => $ventas[$i]['idVenta'], "carrito" => 0, "fecha" => date("Y-m-d H:i:s")); $venta = new Venta($mdb2['dsn']); $venta->save($arrayData); } }