From 17a824f9259a5963cba062d86315fb8d61a8a8f2 Mon Sep 17 00:00:00 2001 From: javier Date: Thu, 18 Jun 2026 09:05:20 +0200 Subject: [PATCH] =?UTF-8?q?feat(api):=20mobile=20API=20Milestone=201+2=20?= =?UTF-8?q?=E2=80=94=20Sanctum=20auth=20+=20offline=20sync=20vertical=20sl?= =?UTF-8?q?ice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Milestone 1 (auth foundation): - Installed laravel/sanctum; HasApiTokens on User; published config + migration. - routes/api.php with /api/v1; Sanctum 'ability' middleware alias registered. - AuthController: POST login (long-lived revocable device token w/ ability mobile-sync + devices table), GET me, POST logout. New Device model/table. Milestone 2 (vertical slice, offline-first): - progress_updates: +uuid (client-generated) +client_updated_at. - ProjectApiController: GET projects (accessibleBy), GET projects/{id}/bundle (project/phases/layers/features, membership-authorized). - SyncController: POST sync — batch ops, idempotent by uuid, per-op result (applied/duplicate/error), server-set user_id, authz by permission+membership. Currently handles progress_update.create. Tests: tests/Feature/Api/MobileApiTest (9 passing) — auth, accessible projects, bundle authz, sync apply+idempotency, permission enforcement. Also fixed a latent schema bug: projects.reference (and external_reference_1) existed in the live DB but had no migration — added a guarded migration so fresh installs match production. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Controllers/Api/V1/AuthController.php | 80 ++++++++ .../Api/V1/ProjectApiController.php | 79 ++++++++ .../Controllers/Api/V1/SyncController.php | 105 ++++++++++ app/Models/Device.php | 21 ++ app/Models/ProgressUpdate.php | 3 +- app/Models/User.php | 5 +- bootstrap/app.php | 5 +- composer.json | 1 + composer.lock | 71 ++++++- config/sanctum.php | 87 ++++++++ ...45_create_personal_access_tokens_table.php | 33 +++ ...2026_06_18_070000_create_devices_table.php | 28 +++ ..._sync_fields_to_progress_updates_table.php | 31 +++ ...070200_add_reference_to_projects_table.php | 37 ++++ routes/api.php | 25 +++ tests/Feature/Api/MobileApiTest.php | 191 ++++++++++++++++++ 16 files changed, 794 insertions(+), 8 deletions(-) create mode 100644 app/Http/Controllers/Api/V1/AuthController.php create mode 100644 app/Http/Controllers/Api/V1/ProjectApiController.php create mode 100644 app/Http/Controllers/Api/V1/SyncController.php create mode 100644 app/Models/Device.php create mode 100644 config/sanctum.php create mode 100644 database/migrations/2026_06_18_065745_create_personal_access_tokens_table.php create mode 100644 database/migrations/2026_06_18_070000_create_devices_table.php create mode 100644 database/migrations/2026_06_18_070100_add_sync_fields_to_progress_updates_table.php create mode 100644 database/migrations/2026_06_18_070200_add_reference_to_projects_table.php create mode 100644 routes/api.php create mode 100644 tests/Feature/Api/MobileApiTest.php diff --git a/app/Http/Controllers/Api/V1/AuthController.php b/app/Http/Controllers/Api/V1/AuthController.php new file mode 100644 index 0000000..dcf6e5f --- /dev/null +++ b/app/Http/Controllers/Api/V1/AuthController.php @@ -0,0 +1,80 @@ +validate([ + 'email' => ['required', 'email'], + 'password' => ['required', 'string'], + 'device_name' => ['required', 'string', 'max:255'], + 'app_version' => ['nullable', 'string', 'max:50'], + ]); + + $user = User::where('email', $data['email'])->first(); + + if (! $user || ! Hash::check($data['password'], $user->password)) { + throw ValidationException::withMessages([ + 'email' => [__('auth.failed')], + ]); + } + + // One token per device name: revoke the previous one for this device. + $user->tokens()->where('name', $data['device_name'])->delete(); + + $token = $user->createToken($data['device_name'], ['mobile-sync']); + + Device::updateOrCreate( + ['user_id' => $user->id, 'name' => $data['device_name']], + [ + 'token_id' => $token->accessToken->id, + 'app_version' => $data['app_version'] ?? null, + 'last_seen_at' => now(), + ] + ); + + return response()->json([ + 'token' => $token->plainTextToken, + 'user' => $this->userPayload($user), + ]); + } + + public function me(Request $request) + { + return response()->json(['user' => $this->userPayload($request->user())]); + } + + public function logout(Request $request) + { + $token = $request->user()->currentAccessToken(); + + // Clean up the device record bound to this token. + Device::where('token_id', $token->id)->delete(); + $token->delete(); + + return response()->json(['message' => 'Logged out']); + } + + private function userPayload(User $user): array + { + return [ + 'id' => $user->id, + 'name' => $user->name, + 'email' => $user->email, + 'roles' => $user->getRoleNames(), + 'permissions' => $user->getAllPermissions()->pluck('name')->values(), + ]; + } +} diff --git a/app/Http/Controllers/Api/V1/ProjectApiController.php b/app/Http/Controllers/Api/V1/ProjectApiController.php new file mode 100644 index 0000000..756bfa0 --- /dev/null +++ b/app/Http/Controllers/Api/V1/ProjectApiController.php @@ -0,0 +1,79 @@ +user()) + ->orderBy('name') + ->get(['id', 'reference', 'name', 'address', 'status', 'lat', 'lng', 'updated_at']); + + return response()->json(['projects' => $projects]); + } + + /** + * Offline bundle for one project (Milestone 2 — minimal: structure, no media yet). + */ + public function bundle(Request $request, Project $project) + { + $user = $request->user(); + abort_unless( + $user->can('manage all') || $project->users()->where('user_id', $user->id)->exists(), + 403 + ); + + $project->load([ + 'phases' => fn ($q) => $q->orderBy('order'), + 'phases.layers', + 'phases.layers.features', + ]); + + $layers = $project->phases->flatMap->layers; + $features = $layers->flatMap->features; + + return response()->json([ + 'server_time' => now()->toIso8601String(), + 'project' => [ + 'id' => $project->id, + 'reference' => $project->reference, + 'name' => $project->name, + 'address' => $project->address, + 'lat' => $project->lat, + 'lng' => $project->lng, + 'status' => $project->status, + 'updated_at' => $project->updated_at?->toIso8601String(), + ], + 'phases' => $project->phases->map(fn ($p) => [ + 'id' => $p->id, + 'name' => $p->name, + 'order' => $p->order, + 'color' => $p->color, + 'progress_percent' => $p->progress_percent, + 'updated_at' => $p->updated_at?->toIso8601String(), + ])->values(), + 'layers' => $layers->map(fn ($l) => [ + 'id' => $l->id, + 'phase_id' => $l->phase_id, + 'name' => $l->name, + 'color' => $l->color, + 'updated_at' => $l->updated_at?->toIso8601String(), + ])->values(), + 'features' => $features->map(fn ($f) => [ + 'id' => $f->id, + 'layer_id' => $f->layer_id, + 'name' => $f->name, + 'geometry' => $f->geometry, + 'status' => $f->status, + 'progress' => $f->progress, + 'updated_at' => $f->updated_at?->toIso8601String(), + ])->values(), + ]); + } +} diff --git a/app/Http/Controllers/Api/V1/SyncController.php b/app/Http/Controllers/Api/V1/SyncController.php new file mode 100644 index 0000000..32aa0ef --- /dev/null +++ b/app/Http/Controllers/Api/V1/SyncController.php @@ -0,0 +1,105 @@ +validate([ + 'operations' => ['required', 'array'], + 'operations.*.entity' => ['required', 'string'], + 'operations.*.op' => ['required', 'string'], + 'operations.*.uuid' => ['required', 'uuid'], + 'operations.*.data' => ['required', 'array'], + 'operations.*.client_updated_at' => ['nullable', 'date'], + ]); + + $user = $request->user(); + $results = []; + + foreach ($data['operations'] as $op) { + $results[] = $this->handle($user, $op); + } + + return response()->json(['results' => $results]); + } + + private function handle(User $user, array $op): array + { + $uuid = $op['uuid']; + + try { + if ($op['entity'] === 'progress_update' && $op['op'] === 'create') { + return $this->progressUpdateCreate($user, $uuid, $op); + } + + return $this->error($uuid, 'unsupported entity/op: ' . $op['entity'] . '.' . $op['op']); + } catch (\Throwable $e) { + return $this->error($uuid, $e->getMessage()); + } + } + + private function progressUpdateCreate(User $user, string $uuid, array $op): array + { + // Idempotency: same uuid already applied → duplicate (no-op). + $existing = ProgressUpdate::where('uuid', $uuid)->first(); + if ($existing) { + return ['uuid' => $uuid, 'status' => 'duplicate', 'server_id' => $existing->id]; + } + + $validator = Validator::make($op['data'], [ + 'phase_id' => ['required', 'integer', 'exists:phases,id'], + 'progress' => ['required', 'integer', 'min:0', 'max:100'], + 'comment' => ['nullable', 'string'], + 'location' => ['nullable', 'array'], + ]); + if ($validator->fails()) { + return $this->error($uuid, 'validation: ' . $validator->errors()->first()); + } + $d = $validator->validated(); + + $phase = Phase::with('project')->findOrFail($d['phase_id']); + + // Authorization: project membership + permission (per-op, never abort the batch). + $isMember = $user->can('manage all') + || ($phase->project && $phase->project->users()->where('user_id', $user->id)->exists()); + if (! $isMember || ! $user->can('update progress')) { + return $this->error($uuid, 'forbidden'); + } + + $pu = ProgressUpdate::create([ + 'uuid' => $uuid, + 'phase_id' => $phase->id, + 'user_id' => $user->id, // server-set, never trust client + 'progress_percent' => $d['progress'], + 'comment' => $d['comment'] ?? null, + 'location' => $d['location'] ?? null, + 'client_updated_at' => $op['client_updated_at'] ?? null, + ]); + + // Mirror the web behaviour: reflect latest progress on the phase. + $phase->progress_percent = $d['progress']; + $phase->save(); + + return ['uuid' => $uuid, 'status' => 'applied', 'server_id' => $pu->id]; + } + + private function error(string $uuid, string $message): array + { + return ['uuid' => $uuid, 'status' => 'error', 'error' => $message]; + } +} diff --git a/app/Models/Device.php b/app/Models/Device.php new file mode 100644 index 0000000..4fe6947 --- /dev/null +++ b/app/Models/Device.php @@ -0,0 +1,21 @@ + 'datetime', + ]; + + public function user() + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Models/ProgressUpdate.php b/app/Models/ProgressUpdate.php index 86608d5..972745e 100644 --- a/app/Models/ProgressUpdate.php +++ b/app/Models/ProgressUpdate.php @@ -7,11 +7,12 @@ use Illuminate\Database\Eloquent\Model; class ProgressUpdate extends Model { protected $fillable = [ - 'phase_id', 'user_id', 'progress_percent', 'comment', 'location' + 'uuid', 'phase_id', 'user_id', 'progress_percent', 'comment', 'location', 'client_updated_at' ]; protected $casts = [ 'location' => 'array', // Store as [lat, lng] + 'client_updated_at' => 'datetime', ]; public function phase() diff --git a/app/Models/User.php b/app/Models/User.php index ce8163a..872e730 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -7,12 +7,13 @@ use Database\Factories\UserFactory; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; -use Spatie\Permission\Traits\HasRoles; +use Laravel\Sanctum\HasApiTokens; +use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { /** @use HasFactory */ - use HasFactory, Notifiable, HasRoles; + use HasFactory, Notifiable, HasRoles, HasApiTokens; /** * The attributes that are mass assignable. diff --git a/bootstrap/app.php b/bootstrap/app.php index 0976f79..ff6354c 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -7,17 +7,20 @@ use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', + api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { $middleware->appendToGroup('web', \App\Http\Middleware\SetLocale::class); - // Spatie permission middleware aliases + // Spatie permission + Sanctum ability middleware aliases $middleware->alias([ 'role' => \Spatie\Permission\Middleware\RoleMiddleware::class, 'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class, 'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class, + 'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class, + 'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class, ]); }) ->withExceptions(function (Exceptions $exceptions): void { diff --git a/composer.json b/composer.json index a28d320..ad57328 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,7 @@ "blade-ui-kit/blade-heroicons": "^2.7", "gasparesganga/php-shapefile": "^3.4", "laravel/framework": "^12.0", + "laravel/sanctum": "^4.3", "laravel/tinker": "^2.10.1", "league/geotools": "^1.3", "livewire/livewire": "^3.6.4", diff --git a/composer.lock b/composer.lock index 1f87a7e..f8de404 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1b74f08906a514a8a24b6e299587d9f3", + "content-hash": "45553317b713050f78b4233c204790f9", "packages": [ { "name": "blade-ui-kit/blade-heroicons", @@ -1753,6 +1753,69 @@ }, "time": "2026-04-20T16:07:33+00:00" }, + { + "name": "laravel/sanctum", + "version": "v4.3.2", + "source": { + "type": "git", + "url": "https://github.com/laravel/sanctum.git", + "reference": "2a9bccc18e9907808e0018dd15fa643937886b1e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/sanctum/zipball/2a9bccc18e9907808e0018dd15fa643937886b1e", + "reference": "2a9bccc18e9907808e0018dd15fa643937886b1e", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/console": "^11.0|^12.0|^13.0", + "illuminate/contracts": "^11.0|^12.0|^13.0", + "illuminate/database": "^11.0|^12.0|^13.0", + "illuminate/support": "^11.0|^12.0|^13.0", + "php": "^8.2", + "symfony/console": "^7.0|^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.6", + "orchestra/testbench": "^9.15|^10.8|^11.0", + "phpstan/phpstan": "^1.10" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Sanctum\\SanctumServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Sanctum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.", + "keywords": [ + "auth", + "laravel", + "sanctum" + ], + "support": { + "issues": "https://github.com/laravel/sanctum/issues", + "source": "https://github.com/laravel/sanctum" + }, + "time": "2026-04-30T11:46:25+00:00" + }, { "name": "laravel/serializable-closure", "version": "v2.0.12", @@ -10429,12 +10492,12 @@ ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": {}, "prefer-stable": true, "prefer-lowest": false, "platform": { "php": "^8.2" }, - "platform-dev": [], - "plugin-api-version": "2.6.0" + "platform-dev": {}, + "plugin-api-version": "2.9.0" } diff --git a/config/sanctum.php b/config/sanctum.php new file mode 100644 index 0000000..cde73cf --- /dev/null +++ b/config/sanctum.php @@ -0,0 +1,87 @@ + explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( + '%s%s', + 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', + Sanctum::currentApplicationUrlWithPort(), + // Sanctum::currentRequestHost(), + ))), + + /* + |-------------------------------------------------------------------------- + | Sanctum Guards + |-------------------------------------------------------------------------- + | + | This array contains the authentication guards that will be checked when + | Sanctum is trying to authenticate a request. If none of these guards + | are able to authenticate the request, Sanctum will use the bearer + | token that's present on an incoming request for authentication. + | + */ + + 'guard' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Expiration Minutes + |-------------------------------------------------------------------------- + | + | This value controls the number of minutes until an issued token will be + | considered expired. This will override any values set in the token's + | "expires_at" attribute, but first-party sessions are not affected. + | + */ + + 'expiration' => null, + + /* + |-------------------------------------------------------------------------- + | Token Prefix + |-------------------------------------------------------------------------- + | + | Sanctum can prefix new tokens in order to take advantage of numerous + | security scanning initiatives maintained by open source platforms + | that notify developers if they commit tokens into repositories. + | + | See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning + | + */ + + 'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''), + + /* + |-------------------------------------------------------------------------- + | Sanctum Middleware + |-------------------------------------------------------------------------- + | + | When authenticating your first-party SPA with Sanctum you may need to + | customize some of the middleware Sanctum uses while processing the + | request. You may change the middleware listed below as required. + | + */ + + 'middleware' => [ + 'authenticate_session' => AuthenticateSession::class, + 'encrypt_cookies' => EncryptCookies::class, + 'validate_csrf_token' => ValidateCsrfToken::class, + ], + +]; diff --git a/database/migrations/2026_06_18_065745_create_personal_access_tokens_table.php b/database/migrations/2026_06_18_065745_create_personal_access_tokens_table.php new file mode 100644 index 0000000..40ff706 --- /dev/null +++ b/database/migrations/2026_06_18_065745_create_personal_access_tokens_table.php @@ -0,0 +1,33 @@ +id(); + $table->morphs('tokenable'); + $table->text('name'); + $table->string('token', 64)->unique(); + $table->text('abilities')->nullable(); + $table->timestamp('last_used_at')->nullable(); + $table->timestamp('expires_at')->nullable()->index(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('personal_access_tokens'); + } +}; diff --git a/database/migrations/2026_06_18_070000_create_devices_table.php b/database/migrations/2026_06_18_070000_create_devices_table.php new file mode 100644 index 0000000..0b2e91a --- /dev/null +++ b/database/migrations/2026_06_18_070000_create_devices_table.php @@ -0,0 +1,28 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('name'); // device_name del login + $table->unsignedBigInteger('token_id')->nullable(); // id del personal_access_token actual + $table->string('app_version')->nullable(); + $table->timestamp('last_seen_at')->nullable(); + $table->timestamps(); + + $table->unique(['user_id', 'name']); + }); + } + + public function down(): void + { + Schema::dropIfExists('devices'); + } +}; diff --git a/database/migrations/2026_06_18_070100_add_sync_fields_to_progress_updates_table.php b/database/migrations/2026_06_18_070100_add_sync_fields_to_progress_updates_table.php new file mode 100644 index 0000000..9b1d714 --- /dev/null +++ b/database/migrations/2026_06_18_070100_add_sync_fields_to_progress_updates_table.php @@ -0,0 +1,31 @@ +uuid('uuid')->nullable()->unique()->after('id'); + } + if (! Schema::hasColumn('progress_updates', 'client_updated_at')) { + $table->timestamp('client_updated_at')->nullable()->after('location'); + } + }); + } + + public function down(): void + { + Schema::table('progress_updates', function (Blueprint $table) { + foreach (['uuid', 'client_updated_at'] as $col) { + if (Schema::hasColumn('progress_updates', $col)) { + $table->dropColumn($col); + } + } + }); + } +}; diff --git a/database/migrations/2026_06_18_070200_add_reference_to_projects_table.php b/database/migrations/2026_06_18_070200_add_reference_to_projects_table.php new file mode 100644 index 0000000..4bba0d6 --- /dev/null +++ b/database/migrations/2026_06_18_070200_add_reference_to_projects_table.php @@ -0,0 +1,37 @@ +string('reference')->nullable()->after('id'); + } + if (! Schema::hasColumn('projects', 'external_reference_1')) { + $table->string('external_reference_1')->nullable()->after('reference'); + } + }); + } + + public function down(): void + { + Schema::table('projects', function (Blueprint $table) { + foreach (['reference', 'external_reference_1'] as $col) { + if (Schema::hasColumn('projects', $col)) { + $table->dropColumn($col); + } + } + }); + } +}; diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..d798a05 --- /dev/null +++ b/routes/api.php @@ -0,0 +1,25 @@ +group(function () { + + // Público + Route::post('login', [AuthController::class, 'login'])->middleware('throttle:10,1'); + + // Protegido: token Sanctum con ability 'mobile-sync' + Route::middleware(['auth:sanctum', 'ability:mobile-sync'])->group(function () { + Route::get('me', [AuthController::class, 'me']); + Route::post('logout', [AuthController::class, 'logout']); + + // PULL + Route::get('projects', [ProjectApiController::class, 'index']); + Route::get('projects/{project}/bundle', [ProjectApiController::class, 'bundle']); + + // PUSH + Route::post('sync', [SyncController::class, 'sync'])->middleware('throttle:60,1'); + }); +}); diff --git a/tests/Feature/Api/MobileApiTest.php b/tests/Feature/Api/MobileApiTest.php new file mode 100644 index 0000000..3938886 --- /dev/null +++ b/tests/Feature/Api/MobileApiTest.php @@ -0,0 +1,191 @@ + 'TEST-1', + 'name' => 'Proyecto Test', + 'address' => 'Calle Falsa 123', + 'lat' => 40.0, + 'lng' => -3.0, + 'start_date' => now()->toDateString(), + 'end_date_estimated' => now()->addMonths(6)->toDateString(), + 'status' => 'in_progress', + 'created_by' => $member?->id ?? User::factory()->create()->id, + ]); + + if ($member) { + $project->users()->attach($member->id, ['role_in_project' => 'supervisor']); + } + + return $project; + } + + private function makePhase(Project $project): Phase + { + return Phase::create([ + 'project_id' => $project->id, + 'name' => 'Fase 1', + 'order' => 1, + 'color' => '#3b82f6', + 'progress_percent' => 0, + ]); + } + + // ── Auth ─────────────────────────────────────────────────────────────────── + + public function test_login_returns_a_token(): void + { + $user = User::factory()->create(); + + $res = $this->postJson('/api/v1/login', [ + 'email' => $user->email, + 'password' => 'password', + 'device_name' => 'Pixel-Test', + ]); + + $res->assertOk()->assertJsonStructure(['token', 'user' => ['id', 'email', 'permissions']]); + $this->assertDatabaseHas('devices', ['user_id' => $user->id, 'name' => 'Pixel-Test']); + } + + public function test_login_fails_with_wrong_password(): void + { + $user = User::factory()->create(); + + $this->postJson('/api/v1/login', [ + 'email' => $user->email, + 'password' => 'incorrecta', + 'device_name' => 'Pixel-Test', + ])->assertStatus(422); + } + + public function test_me_requires_authentication(): void + { + $this->getJson('/api/v1/me')->assertStatus(401); + } + + public function test_me_returns_user_with_token(): void + { + $user = User::factory()->create(); + Sanctum::actingAs($user, ['mobile-sync']); + + $this->getJson('/api/v1/me') + ->assertOk() + ->assertJsonPath('user.id', $user->id); + } + + // ── Pull ───────────────────────────────────────────────────────────────────── + + public function test_projects_index_only_returns_accessible_projects(): void + { + $user = User::factory()->create(); + $mine = $this->makeProject($user); + $other = $this->makeProject(); // not a member + + Sanctum::actingAs($user, ['mobile-sync']); + + $res = $this->getJson('/api/v1/projects')->assertOk(); + $ids = collect($res->json('projects'))->pluck('id'); + $this->assertTrue($ids->contains($mine->id)); + $this->assertFalse($ids->contains($other->id)); + } + + public function test_bundle_is_forbidden_for_non_member(): void + { + $user = User::factory()->create(); + $project = $this->makeProject(); // user is not a member + + Sanctum::actingAs($user, ['mobile-sync']); + + $this->getJson("/api/v1/projects/{$project->id}/bundle")->assertStatus(403); + } + + public function test_bundle_returns_structure_for_member(): void + { + $user = User::factory()->create(); + $project = $this->makeProject($user); + $phase = $this->makePhase($project); + + Sanctum::actingAs($user, ['mobile-sync']); + + $this->getJson("/api/v1/projects/{$project->id}/bundle") + ->assertOk() + ->assertJsonPath('project.id', $project->id) + ->assertJsonPath('phases.0.id', $phase->id); + } + + // ── Push (sync) ────────────────────────────────────────────────────────────── + + public function test_sync_creates_progress_update_and_is_idempotent(): void + { + $user = User::factory()->create(); + $user->givePermissionTo('update progress'); + $project = $this->makeProject($user); + $phase = $this->makePhase($project); + $uuid = (string) Str::uuid(); + + Sanctum::actingAs($user, ['mobile-sync']); + + $payload = ['operations' => [[ + 'entity' => 'progress_update', 'op' => 'create', 'uuid' => $uuid, + 'client_updated_at' => now()->toIso8601String(), + 'data' => ['phase_id' => $phase->id, 'progress' => 75, 'comment' => 'Avance'], + ]]]; + + // First push → applied + $this->postJson('/api/v1/sync', $payload) + ->assertOk() + ->assertJsonPath('results.0.status', 'applied'); + + $this->assertDatabaseHas('progress_updates', ['uuid' => $uuid, 'progress_percent' => 75, 'user_id' => $user->id]); + $this->assertEquals(75, $phase->fresh()->progress_percent); + + // Re-send same uuid → duplicate (no second row) + $this->postJson('/api/v1/sync', $payload) + ->assertOk() + ->assertJsonPath('results.0.status', 'duplicate'); + + $this->assertEquals(1, ProgressUpdate::where('uuid', $uuid)->count()); + } + + public function test_sync_returns_error_without_permission(): void + { + $user = User::factory()->create(); // member but WITHOUT 'update progress' + $project = $this->makeProject($user); + $phase = $this->makePhase($project); + + Sanctum::actingAs($user, ['mobile-sync']); + + $this->postJson('/api/v1/sync', ['operations' => [[ + 'entity' => 'progress_update', 'op' => 'create', 'uuid' => (string) Str::uuid(), + 'data' => ['phase_id' => $phase->id, 'progress' => 50], + ]]]) + ->assertOk() + ->assertJsonPath('results.0.status', 'error'); + + $this->assertDatabaseCount('progress_updates', 0); + } +}