diff --git a/AGENTS.md b/AGENTS.md index b73d420..703ceef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,5 +15,5 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one ## 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 rest from bouwbedrijf.iriks-it.nl, module by module: posts (+labels), pages, reviews, then revisions, audit log, login and profile. Users and media are done. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public. +2. Moving the rest from bouwbedrijf.iriks-it.nl, module by module: pages, reviews, then revisions, audit log, login and profile. Users, media and posts (with labels) are done. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public. 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 index 0d731f2..251da2c 100644 --- a/README.md +++ b/README.md @@ -63,15 +63,32 @@ Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembe `app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do. - No SVG: it can carry scripts. +## Posts module + +Posts written in Markdown, with drafts, scheduling, categories and tags. + +- Routes under `/manager`: `posts` (list, `create`, `{id}/edit`, `{id}/preview`, update, `{id}/online`, + delete) and `labels` (categories and tags: make, rename, merge, remove). Rights: `posts.view`, `write`, + `publish`, `delete`, `labels`. +- Who may not publish only saves drafts, and cannot change or delete a post that is live or scheduled. +- A post is a draft (`published_at` null), scheduled (in the future) or published. For your public pages: + `IriksIT\Manager\Models\Post::published()`, `toCard()` and `IriksIT\Manager\Support\Markdown::toHtml()` + (raw HTML is escaped, external links open in a new window). The package has no public post routes: the + host decides what a visitor sees. +- Categories offered in the form: `manager.posts.categories`, the ones in use, the ones made by hand and + whatever your site adds with + `app(IriksIT\Manager\Modules\Posts\PostLabels::class)->suggestCategories(fn () => $titles)`. +- Covers and bodies count as use of a media file. + ## State of this version -Done: module registry and switches, permissions per module, users (accounts, groups, command) and -media (library and public file route), 30+ tests (`composer test`). +Done: module registry and switches, permissions per module, users (accounts, groups, command), media +(library and public file route) and posts (with categories and tags), 59 tests (`composer test`). The answers of every action are JSON, in the shape the screens of bouwbedrijf.iriks-it.nl got as Inertia props. The screens themselves are not in the package yet: the frontend is an open decision -(`AGENTS.md`). Posts, pages and reviews are still skeletons (a list), and so are login, profile, the -audit log and revisions: they are not part of users and media. +(`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile, the audit log and revisions are not +ported yet. ## Development cycle diff --git a/TOKENS.md b/TOKENS.md index 19109a5..162c107 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -5,5 +5,6 @@ Per stuk werk een rij; zie `dev/token-usage.py`. | Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | Uren | |---|---|---|---|---:|---:|---:|---:|---:|---:| | 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 | +| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 | | 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 | | 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 | diff --git a/composer.json b/composer.json index efcb664..1a195bc 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ "illuminate/http": "^13.0", "illuminate/routing": "^13.0", "illuminate/support": "^13.0", - "illuminate/validation": "^13.0" + "illuminate/validation": "^13.0", + "league/commonmark": "^2.6" }, "require-dev": { "orchestra/testbench": "^11.0", diff --git a/config/manager.php b/config/manager.php index c8101c7..6463bf8 100644 --- a/config/manager.php +++ b/config/manager.php @@ -65,6 +65,21 @@ return [ 'per_minute' => 600, ], + /* + | Posts. `categories` are always offered in the post form, next to the ones in use and the + | ones made by hand; a site can offer more through PostLabels::suggestCategories(). + */ + 'posts' => [ + 'categories' => ['General'], + ], + + /* + | Markdown in posts: hosts besides APP_URL whose links do not open in a new window. + */ + 'markdown' => [ + 'internal_hosts' => [], + ], + /* | Prefix for the tables of the package. */ diff --git a/src/ManagerServiceProvider.php b/src/ManagerServiceProvider.php index 4c25a5d..ff9492c 100644 --- a/src/ManagerServiceProvider.php +++ b/src/ManagerServiceProvider.php @@ -17,6 +17,7 @@ class ManagerServiceProvider extends ServiceProvider $this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); $this->app->singleton(Support\MediaUsage::class); + $this->app->singleton(Modules\Posts\PostLabels::class); $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( $app['config']->get('manager.available', []), diff --git a/src/Models/Post.php b/src/Models/Post.php index 265aef0..239fdf4 100644 --- a/src/Models/Post.php +++ b/src/Models/Post.php @@ -2,4 +2,83 @@ namespace IriksIT\Manager\Models; -class Post extends Model {} +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Support\Str; +use IriksIT\Manager\Support\Markdown; + +class Post extends Model +{ + protected function casts(): array + { + return [ + 'tags' => 'array', + 'is_featured' => 'boolean', + 'published_at' => 'datetime', + ]; + } + + /** + * Posts that are visible on the public site: published and not scheduled for later. + * + * @param Builder $query + */ + public function scopePublished(Builder $query): void + { + $query->whereNotNull('published_at')->where('published_at', '<=', now()); + } + + public function isPublished(): bool + { + return $this->published_at !== null && $this->published_at->lte(now()); + } + + /** `draft`, `scheduled` or `published`. */ + public function status(): string + { + return match (true) { + $this->published_at === null => 'draft', + $this->published_at->isFuture() => 'scheduled', + default => 'published', + }; + } + + /** A slug for $title that no other post uses yet. */ + public static function uniqueSlug(string $title, ?int $ignoreId = null): string + { + $base = Str::slug($title) ?: 'post'; + $slug = $base; + $suffix = 2; + + while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) { + $slug = $base.'-'.$suffix++; + } + + return $slug; + } + + public function readingMinutes(): int + { + return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220)); + } + + /** + * The fields a post card or listing needs, for the host's public pages. + * + * @return array + */ + public function toCard(): array + { + return [ + 'title' => $this->title, + 'slug' => $this->slug, + 'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160), + 'cover_image' => $this->cover_image, + 'cover_focus' => Media::focusFor($this->cover_image), + 'category' => $this->category, + 'tags' => $this->tags ?? [], + 'is_featured' => $this->is_featured, + 'published_at' => $this->published_at?->toIso8601String(), + 'reading_minutes' => $this->readingMinutes(), + ]; + } +} diff --git a/src/Modules/Posts/LabelController.php b/src/Modules/Posts/LabelController.php new file mode 100644 index 0000000..e42d4a7 --- /dev/null +++ b/src/Modules/Posts/LabelController.php @@ -0,0 +1,80 @@ +json($this->labels->overview()); + } + + /** A category or tag that no post uses yet; the post form offers it from then on. */ + public function store(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => $this->nameRules($type)], $this->messages()); + + $name = $request->string('name')->trim()->toString(); + + if (! $this->labels->create($type, $name)) { + return response()->json(['message' => "The {$type} \"{$name}\" already exists.", 'errors' => ['name' => ["The {$type} \"{$name}\" already exists."]]], 422); + } + + return response()->json(['created' => $name], 201); + } + + public function update(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages()); + + $from = $request->string('name')->toString(); + $to = $request->string('new_name')->trim()->toString(); + + return response()->json(['posts' => $this->labels->rename($type, $from, $to)]); + } + + public function destroy(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string']]); + + return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]); + } + + /** + * The same limits as the post form. + * + * @return list + */ + private function nameRules(string $type): array + { + return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])]; + } + + /** @return array */ + private function messages(): array + { + $comma = 'A tag cannot hold a comma: the post form separates tags with it.'; + + return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma]; + } + + private function type(Request $request): string + { + $request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]); + + return $request->string('type')->toString(); + } +} diff --git a/src/Modules/Posts/PostController.php b/src/Modules/Posts/PostController.php new file mode 100644 index 0000000..5d43548 --- /dev/null +++ b/src/Modules/Posts/PostController.php @@ -0,0 +1,189 @@ +orderByRaw('published_at is null desc') + ->latest('published_at') + ->latest('id') + ->get() + ->map(fn (Post $post) => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'category' => $post->category, + 'is_featured' => $post->is_featured, + 'status' => $post->status(), + 'published_at' => $post->published_at?->toIso8601String(), + 'can_change' => Gate::allows('posts.write') && $this->mayTouch($post), + 'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post), + ]) + ->values(); + + return response()->json(['posts' => $posts]); + } + + public function create(): JsonResponse + { + return response()->json([ + 'post' => null, + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + public function store(Request $request): JsonResponse + { + $post = Post::create($this->validated($request)); + + return response()->json(['id' => $post->id], 201); + } + + public function edit(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + + return response()->json([ + 'post' => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'excerpt' => $post->excerpt, + 'body' => $post->body, + 'cover_image' => $post->cover_image, + 'category' => $post->category, + 'tags' => $post->tags ?? [], + 'is_featured' => $post->is_featured, + 'is_published' => $post->published_at !== null, + // datetime-local value, in the app timezone + 'published_at' => $post->published_at?->format('Y-m-d\TH:i'), + 'status' => $post->status(), + ], + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + /** The post as a visitor will see it, also for drafts and scheduled posts. */ + public function preview(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + + return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]); + } + + public function update(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + + $post->update($this->validated($request, $post)); + + return response()->json(['saved' => true]); + } + + /** Puts a post on the site, or takes it off again (a draft) without opening it. */ + public function online(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + $request->validate(['online' => ['required', 'boolean']]); + + $post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]); + + return response()->json(['status' => $post->status()]); + } + + public function destroy(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + + $post->delete(); + + return response()->json(['deleted' => true]); + } + + /** + * Validates the post form and turns it into model attributes. + * + * @return array + */ + private function validated(Request $request, ?Post $post = null): array + { + $request->validate([ + 'title' => ['required', 'string', 'max:255'], + 'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(config('manager.table_prefix').'posts', 'slug')->ignore($post?->id)], + 'excerpt' => ['nullable', 'string', 'max:500'], + 'body' => ['required', 'string'], + 'cover_image' => ['nullable', 'string', 'max:2048'], + 'category' => ['nullable', 'string', 'max:60'], + 'tags' => ['array', 'max:20'], + 'tags.*' => ['nullable', 'string', 'max:40'], + 'is_featured' => ['boolean'], + 'is_published' => ['boolean'], + 'published_at' => ['nullable', 'date'], + ], [ + 'slug.regex' => 'Use only lowercase letters, numbers and dashes.', + ]); + + $title = $request->string('title')->trim()->toString(); + $slug = $request->string('slug')->trim()->toString(); + + // Publishing without a date means "now"; a date in the future schedules the post. + // Who may not publish only gets a draft, and a post that was live is not touched + // (mayTouch refused that before we got here). + $publishedAt = null; + if ($request->boolean('is_published') && Gate::allows('posts.publish')) { + $date = $request->string('published_at')->toString(); + $publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now()); + } + + return [ + 'title' => $title, + 'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id), + 'excerpt' => $this->nullableString($request, 'excerpt'), + 'body' => $request->string('body')->toString(), + 'cover_image' => $this->nullableString($request, 'cover_image'), + 'category' => $this->nullableString($request, 'category'), + 'tags' => array_values(array_filter(array_map( + fn (mixed $tag) => is_string($tag) ? trim($tag) : '', + $request->array('tags'), + ))), + 'is_featured' => $request->boolean('is_featured'), + 'published_at' => $publishedAt, + ]; + } + + private function mayTouch(Post $post): bool + { + return $post->published_at === null || Gate::allows('posts.publish'); + } + + private function nullableString(Request $request, string $key): ?string + { + $value = $request->string($key)->trim()->toString(); + + return $value !== '' ? $value : null; + } +} diff --git a/src/Modules/Posts/PostLabels.php b/src/Modules/Posts/PostLabels.php new file mode 100644 index 0000000..71ffd3a --- /dev/null +++ b/src/Modules/Posts/PostLabels.php @@ -0,0 +1,191 @@ +> */ + private array $suggestions = []; + + /** A site offers more categories in the post form, for instance the titles of its services. */ + public function suggestCategories(Closure $source): void + { + $this->suggestions[] = $source; + } + + /** + * What the post form offers as category: the suggestions of the site, the configured ones, + * and whatever is in use or was made by hand. + * + * @return list + */ + public function categories(): array + { + $suggested = []; + + foreach ($this->suggestions as $source) { + array_push($suggested, ...array_values([...$source()])); + } + + return array_values(array_unique([...$suggested, ...array_values((array) config('manager.posts.categories', [])), ...$this->names(self::CATEGORY)])); + } + + private function table(): string + { + return config('manager.table_prefix').'post_labels'; + } + + /** + * Every category and tag, the ones made by hand included, with the number of posts (drafts + * included) that use it. + * + * @return array{categories: list, tags: list} + */ + public function overview(): array + { + $categories = []; + $tags = []; + + foreach (Post::query()->get(['id', 'category', 'tags']) as $post) { + if ($post->category !== null && $post->category !== '') { + $categories[$post->category] = ($categories[$post->category] ?? 0) + 1; + } + + foreach (array_unique($this->tagsOf($post)) as $tag) { + $tags[$tag] = ($tags[$tag] ?? 0) + 1; + } + } + + foreach (DB::table($this->table())->get(['type', 'name']) as $row) { + if (! is_string($row->name)) { + continue; + } + + if ($row->type === self::CATEGORY) { + $categories[$row->name] ??= 0; + } else { + $tags[$row->name] ??= 0; + } + } + + return ['categories' => $this->listed($categories), 'tags' => $this->listed($tags)]; + } + + /** + * The names of all categories or tags, to offer in the post form. + * + * @return list + */ + public function names(string $type): array + { + return array_column($this->overview()[$type === self::CATEGORY ? 'categories' : 'tags'], 'name'); + } + + /** Makes a category or tag that no post uses yet. False when the name is already there. */ + public function create(string $type, string $name): bool + { + if (in_array($name, $this->names($type), true)) { + return false; + } + + DB::table($this->table())->insert(['type' => $type, 'name' => $name, 'created_at' => now(), 'updated_at' => now()]); + + return true; + } + + /** Gives every post with the label the new name. Returns how many posts changed. */ + public function rename(string $type, string $from, string $to): int + { + if ($from === $to) { + return 0; + } + + // The name that was made by hand moves along, unless the new name is there already. + $made = DB::table($this->table())->where('type', $type); + if ((clone $made)->where('name', $to)->exists()) { + (clone $made)->where('name', $from)->delete(); + } else { + (clone $made)->where('name', $from)->update(['name' => $to, 'updated_at' => now()]); + } + + return $type === self::CATEGORY + ? Post::query()->where('category', $from)->update(['category' => $to]) + : $this->changeTags($from, $to); + } + + /** Takes the label off every post; the posts stay. Returns how many posts changed. */ + public function remove(string $type, string $name): int + { + DB::table($this->table())->where('type', $type)->where('name', $name)->delete(); + + return $type === self::CATEGORY + ? Post::query()->where('category', $name)->update(['category' => null]) + : $this->changeTags($name, null); + } + + /** Replaces a tag in every post that has it, or takes it out when $to is null. */ + private function changeTags(string $from, ?string $to): int + { + return DB::transaction(function () use ($from, $to) { + $changed = 0; + + foreach (Post::query()->whereNotNull('tags')->get() as $post) { + $tags = $this->tagsOf($post); + + if (! in_array($from, $tags, true)) { + continue; + } + + $new = []; + foreach ($tags as $tag) { + $tag = $tag === $from ? $to : $tag; + + // A post that had both names keeps the tag once. + if ($tag !== null && ! in_array($tag, $new, true)) { + $new[] = $tag; + } + } + + $post->update(['tags' => $new]); + $changed++; + } + + return $changed; + }); + } + + /** @return list */ + private function tagsOf(Post $post): array + { + return array_values(array_filter(is_array($post->tags) ? $post->tags : [], fn (mixed $tag) => is_string($tag) && $tag !== '')); + } + + /** + * @param array $counts + * @return list + */ + private function listed(array $counts): array + { + $names = array_map(fn (int|string $name) => (string) $name, array_keys($counts)); + natcasesort($names); + + return array_values(array_map(fn (string $name) => ['name' => $name, 'posts' => $counts[$name]], $names)); + } +} diff --git a/src/Modules/Posts/PostsController.php b/src/Modules/Posts/PostsController.php deleted file mode 100644 index 63c8264..0000000 --- a/src/Modules/Posts/PostsController.php +++ /dev/null @@ -1,14 +0,0 @@ -json(Post::query()->latest()->paginate(25)); - } -} diff --git a/src/Modules/Posts/PostsModule.php b/src/Modules/Posts/PostsModule.php index 986cf1c..54557cd 100644 --- a/src/Modules/Posts/PostsModule.php +++ b/src/Modules/Posts/PostsModule.php @@ -30,7 +30,8 @@ class PostsModule extends BaseModule new Permission('posts.view', 'See the posts, drafts included', 'Posts'), new Permission('posts.write', 'Write posts: create drafts and change them', 'Posts', needs: ['posts.view']), new Permission('posts.publish', 'Publish, schedule and unpublish posts, and change posts that are live', 'Posts', needs: ['posts.view', 'posts.write']), - new Permission('posts.delete', 'Delete posts', 'Posts', needs: ['posts.view']), + new Permission('posts.delete', 'Delete posts (one that is live only together with publishing)', 'Posts', needs: ['posts.view']), + new Permission('posts.labels', 'Manage the categories and tags: make them, and rename, merge and remove them on all posts', 'Posts', needs: ['posts.view']), ]; } @@ -38,12 +39,13 @@ class PostsModule extends BaseModule { return [ ['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'], + ['label' => 'Categories and tags', 'route' => 'manager.labels.index', 'permission' => 'posts.labels'], ]; } /** Where the media library looks for the use of a file: the texts of the posts. */ public function boot(): void { - app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt'])))); + app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt', 'cover_image'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt', 'cover_image'])))); } } 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 index dc00a6d..7a14923 100644 --- 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 @@ -8,19 +8,40 @@ return new class extends Migration { public function up(): void { - Schema::create(config('manager.table_prefix').'posts', function (Blueprint $table) { + $prefix = config('manager.table_prefix'); + + Schema::create($prefix.'posts', function (Blueprint $table) { $table->id(); - $table->string('slug')->unique(); $table->string('title'); - $table->text('excerpt')->nullable(); - $table->longText('body')->nullable(); + $table->string('slug')->unique(); + $table->string('excerpt', 500)->nullable(); + $table->longText('body'); + $table->string('cover_image', 2048)->nullable(); + $table->string('category', 60)->nullable(); + $table->json('tags')->nullable(); + $table->boolean('is_featured')->default(false); + // null = draft; a future date = scheduled $table->timestamp('published_at')->nullable()->index(); $table->timestamps(); }); + + // Categories and tags that were made by hand, so one can exist before a post uses it. + // The ones a post uses are in the post itself; this only remembers names to offer. + Schema::create($prefix.'post_labels', function (Blueprint $table) { + $table->id(); + $table->string('type', 10); + $table->string('name', 60); + $table->timestamps(); + + $table->unique(['type', 'name']); + }); } public function down(): void { - Schema::dropIfExists(config('manager.table_prefix').'posts'); + $prefix = config('manager.table_prefix'); + + Schema::dropIfExists($prefix.'post_labels'); + Schema::dropIfExists($prefix.'posts'); } }; diff --git a/src/Modules/Posts/routes.php b/src/Modules/Posts/routes.php index a9bd985..623d3f6 100644 --- a/src/Modules/Posts/routes.php +++ b/src/Modules/Posts/routes.php @@ -1,6 +1,22 @@ name('posts.index')->middleware('can:posts.view'); +Route::get('/posts', [PostController::class, 'index'])->name('posts.index')->middleware('can:posts.view'); +Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create')->middleware('can:posts.write'); +Route::post('/posts', [PostController::class, 'store'])->name('posts.store')->middleware('can:posts.write'); +Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit')->middleware('can:posts.write')->whereNumber('post'); +Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('posts.preview')->middleware('can:posts.view')->whereNumber('post'); +Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update')->middleware('can:posts.write')->whereNumber('post'); +Route::put('/posts/{post}/online', [PostController::class, 'online'])->name('posts.online')->middleware('can:posts.publish')->whereNumber('post'); +Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy')->middleware('can:posts.delete')->whereNumber('post'); + +// The name of a label travels in the body, not the address: it can hold anything. +Route::middleware('can:posts.labels')->group(function () { + Route::get('/labels', [LabelController::class, 'index'])->name('labels.index'); + Route::post('/labels', [LabelController::class, 'store'])->name('labels.store'); + Route::put('/labels', [LabelController::class, 'update'])->name('labels.update'); + Route::delete('/labels', [LabelController::class, 'destroy'])->name('labels.destroy'); +}); diff --git a/src/Support/Markdown.php b/src/Support/Markdown.php new file mode 100644 index 0000000..83373e4 --- /dev/null +++ b/src/Support/Markdown.php @@ -0,0 +1,37 @@ + 'escape', + 'allow_unsafe_links' => false, + 'external_link' => [ + 'internal_hosts' => array_values(array_filter([$host, ...(array) config('manager.markdown.internal_hosts', [])])), + 'open_in_new_window' => true, + 'noopener' => 'external', + 'noreferrer' => 'external', + ], + ], [new ExternalLinkExtension]); + } + + public static function toPlainText(string $markdown): string + { + $text = strip_tags(self::toHtml($markdown)); + + return trim((string) preg_replace('/\s+/', ' ', html_entity_decode($text, ENT_QUOTES | ENT_HTML5))); + } +} diff --git a/tests/Feature/PostsOffTest.php b/tests/Feature/PostsOffTest.php new file mode 100644 index 0000000..185a0f2 --- /dev/null +++ b/tests/Feature/PostsOffTest.php @@ -0,0 +1,15 @@ +toBeFalse() + ->and(Route::has('manager.labels.index'))->toBeFalse() + ->and(Schema::hasTable('manager_posts'))->toBeFalse() + ->and(Schema::hasTable('manager_post_labels'))->toBeFalse() + ->and(Manager::permissionValues())->not->toContain('posts.view', 'posts.labels'); +}); diff --git a/tests/Feature/PostsTest.php b/tests/Feature/PostsTest.php new file mode 100644 index 0000000..f4289f0 --- /dev/null +++ b/tests/Feature/PostsTest.php @@ -0,0 +1,288 @@ + 'My first post', + 'slug' => '', + 'excerpt' => 'A short text', + 'body' => "# Hello\n\nSome **markdown**.", + 'cover_image' => '', + 'category' => 'Tutorial', + 'tags' => ['Laravel', ' Vue ', ''], + 'is_featured' => true, + 'is_published' => true, + 'published_at' => '', + ...$overrides, + ]; +} + +function post(array $attributes = []): Post +{ + static $n = 0; + $n++; + + return Post::create([ + 'title' => "Post {$n}", + 'slug' => "post-{$n}", + 'body' => 'Body', + 'published_at' => now()->subDay(), + ...$attributes, + ]); +} + +beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true))); + +describe('post list', function () { + it('shows drafts first, then the newest posts, with their status', function () { + post(['title' => 'Published']); + post(['title' => 'Scheduled', 'published_at' => now()->addWeek()]); + post(['title' => 'Draft', 'published_at' => null]); + + $this->getJson('/manager/posts')->assertOk() + ->assertJsonCount(3, 'posts') + ->assertJsonPath('posts.0.status', 'draft') + ->assertJsonPath('posts.1.status', 'scheduled') + ->assertJsonPath('posts.2.status', 'published'); + }); +}); + +describe('creating a post', function () { + it('offers the configured categories, the ones in use, the ones of the site, and tags', function () { + post(['category' => 'Tutorial', 'tags' => ['php']]); + post(['category' => 'Tutorial']); + post(['category' => null]); + app(PostLabels::class)->suggestCategories(fn () => ['Services']); + + $this->getJson('/manager/posts/create')->assertOk() + ->assertJsonPath('post', null) + ->assertJsonPath('categories', ['Services', 'General', 'Tutorial']) + ->assertJsonPath('known_tags', ['php']); + }); + + it('publishes now when no date is given, and makes the slug from the title', function () { + $this->freezeSecond(); + + $this->postJson('/manager/posts', postForm())->assertCreated(); + + $post = Post::sole(); + expect($post->slug)->toBe('my-first-post') + ->and($post->tags)->toBe(['Laravel', 'Vue']) + ->and($post->is_featured)->toBeTrue() + ->and($post->published_at?->equalTo(now()))->toBeTrue() + ->and(Post::published()->count())->toBe(1); + }); + + it('saves a draft without a publish date', function () { + $this->postJson('/manager/posts', postForm(['is_published' => false, 'published_at' => '2026-01-01T10:00'])); + + expect(Post::sole()->published_at)->toBeNull()->and(Post::sole()->status())->toBe('draft'); + }); + + it('schedules a post with a date in the future', function () { + $this->travelTo('2026-11-17 12:00'); + + $this->postJson('/manager/posts', postForm(['published_at' => '2026-12-01T09:30'])); + + $post = Post::sole(); + expect($post->published_at?->format('Y-m-d H:i'))->toBe('2026-12-01 09:30') + ->and($post->isPublished())->toBeFalse() + ->and($post->status())->toBe('scheduled') + ->and(Post::published()->count())->toBe(0); + }); + + it('gives a second post with the same title its own slug', function () { + $this->postJson('/manager/posts', postForm()); + $this->postJson('/manager/posts', postForm()); + + expect(Post::orderBy('id')->pluck('slug')->all())->toBe(['my-first-post', 'my-first-post-2']); + }); + + it('stores empty optional fields as null', function () { + $this->postJson('/manager/posts', postForm(['excerpt' => '', 'cover_image' => '', 'category' => '', 'tags' => []])); + + $post = Post::sole(); + expect($post->excerpt)->toBeNull()->and($post->cover_image)->toBeNull()->and($post->category)->toBeNull()->and($post->tags)->toBe([]); + }); + + it('validates the form', function (array $input, string $field) { + post(['slug' => 'taken']); + + $this->postJson('/manager/posts', postForm($input))->assertJsonValidationErrors($field); + + expect(Post::count())->toBe(1); + })->with([ + 'missing title' => [['title' => ''], 'title'], + 'missing body' => [['body' => ''], 'body'], + 'slug in use' => [['slug' => 'taken'], 'slug'], + 'slug with spaces' => [['slug' => 'Not A Slug'], 'slug'], + 'invalid date' => [['published_at' => 'tomorrow-ish'], 'published_at'], + ]); +}); + +describe('editing a post', function () { + it('shows the form filled in', function () { + $post = post(['published_at' => '2026-03-04 15:30:00']); + + $this->getJson("/manager/posts/{$post->id}/edit")->assertOk() + ->assertJsonPath('post.id', $post->id) + ->assertJsonPath('post.is_published', true) + ->assertJsonPath('post.published_at', '2026-03-04T15:30'); + }); + + it('updates the post and keeps its own slug valid', function () { + $post = post(['slug' => 'my-slug']); + + $this->putJson("/manager/posts/{$post->id}", postForm(['title' => 'New title', 'slug' => 'my-slug']))->assertOk(); + + expect($post->refresh()->title)->toBe('New title')->and($post->slug)->toBe('my-slug'); + }); + + it('keeps the original publish date when saving without a date', function () { + $post = post(['published_at' => '2024-04-09 10:00:00']); + + $this->putJson("/manager/posts/{$post->id}", postForm(['published_at' => ''])); + + expect($post->refresh()->published_at?->toDateTimeString())->toBe('2024-04-09 10:00:00'); + }); + + it('unpublishes a post, which hides it from the site', function () { + $post = post(['slug' => 'my-slug']); + + $this->putJson("/manager/posts/{$post->id}", postForm(['slug' => 'my-slug', 'is_published' => false])); + + expect($post->refresh()->published_at)->toBeNull()->and(Post::published()->count())->toBe(0); + }); + + it('puts a post online and takes it off again', function () { + $post = post(['published_at' => null]); + + $this->putJson("/manager/posts/{$post->id}/online", ['online' => true])->assertJsonPath('status', 'published'); + $this->putJson("/manager/posts/{$post->id}/online", ['online' => false])->assertJsonPath('status', 'draft'); + }); + + it('previews a draft, with the markdown rendered and raw html escaped', function () { + $post = post(['published_at' => null, 'body' => "**Draft** text \n\n[out](https://example.org)"]); + + $html = $this->getJson("/manager/posts/{$post->id}/preview")->assertOk()->assertJsonPath('preview', true)->json('post.body_html'); + + expect($html)->toContain('Draft')->not->toContain('