commit 936c794597b2b4447588d753a22b3bcd13fbde6e Author: Matthijs Iriks Date: Fri Dec 4 01:18:14 2026 +0100 First setup: module registry, switchable modules, permissions diff --git a/.gitea/workflows/pr-ci.yml b/.gitea/workflows/pr-ci.yml new file mode 100644 index 0000000..d6730fc --- /dev/null +++ b/.gitea/workflows/pr-ci.yml @@ -0,0 +1,18 @@ +name: PR CI + +on: + pull_request: + branches: [production, staging] + +jobs: + pr-ci: + runs-on: docker + container: + image: webdevops/php:8.4 + steps: + - uses: actions/checkout@v4 + - run: composer validate + - run: composer install --no-interaction --prefer-dist + - run: vendor/bin/pint --test + - run: vendor/bin/pest + - run: composer audit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4491c10 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +vendor/ +composer.lock +.phpunit.cache/ +.env diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..22ae0db --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,19 @@ +# laravel-manager — context for AI agents + +Composer package (`iriks-it/laravel-manager`, namespace `IriksIT\Manager`): the manager that used to be copied +between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one package. Public repo, published to Packagist. + +## Rules + +- Every part is a `Module` (`src/Modules/`): permissions, menu, `routes.php`, `migrations/`. Off means nothing is registered. +- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`. +- Nothing site-specific in the package. A site's own part is its own module class. +- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint). +- Branches: `production` is main, work on `feature/…` from `develop`; I never merge to `production`. +- No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`). + +## Open decisions + +1. Frontend: ship the Inertia/Vue screens inside the package (built assets, published to the host) or make the package headless with a separate UI package. +2. Moving the real controllers, revisions, audit log and the Thijs-style "simple screens" from bouwbedrijf.iriks-it.nl, module by module. +3. How the host's own `User` and a package `Group` relate when the host has its own roles. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d719b8a --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# iriks-it/laravel-manager + +A modular backend for Laravel sites. Install it, switch on the parts the site needs, done. + +```bash +composer require iriks-it/laravel-manager +php artisan vendor:publish --tag=manager-config +php artisan migrate +``` + +Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager lives at `/manager` +(`MANAGER_PATH`) behind the `web` and `auth` middleware (`config/manager.php`). + +## Modules + +| Key | What | Default | +|---|---|---| +| `users` | Accounts, groups and permissions | on | +| `media` | Media library | on | +| `pages` | Page texts | on | +| `posts` | Posts | on | +| `reviews` | Reviews | off | + +Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`, +`MANAGER_REVIEWS`. A module that is off has **no routes, no tables, no menu item and no permissions**: +its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when +that one is off. + +## Your own module + +Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a +`migrations/` folder next to the class, and add the class to `available` in the config. + +## State of this first version + +Done: module registry and switches, permissions per module as gates, groups, super admin, routes and +migrations per module, a menu that shows only what an account may reach, tests (`composer test`). + +Not done yet, on purpose: the screens. The modules answer with JSON; the frontend (the Inertia/Vue +screens of bouwbedrijf.iriks-it.nl, or something the package ships itself) is the next decision, see +`AGENTS.md`. diff --git a/TOKENS.md b/TOKENS.md new file mode 100644 index 0000000..129b836 --- /dev/null +++ b/TOKENS.md @@ -0,0 +1,6 @@ +# Tokenverbruik van dit project + +Per stuk werk een rij; zie `dev/token-usage.py`. + +| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | +|---|---|---|---|---|---|---|---|---| diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..5373158 --- /dev/null +++ b/composer.json @@ -0,0 +1,51 @@ +{ + "name": "iriks-it/laravel-manager", + "description": "A modular backend (manager) for Laravel sites: users, media, pages, posts, reviews. Every part can be switched on or off.", + "type": "library", + "license": "MIT", + "keywords": ["laravel", "manager", "cms", "admin", "modules"], + "require": { + "php": "^8.4", + "illuminate/support": "^13.0", + "illuminate/database": "^13.0", + "illuminate/http": "^13.0", + "illuminate/routing": "^13.0" + }, + "require-dev": { + "orchestra/testbench": "^11.0", + "pestphp/pest": "^5.0", + "laravel/pint": "^1.15" + }, + "autoload": { + "psr-4": { + "IriksIT\\Manager\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "IriksIT\\Manager\\Tests\\": "tests/" + } + }, + "extra": { + "laravel": { + "providers": [ + "IriksIT\\Manager\\ManagerServiceProvider" + ], + "aliases": { + "Manager": "IriksIT\\Manager\\Facades\\Manager" + } + } + }, + "scripts": { + "test": "pest", + "lint": "pint --test" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/config/manager.php b/config/manager.php new file mode 100644 index 0000000..7963c66 --- /dev/null +++ b/config/manager.php @@ -0,0 +1,56 @@ + env('MANAGER_PATH', 'manager'), + + /* + | Middleware around every manager route. Authentication of the manager itself + | is left to the host app: use the guard it already has. + */ + 'middleware' => ['web', 'auth'], + + /* + | The Eloquent model of the people who log in. Must use IriksIT\Manager\Concerns\HasManagerAccess. + */ + 'user_model' => env('MANAGER_USER_MODEL', 'App\\Models\\User'), + + /* + | The modules this manager knows. Add your own class here to give a site its own part. + */ + 'available' => [ + Modules\Users\UsersModule::class, + Modules\Media\MediaModule::class, + Modules\Pages\PagesModule::class, + Modules\Posts\PostsModule::class, + Modules\Reviews\ReviewsModule::class, + ], + + /* + | Switch a part on or off per site. A key left out falls back to the default of the + | module: users and media are on, everything else is off. A module that is off has no + | routes, no tables (its migrations are not loaded), no menu item and no permissions. + */ + 'modules' => [ + 'users' => true, + 'media' => true, + 'pages' => env('MANAGER_PAGES', true), + 'posts' => env('MANAGER_POSTS', true), + 'reviews' => env('MANAGER_REVIEWS', false), + ], + + /* + | The disk for uploaded media. + */ + 'media_disk' => env('MANAGER_MEDIA_DISK', 'public'), + + /* + | Prefix for the tables of the package. + */ + 'table_prefix' => 'manager_', +]; diff --git a/dev/token-usage.py b/dev/token-usage.py new file mode 100755 index 0000000..9ad27a2 --- /dev/null +++ b/dev/token-usage.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Adds up the tokens of a Claude Code session log, for TOKENS.md. + +Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00] + [--row "Wat er is gemaakt" [--version v0.2.0]] + +With --row it also prints the line for the table of TOKENS.md, with the hours as its last cell. + +The hours are the time that was worked in the period: from one entry of the log to the next, +the time between an answer and the next request included, pauses of more than half an hour +left out. + +LOG.jsonl is the log of the session (~/.claude/projects//.jsonl); the logs of +helper agents in the folder `/subagents` next to it are counted separately. The moments +are UTC, as in the log. An answer of the model can be in the log more than once; it is counted +once, by its message id. + +Standard library only. +""" + +import glob +import json +import os +import sys + + +def answers(path): + """The usage of every answer in a log, by message id, with its moment.""" + found = {} + with open(path, encoding="utf-8") as log: + for line in log: + try: + entry = json.loads(line) + except ValueError: + continue + message = entry.get("message") or {} + if entry.get("type") == "assistant" and message.get("usage") and message.get("id"): + found[message["id"]] = (message["usage"], entry.get("timestamp", ""), message.get("model")) + return found + + +PAUSE = 30 * 60 + + +def hours(path, since, until): + """The hours worked in the period, by the moments in the main log; pauses longer than PAUSE are left out.""" + from datetime import datetime + + moments = [] + with open(path, encoding="utf-8", errors="replace") as log: + for line in log: + try: + entry = json.loads(line) + except ValueError: + continue + if entry.get("isSidechain") or entry.get("type") not in ("user", "assistant") or not entry.get("timestamp"): + continue + moments.append(entry["timestamp"]) + moments.sort() + + seconds = 0.0 + for start, end in zip(moments, moments[1:]): + # A step counts for the period it starts in. + if (since and start[:16] < since) or (until and start[:16] >= until): + continue + gap = (datetime.fromisoformat(end.replace("Z", "+00:00")) - datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds() + if gap <= PAUSE: + seconds += gap + return seconds / 3600 + + +def total(found, since, until): + """Steps, output, input, written to the cache, read from the cache; and the models seen.""" + row = [0, 0, 0, 0, 0] + models = {} + for usage, moment, model in found.values(): + if (since and moment[:16] < since) or (until and moment[:16] >= until): + continue + row[0] += 1 + row[1] += usage.get("output_tokens", 0) + row[2] += usage.get("input_tokens", 0) + row[3] += usage.get("cache_creation_input_tokens", 0) + row[4] += usage.get("cache_read_input_tokens", 0) + if model and not model.startswith("<"): + models[model] = models.get(model, 0) + 1 + return row, models + + +def number(value): + return f"{value:,}".replace(",", ".") + + +def show(name, row): + steps, out, new, written, read = row + print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}") + + +def main(): + args = sys.argv[1:] + names = ("--since", "--until", "--row", "--version") + option = lambda name: args[args.index(name) + 1] if name in args else None + since, until = option("--since"), option("--until") + paths = [arg for index, arg in enumerate(args) if arg not in names and (index == 0 or args[index - 1] not in names)] + + if len(paths) != 1: + sys.exit(__doc__) + + row, models = total(answers(paths[0]), since, until) + show("session", row) + print(f"hours worked: {hours(paths[0], since, until):.2f}") + + helpers = {} + for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")): + helpers.update(answers(path)) + if helpers: + show("helper agents", total(helpers, since, until)[0]) + + if option("--row"): + if len(models) > 1: + print("More than one model in this period: make a row per model (--since/--until).", file=sys.stderr) + model = max(models, key=models.get) if models else "?" + day = (since or "")[:10] or "JJJJ-MM-DD" + worked = f"{hours(paths[0], since, until):.2f}".replace(".", ",") + cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in row] + [worked] + print("| " + " | ".join(cells) + " |") + + +if __name__ == "__main__": + main() diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..929baa7 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,13 @@ + + + + + tests/Feature + + + + + src + + + diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php new file mode 100644 index 0000000..b28b228 --- /dev/null +++ b/resources/views/dashboard.blade.php @@ -0,0 +1,16 @@ + + + + + + Manager + + +

