From 09c2adb73945a0ad62bcc3ef314a4afb0b468fbe Mon Sep 17 00:00:00 2001 From: jorplaz <429-jorplaz@users.noreply.gitlab.inf.uva.es> Date: Tue, 12 Jul 2022 08:43:13 +0200 Subject: [PATCH] Points Function and tests --- README.md | 129 ++++++++++++------ .../Controllers/ElectricBikeController.php | 10 -- .../Controllers/ReservationController.php | 10 -- app/Http/Controllers/RouteController.php | 14 +- app/Http/Resources/ElectricBikeResource.php | 19 --- app/Models/Route.php | 2 + database/seeders/RewardSeeder.php | 10 +- routes/api.php | 2 +- tests/Feature/ExampleTest.php | 21 --- tests/Feature/UnlockBikeTest.php | 43 ++++++ tests/Unit/RouteControllerTest.php | 19 +++ 11 files changed, 166 insertions(+), 113 deletions(-) delete mode 100644 app/Http/Controllers/ElectricBikeController.php delete mode 100644 app/Http/Controllers/ReservationController.php delete mode 100644 app/Http/Resources/ElectricBikeResource.php delete mode 100644 tests/Feature/ExampleTest.php create mode 100644 tests/Feature/UnlockBikeTest.php create mode 100644 tests/Unit/RouteControllerTest.php diff --git a/README.md b/README.md index f171eca..2b866c2 100644 --- a/README.md +++ b/README.md @@ -1,64 +1,105 @@ -<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400"></a></p> +#Retobici Back End -<p align="center"> -<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a> -<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a> -<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a> -<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a> -</p> +## Despliegue Back End -## About Laravel +A continuación se muestran los pasos a seguir para instalar e iniciar +del sistema Back End. Cabe destacar que estos pasos son los referentes +al entorno que se ha utilizado en el proyecto, en este caso se ha +utilizado el propio ordenador portátil como servidor, con un sistema +operativo macOS, por lo que en otro sistema operativo los comandos de +instalación serán diferentes. MacOS ofrece un sistema de paquetes +**[Homebrew](https://brew.sh/)** que facilita enormemente el proceso de +instalación y configuración de la gran mayorÃa de herramientas. -Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as: +### Instalación PHP 8.0.8 -- [Simple, fast routing engine](https://laravel.com/docs/routing). -- [Powerful dependency injection container](https://laravel.com/docs/container). -- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage. -- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent). -- Database agnostic [schema migrations](https://laravel.com/docs/migrations). -- [Robust background job processing](https://laravel.com/docs/queues). -- [Real-time event broadcasting](https://laravel.com/docs/broadcasting). +1. Iniciar un emulador de terminal en cualquier directorio del sistema -Laravel is accessible, powerful, and provides tools required for large, robust applications. +2. Ejecutar el comando `brew install php` -## Learning Laravel +3. Si el sistema no detecta automáticamente la instalación, se puede + cargar en el arranque del terminal de la siguiente manera -Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. + 1. Editar el contenido del fichero `.bashrc` o `.zshrc` dependiendo + de que lenguaje de bash utilices. Normalmente ubicado en el + directorio principal del usuario. Un comando para editar + `vim  /.bashrc` -If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library. + 2. Exporta la ubicación de la instalación de PHP agregando la + siguiente lÃnea `export PATH="/Applications/MAMP/bin/php/php8.0.8/bin:$PATH`. -## Laravel Sponsors +### Instalación PostgreSQL -We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell). +1. Iniciar un emulador de terminal en cualquier directorio del sistema -### Premium Partners +2. Ejecutar el comando `brew install postgresql` -- **[Vehikl](https://vehikl.com/)** -- **[Tighten Co.](https://tighten.co)** -- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)** -- **[64 Robots](https://64robots.com)** -- **[Cubet Techno Labs](https://cubettech.com)** -- **[Cyber-Duck](https://cyber-duck.co.uk)** -- **[Many](https://www.many.co.uk)** -- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)** -- **[DevSquad](https://devsquad.com)** -- **[Curotec](https://www.curotec.com/services/technologies/laravel/)** -- **[OP.GG](https://op.gg)** -- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)** -- **[Lendio](https://lendio.com)** +3. Iniciar el servicio con `brew services start postgres` -## Contributing +4. Entrar en la interfaz de comandos de postgresql con `psql postgres` -Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). +5. Cambiar la contraseña del usuario que se vaya a usar, en este caso + root y de contraseña también root, es recomendable que para un + entorno de producción no se utilice ni el usuario root ni una + contraseña tan débil. El comando serÃa + `ALTER USER root WITH PASSWORD ’password’;` -## Code of Conduct +6. Crear la base de datos con el comando `create database retobici;` -In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). +### Generar claves API Mapbox -## Security Vulnerabilities +Para utilizar el sistema de mapas es necesaria una cuenta y generar las +claves para el uso del sistema. Una vez creada la cuenta, en la +dirección https://account.mapbox.com/ se pueden generar las dos claves, tanto la pública como la privada, que se +usarán más adelante en ambas partes del proyecto. -If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed. +### Instalación Back End -## License +El código se encuentra en este repositorio. -The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). +1. Si no está instalado el sistema de versiones git, el comando para + instalarlo en macOS `brew install git`. + +2. Descargar o clonar el repositorio en el directorio deseado con el + comando\ + `git clone https://gitlab.inf.uva.es/jorplaz/plazalazojorge_2022_backend.git`. + +Ahora, con el código del repositorio descargado es necesario configurar +el entorno del proyecto: + +1. Desde la carpeta raÃz del proyecto copiar el fichero de entorno de + ejemplo con `cp .env.example .env`. + +2. Agregar los contenidos al fichero .env + ``` + DB_CONNECTION=pgsql + DB_HOST=127.0.0.1 + DB_PORT=5432 + DB_DATABASE=retobici + DB_USERNAME=root + DB_PASSWORD=root + MAPBOX_TOKEN=clave pública generada en el paso anterior + ``` + +3. Generar la clave de aplicación con el comando + `php artisan key:generate` + +4. Instalar las dependencias del fichero `composer.yml` con el comando + `composer install` + +Con la instalación y la configuración completada solo serÃa necesario +lanzar el servidor, para ello hay que tener en cuenta de que el proyecto +se ha desarrollado de manera local, entonces para que se comunique la +aplicación Android con el Back End, ambos tienen que estar en la misma +red WiFi. + +1. Obtener la dirección IP del servidor en la red WiFi con el comando + `ifconfig` + +2. Lanzar el servidor apuntando a la IP de la red WiFi obtenida en el + paso anterior\ + `php artisan serv –host=192.168.65.9 –port=8000` + +3. Migrar la base de datos para generar la estructura de las tablas y + poblar la base de datos de información con el comando + `php artisan migrate:fresh –seed` diff --git a/app/Http/Controllers/ElectricBikeController.php b/app/Http/Controllers/ElectricBikeController.php deleted file mode 100644 index cc43434..0000000 --- a/app/Http/Controllers/ElectricBikeController.php +++ /dev/null @@ -1,10 +0,0 @@ -<?php - -namespace App\Http\Controllers; - -use Illuminate\Http\Request; - -class ElectricBikeController extends Controller -{ - // -} diff --git a/app/Http/Controllers/ReservationController.php b/app/Http/Controllers/ReservationController.php deleted file mode 100644 index f7b6132..0000000 --- a/app/Http/Controllers/ReservationController.php +++ /dev/null @@ -1,10 +0,0 @@ -<?php - -namespace App\Http\Controllers; - -use Illuminate\Http\Request; - -class ReservationController extends Controller -{ - // -} diff --git a/app/Http/Controllers/RouteController.php b/app/Http/Controllers/RouteController.php index 7ac0e9a..b75b76f 100644 --- a/app/Http/Controllers/RouteController.php +++ b/app/Http/Controllers/RouteController.php @@ -33,7 +33,6 @@ class RouteController extends Controller public function finishRoute(Request $request){ $route = Route::find($request->id); if($request->missing(['duration', 'final_stop'])){ - //TODO manage Errors return false; } @@ -65,7 +64,16 @@ class RouteController extends Controller return new RouteResource($route); } - private function calculatePoints($route): Int{ - return 50; + public static function calculatePoints($route): Int{ + if ($route->distance<=0) { + return 0; + } + $points = 50+(($route->distance*10)/100)-(($route->duration*5)/60); + if ($points<0) { + return 0; + } + else { + return $points; + } } } diff --git a/app/Http/Resources/ElectricBikeResource.php b/app/Http/Resources/ElectricBikeResource.php deleted file mode 100644 index 56a6caf..0000000 --- a/app/Http/Resources/ElectricBikeResource.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php - -namespace App\Http\Resources; - -use Illuminate\Http\Resources\Json\JsonResource; - -class ElectricBikeResource extends JsonResource -{ - /** - * Transform the resource into an array. - * - * @param \Illuminate\Http\Request $request - * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable - */ - public function toArray($request) - { - return parent::toArray($request); - } -} diff --git a/app/Models/Route.php b/app/Models/Route.php index d33714c..7a79ded 100644 --- a/app/Models/Route.php +++ b/app/Models/Route.php @@ -10,6 +10,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property mixed $user_id * @property \Illuminate\Database\Eloquent\HigherOrderBuilderProxy|mixed $initial_stop_id * @property mixed $bike_id + * @property int|mixed $distance + * @property int|mixed $duration * @method static find(mixed $id) */ class Route extends Model diff --git a/database/seeders/RewardSeeder.php b/database/seeders/RewardSeeder.php index e98dbed..a54e2ea 100644 --- a/database/seeders/RewardSeeder.php +++ b/database/seeders/RewardSeeder.php @@ -16,7 +16,7 @@ class RewardSeeder extends Seeder public function run() { $reward = Reward::create([ - 'name' => 'Reward 1', + 'name' => 'Visita Guiada de Valladolid', 'description' => 'A short description', 'points' => 100, 'total_available' => 5, @@ -24,7 +24,7 @@ class RewardSeeder extends Seeder ]); $reward->users()->sync([1,2]); $reward = Reward::create([ - 'name' => 'Reward 2', + 'name' => 'Restaurante Merinos', 'description' => 'A short description 2', 'points' => 200, 'total_available' => 2, @@ -32,21 +32,21 @@ class RewardSeeder extends Seeder ]); $reward->users()->sync([1]); Reward::create([ - 'name' => 'Reward 3', + 'name' => 'Bar El Corcho', 'description' => 'A short description 3', 'points' => 1000, 'total_available' => 1, "image" => "https://images.unsplash.com/photo-1565599837634-134bc3aadce8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1335&q=80" ]); Reward::create([ - 'name' => 'Reward 4', + 'name' => 'Museo de Escultura de Valladolid', 'description' => 'A short description 4', 'points' => 4, 'total_available' => 10, 'image' => 'https://images.unsplash.com/photo-1617257118084-339d30c49b02?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80' ]); Reward::create([ - 'name' => 'Reward 5', + 'name' => 'Sesión fotográfica profesional', 'description' => 'A short description 5', 'points' => 500, 'total_available' => 5, diff --git a/routes/api.php b/routes/api.php index cbac4b3..2caa2f1 100644 --- a/routes/api.php +++ b/routes/api.php @@ -30,7 +30,7 @@ Route::middleware('auth:sanctum')->group(function (){ Route::post('/stops/{bike}/unlock', [StopController::class, 'unlockBike']); Route::post('/stops/{stop}/reserve/{type}', [StopController::class, 'reserveBike']); - Route::post('/stops/{stop}/lock', [StopController::class, 'lockBike']); + Route::get('/stops/{stop}/lock', [StopController::class, 'lockBike']); Route::put('/routes/{bike}', [RouteController::class, 'createRoute']); Route::post('/routes/finish', [RouteController::class, 'finishRoute']); diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php deleted file mode 100644 index 78ccc21..0000000 --- a/tests/Feature/ExampleTest.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php - -namespace Tests\Feature; - -use Illuminate\Foundation\Testing\RefreshDatabase; -use Tests\TestCase; - -class ExampleTest extends TestCase -{ - /** - * A basic test example. - * - * @return void - */ - public function test_the_application_returns_a_successful_response() - { - $response = $this->get('/'); - - $response->assertStatus(200); - } -} diff --git a/tests/Feature/UnlockBikeTest.php b/tests/Feature/UnlockBikeTest.php new file mode 100644 index 0000000..7b057d1 --- /dev/null +++ b/tests/Feature/UnlockBikeTest.php @@ -0,0 +1,43 @@ +<?php + +namespace Tests\Feature; + +use App\Models\User; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Testing\Fluent\AssertableJson; +use Tests\TestCase; + +class UnlockBikeTest extends TestCase +{ + private const BIKEID = 1; + private const ENDPOINT = "/api/stops/1/unlock"; + private const LOGIN = "/api/login"; + private const PASSWORD = "123456"; + private const EMAIL = "jorge@uva.es"; + + /** + * A basic test example. + * + * @return void + */ + public function test_check_unlocking_availability_endpoint() + { + $login = $this->postJson(self::LOGIN, [ + 'email' => self::EMAIL, + 'password' => self::PASSWORD + ]); + $token = $login->json('token'); + $this->withHeaders([ + 'Authorization' => 'Bearer '. $token, + 'Accept' => 'application/json' + ]) + ->postJson(self::ENDPOINT) + ->assertStatus(200) + ->assertJson(fn(AssertableJson $json) => + $json + ->where('bike_id', self::BIKEID) + ->where('unlocked', false) + ->etc() + ); + } +} diff --git a/tests/Unit/RouteControllerTest.php b/tests/Unit/RouteControllerTest.php new file mode 100644 index 0000000..71b3e13 --- /dev/null +++ b/tests/Unit/RouteControllerTest.php @@ -0,0 +1,19 @@ +<?php + +namespace Tests\Unit; + +use App\Http\Controllers\RouteController; +use App\Models\Route; +use PHPUnit\Framework\TestCase; +use function dump; + +class RouteControllerTest extends TestCase +{ + public function test_calculate_points(){ + $route = new Route(); + $route->distance = 1000; + $route->duration = 600; + $points = RouteController::calculatePoints($route); + dump($points); + } +} -- GitLab