Manager

+ + + diff --git a/routes/manager.php b/routes/manager.php new file mode 100644 index 0000000..752ce8f --- /dev/null +++ b/routes/manager.php @@ -0,0 +1,6 @@ +name('dashboard'); diff --git a/src/Concerns/HasManagerAccess.php b/src/Concerns/HasManagerAccess.php new file mode 100644 index 0000000..510caa1 --- /dev/null +++ b/src/Concerns/HasManagerAccess.php @@ -0,0 +1,34 @@ +belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id'); + } + + public function isManagerSuperAdmin(): bool + { + return (bool) $this->manager_super_admin; + } + + public function hasManagerPermission(string $permission): bool + { + if ($this->isManagerSuperAdmin()) { + return true; + } + + return $this->managerGroups->contains(fn (Group $group) => in_array($permission, $group->permissions ?? [], true)); + } +} diff --git a/src/Contracts/Module.php b/src/Contracts/Module.php new file mode 100644 index 0000000..cb3e68b --- /dev/null +++ b/src/Contracts/Module.php @@ -0,0 +1,38 @@ + keys of modules this one cannot work without */ + public function requires(): array; + + /** + * Permissions this module adds, as value => label. Values are prefixed by the module key. + * + * @return array + */ + public function permissions(): array; + + /** @return list */ + public function navigation(): array; + + /** Absolute path of the routes file, or null. */ + public function routes(): ?string; + + /** Absolute path of the migrations folder, or null. */ + public function migrations(): ?string; +} diff --git a/src/Exceptions/ModuleException.php b/src/Exceptions/ModuleException.php new file mode 100644 index 0000000..0ce1606 --- /dev/null +++ b/src/Exceptions/ModuleException.php @@ -0,0 +1,5 @@ +navigation(), + fn (array $item) => $request->user()?->can($item['permission']), + )); + + return view('manager::dashboard', ['navigation' => $navigation]); + } +} diff --git a/src/ManagerServiceProvider.php b/src/ManagerServiceProvider.php new file mode 100644 index 0000000..a04b04b --- /dev/null +++ b/src/ManagerServiceProvider.php @@ -0,0 +1,63 @@ +mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); + + $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( + $app['config']->get('manager.available', []), + $app['config']->get('manager.modules', []), + )); + } + + public function boot(ModuleRegistry $modules): void + { + $modules->validate(); + + $this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config'); + + $this->loadViewsFrom(__DIR__.'/../resources/views', 'manager'); + + // A module that is off adds no migrations, so a site without reviews has no reviews table. + foreach ($modules->active() as $module) { + if ($module->migrations() !== null) { + $this->loadMigrationsFrom($module->migrations()); + } + } + + $this->registerGates($modules); + $this->registerRoutes($modules); + } + + private function registerGates(ModuleRegistry $modules): void + { + foreach (array_keys($modules->permissions()) as $permission) { + Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission)); + } + } + + private function registerRoutes(ModuleRegistry $modules): void + { + Route::middleware(config('manager.middleware')) + ->prefix(config('manager.path')) + ->name('manager.') + ->group(function () use ($modules) { + $this->loadRoutesFrom(__DIR__.'/../routes/manager.php'); + + foreach ($modules->active() as $module) { + if ($module->routes() !== null) { + $this->loadRoutesFrom($module->routes()); + } + } + }); + } +} diff --git a/src/Models/Group.php b/src/Models/Group.php new file mode 100644 index 0000000..c851492 --- /dev/null +++ b/src/Models/Group.php @@ -0,0 +1,11 @@ + 'array']; + } +} diff --git a/src/Models/Media.php b/src/Models/Media.php new file mode 100644 index 0000000..7fc2b58 --- /dev/null +++ b/src/Models/Media.php @@ -0,0 +1,11 @@ +table ?? config('manager.table_prefix').parent::getTable(); + } +} diff --git a/src/Models/Page.php b/src/Models/Page.php new file mode 100644 index 0000000..66fa1ea --- /dev/null +++ b/src/Models/Page.php @@ -0,0 +1,5 @@ +path('routes.php'); + } + + public function migrations(): ?string + { + return $this->path('migrations'); + } + + private function path(string $name): ?string + { + $path = dirname((new \ReflectionClass($this))->getFileName()).'/'.$name; + + return file_exists($path) ? $path : null; + } +} diff --git a/src/Modules/Media/MediaController.php b/src/Modules/Media/MediaController.php new file mode 100644 index 0000000..ab760f5 --- /dev/null +++ b/src/Modules/Media/MediaController.php @@ -0,0 +1,14 @@ +json(Media::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Media/MediaModule.php b/src/Modules/Media/MediaModule.php new file mode 100644 index 0000000..df698be --- /dev/null +++ b/src/Modules/Media/MediaModule.php @@ -0,0 +1,40 @@ + 'See the media library', + 'media.upload' => 'Upload files', + 'media.edit' => 'Change name and description of a file', + 'media.delete' => 'Delete files', + ]; + } + + public function navigation(): array + { + return [ + ['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'], + ]; + } +} diff --git a/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php new file mode 100644 index 0000000..5c38cf8 --- /dev/null +++ b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php @@ -0,0 +1,31 @@ +id(); + $table->string('disk'); + $table->string('path'); + $table->string('filename'); + $table->string('mime_type'); + $table->unsignedBigInteger('size'); + $table->unsignedInteger('width')->nullable(); + $table->unsignedInteger('height')->nullable(); + $table->string('title')->nullable(); + $table->text('description')->nullable(); + $table->unsignedBigInteger('uploaded_by')->nullable()->index(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(config('manager.table_prefix').'media'); + } +}; diff --git a/src/Modules/Media/routes.php b/src/Modules/Media/routes.php new file mode 100644 index 0000000..0cec8fb --- /dev/null +++ b/src/Modules/Media/routes.php @@ -0,0 +1,6 @@ +name('media.index')->middleware('can:media.view'); diff --git a/src/Modules/Pages/PagesController.php b/src/Modules/Pages/PagesController.php new file mode 100644 index 0000000..7e0b8de --- /dev/null +++ b/src/Modules/Pages/PagesController.php @@ -0,0 +1,14 @@ +json(Page::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Pages/PagesModule.php b/src/Modules/Pages/PagesModule.php new file mode 100644 index 0000000..25fc4c4 --- /dev/null +++ b/src/Modules/Pages/PagesModule.php @@ -0,0 +1,37 @@ + 'Change the texts of the pages', + ]; + } + + public function navigation(): array + { + return [ + ['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'], + ]; + } +} diff --git a/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php new file mode 100644 index 0000000..6f16a33 --- /dev/null +++ b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php @@ -0,0 +1,25 @@ +id(); + $table->string('slug')->unique(); + $table->string('title'); + $table->longText('body')->nullable(); + $table->boolean('is_published')->default(false); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(config('manager.table_prefix').'pages'); + } +}; diff --git a/src/Modules/Pages/routes.php b/src/Modules/Pages/routes.php new file mode 100644 index 0000000..3dae8d8 --- /dev/null +++ b/src/Modules/Pages/routes.php @@ -0,0 +1,6 @@ +name('pages.index')->middleware('can:pages.edit'); diff --git a/src/Modules/Posts/PostsController.php b/src/Modules/Posts/PostsController.php new file mode 100644 index 0000000..63c8264 --- /dev/null +++ b/src/Modules/Posts/PostsController.php @@ -0,0 +1,14 @@ +json(Post::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Posts/PostsModule.php b/src/Modules/Posts/PostsModule.php new file mode 100644 index 0000000..1de85ac --- /dev/null +++ b/src/Modules/Posts/PostsModule.php @@ -0,0 +1,40 @@ + 'See the posts, drafts included', + 'posts.write' => 'Write and change posts', + 'posts.publish' => 'Publish and unpublish posts', + 'posts.delete' => 'Delete posts', + ]; + } + + public function navigation(): array + { + return [ + ['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'], + ]; + } +} diff --git a/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php new file mode 100644 index 0000000..dc00a6d --- /dev/null +++ b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php @@ -0,0 +1,26 @@ +id(); + $table->string('slug')->unique(); + $table->string('title'); + $table->text('excerpt')->nullable(); + $table->longText('body')->nullable(); + $table->timestamp('published_at')->nullable()->index(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(config('manager.table_prefix').'posts'); + } +}; diff --git a/src/Modules/Posts/routes.php b/src/Modules/Posts/routes.php new file mode 100644 index 0000000..a9bd985 --- /dev/null +++ b/src/Modules/Posts/routes.php @@ -0,0 +1,6 @@ +name('posts.index')->middleware('can:posts.view'); diff --git a/src/Modules/Reviews/ReviewsController.php b/src/Modules/Reviews/ReviewsController.php new file mode 100644 index 0000000..d74ed8f --- /dev/null +++ b/src/Modules/Reviews/ReviewsController.php @@ -0,0 +1,14 @@ +json(Review::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Reviews/ReviewsModule.php b/src/Modules/Reviews/ReviewsModule.php new file mode 100644 index 0000000..0217148 --- /dev/null +++ b/src/Modules/Reviews/ReviewsModule.php @@ -0,0 +1,37 @@ + 'Manage the reviews', + ]; + } + + public function navigation(): array + { + return [ + ['label' => 'Reviews', 'route' => 'manager.reviews.index', 'permission' => 'reviews.manage'], + ]; + } +} diff --git a/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php new file mode 100644 index 0000000..330ec4e --- /dev/null +++ b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php @@ -0,0 +1,26 @@ +id(); + $table->string('author'); + $table->string('place')->nullable(); + $table->unsignedTinyInteger('rating')->nullable(); + $table->text('body'); + $table->boolean('is_visible')->default(true); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(config('manager.table_prefix').'reviews'); + } +}; diff --git a/src/Modules/Reviews/routes.php b/src/Modules/Reviews/routes.php new file mode 100644 index 0000000..bbbd424 --- /dev/null +++ b/src/Modules/Reviews/routes.php @@ -0,0 +1,6 @@ +name('reviews.index')->middleware('can:reviews.manage'); diff --git a/src/Modules/Users/UsersController.php b/src/Modules/Users/UsersController.php new file mode 100644 index 0000000..15f447b --- /dev/null +++ b/src/Modules/Users/UsersController.php @@ -0,0 +1,14 @@ +json($user::query()->with('managerGroups')->latest()->paginate(25)); + } +} diff --git a/src/Modules/Users/UsersModule.php b/src/Modules/Users/UsersModule.php new file mode 100644 index 0000000..51bae60 --- /dev/null +++ b/src/Modules/Users/UsersModule.php @@ -0,0 +1,37 @@ + 'Create, change and delete accounts, and put them in groups', + ]; + } + + public function navigation(): array + { + return [ + ['label' => 'Users', 'route' => 'manager.users.index', 'permission' => 'users.manage'], + ]; + } +} diff --git a/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php new file mode 100644 index 0000000..71626df --- /dev/null +++ b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php @@ -0,0 +1,39 @@ +id(); + $table->string('name')->unique(); + $table->json('permissions')->nullable(); + $table->timestamps(); + }); + + Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix) { + $table->foreignId('group_id')->constrained($prefix.'groups')->cascadeOnDelete(); + $table->unsignedBigInteger('user_id')->index(); + $table->primary(['group_id', 'user_id']); + }); + + Schema::table('users', function (Blueprint $table) { + $table->boolean('manager_super_admin')->default(false); + }); + } + + public function down(): void + { + $prefix = config('manager.table_prefix'); + + Schema::table('users', fn (Blueprint $table) => $table->dropColumn('manager_super_admin')); + Schema::dropIfExists($prefix.'group_user'); + Schema::dropIfExists($prefix.'groups'); + } +}; diff --git a/src/Modules/Users/routes.php b/src/Modules/Users/routes.php new file mode 100644 index 0000000..cfef85a --- /dev/null +++ b/src/Modules/Users/routes.php @@ -0,0 +1,6 @@ +name('users.index')->middleware('can:users.manage'); diff --git a/src/Support/ModuleRegistry.php b/src/Support/ModuleRegistry.php new file mode 100644 index 0000000..8200989 --- /dev/null +++ b/src/Support/ModuleRegistry.php @@ -0,0 +1,91 @@ + */ + private array $all = []; + + /** + * @param list> $available + * @param array $switches + */ + public function __construct(array $available, private readonly array $switches) + { + foreach ($available as $class) { + $module = new $class; + $this->all[$module->key()] = $module; + } + } + + /** @return array every known module */ + public function all(): array + { + return $this->all; + } + + public function has(string $key): bool + { + return isset($this->all[$key]); + } + + public function enabled(string $key): bool + { + if (! $this->has($key)) { + return false; + } + + return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault()); + } + + /** @return array the modules that are on */ + public function active(): array + { + return array_filter($this->all, fn (Module $module) => $this->enabled($module->key())); + } + + /** + * A module that is on while one it needs is off is a configuration mistake: fail loudly at boot. + */ + public function validate(): void + { + foreach ($this->active() as $module) { + foreach ($module->requires() as $needed) { + if (! $this->enabled($needed)) { + throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off."); + } + } + } + } + + /** @return array permission value => label, of the active modules only */ + public function permissions(): array + { + $permissions = []; + + foreach ($this->active() as $module) { + $permissions += $module->permissions(); + } + + return $permissions; + } + + /** @return list */ + public function navigation(): array + { + $items = []; + + foreach ($this->active() as $module) { + array_push($items, ...$module->navigation()); + } + + return $items; + } +} diff --git a/tests/Feature/ModulesTest.php b/tests/Feature/ModulesTest.php new file mode 100644 index 0000000..b100c40 --- /dev/null +++ b/tests/Feature/ModulesTest.php @@ -0,0 +1,45 @@ +toBeTrue() + ->and(Manager::enabled('media'))->toBeTrue() + ->and(Manager::enabled('reviews'))->toBeFalse(); +}); + +it('adds no routes, tables or permissions for a module that is off', function () { + expect(Route::has('manager.reviews.index'))->toBeFalse() + ->and(Schema::hasTable('manager_reviews'))->toBeFalse() + ->and(Manager::permissions())->not->toHaveKey('reviews.manage') + ->and(collect(Manager::navigation())->pluck('label'))->not->toContain('Reviews'); +}); + +it('adds all of it for a module that is on', function () { + expect(Route::has('manager.posts.index'))->toBeTrue() + ->and(Schema::hasTable('manager_posts'))->toBeTrue() + ->and(Manager::permissions())->toHaveKey('posts.publish'); +}); + +it('lets a super admin in and keeps others out without the permission', function () { + $admin = User::create(['name' => 'a', 'email' => 'a@x.nl', 'password' => 'x', 'manager_super_admin' => true]); + $other = User::create(['name' => 'b', 'email' => 'b@x.nl', 'password' => 'x']); + + $this->actingAs($admin)->getJson('/manager/posts')->assertOk(); + $this->actingAs($other)->getJson('/manager/posts')->assertForbidden(); +}); + +it('gives a group member the permissions of the group', function () { + $user = User::create(['name' => 'c', 'email' => 'c@x.nl', 'password' => 'x']); + $group = Group::create(['name' => 'Editors', 'permissions' => ['posts.view']]); + $user->managerGroups()->attach($group); + + $this->actingAs($user)->getJson('/manager/posts')->assertOk(); + $this->actingAs($user)->getJson('/manager/pages')->assertForbidden(); +}); diff --git a/tests/Feature/ReviewsOnTest.php b/tests/Feature/ReviewsOnTest.php new file mode 100644 index 0000000..6cf915b --- /dev/null +++ b/tests/Feature/ReviewsOnTest.php @@ -0,0 +1,11 @@ +toBeTrue() + ->and(Schema::hasTable('manager_reviews'))->toBeTrue(); +}); diff --git a/tests/Fixtures/User.php b/tests/Fixtures/User.php new file mode 100644 index 0000000..50506f5 --- /dev/null +++ b/tests/Fixtures/User.php @@ -0,0 +1,13 @@ +id(); + $table->string('name'); + $table->string('email')->unique(); + $table->string('password'); + $table->timestamps(); + }); + } +}; diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..b3d9bbc --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1 @@ + true]; +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..d8e1dd7 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,34 @@ + */ + protected array $modules = []; + + protected function getPackageProviders($app): array + { + return [ManagerServiceProvider::class]; + } + + protected function defineEnvironment($app): void + { + $app['config']->set('database.default', 'testing'); + $app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('a', 32))); + $app['config']->set('manager.user_model', User::class); + $app['config']->set('manager.modules', array_merge($app['config']->get('manager.modules'), $this->modules)); + } + + protected function defineDatabaseMigrations(): void + { + $this->loadMigrationsFrom(__DIR__.'/Fixtures/migrations'); + } +}