Gruppen-Plugin 1.0.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 17:17:10 +00:00
commit 5bdfb8a082
49 changed files with 4679 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules/
*.zip

38
README.md Normal file
View file

@ -0,0 +1,38 @@
# Gruppen – Diskussionsgruppen für Inhaus
Austausch zu Themen, Hobbys und Projekten – wie Gruppen bei Facebook, im eigenen Mitarbeiterportal.
- **Alle können Gruppen gründen**, in drei Arten:
- **Offen** – alle sehen die Beiträge und treten mit einem Klick bei.
- **Geschlossen** – alle finden die Gruppe, Beiträge sehen nur Mitglieder; Beitritt auf Anfrage.
- **Privat** – nur Mitglieder finden die Gruppe; Beitritt nur auf Einladung.
- **Beiträge** mit Text (Links werden erkannt), bis zu 10 **Fotos und Dateien**, **Umfragen** (eine oder mehrere
Antworten), **Reaktionen** (👍 ❤️ 😂 😮 😢 👏), **Kommentare mit Antworten**; eigene Beiträge bearbeiten.
- **Rollen** je Gruppe: Admin, Moderation, Mitglied. Admins bearbeiten die Gruppe (Name, Beschreibung, Art,
Titelbild), vergeben Rollen und löschen die Gruppe; Moderation nimmt Anfragen an, **pinnt** Beiträge (bis zu 3),
löscht Beiträge und Kommentare und bearbeitet **Meldungen** der Mitglieder.
- **Benachrichtigungen**: neuer Beitrag (je Gruppe einmal, bis man wieder vorbeischaut; pro Gruppe abschaltbar),
Kommentare zu eigenen Beiträgen, Antworten, Einladungen, Beitrittsanfragen.
- Feed „Neues aus Ihren Gruppen“, Gruppen entdecken, Treffer in der globalen Suche, Startseiten-Kachel,
Abschnitt im Wochenüberblick.
- Fotos, Dateien und Titelbilder liegen nicht im öffentlichen Ordner und werden nur an Berechtigte ausgeliefert.
Das Recht **„Alle Gruppen verwalten“** (Rollen) erlaubt, auch private Gruppen zu sehen und bei Meldungen
einzugreifen – bitte nur an die Personen vergeben, die das wirklich brauchen.
Voraussetzung: Inhaus **0.39.0** oder neuer.
## Installation
1. `gruppen-<version>.zip` unter https://git.loheide.cloud/friloo/inhaus-plugin-gruppen/releases laden.
2. Backend → **Plugins** → hochladen → aktivieren. Updates erscheinen danach automatisch.
## Entwicklung
```bash
npm install && npm run build # dist/ wird eingecheckt
npm run package # gruppen-<version>.zip
```
Tests laufen in einer Inhaus-Installation mit dem Plugin unter `plugins/gruppen`:
`vendor-dev/bin/phpunit plugins/gruppen/tests`.

29
bin/package Executable file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env php
<?php
/**
* Baut gruppen-<version>.zip zum Hochladen unter Administration → Plugins.
* Enthält alles außer Quelltexten fürs Frontend-Build und node_modules.
*/
$root = dirname(__DIR__);
$manifest = json_decode(file_get_contents("{$root}/plugin.json"), true);
$target = "{$root}/gruppen-{$manifest['version']}.zip";
$skip = ['node_modules', '.git', 'inhaus-sdk', 'package.json', 'package-lock.json', 'vite.config.js', basename($target)];
@unlink($target);
$zip = new ZipArchive;
$zip->open($target, ZipArchive::CREATE);
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
foreach ($files as $file) {
$relative = substr($file->getPathname(), strlen($root) + 1);
if (in_array(explode(DIRECTORY_SEPARATOR, $relative)[0], $skip, true) || str_ends_with($relative, '.zip')) {
continue;
}
$zip->addFile($file->getPathname(), 'gruppen/'.$relative);
}
$zip->close();
echo "Paket: {$target}\n";

View file

@ -0,0 +1,117 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('gruppen_groups', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->string('slug', 120)->unique();
$table->text('description')->nullable();
$table->string('cover_path', 300)->nullable();
// open: jeder tritt bei | closed: sichtbar, Beitritt auf Anfrage | secret: unsichtbar, nur auf Einladung
$table->string('privacy', 10)->default('open');
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->unsignedInteger('members_count')->default(0);
$table->unsignedInteger('posts_count')->default(0);
$table->timestamp('last_activity_at')->nullable()->index();
$table->timestamps();
});
Schema::create('gruppen_members', function (Blueprint $table) {
$table->foreignId('group_id')->constrained('gruppen_groups')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('role', 10)->default('member'); // admin | moderator | member
$table->string('status', 10)->default('active'); // active | pending | invited
$table->foreignId('invited_by')->nullable()->constrained('users')->nullOnDelete();
$table->string('notify', 10)->default('all'); // all | off
$table->timestamp('joined_at')->nullable();
$table->timestamp('last_seen_at')->nullable();
$table->timestamp('notified_at')->nullable();
$table->timestamps();
$table->primary(['group_id', 'user_id']);
$table->index(['user_id', 'status']);
});
Schema::create('gruppen_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('group_id')->constrained('gruppen_groups')->cascadeOnDelete();
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->text('body')->nullable();
$table->json('poll')->nullable(); // { options: [...], multiple: bool }
$table->timestamp('pinned_at')->nullable();
$table->timestamp('edited_at')->nullable();
$table->unsignedInteger('comments_count')->default(0);
$table->timestamps();
$table->index(['group_id', 'created_at']);
});
Schema::create('gruppen_attachments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained('gruppen_posts')->cascadeOnDelete();
$table->string('path', 300);
$table->string('thumb_path', 300)->nullable();
$table->string('name', 200);
$table->string('mime', 100);
$table->unsignedBigInteger('size');
$table->unsignedInteger('width')->nullable();
$table->unsignedInteger('height')->nullable();
$table->unsignedSmallInteger('sort')->default(0);
});
Schema::create('gruppen_poll_votes', function (Blueprint $table) {
$table->foreignId('post_id')->constrained('gruppen_posts')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->unsignedTinyInteger('option');
$table->primary(['post_id', 'user_id', 'option']);
});
Schema::create('gruppen_comments', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained('gruppen_posts')->cascadeOnDelete();
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('parent_id')->nullable()->constrained('gruppen_comments')->cascadeOnDelete();
$table->text('body');
$table->timestamp('edited_at')->nullable();
$table->timestamps();
$table->index(['post_id', 'id']);
});
Schema::create('gruppen_reactions', function (Blueprint $table) {
$table->foreignId('post_id')->constrained('gruppen_posts')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('emoji', 16);
$table->primary(['post_id', 'user_id']);
});
Schema::create('gruppen_reports', function (Blueprint $table) {
$table->id();
$table->foreignId('group_id')->constrained('gruppen_groups')->cascadeOnDelete();
$table->foreignId('post_id')->constrained('gruppen_posts')->cascadeOnDelete();
$table->foreignId('comment_id')->nullable()->constrained('gruppen_comments')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('reason', 500);
$table->timestamp('resolved_at')->nullable();
$table->timestamps();
$table->unique(['user_id', 'post_id', 'comment_id']);
});
}
public function down(): void
{
foreach (['gruppen_reports', 'gruppen_reactions', 'gruppen_comments', 'gruppen_poll_votes', 'gruppen_attachments', 'gruppen_posts', 'gruppen_members', 'gruppen_groups'] as $table) {
Schema::dropIfExists($table);
}
}
};

2
dist/assets/style-CWIv2Jl3.css vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/chunks/GroupCard-5fLVVVGb.js vendored Normal file
View file

@ -0,0 +1 @@
import{n as e}from"./loader-circle-CxzeMpQS.js";import{a as t,i as n,n as r,o as i}from"./GroupDialog-DkTJQL7Q.js";import{createBlock as a,createCommentVNode as o,createElementBlock as s,createElementVNode as c,createTextVNode as l,createVNode as u,normalizeStyle as d,openBlock as f,resolveDynamicComponent as p,toDisplayString as m,unref as h,withCtx as g}from"vue";import{Link as _,router as v}from"@inertiajs/vue3";import{Button as y}from"@inhaus/ui";var b=e({name:`compass`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`,key:`9ktpf1`}]]}),x={class:`ih:flex ih:flex-col ih:overflow-hidden ih:rounded-xl ih:border ih:bg-card ih:shadow-xs`},S={class:`ih:flex ih:flex-1 ih:flex-col ih:gap-1 ih:p-4`},C={class:`ih:flex ih:items-center ih:gap-1.5 ih:text-xs ih:text-muted-foreground`},w={key:0,class:`ih:line-clamp-2 ih:text-sm ih:text-muted-foreground`},T={class:`ih:mt-auto ih:pt-3`},E={__name:`GroupCard`,props:{group:{type:Object,required:!0}},setup(e){let b=e,E={open:t,closed:n,secret:i},D=()=>v.post(`/gruppen/${b.group.slug}/beitreten`,{},{preserveScroll:!0});return(t,n)=>(f(),s(`article`,x,[u(h(_),{href:e.group.url,class:`ih:block ih:h-24 ih:bg-brand ih:bg-cover ih:bg-center`,style:d(e.group.cover_url?{backgroundImage:`url(${e.group.cover_url})`}:{}),"aria-label":e.group.name},null,8,[`href`,`style`,`aria-label`]),c(`div`,S,[u(h(_),{href:e.group.url,class:`ih:font-semibold ih:hover:underline`},{default:g(()=>[l(m(e.group.name),1)]),_:1},8,[`href`]),c(`p`,C,[(f(),a(p(E[e.group.privacy]),{class:`ih:size-3.5`})),l(` `+m(e.group.privacy_label)+` · `,1),u(h(r),{class:`ih:size-3.5`}),l(` `+m(e.group.members_count),1)]),e.group.description?(f(),s(`p`,w,m(e.group.description),1)):o(``,!0),c(`div`,T,[e.group.status===`active`?(f(),a(h(y),{key:0,variant:`outline`,size:`sm`,class:`ih:w-full`,"as-child":``},{default:g(()=>[u(h(_),{href:e.group.url},{default:g(()=>[...n[0]||=[l(`Ansehen`,-1)]]),_:1},8,[`href`])]),_:1})):e.group.status===`pending`?(f(),a(h(y),{key:1,variant:`outline`,size:`sm`,class:`ih:w-full`,disabled:``},{default:g(()=>[...n[1]||=[l(`Angefragt`,-1)]]),_:1})):(f(),a(h(y),{key:2,size:`sm`,class:`ih:w-full`,onClick:D},{default:g(()=>[l(m(e.group.status===`invited`?`Einladung annehmen`:e.group.privacy===`open`?`Beitreten`:`Beitritt anfragen`),1)]),_:1}))])])]))}};export{b as n,E as t};

1
dist/chunks/GroupDialog-DkTJQL7Q.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/chunks/PostCard-hYMtqskw.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/chunks/loader-circle-CxzeMpQS.js vendored Normal file
View file

@ -0,0 +1 @@
import{h as e,inject as t}from"vue";var n={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},r=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim();function i(e){return e!=null}function a(e,t={}){let a=t.attributeNames??{},o=e=>a[e]??e,s=e.size??e.width??n.width,c=e.size??e.height??n.height,l=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],u=[...e.name?[`lucide-${e.name}`]:[],...l],d=t.className?.split(` `).filter(Boolean)??[],f=t.includeDefaultClasses===!1?r(...d):r(`lucide`,...u,...d),p=t.absoluteStrokeWidth?Number(t.strokeWidth??n[`stroke-width`])*Number(e.size??e.width??n.width)/Number(t.size??t.width??n.width):t.strokeWidth??n[`stroke-width`];return[`svg`,{...Object.entries(n).reduce((e,[t,n])=>(e[o(t)]=n,e),{}),...`color`in t&&t.color&&{[o(`stroke`)]:t.color},...`size`in t&&i(t.size)&&{[o(`width`)]:t.size,[o(`height`)]:t.size},...`width`in t&&i(t.width)&&{[o(`width`)]:t.width},...`height`in t&&i(t.height)&&{[o(`height`)]:t.height},[o(`stroke-width`)]:p,...f&&{[o(`class`)]:f},[o(`viewBox`)]:`0 0 ${s} ${c}`,...t.hasA11yProp===!1?{[o(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,r,i]=e,a=t.nonScalingStroke?{[o(`vector-effect`)]:`non-scaling-stroke`,...r}:r;return i?[n,a,i]:[n,a]})]}var o=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},s=e=>e===``,c=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),l=Symbol(`lucide-icons`);function u(){return t(l,{})}var d=({name:t,iconNode:n,"icon-node":r,icon:i={name:t&&c(t),node:n??r??[],size:24,aliases:[]},absoluteStrokeWidth:l,"absolute-stroke-width":d,nonScalingStroke:f,"non-scaling-stroke":p,strokeWidth:m,"stroke-width":h,size:g,width:_=g,height:v=g,color:y,...b},{slots:x})=>{let{size:S,color:C,strokeWidth:w=2,absoluteStrokeWidth:T=!1,nonScalingStroke:E=!1,class:D=``}=u(),O=s(l)||s(d)||l===!0||d===!0||T===!0,k=s(f)||s(p)||f===!0||p===!0||E===!0;delete b.class;let A=x.default?.(),[,j,M=[]]=a(i,{color:y??C,width:_??g??S,height:v??g??S,strokeWidth:m??h??w,absoluteStrokeWidth:O,nonScalingStroke:k,className:D,hasA11yProp:A!=null&&A.length>0||o(b),attributes:b});return e(`svg`,j,[...M.map(([t,n])=>e(t,n)),...A??[]])};function f(t,n=[]){let r=typeof t==`string`?{name:t,node:n}:t;return(t,{slots:n})=>e(d,{...t,icon:r},n.default?{default:n.default}:void 0)}var p=f({name:`loader-circle`,size:24,node:[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]],aliases:[`loader-2`]});export{f as n,p as t};

1
dist/chunks/search-7rL_HYGC.js vendored Normal file
View file

@ -0,0 +1 @@
import{n as e}from"./loader-circle-CxzeMpQS.js";var t=e({name:`search`,size:24,node:[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]});export{t};

12
dist/inhaus.json vendored Normal file
View file

@ -0,0 +1,12 @@
{
"components": {
"pages/Discover": "pages/Discover.js",
"pages/Index": "pages/Index.js",
"pages/Post": "pages/Post.js",
"pages/Show": "pages/Show.js",
"widgets/Recent": "widgets/Recent.js"
},
"css": [
"assets/style-CWIv2Jl3.css"
]
}

1
dist/pages/Discover.js vendored Normal file
View file

@ -0,0 +1 @@
import{n as e,t}from"../chunks/GroupCard-5fLVVVGb.js";import{r as n,t as r}from"../chunks/GroupDialog-DkTJQL7Q.js";import{t as i}from"../chunks/search-7rL_HYGC.js";import{Fragment as a,createBlock as o,createCommentVNode as s,createElementBlock as c,createElementVNode as l,createTextVNode as u,createVNode as d,openBlock as f,ref as p,renderList as m,unref as h,vModelText as g,watch as _,withCtx as v,withDirectives as y}from"vue";import{Link as b,router as x,usePage as S}from"@inertiajs/vue3";import{AppLayout as C,Button as w,EmptyState as T,PageHeader as E,toast as D}from"@inhaus/ui";var O={class:`ih:relative ih:mb-5 ih:max-w-md`},k={key:0,class:`ih:grid ih:gap-4 ih:sm:grid-cols-2 ih:lg:grid-cols-3 ih:xl:grid-cols-4`},A={key:1,class:`ih:rounded-xl ih:border ih:bg-card`},j={key:2,class:`ih:mt-6 ih:flex ih:justify-between ih:text-sm`},M={key:1},N={__name:`Discover`,props:{groups:{type:Array,required:!0},pagination:{type:Object,required:!0},q:{type:String,default:``},privacy:{type:Object,required:!0},privacyHints:{type:Object,required:!0}},setup(N){let P=N,F=S();_(()=>F.props.flash?.status,e=>e&&D.success(e),{immediate:!0});let I=p(P.q),L=p(!1),R;return _(I,e=>{clearTimeout(R),R=setTimeout(()=>x.get(`/gruppen/entdecken`,e?{q:e}:{},{preserveState:!0}),300)}),(p,_)=>(f(),o(h(C),{title:`Gruppen entdecken`},{default:v(()=>[d(h(E),{title:`Gruppen entdecken`,breadcrumbs:[{label:`Gruppen`,href:`/gruppen`}]},{actions:v(()=>[d(h(w),{onClick:_[0]||=e=>L.value=!0},{default:v(()=>[d(h(n)),_[3]||=u(` Gruppe gründen`,-1)]),_:1})]),_:1}),l(`div`,O,[d(h(i),{class:`ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground`}),y(l(`input`,{"onUpdate:modelValue":_[1]||=e=>I.value=e,type:`search`,placeholder:`Gruppen suchen`,"aria-label":`Gruppen suchen`,class:`ih:h-10 ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-card ih:pr-3 ih:pl-8 ih:text-sm ih:shadow-xs`},null,512),[[g,I.value]])]),N.groups.length?(f(),c(`div`,k,[(f(!0),c(a,null,m(N.groups,e=>(f(),o(t,{key:e.id,group:e},null,8,[`group`]))),128))])):(f(),c(`div`,A,[d(h(T),{icon:h(e),title:N.q?`Keine passenden Gruppen`:`Noch keine Gruppen`,text:`Gründen Sie die erste!`},null,8,[`icon`,`title`])])),N.pagination.prev||N.pagination.next?(f(),c(`nav`,j,[N.pagination.prev?(f(),o(h(b),{key:0,href:N.pagination.prev,class:`ih:text-brand-text ih:hover:underline`},{default:v(()=>[..._[4]||=[u(`← Zurück`,-1)]]),_:1},8,[`href`])):(f(),c(`span`,M)),N.pagination.next?(f(),o(h(b),{key:2,href:N.pagination.next,class:`ih:text-brand-text ih:hover:underline`},{default:v(()=>[..._[5]||=[u(`Weiter →`,-1)]]),_:1},8,[`href`])):s(``,!0)])):s(``,!0),d(r,{open:L.value,"onUpdate:open":_[2]||=e=>L.value=e,privacy:N.privacy,"privacy-hints":N.privacyHints},null,8,[`open`,`privacy`,`privacy-hints`])]),_:1}))}};export{N as default};

1
dist/pages/Index.js vendored Normal file
View file

@ -0,0 +1 @@
import{n as e,t}from"../chunks/loader-circle-CxzeMpQS.js";import{n,t as r}from"../chunks/GroupCard-5fLVVVGb.js";import{t as i}from"../chunks/PostCard-hYMtqskw.js";import{r as a,t as o}from"../chunks/GroupDialog-DkTJQL7Q.js";import{Fragment as s,createBlock as c,createCommentVNode as l,createElementBlock as u,createElementVNode as d,createTextVNode as f,createVNode as p,normalizeStyle as m,openBlock as h,ref as g,renderList as _,toDisplayString as v,unref as y,watch as b,withCtx as x}from"vue";import{Link as S,usePage as C}from"@inertiajs/vue3";import{AppLayout as w,Button as T,EmptyState as E,PageHeader as D,http as O,toast as k}from"@inhaus/ui";var A=e({name:`users-round`,size:24,node:[[`path`,{d:`M18 21a8 8 0 0 0-16 0`,key:`3ypg7q`}],[`circle`,{cx:`10`,cy:`8`,r:`5`,key:`o932ke`}],[`path`,{d:`M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3`,key:`10s06x`}]],aliases:[`users-2`]}),j={class:`ih:grid ih:gap-6 ih:lg:grid-cols-[minmax(0,1fr)_20rem]`},M={class:`ih:mx-auto ih:grid ih:w-full ih:max-w-2xl ih:content-start ih:gap-4`,"aria-label":`Neue Beiträge aus Ihren Gruppen`},N={key:1,class:`ih:rounded-xl ih:border ih:bg-card`},P={class:`ih:grid ih:content-start ih:gap-5`},F={key:0,class:`ih:rounded-xl ih:border ih:border-brand/40 ih:bg-brand-soft/40 ih:p-4`},I={class:`ih:grid ih:gap-3`},L={class:`ih:rounded-xl ih:border ih:bg-card ih:p-4`},R={key:0,class:`ih:-mx-2 ih:grid`},z={class:`ih:min-w-0`},B={class:`ih:block ih:truncate ih:text-sm ih:font-medium`},V={class:`ih:text-xs ih:text-muted-foreground`},H={key:1,class:`ih:text-sm ih:text-muted-foreground`},U={key:1,class:`ih:grid ih:gap-3`},W={__name:`Index`,props:{posts:{type:Array,required:!0},more:{type:Boolean,default:!1},groups:{type:Array,required:!0},invitations:{type:Array,default:()=>[]},suggested:{type:Array,default:()=>[]},privacy:{type:Object,required:!0},privacyHints:{type:Object,required:!0}},setup(e){let W=e,G=C();b(()=>G.props.flash?.status,e=>e&&k.success(e),{immediate:!0});let K=g(W.posts),q=g(W.more),J=g(!1),Y=g(!1),X=[`👍`,`❤️`,`😂`,`😮`,`😢`,`👏`];async function Z(){J.value=!0;let e=await O.get(`/gruppen?vor=${K.value.at(-1).id}`);K.value.push(...e.posts),q.value=e.more,J.value=!1}return(g,b)=>(h(),c(y(w),{title:`Gruppen`},{default:x(()=>[p(y(D),{title:`Gruppen`,description:`Austausch zu Themen, Hobbys und Projekten – offen, geschlossen oder privat.`},{actions:x(()=>[p(y(T),{variant:`outline`,"as-child":``},{default:x(()=>[p(y(S),{href:`/gruppen/entdecken`},{default:x(()=>[p(y(n)),b[2]||=f(` Gruppen entdecken`,-1)]),_:1})]),_:1}),p(y(T),{onClick:b[0]||=e=>Y.value=!0},{default:x(()=>[p(y(a)),b[3]||=f(` Gruppe gründen`,-1)]),_:1})]),_:1}),d(`div`,j,[d(`section`,M,[(h(!0),u(s,null,_(K.value,e=>(h(),c(i,{key:e.id,post:e,reactions:X,"show-group":``,onDeleted:t=>K.value=K.value.filter(t=>t.id!==e.id)},null,8,[`post`,`onDeleted`]))),128)),q.value?(h(),c(y(T),{key:0,variant:`outline`,disabled:J.value,onClick:Z},{default:x(()=>[J.value?(h(),c(y(t),{key:0,class:`ih:animate-spin`})):l(``,!0),b[4]||=f(` Ältere Beiträge laden`,-1)]),_:1},8,[`disabled`])):l(``,!0),K.value.length?l(``,!0):(h(),u(`div`,N,[p(y(E),{icon:y(A),title:e.groups.length?`Noch keine Beiträge`:`Sie sind noch in keiner Gruppe`,text:e.groups.length?`Schreiben Sie den ersten Beitrag in einer Ihrer Gruppen.`:`Entdecken Sie Gruppen zu Ihren Themen – oder gründen Sie selbst eine.`},null,8,[`icon`,`title`,`text`])]))]),d(`aside`,P,[e.invitations.length?(h(),u(`section`,F,[b[5]||=d(`h2`,{class:`ih:mb-2 ih:text-sm ih:font-semibold`},`Einladungen`,-1),d(`div`,I,[(h(!0),u(s,null,_(e.invitations,e=>(h(),c(r,{key:e.id,group:e},null,8,[`group`]))),128))])])):l(``,!0),d(`section`,L,[b[6]||=d(`h2`,{class:`ih:mb-2 ih:text-sm ih:font-semibold`},`Ihre Gruppen`,-1),e.groups.length?(h(),u(`ul`,R,[(h(!0),u(s,null,_(e.groups,e=>(h(),u(`li`,{key:e.id},[p(y(S),{href:e.url,class:`ih:flex ih:items-center ih:gap-3 ih:rounded-md ih:p-2 ih:hover:bg-accent/60`},{default:x(()=>[d(`span`,{class:`ih:size-10 ih:shrink-0 ih:rounded-md ih:bg-brand ih:bg-cover ih:bg-center`,style:m(e.cover_url?{backgroundImage:`url(${e.cover_url})`}:{})},null,4),d(`span`,z,[d(`span`,B,v(e.name),1),d(`span`,V,v(e.members_count)+` `+v(e.members_count===1?`Mitglied`:`Mitglieder`),1)])]),_:2},1032,[`href`])]))),128))])):(h(),u(`p`,H,`Noch keine.`))]),e.suggested.length?(h(),u(`section`,U,[b[7]||=d(`h2`,{class:`ih:text-sm ih:font-semibold`},`Vorschläge`,-1),(h(!0),u(s,null,_(e.suggested,e=>(h(),c(r,{key:e.id,group:e},null,8,[`group`]))),128))])):l(``,!0)])]),p(o,{open:Y.value,"onUpdate:open":b[1]||=e=>Y.value=e,privacy:e.privacy,"privacy-hints":e.privacyHints},null,8,[`open`,`privacy`,`privacy-hints`])]),_:1}))}};export{W as default};

1
dist/pages/Post.js vendored Normal file
View file

@ -0,0 +1 @@
import{n as e}from"../chunks/loader-circle-CxzeMpQS.js";import{i as t,t as n}from"../chunks/PostCard-hYMtqskw.js";import{Fragment as r,createBlock as i,createCommentVNode as a,createElementBlock as o,createElementVNode as s,createTextVNode as c,createVNode as l,onMounted as u,openBlock as d,renderList as f,toDisplayString as p,unref as m,withCtx as h}from"vue";import{Link as g,router as _}from"@inertiajs/vue3";import{AppLayout as v,Button as y,http as b,toast as x}from"@inhaus/ui";var S=e({name:`chevron-left`,size:24,node:[[`path`,{d:`m15 18-6-6 6-6`,key:`1wnfg3`}]]}),C={class:`ih:mx-auto ih:grid ih:max-w-2xl ih:gap-4`},w={key:0,class:`ih:rounded-md ih:border ih:border-destructive/30 ih:bg-destructive/5 ih:p-3 ih:text-sm`},T={class:`ih:flex ih:items-center ih:gap-2 ih:font-medium`},E={class:`ih:mt-1 ih:list-disc ih:pl-6 ih:text-muted-foreground`},D={__name:`Post`,props:{group:{type:Object,required:!0},post:{type:Object,required:!0},comments:{type:Array,required:!0},reactions:{type:Array,required:!0},reports:{type:Array,default:()=>[]}},setup(e){let D=e;u(()=>{(location.hash&&document.querySelector(location.hash))?.scrollIntoView({block:`center`})});async function O(){await b.post(`/gruppen/beitraege/${D.post.id}/meldungen-erledigt`),x.success(`Meldungen erledigt`),_.reload()}return(u,b)=>(d(),i(m(v),{title:`Beitrag in ${e.group.name}`},{default:h(()=>[s(`div`,C,[l(m(g),{href:e.group.url,class:`ih:inline-flex ih:items-center ih:gap-1 ih:text-sm ih:font-medium ih:text-muted-foreground ih:hover:text-foreground`},{default:h(()=>[l(m(S),{class:`ih:size-4`}),c(` `+p(e.group.name),1)]),_:1},8,[`href`]),e.reports.length?(d(),o(`div`,w,[s(`p`,T,[l(m(t),{class:`ih:size-4 ih:text-destructive`}),c(` `+p(e.reports.length)+` `+p(e.reports.length===1?`Meldung`:`Meldungen`),1)]),s(`ul`,E,[(d(!0),o(r,null,f(e.reports,e=>(d(),o(`li`,{key:e.id},p(e.comment_id?`Kommentar: `:``)+p(e.reason),1))),128))]),l(m(y),{size:`sm`,variant:`outline`,class:`ih:mt-2`,onClick:O},{default:h(()=>[...b[1]||=[c(`In Ordnung – erledigt`,-1)]]),_:1})])):a(``,!0),l(n,{post:e.post,reactions:e.reactions,"full-comments":e.comments,onDeleted:b[0]||=t=>m(_).visit(e.group.url)},null,8,[`post`,`reactions`,`full-comments`])])]),_:1},8,[`title`]))}};export{D as default};

1
dist/pages/Show.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/widgets/Recent.js vendored Normal file
View file

@ -0,0 +1 @@
import{Fragment as e,createBlock as t,createCommentVNode as n,createElementBlock as r,createElementVNode as i,createTextVNode as a,openBlock as o,renderList as s,toDisplayString as c,unref as l,withCtx as u}from"vue";import{Panel as d,PersonAvatar as f,formatRelative as p}from"@inhaus/ui";var m={class:`ih:-my-1 ih:grid ih:gap-1`},h=[`href`],g={class:`ih:min-w-0 ih:text-sm`},_={class:`ih:block ih:truncate`},v={class:`ih:font-medium`},y={class:`ih:text-muted-foreground`},b={class:`ih:line-clamp-2 ih:text-[13px] ih:text-muted-foreground`},x={class:`ih:text-xs ih:text-muted-foreground`},S={__name:`Recent`,props:{posts:{type:Array,required:!0}},setup(S){return(C,w)=>(o(),t(l(d),{title:`Aus Ihren Gruppen`,"action-label":`Alle Gruppen`,"action-href":`/gruppen`},{default:u(()=>[i(`ul`,m,[(o(!0),r(e,null,s(S.posts,e=>(o(),r(`li`,{key:e.id},[i(`a`,{href:e.url,class:`ih:-mx-2 ih:flex ih:gap-2.5 ih:rounded-md ih:p-2 ih:hover:bg-accent/50`},[e.user?(o(),t(l(f),{key:0,person:e.user,class:`ih:size-8 ih:text-[11px]`},null,8,[`person`])):n(``,!0),i(`span`,g,[i(`span`,_,[i(`span`,v,c(e.user?.name),1),w[0]||=a(),i(`span`,y,`in `+c(e.group),1)]),i(`span`,b,c(e.text),1),i(`span`,x,c(l(p)(e.created_at)),1)])],8,h)]))),128))])]),_:1}))}};export{S as default};

63
inhaus-sdk/theme.css Normal file
View file

@ -0,0 +1,63 @@
/*
* Automatisch erzeugt (scripts/generate-sdk-shims.mjs) – Design-Tokens des Portals.
* In der style.css eines Plugins: @import "../../inhaus-sdk/theme.css";
* Farben, Ecken und Schrift folgen so dem Erscheinungsbild der Installation.
*
* Tailwind-Klassen in Plugins tragen das Präfix „ih:“ (z. B. ih:grid, ih:lg:grid-cols-2, ih:bg-brand).
* So kann das CSS eines Plugins nie die Klassen des Portals überschreiben.
* Nur Hilfsklassen – Grundstile (Preflight) bringt das Portal selbst mit.
*/
@import "tailwindcss/theme" layer(theme) prefix(ih);
@import "tailwindcss/utilities" layer(utilities);
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-sans: var(--font-body);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.5);
--radius-2xl: calc(var(--radius) * 2);
/* „Pille“: voll gerundet – außer bei „Eckig“ im Erscheinungsbild (dann 0) */
--radius-pill: calc(var(--radius) * 1000);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-brand: var(--brand);
--color-brand-foreground: var(--brand-foreground);
--color-brand-text: var(--brand-text);
--color-accent2: var(--accent2);
--color-accent2-foreground: var(--accent2-foreground);
--color-accent2-text: var(--accent2-text);
--color-brand-soft: var(--brand-soft);
--color-brand-soft-foreground: var(--brand-soft-foreground);
--color-brand-50: var(--brand-50);
--color-brand-100: var(--brand-100);
--color-brand-200: var(--brand-200);
--color-brand-300: var(--brand-300);
--color-brand-400: var(--brand-400);
--color-brand-500: var(--brand-500);
--color-brand-600: var(--brand-600);
--color-brand-700: var(--brand-700);
--color-brand-800: var(--brand-800);
--color-brand-900: var(--brand-900);
--color-brand-950: var(--brand-950);
}

127
inhaus-sdk/vite.js Normal file
View file

@ -0,0 +1,127 @@
/**
* Vite-Voreinstellung für Inhaus-Plugins (Plugin-SDK).
*
* // vite.config.js im Plugin
* import { defineConfig } from 'vite';
* import { inhausPlugin } from './inhaus-sdk/vite.js';
* export default defineConfig(inhausPlugin());
*
* Baut jede Vue-Datei unter resources/js/{pages,widgets,blocks,profile,profile-panels,editorial,header}/
* als eigenes ES-Modul nach dist/ und schreibt dist/inhaus.json. Vue, Inertia und @inhaus/ui
* bleiben extern – das Portal stellt sie per Import Map bereit.
*/
import { existsSync, globSync } from 'node:fs';
import { resolve } from 'node:path';
import postcss from 'postcss';
import vue from '@vitejs/plugin-vue';
import tailwindcss from '@tailwindcss/vite';
export const KINDS = ['pages', 'widgets', 'blocks', 'profile', 'profile-panels', 'editorial', 'header'];
export const EXTERNAL = ['vue', '@inertiajs/vue3', '@inhaus/ui'];
export function inhausPlugin({ root = process.cwd() } = {}) {
const input = {};
for (const kind of KINDS) {
for (const file of globSync(`resources/js/${kind}/**/*.vue`, { cwd: root })) {
const name = file.replace(`resources/js/${kind}/`, '').replace(/\.vue$/, '');
input[`${kind}/${name}`] = resolve(root, file);
}
}
if (existsSync(resolve(root, 'resources/css/style.css'))) {
input.style = resolve(root, 'resources/css/style.css');
}
if (Object.keys(input).length === 0) {
throw new Error('Keine Oberfläche gefunden: Vue-Dateien gehören nach resources/js/<pages|widgets|blocks|profile|profile-panels|editorial|header>/.');
}
return {
plugins: [vue(), tailwindcss(), manifest(Object.keys(input)), strongerVariants()],
// Plugins laufen unter /plugin-assets/<slug>/<version>/ – Pfade relativ halten
base: './',
build: {
outDir: 'dist',
emptyOutDir: true,
target: 'es2022',
rollupOptions: {
input,
external: EXTERNAL,
preserveEntrySignatures: 'strict',
output: {
format: 'es',
entryFileNames: '[name].js',
chunkFileNames: 'chunks/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash][extname]',
},
},
},
};
}
/** dist/inhaus.json: welche Komponente in welcher Datei steckt, welches CSS dazugehört */
function manifest(entries) {
return {
name: 'inhaus-manifest',
generateBundle(_, bundle) {
const components = {};
const css = [];
for (const file of Object.values(bundle)) {
if (file.type === 'chunk' && file.isEntry && entries.includes(file.name) && file.name !== 'style') {
components[file.name] = file.fileName;
}
if (file.type === 'asset' && file.fileName.endsWith('.css')) {
css.push(file.fileName);
}
}
// Leere Hülle des CSS-Einstiegs nicht ausliefern
for (const [key, file] of Object.entries(bundle)) {
if (file.type === 'chunk' && file.name === 'style') delete bundle[key];
}
this.emitFile({ type: 'asset', fileName: 'inhaus.json', source: JSON.stringify({ components, css: [...new Set(css)] }, null, 4) });
},
};
}
/**
* Mehrere Plugins bringen jeweils eigenes CSS mit, und dieselbe Hilfsklasse (z. B. ih:grid) kann in
* mehreren Dateien stehen. Lädt ein anderes Plugin sein CSS später, würde dessen „ih:grid“ sonst
* die Varianten dieses Plugins (ih:lg:hidden, ih:hover:…) überstimmen. Deshalb bekommen Regeln
* mit Variante (Media Query, :hover …) eine doppelte Klasse – sie gewinnen so immer gegen
* einfache Klassen, egal in welcher Reihenfolge die Dateien laden.
*/
export function strongerVariants() {
const pseudo = /(?<!\\):/;
const firstClass = /\.((?:\\.|[\w-])+)/;
return {
name: 'inhaus-stronger-variants',
enforce: 'post',
generateBundle(_, bundle) {
for (const file of Object.values(bundle)) {
if (file.type !== 'asset' || !file.fileName.endsWith('.css')) continue;
const root = postcss.parse(String(file.source));
root.walkRules((rule) => {
let conditional = false;
for (let parent = rule.parent; parent && parent.type !== 'root'; parent = parent.parent) {
if (parent.type === 'atrule' && parent.name !== 'layer') conditional = true;
}
rule.selectors = rule.selectors.map((selector) => (conditional || pseudo.test(selector.replace(/^[^.]*/, ''))) && firstClass.test(selector)
? selector.replace(firstClass, (match) => match + match)
: selector);
});
file.source = root.toString();
}
},
};
}

1712
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

21
package.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "inhaus-plugin-gruppen",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite build --watch",
"package": "vite build && php bin/package"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@vitejs/plugin-vue": "^6.0.9",
"postcss": "^8.5.28",
"tailwindcss": "^4.3.3",
"vite": "^8.3.1",
"vue": "^3.5.43"
},
"dependencies": {
"@lucide/vue": "^1.48.0"
}
}

14
plugin.json Normal file
View file

@ -0,0 +1,14 @@
{
"slug": "gruppen",
"name": "Gruppen",
"version": "1.0.0",
"description": "Diskussionsgruppen wie bei Facebook: offen, geschlossen (Beitritt auf Anfrage) oder privat (nur auf Einladung). Beiträge mit Fotos, Dateien und Umfragen, Reaktionen, Kommentare mit Antworten, Anpinnen, Melden und Moderation.",
"author": "Loheide",
"namespace": "Inhaus\\Plugins\\Gruppen\\",
"class": "Inhaus\\Plugins\\Gruppen\\GruppenPlugin",
"requires": {
"core": ">=0.39.1",
"php": ">=8.3"
},
"update_url": "https://git.loheide.cloud/api/v1/repos/friloo/inhaus-plugin-gruppen/releases/latest"
}

3
resources/css/style.css Normal file
View file

@ -0,0 +1,3 @@
/* Tailwind mit den Design-Tokens des Portals – Klassen mit Präfix „ih:“, z. B. ih:bg-brand, ih:text-muted-foreground, ih:rounded-lg */
@import "../../inhaus-sdk/theme.css";
@source "../js";

View file

@ -0,0 +1,103 @@
<script setup>
import { ref } from 'vue';
import { CornerDownRight, LoaderCircle, SendHorizontal, Trash2 } from '@lucide/vue';
import { PersonAvatar, formatRelative, http, toast } from '@inhaus/ui';
import RichText from './RichText.vue';
/** Kommentare unter einem Beitrag – mit Antworten (eine Ebene) */
const props = defineProps({
post: { type: Object, required: true },
full: { type: Boolean, default: false },
initial: { type: Array, default: null },
});
const comments = ref(props.initial ?? props.post.comments);
const loadedAll = ref(props.full);
const body = ref('');
const replyTo = ref(null);
const replyBody = ref('');
const busy = ref(false);
async function loadAll() {
comments.value = (await http.get(`/gruppen/beitraege/${props.post.id}/kommentare`)).comments;
loadedAll.value = true;
}
async function send(text, parentId = null) {
if (!text.trim()) return;
busy.value = true;
try {
const data = await http.post(`/gruppen/beitraege/${props.post.id}/kommentare`, { body: text, parent_id: parentId });
comments.value = data.comments;
loadedAll.value = true;
props.post.comments_count = data.comments.reduce((n, c) => n + 1 + c.replies.length, 0);
body.value = replyBody.value = '';
replyTo.value = null;
} catch (error) {
toast.error(error.message);
} finally {
busy.value = false;
}
}
async function remove(comment) {
if (!window.confirm('Kommentar löschen?')) return;
await http.delete(`/gruppen/kommentare/${comment.id}`);
await loadAll();
props.post.comments_count = comments.value.reduce((n, c) => n + 1 + c.replies.length, 0);
}
</script>
<template>
<div class="ih:grid ih:gap-3 ih:border-t ih:px-4 ih:pt-3 ih:pb-4 ih:sm:px-5">
<button v-if="!loadedAll && post.comments_count > comments.length" type="button" class="ih:justify-self-start ih:text-[13px] ih:font-medium ih:text-muted-foreground ih:hover:text-foreground ih:hover:underline" @click="loadAll">
Alle {{ post.comments_count }} Kommentare anzeigen
</button>
<div v-for="c in comments" :id="`kommentar-${c.id}`" :key="c.id" class="ih:grid ih:gap-2">
<div class="ih:flex ih:gap-2.5">
<PersonAvatar v-if="c.user" :person="c.user" class="ih:size-8 ih:text-[11px]" />
<div class="ih:min-w-0 ih:flex-1">
<div class="ih:inline-block ih:max-w-full ih:rounded-2xl ih:bg-muted ih:px-3 ih:py-2 ih:text-sm">
<a v-if="c.user" :href="`/personen/${c.user.id}`" class="ih:font-semibold ih:hover:underline">{{ c.user.name }}</a>
<RichText :text="c.body" :limit="400" />
</div>
<div class="ih:mt-0.5 ih:flex ih:gap-3 ih:px-3 ih:text-xs ih:text-muted-foreground">
<span>{{ formatRelative(c.created_at) }}</span>
<button v-if="post.can_comment" type="button" class="ih:font-medium ih:hover:text-foreground" @click="replyTo = replyTo === c.id ? null : c.id">Antworten</button>
<button v-if="c.can_delete" type="button" class="ih:hover:text-destructive" :aria-label="`Kommentar von ${c.user?.name} löschen`" @click="remove(c)"><Trash2 class="ih:size-3.5" /></button>
</div>
</div>
</div>
<div v-for="r in c.replies" :id="`kommentar-${r.id}`" :key="r.id" class="ih:ml-10 ih:flex ih:gap-2.5">
<PersonAvatar v-if="r.user" :person="r.user" class="ih:size-7 ih:text-[10px]" />
<div class="ih:min-w-0 ih:flex-1">
<div class="ih:inline-block ih:max-w-full ih:rounded-2xl ih:bg-muted ih:px-3 ih:py-2 ih:text-sm">
<a v-if="r.user" :href="`/personen/${r.user.id}`" class="ih:font-semibold ih:hover:underline">{{ r.user.name }}</a>
<RichText :text="r.body" :limit="400" />
</div>
<div class="ih:mt-0.5 ih:flex ih:gap-3 ih:px-3 ih:text-xs ih:text-muted-foreground">
<span>{{ formatRelative(r.created_at) }}</span>
<button v-if="r.can_delete" type="button" class="ih:hover:text-destructive" aria-label="Antwort löschen" @click="remove(r)"><Trash2 class="ih:size-3.5" /></button>
</div>
</div>
</div>
<form v-if="replyTo === c.id" class="ih:ml-10 ih:flex ih:items-center ih:gap-2" @submit.prevent="send(replyBody, c.id)">
<CornerDownRight class="ih:size-4 ih:shrink-0 ih:text-muted-foreground" />
<input v-model="replyBody" maxlength="3000" :placeholder="`Antwort an ${c.user?.name ?? ''}`" aria-label="Antwort" autofocus class="ih:h-9 ih:min-w-0 ih:flex-1 ih:rounded-full ih:border ih:border-input ih:bg-background ih:px-4 ih:text-sm ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none" />
</form>
</div>
<form v-if="post.can_comment" class="ih:flex ih:items-center ih:gap-2" @submit.prevent="send(body)">
<input v-model="body" maxlength="3000" placeholder="Kommentieren …" aria-label="Kommentar" class="ih:h-9 ih:min-w-0 ih:flex-1 ih:rounded-full ih:border ih:border-input ih:bg-background ih:px-4 ih:text-sm ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none" />
<button type="submit" class="ih:grid ih:size-9 ih:shrink-0 ih:place-items-center ih:rounded-full ih:text-brand-text ih:hover:bg-brand-soft ih:disabled:opacity-40" :disabled="busy || !body.trim()" aria-label="Kommentar senden">
<LoaderCircle v-if="busy" class="ih:size-4 ih:animate-spin" /><SendHorizontal v-else class="ih:size-4" />
</button>
</form>
</div>
</template>

View file

@ -0,0 +1,27 @@
<script setup>
import { Link, router } from '@inertiajs/vue3';
import { Globe, Lock, EyeOff, Users } from '@lucide/vue';
import { Button } from '@inhaus/ui';
const props = defineProps({ group: { type: Object, required: true } });
const icons = { open: Globe, closed: Lock, secret: EyeOff };
const join = () => router.post(`/gruppen/${props.group.slug}/beitreten`, {}, { preserveScroll: true });
</script>
<template>
<article class="ih:flex ih:flex-col ih:overflow-hidden ih:rounded-xl ih:border ih:bg-card ih:shadow-xs">
<Link :href="group.url" class="ih:block ih:h-24 ih:bg-brand ih:bg-cover ih:bg-center" :style="group.cover_url ? { backgroundImage: `url(${group.cover_url})` } : {}" :aria-label="group.name" />
<div class="ih:flex ih:flex-1 ih:flex-col ih:gap-1 ih:p-4">
<Link :href="group.url" class="ih:font-semibold ih:hover:underline">{{ group.name }}</Link>
<p class="ih:flex ih:items-center ih:gap-1.5 ih:text-xs ih:text-muted-foreground">
<component :is="icons[group.privacy]" class="ih:size-3.5" /> {{ group.privacy_label }} · <Users class="ih:size-3.5" /> {{ group.members_count }}
</p>
<p v-if="group.description" class="ih:line-clamp-2 ih:text-sm ih:text-muted-foreground">{{ group.description }}</p>
<div class="ih:mt-auto ih:pt-3">
<Button v-if="group.status === 'active'" variant="outline" size="sm" class="ih:w-full" as-child><Link :href="group.url">Ansehen</Link></Button>
<Button v-else-if="group.status === 'pending'" variant="outline" size="sm" class="ih:w-full" disabled>Angefragt</Button>
<Button v-else size="sm" class="ih:w-full" @click="join">{{ group.status === 'invited' ? 'Einladung annehmen' : group.privacy === 'open' ? 'Beitreten' : 'Beitritt anfragen' }}</Button>
</div>
</div>
</article>
</template>

View file

@ -0,0 +1,60 @@
<script setup>
import { watch } from 'vue';
import { useForm } from '@inertiajs/vue3';
import { LoaderCircle } from '@lucide/vue';
import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, FormField, Input, Textarea } from '@inhaus/ui';
/** Gruppe gründen bzw. bearbeiten */
const props = defineProps({
group: { type: Object, default: null },
privacy: { type: Object, required: true },
privacyHints: { type: Object, required: true },
});
const open = defineModel('open', { type: Boolean, default: false });
const form = useForm({ name: '', description: '', privacy: 'open', cover: null, remove_cover: false });
watch(open, (value) => {
if (!value) return;
form.clearErrors();
form.defaults({ name: props.group?.name ?? '', description: props.group?.description ?? '', privacy: props.group?.privacy ?? 'open', cover: null, remove_cover: false });
form.reset();
});
function submit() {
form.post(props.group ? `/gruppen/${props.group.slug}` : '/gruppen', { forceFormData: true, preserveScroll: true, onSuccess: () => (open.value = false) });
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="ih:sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ group ? 'Gruppe bearbeiten' : 'Gruppe gründen' }}</DialogTitle>
<DialogDescription>{{ group ? 'Name, Beschreibung, Art und Titelbild.' : 'Zu einem Thema, einem Hobby oder einem Projekt – Sie verwalten die Gruppe.' }}</DialogDescription>
</DialogHeader>
<form id="group-form" class="ih:grid ih:gap-4" @submit.prevent="submit">
<FormField id="g-name" label="Name" :error="form.errors.name">
<Input id="g-name" v-model="form.name" maxlength="100" placeholder="z. B. Laufgruppe Mainz" />
</FormField>
<FormField id="g-description" label="Worum geht es? (optional)" :error="form.errors.description">
<Textarea id="g-description" v-model="form.description" rows="3" maxlength="2000" />
</FormField>
<fieldset class="ih:grid ih:gap-2">
<legend class="ih:mb-1 ih:text-sm ih:font-medium">Wer darf rein?</legend>
<label v-for="(label, key) in privacy" :key="key" class="ih:flex ih:cursor-pointer ih:items-start ih:gap-3 ih:rounded-md ih:border ih:p-3 ih:text-sm ih:has-[:checked]:border-brand ih:has-[:checked]:bg-brand-soft/50">
<input v-model="form.privacy" type="radio" name="privacy" :value="key" class="ih:mt-0.5 ih:size-4 ih:accent-[var(--color-brand)]" />
<span><span class="ih:font-medium">{{ label }}</span><span class="ih:block ih:text-xs ih:text-muted-foreground">{{ privacyHints[key] }}</span></span>
</label>
</fieldset>
<FormField id="g-cover" label="Titelbild (optional)" :error="form.errors.cover">
<input id="g-cover" type="file" accept="image/jpeg,image/png,image/webp" class="ih:text-sm" @change="form.cover = $event.target.files[0] ?? null" />
</FormField>
<label v-if="group?.cover_url" class="ih:flex ih:items-center ih:gap-2 ih:text-sm"><input v-model="form.remove_cover" type="checkbox" /> Titelbild entfernen</label>
</form>
<DialogFooter>
<Button variant="ghost" @click="open = false">Abbrechen</Button>
<Button type="submit" form="group-form" :disabled="form.processing || !form.name.trim()"><LoaderCircle v-if="form.processing" class="ih:animate-spin" /> {{ group ? 'Speichern' : 'Gründen' }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>

View file

@ -0,0 +1,98 @@
<script setup>
import { ref, watch } from 'vue';
import { Search, X } from '@lucide/vue';
import { PersonAvatar } from '@inhaus/ui';
import { http } from '@inhaus/ui';
/**
* Personen suchen und auswählen – einzeln (Direktnachricht) oder mehrere (Gruppe).
* v-model: Liste der Personen [{ id, name, … }]
*/
const props = defineProps({
multiple: { type: Boolean, default: false },
exclude: { type: Array, default: () => [] },
placeholder: { type: String, default: 'Name oder E-Mail eingeben …' },
autofocus: { type: Boolean, default: false },
});
const emit = defineEmits(['pick']);
const selected = defineModel({ type: Array, default: () => [] });
const query = ref('');
const results = ref([]);
const active = ref(0);
const loading = ref(false);
let timer;
watch(query, (value) => {
clearTimeout(timer);
if (value.trim().length < 2) {
results.value = [];
return;
}
timer = setTimeout(async () => {
loading.value = true;
try {
const ids = [...props.exclude, ...selected.value.map((p) => p.id)];
results.value = (await http.get(`/personen/suche?q=${encodeURIComponent(value.trim())}`)).people.filter((p) => !ids.includes(p.id));
active.value = 0;
} finally {
loading.value = false;
}
}, 200);
});
function choose(person) {
if (!person) return;
emit('pick', person);
if (props.multiple) selected.value = [...selected.value, person];
query.value = '';
results.value = [];
}
const remove = (person) => (selected.value = selected.value.filter((p) => p.id !== person.id));
</script>
<template>
<div class="ih:grid ih:gap-2">
<div v-if="multiple && selected.length" class="ih:flex ih:flex-wrap ih:gap-1.5">
<span v-for="person in selected" :key="person.id" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-full ih:border ih:bg-card ih:py-0.5 ih:pr-1 ih:pl-0.5 ih:text-[13px]">
<PersonAvatar :person="person" class="ih:size-6 ih:text-[10px]" />
{{ person.name }}
<button type="button" class="ih:rounded-full ih:p-0.5 ih:text-muted-foreground ih:hover:bg-muted ih:hover:text-foreground" :aria-label="`${person.name} entfernen`" @click="remove(person)"><X class="ih:size-3.5" /></button>
</span>
</div>
<div class="ih:relative">
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
<input
v-model="query"
type="search"
autocomplete="off"
:autofocus="autofocus"
:placeholder="placeholder"
aria-label="Person suchen"
class="ih:h-10 ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-card ih:pr-3 ih:pl-8 ih:text-sm ih:shadow-xs ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none"
@keydown.down.prevent="active = Math.min(results.length - 1, active + 1)"
@keydown.up.prevent="active = Math.max(0, active - 1)"
@keydown.enter.prevent="choose(results[active])"
/>
</div>
<ul v-if="results.length" class="ih:max-h-64 ih:overflow-y-auto ih:rounded-md ih:border ih:bg-popover ih:p-1" role="listbox">
<li v-for="(person, i) in results" :key="person.id" role="option" :aria-selected="i === active">
<button type="button" class="ih:flex ih:w-full ih:items-center ih:gap-2.5 ih:rounded ih:px-2 ih:py-1.5 ih:text-left ih:text-sm" :class="i === active ? 'ih:bg-accent' : 'ih:hover:bg-accent/60'" @click="choose(person)" @mouseenter="active = i">
<PersonAvatar :person="person" class="ih:size-7 ih:text-[11px]" />
<span class="ih:min-w-0 ih:flex-1">
<span class="ih:block ih:truncate ih:font-medium">{{ person.name }}</span>
<span v-if="person.job_title || person.department" class="ih:block ih:truncate ih:text-xs ih:text-muted-foreground">{{ [person.job_title, person.department].filter(Boolean).join(' · ') }}</span>
</span>
</button>
</li>
</ul>
<p v-else-if="query.trim().length >= 2 && !loading" class="ih:px-1 ih:text-[13px] ih:text-muted-foreground">Niemand gefunden.</p>
</div>
</template>

View file

@ -0,0 +1,191 @@
<script setup>
import { computed, ref } from 'vue';
import { Download, Flag, MessageCircle, MoreHorizontal, Pencil, Pin, PinOff, Trash2 } from '@lucide/vue';
import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, FileIcon, PersonAvatar, formatRelative, http, toast } from '@inhaus/ui';
import Comments from './Comments.vue';
import RichText from './RichText.vue';
import { fileSize } from '../lib/format';
const props = defineProps({
post: { type: Object, required: true },
reactions: { type: Array, required: true },
showGroup: { type: Boolean, default: false },
fullComments: { type: Array, default: null },
});
const emit = defineEmits(['deleted', 'changed']);
const p = props.post;
const showComments = ref(!!props.fullComments || p.comments.length > 0);
const editing = ref(false);
const draft = ref(p.body ?? '');
// Reaktion: ein Klick = 👍, Auswahl beim Überfahren
async function react(emoji) {
const next = p.my_reaction === emoji ? null : emoji;
const old = p.my_reaction;
const bump = (e, d) => {
if (!e) return;
const r = p.reactions.find((x) => x.emoji === e);
r ? (r.count += d) : d > 0 && p.reactions.push({ emoji: e, count: 1 });
p.reactions = p.reactions.filter((x) => x.count > 0).sort((a, b) => b.count - a.count);
p.reactions_total += d;
};
bump(old, -1);
bump(next, 1);
p.my_reaction = next;
await http.post(`/gruppen/beitraege/${p.id}/reaktion`, { emoji: next }).catch((e) => toast.error(e.message));
}
// Umfrage
const selection = ref([...(p.poll?.mine ?? [])]);
const voted = computed(() => (p.poll?.mine ?? []).length > 0);
const totalVotes = computed(() => p.poll?.options.reduce((n, o) => n + o.votes, 0) ?? 0);
async function vote(options) {
try {
p.poll = (await http.post(`/gruppen/beitraege/${p.id}/abstimmen`, { options })).poll;
selection.value = [...p.poll.mine];
} catch (e) {
toast.error(e.message);
}
}
function choose(i) {
if (!p.can_comment) return;
if (p.poll.multiple) {
selection.value = selection.value.includes(i) ? selection.value.filter((x) => x !== i) : [...selection.value, i];
} else {
vote([i]);
}
}
async function pin() {
try {
await http.post(`/gruppen/beitraege/${p.id}/anpinnen`, { pinned: !p.pinned });
p.pinned = !p.pinned;
emit('changed');
} catch (e) {
toast.error(e.message);
}
}
async function remove() {
if (!window.confirm('Beitrag löschen?')) return;
await http.delete(`/gruppen/beitraege/${p.id}`);
emit('deleted', p);
}
async function saveEdit() {
await http.put(`/gruppen/beitraege/${p.id}`, { body: draft.value });
p.body = draft.value;
p.edited = true;
editing.value = false;
}
async function report() {
const reason = window.prompt('Was stimmt mit diesem Beitrag nicht?');
if (!reason?.trim()) return;
const data = await http.post(`/gruppen/beitraege/${p.id}/melden`, { reason });
toast.success(data.message);
}
const shownImages = computed(() => p.images.slice(0, 4));
</script>
<template>
<article class="ih:overflow-hidden ih:rounded-xl ih:border ih:bg-card ih:shadow-xs" :aria-label="`Beitrag von ${p.user?.name ?? 'Gelöschtes Konto'}`">
<header class="ih:flex ih:items-start ih:gap-3 ih:px-4 ih:pt-4 ih:sm:px-5">
<PersonAvatar v-if="p.user" :person="p.user" class="ih:size-10" />
<div class="ih:min-w-0 ih:flex-1 ih:text-sm">
<p class="ih:leading-snug">
<a v-if="p.user" :href="`/personen/${p.user.id}`" class="ih:font-semibold ih:hover:underline">{{ p.user.name }}</a>
<template v-if="showGroup"><span class="ih:mx-1 ih:text-muted-foreground">in</span><a :href="`/gruppen/${p.group.slug}`" class="ih:font-semibold ih:hover:underline">{{ p.group.name }}</a></template>
</p>
<p class="ih:flex ih:items-center ih:gap-1.5 ih:text-xs ih:text-muted-foreground">
<a :href="p.url" class="ih:hover:underline">{{ formatRelative(p.created_at) }}</a>
<template v-if="p.edited"> · bearbeitet</template>
<span v-if="p.pinned" class="ih:inline-flex ih:items-center ih:gap-0.5 ih:font-medium ih:text-brand-text"><Pin class="ih:size-3" /> Angepinnt</span>
</p>
</div>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button type="button" class="ih:grid ih:size-8 ih:place-items-center ih:rounded-full ih:text-muted-foreground ih:hover:bg-accent" aria-label="Weitere Aktionen"><MoreHorizontal class="ih:size-5" /></button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem v-if="p.can_pin" @select="pin"><component :is="p.pinned ? PinOff : Pin" /> {{ p.pinned ? 'Nicht mehr anpinnen' : 'Oben anpinnen' }}</DropdownMenuItem>
<DropdownMenuItem v-if="p.can_edit && p.body !== null" @select="editing = true; draft = p.body"><Pencil /> Bearbeiten</DropdownMenuItem>
<DropdownMenuItem v-if="p.can_delete" class="ih:text-destructive" @select="remove"><Trash2 /> Löschen</DropdownMenuItem>
<DropdownMenuItem v-if="!p.can_edit" @select="report"><Flag /> Melden</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</header>
<div class="ih:px-4 ih:pt-3 ih:text-[15px] ih:leading-relaxed ih:sm:px-5">
<form v-if="editing" class="ih:grid ih:gap-2" @submit.prevent="saveEdit">
<textarea v-model="draft" rows="4" maxlength="10000" aria-label="Beitrag bearbeiten" class="ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-background ih:p-3 ih:text-sm" />
<div class="ih:flex ih:gap-2"><Button size="sm" type="submit">Speichern</Button><Button size="sm" variant="ghost" type="button" @click="editing = false">Abbrechen</Button></div>
</form>
<RichText v-else-if="p.body" :text="p.body" />
</div>
<!-- Fotos -->
<div v-if="p.images.length" class="ih:mt-3 ih:grid ih:gap-0.5" :class="p.images.length === 1 ? '' : 'ih:grid-cols-2'">
<a v-for="(img, i) in shownImages" :key="img.id" :href="img.url" target="_blank" rel="noopener" class="ih:relative ih:block ih:overflow-hidden ih:bg-muted" :class="p.images.length === 3 && i === 0 ? 'ih:row-span-2' : ''">
<img :src="p.images.length === 1 ? img.url : img.thumb_url" :alt="img.name" loading="lazy" class="ih:w-full ih:object-cover" :class="p.images.length === 1 ? 'ih:max-h-[32rem]' : 'ih:aspect-square ih:h-full'" />
<span v-if="i === 3 && p.images.length > 4" class="ih:absolute ih:inset-0 ih:grid ih:place-items-center ih:bg-foreground/55 ih:text-2xl ih:font-semibold ih:text-background">+{{ p.images.length - 4 }}</span>
</a>
</div>
<!-- Dateien -->
<div v-if="p.files.length" class="ih:grid ih:gap-2 ih:px-4 ih:pt-3 ih:sm:px-5">
<a v-for="f in p.files" :key="f.id" :href="f.url" class="ih:flex ih:items-center ih:gap-3 ih:rounded-lg ih:border ih:p-2.5 ih:hover:bg-accent/60">
<FileIcon :extension="f.name.split('.').pop()" class="ih:shrink-0" />
<span class="ih:min-w-0 ih:flex-1"><span class="ih:block ih:truncate ih:text-sm ih:font-medium">{{ f.name }}</span><span class="ih:text-xs ih:text-muted-foreground">{{ fileSize(f.size) }}</span></span>
<Download class="ih:size-4 ih:text-muted-foreground" />
</a>
</div>
<!-- Umfrage -->
<fieldset v-if="p.poll" class="ih:mx-4 ih:mt-3 ih:grid ih:gap-2 ih:rounded-lg ih:border ih:p-3 ih:sm:mx-5">
<legend class="ih:px-1 ih:text-xs ih:font-semibold ih:text-muted-foreground">Umfrage{{ p.poll.multiple ? ' · mehrere Antworten möglich' : '' }}</legend>
<button
v-for="(o, i) in p.poll.options"
:key="i"
type="button"
class="ih:relative ih:overflow-hidden ih:rounded-md ih:border ih:px-3 ih:py-2 ih:text-left ih:text-sm ih:disabled:cursor-default"
:class="(voted ? p.poll.mine : selection).includes(i) ? 'ih:border-brand' : 'ih:hover:border-brand/50'"
:aria-pressed="(voted ? p.poll.mine : selection).includes(i)"
:disabled="!p.can_comment"
@click="choose(i)"
>
<span v-if="voted" class="ih:absolute ih:inset-y-0 ih:left-0 ih:bg-brand-soft" :style="{ width: `${totalVotes ? Math.round((o.votes / totalVotes) * 100) : 0}%` }" aria-hidden="true" />
<span class="ih:relative ih:flex ih:justify-between ih:gap-3">
<span :class="{ 'ih:font-semibold': p.poll.mine.includes(i) }">{{ o.label }}</span>
<span v-if="voted" class="ih:text-muted-foreground ih:tabular-nums">{{ totalVotes ? Math.round((o.votes / totalVotes) * 100) : 0 }} % · {{ o.votes }}</span>
</span>
</button>
<div class="ih:flex ih:items-center ih:justify-between ih:text-xs ih:text-muted-foreground">
<span>{{ p.poll.voters }} {{ p.poll.voters === 1 ? 'Person hat' : 'Personen haben' }} abgestimmt</span>
<Button v-if="p.poll.multiple && p.can_comment" size="sm" variant="outline" :disabled="!selection.length && !voted" @click="vote(selection)">{{ voted ? 'Stimme ändern' : 'Abstimmen' }}</Button>
</div>
</fieldset>
<!-- Reaktionen und Kommentare -->
<div class="ih:mt-3 ih:flex ih:items-center ih:justify-between ih:px-4 ih:text-[13px] ih:text-muted-foreground ih:sm:px-5">
<span v-if="p.reactions_total" class="ih:inline-flex ih:items-center ih:gap-1"><span class="ih:tracking-tighter">{{ p.reactions.slice(0, 3).map((r) => r.emoji).join('') }}</span> {{ p.reactions_total }}</span><span v-else />
<button v-if="p.comments_count" type="button" class="ih:hover:underline" @click="showComments = !showComments">{{ p.comments_count }} {{ p.comments_count === 1 ? 'Kommentar' : 'Kommentare' }}</button>
</div>
<div v-if="p.can_comment" class="ih:mx-4 ih:mt-2 ih:grid ih:grid-cols-2 ih:border-t ih:py-1 ih:sm:mx-5">
<div class="ih:group/react ih:relative">
<button type="button" class="ih:flex ih:w-full ih:items-center ih:justify-center ih:gap-2 ih:rounded-md ih:py-2 ih:text-sm ih:font-medium ih:hover:bg-accent" :class="p.my_reaction ? 'ih:text-brand-text' : 'ih:text-muted-foreground'" :aria-pressed="!!p.my_reaction" @click="react(p.my_reaction ?? '👍')">
<span class="ih:text-base">{{ p.my_reaction ?? '👍' }}</span> {{ p.my_reaction ? 'Reagiert' : 'Gefällt mir' }}
</button>
<div class="ih:absolute ih:bottom-full ih:left-2 ih:z-20 ih:hidden ih:gap-0.5 ih:rounded-full ih:border ih:bg-popover ih:p-1 ih:shadow-md ih:group-focus-within/react:flex ih:group-hover/react:flex">
<button v-for="emoji in reactions" :key="emoji" type="button" class="ih:grid ih:size-9 ih:place-items-center ih:rounded-full ih:text-xl ih:transition-transform ih:hover:scale-125" :aria-label="`Mit ${emoji} reagieren`" @click="react(emoji)">{{ emoji }}</button>
</div>
</div>
<button type="button" class="ih:flex ih:items-center ih:justify-center ih:gap-2 ih:rounded-md ih:py-2 ih:text-sm ih:font-medium ih:text-muted-foreground ih:hover:bg-accent" @click="showComments = true"><MessageCircle class="ih:size-4" /> Kommentieren</button>
</div>
<div v-else class="ih:h-3" />
<Comments v-if="showComments" :post="p" :full="!!fullComments" :initial="fullComments" />
</article>
</template>

View file

@ -0,0 +1,112 @@
<script setup>
import { computed, ref } from 'vue';
import { BarChart3, File as FileGlyph, ImagePlus, LoaderCircle, Paperclip, Plus, X } from '@lucide/vue';
import { Button, PersonAvatar, Switch, http, toast } from '@inhaus/ui';
import { fileSize } from '../lib/format';
const props = defineProps({
group: { type: Object, required: true },
me: { type: Object, required: true },
});
const emit = defineEmits(['created']);
const body = ref('');
const files = ref([]);
const poll = ref(null); // Liste der Antworten oder null
const multiple = ref(false);
const busy = ref(false);
const photoInput = ref(null);
const fileInput = ref(null);
const focused = ref(false);
const canSend = computed(() => !busy.value && (body.value.trim() || files.value.length || (poll.value && poll.value.filter((o) => o.trim()).length >= 2)));
function add(list) {
for (const file of list) {
if (files.value.length >= 10) {
toast.error('Höchstens 10 Dateien je Beitrag.');
break;
}
files.value.push({ file, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : null });
}
focused.value = true;
}
function removeFile(i) {
const [f] = files.value.splice(i, 1);
f?.url && URL.revokeObjectURL(f.url);
}
async function submit() {
busy.value = true;
const data = new FormData();
body.value.trim() && data.append('body', body.value);
files.value.forEach((f) => data.append('files[]', f.file));
if (poll.value) {
poll.value.filter((o) => o.trim()).forEach((o) => data.append('poll[]', o));
data.append('multiple', multiple.value ? '1' : '0');
}
try {
const { post } = await http.post(`/gruppen/${props.group.slug}/beitraege`, data);
emit('created', post);
files.value.forEach((f) => f.url && URL.revokeObjectURL(f.url));
body.value = '';
files.value = [];
poll.value = null;
focused.value = false;
} catch (error) {
toast.error(error.message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section class="ih:rounded-xl ih:border ih:bg-card ih:p-4 ih:shadow-xs" aria-label="Neuer Beitrag" @dragover.prevent @drop.prevent="add([...$event.dataTransfer.files])">
<div class="ih:flex ih:gap-3">
<PersonAvatar :person="me" class="ih:size-10" />
<textarea
v-model="body"
:rows="focused || body ? 4 : 1"
maxlength="10000"
:placeholder="`Was möchten Sie mit „${group.name}“ teilen?`"
aria-label="Beitrag schreiben"
class="ih:min-h-10 ih:flex-1 ih:resize-none ih:rounded-2xl ih:bg-muted ih:px-4 ih:py-2 ih:text-[15px] ih:focus-visible:bg-background ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none"
@focus="focused = true"
@paste="$event.clipboardData?.files?.length && ($event.preventDefault(), add([...$event.clipboardData.files]))"
/>
</div>
<ul v-if="files.length" class="ih:mt-3 ih:flex ih:flex-wrap ih:gap-2 ih:pl-13">
<li v-for="(f, i) in files" :key="i" class="ih:relative">
<img v-if="f.url" :src="f.url" :alt="f.file.name" class="ih:size-20 ih:rounded-md ih:border ih:object-cover" />
<span v-else class="ih:flex ih:h-20 ih:w-40 ih:items-center ih:gap-2 ih:rounded-md ih:border ih:bg-muted ih:px-2 ih:text-xs"><FileGlyph class="ih:size-5 ih:shrink-0" /><span class="ih:min-w-0"><span class="ih:block ih:truncate ih:font-medium">{{ f.file.name }}</span>{{ fileSize(f.file.size) }}</span></span>
<button type="button" class="ih:absolute ih:-top-1.5 ih:-right-1.5 ih:grid ih:size-5 ih:place-items-center ih:rounded-full ih:bg-foreground ih:text-background" :aria-label="`${f.file.name} entfernen`" @click="removeFile(i)"><X class="ih:size-3" /></button>
</li>
</ul>
<div v-if="poll" class="ih:mt-3 ih:grid ih:gap-2 ih:rounded-lg ih:border ih:p-3 ih:sm:ml-13">
<div class="ih:flex ih:items-center ih:justify-between">
<span class="ih:text-sm ih:font-medium">Umfrage</span>
<button type="button" class="ih:text-xs ih:text-muted-foreground ih:hover:text-foreground" @click="poll = null">Entfernen</button>
</div>
<input v-for="(o, i) in poll" :key="i" v-model="poll[i]" maxlength="120" :placeholder="`Antwort ${i + 1}`" :aria-label="`Antwort ${i + 1}`" class="ih:h-9 ih:rounded-md ih:border ih:border-input ih:bg-background ih:px-3 ih:text-sm" />
<div class="ih:flex ih:flex-wrap ih:items-center ih:justify-between ih:gap-2">
<button v-if="poll.length < 10" type="button" class="ih:inline-flex ih:items-center ih:gap-1 ih:text-sm ih:text-brand-text ih:hover:underline" @click="poll.push('')"><Plus class="ih:size-4" /> Antwort</button>
<label class="ih:flex ih:items-center ih:gap-2 ih:text-sm"><Switch v-model="multiple" /> Mehrere Antworten erlauben</label>
</div>
</div>
<div v-if="focused || body || files.length || poll" class="ih:mt-3 ih:flex ih:flex-wrap ih:items-center ih:gap-1 ih:border-t ih:pt-3">
<button type="button" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-md ih:px-2.5 ih:py-1.5 ih:text-sm ih:text-muted-foreground ih:hover:bg-accent" @click="photoInput?.click()"><ImagePlus class="ih:size-4" /> Foto</button>
<button type="button" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-md ih:px-2.5 ih:py-1.5 ih:text-sm ih:text-muted-foreground ih:hover:bg-accent" @click="fileInput?.click()"><Paperclip class="ih:size-4" /> Datei</button>
<button v-if="!poll" type="button" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-md ih:px-2.5 ih:py-1.5 ih:text-sm ih:text-muted-foreground ih:hover:bg-accent" @click="poll = ['', '']"><BarChart3 class="ih:size-4" /> Umfrage</button>
<span class="ih:flex-1" />
<Button :disabled="!canSend" @click="submit"><LoaderCircle v-if="busy" class="ih:animate-spin" /> Veröffentlichen</Button>
<input ref="photoInput" type="file" accept="image/*" multiple class="ih:hidden" @change="add([...$event.target.files]); $event.target.value = ''" />
<input ref="fileInput" type="file" multiple class="ih:hidden" @change="add([...$event.target.files]); $event.target.value = ''" />
</div>
</section>
</template>

View file

@ -0,0 +1,23 @@
<script setup>
import { computed, ref } from 'vue';
import { linkify } from '../lib/format';
/** Text mit Links; lange Texte werden gekürzt („Mehr anzeigen“) */
const props = defineProps({
text: { type: String, default: '' },
limit: { type: Number, default: 600 },
});
const expanded = ref(false);
const long = computed(() => props.text.length > props.limit);
const shown = computed(() => (long.value && !expanded.value ? `${props.text.slice(0, props.limit).trimEnd()} …` : props.text));
</script>
<template>
<p class="ih:break-words ih:whitespace-pre-wrap">
<template v-for="(part, i) in linkify(shown)" :key="i">
<a v-if="part.href" :href="part.href" target="_blank" rel="noopener noreferrer" class="ih:text-brand-text ih:underline ih:underline-offset-2">{{ part.text }}</a>
<template v-else>{{ part.text }}</template>
</template>
<button v-if="long" type="button" class="ih:ml-1 ih:font-medium ih:text-brand-text ih:hover:underline" @click="expanded = !expanded">{{ expanded ? 'Weniger' : 'Mehr anzeigen' }}</button>
</p>
</template>

View file

@ -0,0 +1,22 @@
/** Text in Stücke zerlegen, Links erkennen – ohne v-html */
export function linkify(text) {
const parts = [];
const pattern = /(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g;
let last = 0;
for (const match of (text ?? '').matchAll(pattern)) {
if (match.index > last) parts.push({ text: text.slice(last, match.index) });
parts.push({ text: match[0], href: match[0] });
last = match.index + match[0].length;
}
if (last < (text ?? '').length) parts.push({ text: text.slice(last) });
return parts;
}
export function fileSize(bytes) {
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
return `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB`;
}

View file

@ -0,0 +1,47 @@
<script setup>
import { ref, watch } from 'vue';
import { Link, router, usePage } from '@inertiajs/vue3';
import { Compass, Plus, Search } from '@lucide/vue';
import { AppLayout, Button, EmptyState, PageHeader, toast } from '@inhaus/ui';
import GroupCard from '../components/GroupCard.vue';
import GroupDialog from '../components/GroupDialog.vue';
const props = defineProps({
groups: { type: Array, required: true },
pagination: { type: Object, required: true },
q: { type: String, default: '' },
privacy: { type: Object, required: true },
privacyHints: { type: Object, required: true },
});
const page = usePage();
watch(() => page.props.flash?.status, (status) => status && toast.success(status), { immediate: true });
const query = ref(props.q);
const creating = ref(false);
let timer;
watch(query, (value) => {
clearTimeout(timer);
timer = setTimeout(() => router.get('/gruppen/entdecken', value ? { q: value } : {}, { preserveState: true }), 300);
});
</script>
<template>
<AppLayout title="Gruppen entdecken">
<PageHeader title="Gruppen entdecken" :breadcrumbs="[{ label: 'Gruppen', href: '/gruppen' }]">
<template #actions><Button @click="creating = true"><Plus /> Gruppe gründen</Button></template>
</PageHeader>
<div class="ih:relative ih:mb-5 ih:max-w-md">
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
<input v-model="query" type="search" placeholder="Gruppen suchen" aria-label="Gruppen suchen" class="ih:h-10 ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-card ih:pr-3 ih:pl-8 ih:text-sm ih:shadow-xs" />
</div>
<div v-if="groups.length" class="ih:grid ih:gap-4 ih:sm:grid-cols-2 ih:lg:grid-cols-3 ih:xl:grid-cols-4">
<GroupCard v-for="g in groups" :key="g.id" :group="g" />
</div>
<div v-else class="ih:rounded-xl ih:border ih:bg-card"><EmptyState :icon="Compass" :title="q ? 'Keine passenden Gruppen' : 'Noch keine Gruppen'" text="Gründen Sie die erste!" /></div>
<nav v-if="pagination.prev || pagination.next" class="ih:mt-6 ih:flex ih:justify-between ih:text-sm">
<Link v-if="pagination.prev" :href="pagination.prev" class="ih:text-brand-text ih:hover:underline">← Zurück</Link><span v-else />
<Link v-if="pagination.next" :href="pagination.next" class="ih:text-brand-text ih:hover:underline">Weiter →</Link>
</nav>
<GroupDialog v-model:open="creating" :privacy="privacy" :privacy-hints="privacyHints" />
</AppLayout>
</template>

View file

@ -0,0 +1,82 @@
<script setup>
import { ref, watch } from 'vue';
import { Link, usePage } from '@inertiajs/vue3';
import { Compass, LoaderCircle, Plus, UsersRound } from '@lucide/vue';
import { AppLayout, Button, EmptyState, PageHeader, http, toast } from '@inhaus/ui';
import GroupCard from '../components/GroupCard.vue';
import GroupDialog from '../components/GroupDialog.vue';
import PostCard from '../components/PostCard.vue';
const props = defineProps({
posts: { type: Array, required: true },
more: { type: Boolean, default: false },
groups: { type: Array, required: true },
invitations: { type: Array, default: () => [] },
suggested: { type: Array, default: () => [] },
privacy: { type: Object, required: true },
privacyHints: { type: Object, required: true },
});
const page = usePage();
watch(() => page.props.flash?.status, (status) => status && toast.success(status), { immediate: true });
const feed = ref(props.posts);
const hasMore = ref(props.more);
const loading = ref(false);
const creating = ref(false);
const reactions = ['👍', '❤️', '😂', '😮', '😢', '👏'];
async function loadMore() {
loading.value = true;
const data = await http.get(`/gruppen?vor=${feed.value.at(-1).id}`);
feed.value.push(...data.posts);
hasMore.value = data.more;
loading.value = false;
}
</script>
<template>
<AppLayout title="Gruppen">
<PageHeader title="Gruppen" description="Austausch zu Themen, Hobbys und Projekten – offen, geschlossen oder privat.">
<template #actions>
<Button variant="outline" as-child><Link href="/gruppen/entdecken"><Compass /> Gruppen entdecken</Link></Button>
<Button @click="creating = true"><Plus /> Gruppe gründen</Button>
</template>
</PageHeader>
<div class="ih:grid ih:gap-6 ih:lg:grid-cols-[minmax(0,1fr)_20rem]">
<section class="ih:mx-auto ih:grid ih:w-full ih:max-w-2xl ih:content-start ih:gap-4" aria-label="Neue Beiträge aus Ihren Gruppen">
<PostCard v-for="post in feed" :key="post.id" :post="post" :reactions="reactions" show-group @deleted="feed = feed.filter((p) => p.id !== post.id)" />
<Button v-if="hasMore" variant="outline" :disabled="loading" @click="loadMore"><LoaderCircle v-if="loading" class="ih:animate-spin" /> Ältere Beiträge laden</Button>
<div v-if="!feed.length" class="ih:rounded-xl ih:border ih:bg-card">
<EmptyState :icon="UsersRound" :title="groups.length ? 'Noch keine Beiträge' : 'Sie sind noch in keiner Gruppe'" :text="groups.length ? 'Schreiben Sie den ersten Beitrag in einer Ihrer Gruppen.' : 'Entdecken Sie Gruppen zu Ihren Themen – oder gründen Sie selbst eine.'" />
</div>
</section>
<aside class="ih:grid ih:content-start ih:gap-5">
<section v-if="invitations.length" class="ih:rounded-xl ih:border ih:border-brand/40 ih:bg-brand-soft/40 ih:p-4">
<h2 class="ih:mb-2 ih:text-sm ih:font-semibold">Einladungen</h2>
<div class="ih:grid ih:gap-3"><GroupCard v-for="g in invitations" :key="g.id" :group="g" /></div>
</section>
<section class="ih:rounded-xl ih:border ih:bg-card ih:p-4">
<h2 class="ih:mb-2 ih:text-sm ih:font-semibold">Ihre Gruppen</h2>
<ul v-if="groups.length" class="ih:-mx-2 ih:grid">
<li v-for="g in groups" :key="g.id">
<Link :href="g.url" class="ih:flex ih:items-center ih:gap-3 ih:rounded-md ih:p-2 ih:hover:bg-accent/60">
<span class="ih:size-10 ih:shrink-0 ih:rounded-md ih:bg-brand ih:bg-cover ih:bg-center" :style="g.cover_url ? { backgroundImage: `url(${g.cover_url})` } : {}" />
<span class="ih:min-w-0"><span class="ih:block ih:truncate ih:text-sm ih:font-medium">{{ g.name }}</span><span class="ih:text-xs ih:text-muted-foreground">{{ g.members_count }} {{ g.members_count === 1 ? 'Mitglied' : 'Mitglieder' }}</span></span>
</Link>
</li>
</ul>
<p v-else class="ih:text-sm ih:text-muted-foreground">Noch keine.</p>
</section>
<section v-if="suggested.length" class="ih:grid ih:gap-3">
<h2 class="ih:text-sm ih:font-semibold">Vorschläge</h2>
<GroupCard v-for="g in suggested" :key="g.id" :group="g" />
</section>
</aside>
</div>
<GroupDialog v-model:open="creating" :privacy="privacy" :privacy-hints="privacyHints" />
</AppLayout>
</template>

View file

@ -0,0 +1,40 @@
<script setup>
import { onMounted } from 'vue';
import { Link, router } from '@inertiajs/vue3';
import { ChevronLeft, Flag } from '@lucide/vue';
import { AppLayout, Button, http, toast } from '@inhaus/ui';
import PostCard from '../components/PostCard.vue';
const props = defineProps({
group: { type: Object, required: true },
post: { type: Object, required: true },
comments: { type: Array, required: true },
reactions: { type: Array, required: true },
reports: { type: Array, default: () => [] },
});
onMounted(() => {
const target = location.hash && document.querySelector(location.hash);
target?.scrollIntoView({ block: 'center' });
});
async function resolve() {
await http.post(`/gruppen/beitraege/${props.post.id}/meldungen-erledigt`);
toast.success('Meldungen erledigt');
router.reload();
}
</script>
<template>
<AppLayout :title="`Beitrag in ${group.name}`">
<div class="ih:mx-auto ih:grid ih:max-w-2xl ih:gap-4">
<Link :href="group.url" class="ih:inline-flex ih:items-center ih:gap-1 ih:text-sm ih:font-medium ih:text-muted-foreground ih:hover:text-foreground"><ChevronLeft class="ih:size-4" /> {{ group.name }}</Link>
<div v-if="reports.length" class="ih:rounded-md ih:border ih:border-destructive/30 ih:bg-destructive/5 ih:p-3 ih:text-sm">
<p class="ih:flex ih:items-center ih:gap-2 ih:font-medium"><Flag class="ih:size-4 ih:text-destructive" /> {{ reports.length }} {{ reports.length === 1 ? 'Meldung' : 'Meldungen' }}</p>
<ul class="ih:mt-1 ih:list-disc ih:pl-6 ih:text-muted-foreground"><li v-for="r in reports" :key="r.id">{{ r.comment_id ? 'Kommentar: ' : '' }}{{ r.reason }}</li></ul>
<Button size="sm" variant="outline" class="ih:mt-2" @click="resolve">In Ordnung – erledigt</Button>
</div>
<PostCard :post="post" :reactions="reactions" :full-comments="comments" @deleted="router.visit(group.url)" />
</div>
</AppLayout>
</template>

168
resources/js/pages/Show.vue Normal file
View file

@ -0,0 +1,168 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { Link, router, usePage } from '@inertiajs/vue3';
import { Bell, BellOff, Check, EyeOff, Flag, Globe, LoaderCircle, Lock, LogOut, PencilLine, Trash2, UserMinus, UserPlus, Users, X } from '@lucide/vue';
import { AppLayout, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, EmptyState, PersonAvatar, http, toast } from '@inhaus/ui';
import GroupDialog from '../components/GroupDialog.vue';
import PeopleSelect from '../components/PeopleSelect.vue';
import PostCard from '../components/PostCard.vue';
import PostComposer from '../components/PostComposer.vue';
const props = defineProps({
group: { type: Object, required: true },
membership: { type: Object, default: null },
can: { type: Object, required: true },
posts: { type: Array, required: true },
more: { type: Boolean, default: false },
members: { type: Object, default: null },
privacy: { type: Object, required: true },
privacyHints: { type: Object, required: true },
roles: { type: Object, required: true },
reactions: { type: Array, required: true },
tab: { type: String, default: 'beitraege' },
reports: { type: Number, default: 0 },
});
const page = usePage();
watch(() => page.props.flash?.status, (status) => status && toast.success(status), { immediate: true });
const me = computed(() => page.props.auth.user);
const feed = ref(props.posts);
watch(() => props.posts, (posts) => (feed.value = posts));
const hasMore = ref(props.more);
const loading = ref(false);
const activeTab = ref(props.tab);
const editing = ref(false);
const inviting = ref(false);
const invitees = ref([]);
const icons = { open: Globe, closed: Lock, secret: EyeOff };
const status = computed(() => props.membership?.status);
async function loadMore() {
loading.value = true;
const last = feed.value.filter((p) => !p.pinned).at(-1);
const data = await http.get(`/gruppen/${props.group.slug}?vor=${last?.id ?? 0}`);
feed.value.push(...data.posts.filter((p) => !feed.value.some((x) => x.id === p.id)));
hasMore.value = data.more;
loading.value = false;
}
const act = (url, data = {}, method = 'post') => router.visit(`/gruppen/${props.group.slug}${url}`, { method, data, preserveScroll: true });
const removeMember = (m) => window.confirm(`${m.name} aus der Gruppe entfernen?`) && act(`/mitglieder/${m.id}`, {}, 'delete');
const leave = () => window.confirm(`„${props.group.name}“ verlassen?`) && act('/verlassen');
const destroy = () => window.confirm(`Gruppe „${props.group.name}“ mit allen Beiträgen löschen?`) && act('', {}, 'delete');
function invite() {
router.post(`/gruppen/${props.group.slug}/einladen`, { users: invitees.value.map((p) => p.id) }, { preserveScroll: true, onSuccess: () => { inviting.value = false; invitees.value = []; } });
}
const canInvite = computed(() => props.can.post && (props.group.privacy === 'open' || props.can.moderate));
</script>
<template>
<AppLayout :title="group.name">
<!-- Kopf mit Titelbild -->
<header class="ih:overflow-hidden ih:rounded-xl ih:border ih:bg-card ih:shadow-xs">
<div class="ih:h-36 ih:bg-brand ih:bg-cover ih:bg-center ih:sm:h-52" :style="group.cover_url ? { backgroundImage: `url(${group.cover_url})` } : {}" />
<div class="ih:flex ih:flex-wrap ih:items-end ih:gap-4 ih:p-5">
<div class="ih:min-w-0 ih:flex-1">
<p class="ih:mb-1 ih:text-[13px]"><Link href="/gruppen" class="ih:text-muted-foreground ih:hover:underline">Gruppen</Link></p>
<h1 class="ih:text-2xl ih:font-semibold ih:tracking-tight">{{ group.name }}</h1>
<p class="ih:mt-1 ih:flex ih:flex-wrap ih:items-center ih:gap-x-3 ih:gap-y-1 ih:text-sm ih:text-muted-foreground">
<span class="ih:inline-flex ih:items-center ih:gap-1" :title="group.privacy_hint"><component :is="icons[group.privacy]" class="ih:size-4" /> {{ group.privacy_label }}e Gruppe</span>
<span class="ih:inline-flex ih:items-center ih:gap-1"><Users class="ih:size-4" /> {{ group.members_count }} {{ group.members_count === 1 ? 'Mitglied' : 'Mitglieder' }}</span>
</p>
</div>
<div class="ih:flex ih:flex-wrap ih:gap-2">
<template v-if="status === 'active'">
<Button v-if="canInvite" @click="inviting = true"><UserPlus /> Einladen</Button>
<Button variant="outline" size="icon" :aria-label="membership.notify === 'all' ? 'Benachrichtigungen ausschalten' : 'Benachrichtigungen einschalten'" :title="membership.notify === 'all' ? 'Sie werden über neue Beiträge benachrichtigt' : 'Keine Benachrichtigungen'" @click="act('/benachrichtigungen', { notify: membership.notify === 'all' ? 'off' : 'all' }, 'put')">
<component :is="membership.notify === 'all' ? Bell : BellOff" />
</Button>
<Button v-if="can.admin" variant="outline" @click="editing = true"><PencilLine /> Bearbeiten</Button>
<Button variant="ghost" class="ih:text-muted-foreground" @click="leave"><LogOut /> Verlassen</Button>
</template>
<Button v-else-if="status === 'pending'" variant="outline" disabled>Beitritt angefragt</Button>
<Button v-else-if="status === 'invited'" @click="act('/beitreten')"><Check /> Einladung annehmen</Button>
<Button v-else-if="group.privacy !== 'secret'" @click="act('/beitreten')">{{ group.privacy === 'open' ? 'Beitreten' : 'Beitritt anfragen' }}</Button>
<Button v-if="can.admin && status !== 'active'" variant="outline" @click="editing = true"><PencilLine /> Bearbeiten</Button>
</div>
</div>
<nav class="ih:flex ih:gap-1 ih:border-t ih:px-3" role="tablist">
<button v-for="t in [{ key: 'beitraege', label: 'Beiträge' }, { key: 'mitglieder', label: 'Mitglieder' }, { key: 'info', label: 'Info' }]" :key="t.key" type="button" role="tab" :aria-selected="activeTab === t.key" class="ih:relative ih:px-3 ih:py-3 ih:text-sm ih:font-medium" :class="activeTab === t.key ? 'ih:text-foreground' : 'ih:text-muted-foreground ih:hover:text-foreground'" @click="activeTab = t.key">
{{ t.label }}<span v-if="t.key === 'mitglieder' && members?.pending.length" class="ih:ml-1 ih:rounded-full ih:bg-brand ih:px-1.5 ih:text-[11px] ih:text-brand-foreground">{{ members.pending.length }}</span>
<span v-if="activeTab === t.key" class="ih:absolute ih:inset-x-2 ih:bottom-0 ih:h-[3px] ih:rounded-t-full ih:bg-brand" />
</button>
</nav>
</header>
<div class="ih:mx-auto ih:mt-6 ih:grid ih:max-w-2xl ih:gap-4">
<p v-if="can.moderate && reports" class="ih:flex ih:items-center ih:gap-2 ih:rounded-md ih:border ih:border-destructive/30 ih:bg-destructive/5 ih:p-3 ih:text-sm"><Flag class="ih:size-4 ih:text-destructive" /> {{ reports }} offene {{ reports === 1 ? 'Meldung' : 'Meldungen' }} – zu finden an den betroffenen Beiträgen.</p>
<!-- Beiträge -->
<template v-if="activeTab === 'beitraege'">
<template v-if="can.read">
<PostComposer v-if="can.post" :group="group" :me="me" @created="(post) => feed.splice(feed.filter((p) => p.pinned).length, 0, post)" />
<PostCard v-for="post in feed" :key="post.id" :post="post" :reactions="reactions" @deleted="feed = feed.filter((p) => p.id !== post.id)" />
<Button v-if="hasMore" variant="outline" :disabled="loading" @click="loadMore"><LoaderCircle v-if="loading" class="ih:animate-spin" /> Ältere Beiträge laden</Button>
<div v-if="!feed.length" class="ih:rounded-xl ih:border ih:bg-card"><EmptyState :icon="Users" title="Noch keine Beiträge" :text="can.post ? 'Schreiben Sie den ersten Beitrag!' : 'Treten Sie bei, um mitzuschreiben.'" /></div>
</template>
<div v-else class="ih:rounded-xl ih:border ih:bg-card"><EmptyState :icon="Lock" title="Nur für Mitglieder" :text="group.privacy_hint" /></div>
</template>
<!-- Mitglieder -->
<section v-else-if="activeTab === 'mitglieder'" class="ih:rounded-xl ih:border ih:bg-card ih:p-5">
<template v-if="members">
<template v-if="members.pending.length">
<h2 class="ih:mb-2 ih:text-sm ih:font-semibold">Beitrittsanfragen</h2>
<ul class="ih:-mx-2 ih:mb-5 ih:grid">
<li v-for="m in members.pending" :key="m.id" class="ih:flex ih:items-center ih:gap-3 ih:rounded-md ih:p-2">
<PersonAvatar :person="m" class="ih:size-9" />
<span class="ih:min-w-0 ih:flex-1 ih:text-sm"><span class="ih:font-medium">{{ m.name }}</span><span class="ih:block ih:text-xs ih:text-muted-foreground">{{ m.job_title }}</span></span>
<Button size="sm" @click="act(`/anfragen/${m.id}`, { accept: true })"><Check /> Aufnehmen</Button>
<Button size="sm" variant="ghost" :aria-label="`Anfrage von ${m.name} ablehnen`" @click="act(`/anfragen/${m.id}`, { accept: false })"><X /></Button>
</li>
</ul>
</template>
<h2 class="ih:mb-2 ih:text-sm ih:font-semibold">{{ members.active.length }} {{ members.active.length === 1 ? 'Mitglied' : 'Mitglieder' }}</h2>
<ul class="ih:-mx-2 ih:grid">
<li v-for="m in members.active" :key="m.id" class="ih:flex ih:items-center ih:gap-3 ih:rounded-md ih:p-2 ih:hover:bg-muted/50">
<PersonAvatar :person="m" class="ih:size-9" />
<a :href="`/personen/${m.id}`" class="ih:min-w-0 ih:flex-1 ih:text-sm ih:hover:underline"><span class="ih:font-medium">{{ m.name }}</span><span class="ih:block ih:text-xs ih:text-muted-foreground">{{ m.job_title }}</span></a>
<select v-if="can.admin && m.id !== me.id" :value="m.role" class="ih:h-8 ih:rounded-md ih:border ih:bg-card ih:px-2 ih:text-xs" :aria-label="`Rolle von ${m.name}`" @change="act(`/mitglieder/${m.id}`, { role: $event.target.value }, 'put')">
<option v-for="(label, key) in roles" :key="key" :value="key">{{ label }}</option>
</select>
<span v-else-if="m.role !== 'member'" class="ih:rounded ih:bg-brand-soft ih:px-1.5 ih:py-0.5 ih:text-[11px] ih:font-medium ih:text-brand-text">{{ roles[m.role] }}</span>
<button v-if="can.moderate && m.id !== me.id && (can.admin || m.role === 'member')" type="button" class="ih:rounded ih:p-1.5 ih:text-muted-foreground ih:hover:text-destructive" :aria-label="`${m.name} entfernen`" @click="removeMember(m)"><UserMinus class="ih:size-4" /></button>
</li>
</ul>
<template v-if="members.invited.length">
<h2 class="ih:mt-5 ih:mb-2 ih:text-sm ih:font-semibold">Eingeladen</h2>
<p class="ih:text-sm ih:text-muted-foreground">{{ members.invited.map((m) => m.name).join(', ') }}</p>
</template>
</template>
<p v-else class="ih:text-sm ih:text-muted-foreground">Die Mitgliederliste sehen nur Mitglieder.</p>
</section>
<!-- Info -->
<section v-else class="ih:grid ih:gap-4 ih:rounded-xl ih:border ih:bg-card ih:p-5 ih:text-sm">
<p v-if="group.description" class="ih:text-[15px] ih:leading-relaxed ih:whitespace-pre-line">{{ group.description }}</p>
<p class="ih:flex ih:items-start ih:gap-2 ih:text-muted-foreground"><component :is="icons[group.privacy]" class="ih:mt-0.5 ih:size-4 ih:shrink-0" /> {{ group.privacy_hint }}</p>
<Button v-if="can.admin" variant="outline" class="ih:justify-self-start ih:text-destructive ih:hover:text-destructive" @click="destroy"><Trash2 /> Gruppe löschen</Button>
</section>
</div>
<GroupDialog v-model:open="editing" :group="group" :privacy="privacy" :privacy-hints="privacyHints" />
<Dialog v-model:open="inviting">
<DialogContent class="ih:sm:max-w-md">
<DialogHeader>
<DialogTitle>In „{{ group.name }}“ einladen</DialogTitle>
<DialogDescription>Die Eingeladenen bekommen eine Benachrichtigung und können annehmen.</DialogDescription>
</DialogHeader>
<PeopleSelect v-model="invitees" multiple :exclude="members?.active.map((m) => m.id) ?? []" />
<DialogFooter>
<Button variant="ghost" @click="inviting = false">Abbrechen</Button>
<Button :disabled="!invitees.length" @click="invite">Einladen</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</AppLayout>
</template>

View file

@ -0,0 +1,22 @@
<script setup>
import { Panel, PersonAvatar, formatRelative } from '@inhaus/ui';
defineProps({ posts: { type: Array, required: true } });
</script>
<template>
<Panel title="Aus Ihren Gruppen" action-label="Alle Gruppen" action-href="/gruppen">
<ul class="ih:-my-1 ih:grid ih:gap-1">
<li v-for="p in posts" :key="p.id">
<a :href="p.url" class="ih:-mx-2 ih:flex ih:gap-2.5 ih:rounded-md ih:p-2 ih:hover:bg-accent/50">
<PersonAvatar v-if="p.user" :person="p.user" class="ih:size-8 ih:text-[11px]" />
<span class="ih:min-w-0 ih:text-sm">
<span class="ih:block ih:truncate"><span class="ih:font-medium">{{ p.user?.name }}</span> <span class="ih:text-muted-foreground">in {{ p.group }}</span></span>
<span class="ih:line-clamp-2 ih:text-[13px] ih:text-muted-foreground">{{ p.text }}</span>
<span class="ih:text-xs ih:text-muted-foreground">{{ formatRelative(p.created_at) }}</span>
</span>
</a>
</li>
</ul>
</Panel>
</template>

38
routes/web.php Normal file
View file

@ -0,0 +1,38 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Gruppen\Http\Controllers\GroupController;
use Inhaus\Plugins\Gruppen\Http\Controllers\PostController;
Route::middleware('auth')->prefix('gruppen')->name('gruppen.')->group(function () {
Route::get('/', [GroupController::class, 'index'])->name('index');
Route::get('/entdecken', [GroupController::class, 'discover'])->name('discover');
Route::post('/', [GroupController::class, 'store'])->middleware('throttle:10,60')->name('store');
Route::get('/dateien/{attachment}/{size}', [PostController::class, 'file'])->whereIn('size', ['thumb', 'full'])->name('file');
// Beiträge und Kommentare (JSON)
Route::put('/beitraege/{post}', [PostController::class, 'update'])->name('posts.update');
Route::delete('/beitraege/{post}', [PostController::class, 'destroy'])->name('posts.destroy');
Route::post('/beitraege/{post}/anpinnen', [PostController::class, 'pin'])->name('posts.pin');
Route::post('/beitraege/{post}/reaktion', [PostController::class, 'react'])->middleware('throttle:60,1')->name('posts.react');
Route::post('/beitraege/{post}/abstimmen', [PostController::class, 'vote'])->middleware('throttle:60,1')->name('posts.vote');
Route::get('/beitraege/{post}/kommentare', [PostController::class, 'comments'])->name('posts.comments');
Route::post('/beitraege/{post}/kommentare', [PostController::class, 'comment'])->middleware('throttle:30,1')->name('posts.comment');
Route::post('/beitraege/{post}/melden', [PostController::class, 'report'])->middleware('throttle:10,60')->name('posts.report');
Route::post('/beitraege/{post}/meldungen-erledigt', [PostController::class, 'resolveReports'])->name('posts.resolve');
Route::delete('/kommentare/{comment}', [PostController::class, 'deleteComment'])->name('comments.destroy');
Route::get('/{group}', [GroupController::class, 'show'])->name('show');
Route::post('/{group}', [GroupController::class, 'update'])->name('update'); // POST wegen Titelbild-Upload
Route::delete('/{group}', [GroupController::class, 'destroy'])->name('destroy');
Route::get('/{group}/titelbild', [GroupController::class, 'cover'])->name('cover');
Route::post('/{group}/beitreten', [GroupController::class, 'join'])->name('join');
Route::post('/{group}/verlassen', [GroupController::class, 'leave'])->name('leave');
Route::post('/{group}/einladen', [GroupController::class, 'invite'])->middleware('throttle:20,60')->name('invite');
Route::post('/{group}/anfragen/{user}', [GroupController::class, 'decide'])->name('decide');
Route::put('/{group}/mitglieder/{user}', [GroupController::class, 'role'])->name('role');
Route::delete('/{group}/mitglieder/{user}', [GroupController::class, 'remove'])->name('remove');
Route::put('/{group}/benachrichtigungen', [GroupController::class, 'notifications'])->name('notifications');
Route::post('/{group}/beitraege', [PostController::class, 'store'])->middleware('throttle:20,1')->name('posts.store');
Route::get('/{group}/beitraege/{post}', [PostController::class, 'show'])->name('post');
});

93
src/Files.php Normal file
View file

@ -0,0 +1,93 @@
<?php
namespace Inhaus\Plugins\Gruppen;
use App\Support\BlockedFiles;
use App\Support\Images;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Gruppen\Models\Attachment;
use Inhaus\Plugins\Gruppen\Models\Post;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\ImageManager;
use Throwable;
/**
* Anhänge und Titelbilder – außerhalb des öffentlichen Ordners, ausgeliefert nur an Berechtigte.
* Fotos werden verkleinert (max. 1600 px) und bekommen eine Vorschau.
*/
class Files
{
public const DISK = 'local';
public const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
public function attach(Post $post, UploadedFile $file, int $sort): Attachment
{
$name = Str::limit(preg_replace('/[^\pL\pN ._()-]+/u', '_', $file->getClientOriginalName()) ?: 'Datei', 150, '');
$mime = $file->getMimeType() ?: 'application/octet-stream';
$base = "gruppen/{$post->group_id}/{$post->id}/".Str::random(24);
// Fotos (außer GIF – Animation erhalten) verkleinern
if (in_array($mime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
try {
return Images::withLocalCopy($file, function (string $local) use ($post, $base, $name, $sort) {
Images::raiseMemoryLimitFor($local);
$image = ImageManager::usingDriver(Driver::class)->decodePath($local)->scaleDown(1600, 1600);
$disk = Storage::disk(self::DISK);
$disk->put("{$base}.webp", $full = $image->encode(new WebpEncoder(quality: 82))->toString());
[$w, $h] = [$image->width(), $image->height()];
$disk->put("{$base}-thumb.webp", $image->scaleDown(720, 720)->encode(new WebpEncoder(quality: 78))->toString());
return $post->attachments()->create(['path' => "{$base}.webp", 'thumb_path' => "{$base}-thumb.webp", 'name' => $name, 'mime' => 'image/webp', 'size' => strlen($full), 'width' => $w, 'height' => $h, 'sort' => $sort]);
});
} catch (ValidationException $e) {
throw $e;
} catch (Throwable $e) {
report($e);
throw ValidationException::withMessages(['files' => "„{$name}“ ließ sich nicht als Bild lesen."]);
}
}
$extension = strtolower($file->guessExtension() ?: $file->getClientOriginalExtension());
if (in_array($extension, BlockedFiles::EXTENSIONS, true) || in_array(strtolower($file->getClientOriginalExtension()), BlockedFiles::EXTENSIONS, true)) {
throw ValidationException::withMessages(['files' => "Dateien dieses Typs („{$name}“) sind nicht erlaubt."]);
}
$path = $file->storeAs(dirname($base), basename($base).($extension ? '.'.$extension : ''), self::DISK);
$size = $mime === 'image/gif' ? @getimagesize($file->getRealPath()) : false;
return $post->attachments()->create([
'path' => $path, 'thumb_path' => $mime === 'image/gif' ? $path : null, 'name' => $name, 'mime' => $mime,
'size' => $file->getSize(), 'width' => $size[0] ?? null, 'height' => $size[1] ?? null, 'sort' => $sort,
]);
}
public function storeCover(int $groupId, UploadedFile $file): string
{
$path = "gruppen/{$groupId}/cover-".Str::random(16).'.webp';
Images::withLocalCopy($file, function (string $local) use ($path) {
Images::raiseMemoryLimitFor($local);
$image = ImageManager::usingDriver(Driver::class)->decodePath($local)->coverDown(1600, 500);
Storage::disk(self::DISK)->put($path, $image->encode(new WebpEncoder(quality: 82))->toString());
});
return $path;
}
public function deletePost(Post $post): void
{
Storage::disk(self::DISK)->deleteDirectory("gruppen/{$post->group_id}/{$post->id}");
}
public function deleteGroup(int $groupId): void
{
Storage::disk(self::DISK)->deleteDirectory("gruppen/{$groupId}");
}
}

382
src/Groups.php Normal file
View file

@ -0,0 +1,382 @@
<?php
namespace Inhaus\Plugins\Gruppen;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Plugins\PluginAccess;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inhaus\Plugins\Gruppen\Models\Comment;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Member;
use Inhaus\Plugins\Gruppen\Models\Post;
/**
* Diskussionsgruppen: Zugriff je Art (offen, geschlossen, privat), Mitgliedschaft,
* Beiträge, Kommentare, Reaktionen und Umfragen.
*/
class Groups
{
public const MAX_PINNED = 3;
public const MAX_FILES = 10;
public function __construct(private readonly Files $files) {}
/**
* Was darf die Person in dieser Gruppe?
*
* @return array{member: ?Member, see: bool, read: bool, post: bool, moderate: bool, admin: bool}
*/
public function access(Group $group, User $user): array
{
$member = $group->membership($user);
$active = $member?->isActive() ?? false;
$manager = $user->can('gruppen.manage');
return [
'member' => $member,
'see' => $group->privacy !== 'secret' || $manager || in_array($member?->status, ['active', 'invited'], true),
'read' => $group->privacy === 'open' || $active || $manager,
'post' => $active,
'moderate' => ($member?->canModerate() ?? false) || $manager,
'admin' => ($member?->isAdmin() ?? false) || $manager,
];
}
public function create(User $creator, array $data, ?UploadedFile $cover = null): Group
{
$group = DB::transaction(function () use ($creator, $data) {
$group = Group::query()->create([
'name' => $data['name'],
'slug' => $this->slug($data['name']),
'description' => $data['description'] ?? null,
'privacy' => $data['privacy'],
'created_by' => $creator->id,
'last_activity_at' => now(),
]);
$group->memberships()->create(['user_id' => $creator->id, 'role' => 'admin', 'status' => 'active', 'joined_at' => now()]);
return $group;
});
if ($cover) {
$group->update(['cover_path' => $this->files->storeCover($group->id, $cover)]);
}
$group->refreshCounts();
return $group;
}
/** Beitreten: offen sofort, geschlossen als Anfrage, privat nur mit Einladung */
public function join(Group $group, User $user): string
{
$member = $group->membership($user);
if ($member?->isActive()) {
return 'active';
}
if ($member?->status === 'invited' || $group->privacy === 'open') {
$this->upsert($group, $user, ['status' => 'active', 'joined_at' => now()]);
$group->refreshCounts();
return 'active';
}
abort_if($group->privacy === 'secret', 404);
$this->upsert($group, $user, ['status' => 'pending']);
Notification::send($this->moderators($group), new PortalNotification(
"Beitrittsanfrage für „{$group->name}“",
"{$user->name} möchte beitreten.",
route('gruppen.show', [$group, 'tab' => 'mitglieder'], false),
'users',
));
return 'pending';
}
public function leave(Group $group, User $user): void
{
$member = $group->membership($user);
if (! $member) {
return;
}
$member->delete();
// Letzte Admin-Person weg: die am längsten dabei ist, übernimmt
if (! $group->memberships()->where('status', 'active')->where('role', 'admin')->exists()) {
$group->memberships()->where('status', 'active')->orderBy('joined_at')->first()?->forceFill(['role' => 'admin'])->save();
}
$group->refreshCounts();
}
/**
* Einladen: in offenen Gruppen alle Mitglieder, sonst Admins und Moderation.
*
* @param list<int> $userIds
*/
public function invite(Group $group, User $actor, array $userIds): int
{
$access = $this->access($group, $actor);
abort_unless($access['post'] && ($group->privacy === 'open' || $access['moderate']), 403);
$count = 0;
foreach (User::query()->whereKey(array_slice(array_map('intval', $userIds), 0, 100))->whereKeyNot($actor->id)->get() as $user) {
if (! $user->is_active || ! app(PluginAccess::class)->allows('gruppen', $user)) {
continue;
}
$existing = $group->membership($user);
if ($existing?->isActive() || $existing?->status === 'invited') {
continue;
}
// Wer schon angefragt hat, ist mit der Einladung drin
$this->upsert($group, $user, $existing?->status === 'pending'
? ['status' => 'active', 'joined_at' => now()]
: ['status' => 'invited', 'invited_by' => $actor->id]);
$count++;
$user->notify(new PortalNotification("Einladung in die Gruppe „{$group->name}“", "{$actor->name} lädt Sie ein.", route('gruppen.show', $group, false), 'users'));
}
$group->refreshCounts();
return $count;
}
public function decide(Group $group, User $actor, User $user, bool $accept): void
{
abort_unless($this->access($group, $actor)['moderate'], 403);
$member = $group->membership($user);
abort_unless($member?->status === 'pending', 404);
if ($accept) {
$member->forceFill(['status' => 'active', 'joined_at' => now()])->save();
$user->notify(new PortalNotification("Willkommen in „{$group->name}“", 'Ihre Beitrittsanfrage wurde angenommen.', route('gruppen.show', $group, false), 'users'));
} else {
$member->delete();
}
$group->refreshCounts();
}
public function setRole(Group $group, User $actor, User $user, string $role): void
{
abort_unless($this->access($group, $actor)['admin'] && isset(Member::ROLES[$role]), 403);
$member = $group->membership($user);
abort_unless($member?->isActive(), 404);
if ($role !== 'admin' && $member->role === 'admin' && $group->memberships()->where('role', 'admin')->where('status', 'active')->count() === 1) {
throw ValidationException::withMessages(['role' => 'Eine Gruppe braucht mindestens eine Admin-Person.']);
}
$member->forceFill(['role' => $role])->save();
}
public function removeMember(Group $group, User $actor, User $user): void
{
$access = $this->access($group, $actor);
$member = $group->membership($user);
abort_unless($member && $access['moderate'] && ($access['admin'] || $member->role === 'member'), 403);
$this->leave($group, $user);
}
/**
* @param list<UploadedFile> $files
* @param list<string>|null $pollOptions
*/
public function post(Group $group, User $user, ?string $body, array $files = [], ?array $pollOptions = null, bool $multiple = false): Post
{
abort_unless($this->access($group, $user)['post'], 403);
$body = filled($body) ? trim($body) : null;
$options = $pollOptions ? array_values(array_filter(array_map(fn ($o) => Str::limit(trim((string) $o), 120, ''), $pollOptions))) : [];
if ($pollOptions !== null && count($options) < 2) {
throw ValidationException::withMessages(['poll' => 'Eine Umfrage braucht mindestens zwei Antworten.']);
}
if ($body === null && $files === [] && $options === []) {
throw ValidationException::withMessages(['body' => 'Der Beitrag ist leer.']);
}
$post = $group->posts()->create(['user_id' => $user->id, 'body' => $body, 'poll' => $options ? ['options' => array_slice($options, 0, 10), 'multiple' => $multiple] : null]);
foreach (array_values($files) as $i => $file) {
$this->files->attach($post, $file, $i);
}
$group->forceFill(['last_activity_at' => now()])->save();
$group->refreshCounts();
$this->notifyNewPost($group, $post, $user);
return $post;
}
public function deletePost(Post $post, User $user): void
{
abort_unless($post->user_id === $user->id || $this->access($post->group, $user)['moderate'], 403);
$this->files->deletePost($post);
$post->delete();
$post->group->refreshCounts();
}
public function pin(Post $post, User $user, bool $pinned): void
{
abort_unless($this->access($post->group, $user)['moderate'], 403);
if ($pinned && $post->group->posts()->whereNotNull('pinned_at')->count() >= self::MAX_PINNED) {
throw ValidationException::withMessages(['pin' => 'Höchstens '.self::MAX_PINNED.' Beiträge lassen sich anpinnen.']);
}
$post->forceFill(['pinned_at' => $pinned ? now() : null])->save();
}
public function react(Post $post, User $user, ?string $emoji): void
{
abort_unless($this->access($post->group, $user)['post'], 403);
DB::table('gruppen_reactions')->where(['post_id' => $post->id, 'user_id' => $user->id])->delete();
if ($emoji !== null) {
abort_unless(in_array($emoji, Post::REACTIONS, true), 422);
DB::table('gruppen_reactions')->insert(['post_id' => $post->id, 'user_id' => $user->id, 'emoji' => $emoji]);
}
}
/**
* @param list<int> $options
*/
public function vote(Post $post, User $user, array $options): void
{
abort_unless($post->poll && $this->access($post->group, $user)['post'], 403);
$count = count($post->poll['options']);
$options = array_values(array_unique(array_filter(array_map('intval', $options), fn ($o) => $o >= 0 && $o < $count)));
$options = $post->poll['multiple'] ? $options : array_slice($options, 0, 1);
DB::transaction(function () use ($post, $user, $options) {
DB::table('gruppen_poll_votes')->where(['post_id' => $post->id, 'user_id' => $user->id])->delete();
DB::table('gruppen_poll_votes')->insert(array_map(fn ($o) => ['post_id' => $post->id, 'user_id' => $user->id, 'option' => $o], $options));
});
}
public function comment(Post $post, User $user, string $body, ?int $parentId): Comment
{
abort_unless($this->access($post->group, $user)['post'], 403);
$parent = $parentId ? $post->comments()->find($parentId) : null;
// Antworten hängen immer am obersten Kommentar
$parent = $parent?->parent_id ? $post->comments()->find($parent->parent_id) : $parent;
$comment = $post->comments()->create(['user_id' => $user->id, 'parent_id' => $parent?->id, 'body' => trim($body)]);
$post->forceFill(['comments_count' => $post->comments()->count()])->saveQuietly();
$post->group->forceFill(['last_activity_at' => now()])->save();
$url = route('gruppen.post', [$post->group, $post], false).'#kommentar-'.$comment->id;
$recipients = collect([$post->user, $parent?->user])->filter()->unique('id')->reject(fn (User $u) => $u->is($user) || ! $u->is_active);
foreach ($recipients as $recipient) {
$recipient->notify(new PortalNotification(
$recipient->is($parent?->user) ? "{$user->name} hat Ihnen geantwortet" : "{$user->name} hat Ihren Beitrag kommentiert",
Str::limit($comment->body, 100),
$url,
'message-circle',
));
}
return $comment;
}
public function deleteComment(Comment $comment, User $user): void
{
abort_unless($comment->user_id === $user->id || $this->access($comment->post->group, $user)['moderate'], 403);
$post = $comment->post;
$comment->delete();
$post->forceFill(['comments_count' => $post->comments()->count()])->saveQuietly();
}
public function report(Post $post, ?Comment $comment, User $user, string $reason): void
{
abort_unless($this->access($post->group, $user)['read'], 404);
$created = DB::table('gruppen_reports')->insertOrIgnore([
'group_id' => $post->group_id, 'post_id' => $post->id, 'comment_id' => $comment?->id, 'user_id' => $user->id,
'reason' => $reason, 'created_at' => now(), 'updated_at' => now(),
]);
if ($created) {
Notification::send($this->moderators($post->group)->reject(fn (User $u) => $u->is($user)), new PortalNotification(
($comment ? 'Kommentar' : 'Beitrag')." in „{$post->group->name}“ gemeldet",
Str::limit($reason, 100),
route('gruppen.post', [$post->group, $post], false),
'flag',
));
}
}
/** Beim Besuch: gesehen – ab jetzt wieder benachrichtigen */
public function seen(Group $group, User $user): void
{
$group->memberships()->where('user_id', $user->id)->update(['last_seen_at' => now()]);
}
/**
* @return Collection<int, User>
*/
public function moderators(Group $group): Collection
{
return User::query()->active()->whereIn('id', $group->memberships()->where('status', 'active')->whereIn('role', ['admin', 'moderator'])->pluck('user_id'))->get();
}
/**
* Neue Beiträge: Mitglieder mit „alle Beiträge“ – je Gruppe einmal, bis sie wieder vorbeischauen.
*/
private function notifyNewPost(Group $group, Post $post, User $author): void
{
$members = $group->memberships()->with('user')->where('status', 'active')->where('notify', 'all')->where('user_id', '!=', $author->id)
->where(fn ($q) => $q->whereNull('notified_at')->orWhereColumn('last_seen_at', '>', 'notified_at'))->get();
foreach ($members as $member) {
if (! $member->user?->is_active) {
continue;
}
$member->forceFill(['notified_at' => now()])->save();
$member->user->notify(new PortalNotification(
"Neu in „{$group->name}“",
$author->name.': '.Str::limit($post->body ?: ($post->poll ? 'Umfrage' : 'Fotos/Dateien'), 90),
route('gruppen.post', [$group, $post], false),
'users',
));
}
}
private function upsert(Group $group, User $user, array $values): void
{
$existing = $group->membership($user);
$existing ? $existing->forceFill($values)->save() : $group->memberships()->create(['user_id' => $user->id, 'role' => 'member', ...$values]);
}
private function slug(string $name): string
{
$base = Str::slug($name, language: 'de') ?: 'gruppe';
$slug = $base;
for ($i = 2; Group::query()->where('slug', $slug)->exists(); $i++) {
$slug = "{$base}-{$i}";
}
return $slug;
}
}

73
src/GruppenPlugin.php Normal file
View file

@ -0,0 +1,73 @@
<?php
namespace Inhaus\Plugins\Gruppen;
use App\Dashboard\Widgets;
use App\Digest\Digest;
use App\Models\User;
use App\Plugins\Plugin;
use App\Search\GlobalSearch;
use App\Support\Abilities;
use App\Support\Navigation;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Member;
use Inhaus\Plugins\Gruppen\Models\Post;
/**
* Diskussionsgruppen – offen, geschlossen oder privat, mit Beiträgen, Kommentaren und Umfragen.
*/
class GruppenPlugin extends Plugin
{
public function register(): void
{
$this->app->singleton(Groups::class);
$this->app->make(Navigation::class)->add('gruppen', 'Gruppen', '/gruppen', active: 'gruppen.*', sort: 25);
$this->app->make(Abilities::class)->define('gruppen.manage', 'Alle Gruppen verwalten (auch private) und bei Meldungen eingreifen', 'Gruppen', portal: true);
$this->app->make(GlobalSearch::class)->add('gruppen', 'Gruppen', 'users', function (User $user, string $search, int $limit) {
$query = Group::query()->discoverableBy($user);
GlobalSearch::whereTerms($query, ['name', 'description'], $search);
return $query->orderByDesc('members_count')->limit($limit)->get()->map(fn (Group $g) => [
'title' => $g->name,
'url' => '/gruppen/'.$g->slug,
'excerpt' => GlobalSearch::excerpt((string) $g->description, $search),
'meta' => Group::PRIVACY[$g->privacy].' · '.$g->members_count.($g->members_count === 1 ? ' Mitglied' : ' Mitglieder'),
])->all();
}, sort: 45);
// Startseite: Neues aus den eigenen Gruppen
$this->app->make(Widgets::class)->add('gruppen.feed', 'gruppen::Recent', 'aside', sort: 35, props: function (User $user) {
$ids = Member::query()->where('user_id', $user->id)->where('status', 'active')->pluck('group_id');
$posts = Post::query()->with(['user', 'group'])->whereIn('group_id', $ids)->latest('id')->limit(4)->get();
return $posts->isEmpty() ? null : ['posts' => $posts->map(fn (Post $p) => [
'id' => $p->id,
'group' => $p->group->name,
'user' => Presenter::person($p->user),
'text' => Str::limit((string) ($p->body ?: ($p->poll ? 'Umfrage' : 'Fotos/Dateien')), 90),
'created_at' => $p->created_at?->toIso8601String(),
'url' => route('gruppen.post', [$p->group, $p]),
])->all()];
}, label: 'Gruppen', mobileSort: 42);
if (class_exists(Digest::class)) {
$this->app->make(Digest::class)->add('gruppen', 'Aus Ihren Gruppen', 45, function (User $user, CarbonImmutable $since) {
$ids = Member::query()->where('user_id', $user->id)->where('status', 'active')->pluck('group_id');
return Group::query()->whereIn('id', $ids)->withCount(['posts as new_posts' => fn ($q) => $q->where('created_at', '>=', $since)])->get()
->where('new_posts', '>', 0)->sortByDesc('new_posts')->take(6)
->map(fn (Group $g) => ['title' => $g->name, 'url' => route('gruppen.show', $g), 'meta' => $g->new_posts === 1 ? '1 neuer Beitrag' : "{$g->new_posts} neue Beiträge"])->values()->all();
});
}
}
public function uninstall(): void
{
Storage::disk(Files::DISK)->deleteDirectory('gruppen');
}
}

View file

@ -0,0 +1,232 @@
<?php
namespace Inhaus\Plugins\Gruppen\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Gruppen\Files;
use Inhaus\Plugins\Gruppen\Groups;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Member;
use Inhaus\Plugins\Gruppen\Models\Post;
use Inhaus\Plugins\Gruppen\Presenter;
use Symfony\Component\HttpFoundation\StreamedResponse;
class GroupController extends Controller
{
public const PAGE = 15;
public function __construct(private readonly Groups $groups, private readonly Files $files) {}
/** Übersicht: Beiträge aus den eigenen Gruppen, dazu die eigenen Gruppen und Einladungen */
public function index(Request $request): Response|JsonResponse
{
$user = $request->user();
$groupIds = Member::query()->where('user_id', $user->id)->where('status', 'active')->pluck('group_id');
$posts = Post::query()->with(['user', 'attachments', 'group'])->whereIn('group_id', $groupIds)
->when($request->integer('vor'), fn ($q, $before) => $q->where('id', '<', $before))
->latest('id')->limit(self::PAGE)->get();
$payload = ['posts' => Presenter::posts($posts, $user, $this->groups), 'more' => $posts->count() === self::PAGE];
if ($request->wantsJson() && ! $request->header('X-Inertia')) {
return response()->json($payload);
}
$memberships = Member::query()->with('group')->where('user_id', $user->id)->whereIn('status', ['active', 'invited', 'pending'])->get();
return Inertia::render('gruppen::Index', [
...$payload,
'groups' => $memberships->where('status', 'active')->sortByDesc(fn ($m) => $m->group->last_activity_at)->map(fn ($m) => Presenter::group($m->group, 'active'))->values()->all(),
'invitations' => $memberships->where('status', 'invited')->map(fn ($m) => Presenter::group($m->group, 'invited'))->values()->all(),
'suggested' => Group::query()->where('privacy', 'open')->whereNotIn('id', $memberships->pluck('group_id'))->orderByDesc('members_count')->limit(4)->get()->map(fn ($g) => Presenter::group($g))->all(),
'privacy' => Group::PRIVACY,
'privacyHints' => Group::PRIVACY_HINTS,
]);
}
public function discover(Request $request): Response
{
$user = $request->user();
$q = trim((string) $request->query('q', ''));
$statuses = Member::query()->where('user_id', $user->id)->pluck('status', 'group_id');
$groups = Group::query()->discoverableBy($user)
->when($q !== '', fn ($query) => $query->where(fn ($w) => $w->where('name', 'like', '%'.addcslashes($q, '%_\\').'%')->orWhere('description', 'like', '%'.addcslashes($q, '%_\\').'%')))
->orderByDesc('last_activity_at')->paginate(24)->withQueryString();
return Inertia::render('gruppen::Discover', [
'groups' => collect($groups->items())->map(fn (Group $g) => Presenter::group($g, $statuses[$g->id] ?? null))->all(),
'pagination' => ['prev' => $groups->previousPageUrl(), 'next' => $groups->nextPageUrl()],
'q' => $q,
'privacy' => Group::PRIVACY,
'privacyHints' => Group::PRIVACY_HINTS,
]);
}
public function show(Request $request, Group $group): Response|JsonResponse
{
$user = $request->user();
$access = $this->groups->access($group, $user);
abort_unless($access['see'], 404);
$posts = $access['read']
? $group->posts()->with(['user', 'attachments', 'group'])
->when($request->integer('vor'), fn ($q, $before) => $q->where('id', '<', $before)->whereNull('pinned_at'))
->orderByRaw('pinned_at IS NULL')->orderByDesc('pinned_at')->latest('id')->limit(self::PAGE)->get()
: collect();
$payload = ['posts' => Presenter::posts($posts, $user, $this->groups), 'more' => $posts->count() === self::PAGE];
if ($request->wantsJson() && ! $request->header('X-Inertia')) {
return response()->json($payload);
}
$this->groups->seen($group, $user);
return Inertia::render('gruppen::Show', [
...$payload,
'group' => Presenter::group($group, $access['member']?->status),
'membership' => $access['member'] ? ['status' => $access['member']->status, 'role' => $access['member']->role, 'notify' => $access['member']->notify] : null,
'can' => collect($access)->except('member')->all(),
'members' => $access['read'] ? $this->members($group, $access['moderate']) : null,
'privacy' => Group::PRIVACY,
'privacyHints' => Group::PRIVACY_HINTS,
'roles' => Member::ROLES,
'reactions' => Post::REACTIONS,
'tab' => $request->query('tab') === 'mitglieder' ? 'mitglieder' : 'beitraege',
'reports' => $access['moderate'] ? DB::table('gruppen_reports')->where('group_id', $group->id)->whereNull('resolved_at')->count() : 0,
]);
}
public function store(Request $request): RedirectResponse
{
$data = $this->validated($request);
$group = $this->groups->create($request->user(), $data, $request->file('cover'));
return to_route('gruppen.show', $group)->with('status', 'Gruppe gegründet – laden Sie jetzt Kolleginnen und Kollegen ein.');
}
public function update(Request $request, Group $group): RedirectResponse
{
abort_unless($this->groups->access($group, $request->user())['admin'], 403);
$data = $this->validated($request);
$group->update(collect($data)->only(['name', 'description', 'privacy'])->all());
if ($request->hasFile('cover')) {
$old = $group->cover_path;
$group->update(['cover_path' => $this->files->storeCover($group->id, $request->file('cover'))]);
$old && Storage::disk(Files::DISK)->delete($old);
} elseif ($request->boolean('remove_cover') && $group->cover_path) {
Storage::disk(Files::DISK)->delete($group->cover_path);
$group->update(['cover_path' => null]);
}
return back()->with('status', 'Gruppe gespeichert.');
}
public function destroy(Request $request, Group $group): RedirectResponse
{
abort_unless($this->groups->access($group, $request->user())['admin'], 403);
$this->files->deleteGroup($group->id);
$group->delete();
return to_route('gruppen.index')->with('status', "Gruppe „{$group->name}“ gelöscht.");
}
public function join(Request $request, Group $group): RedirectResponse
{
abort_unless($this->groups->access($group, $request->user())['see'], 404);
$status = $this->groups->join($group, $request->user());
return back()->with('status', $status === 'active' ? 'Willkommen in der Gruppe!' : 'Anfrage gesendet – die Gruppe entscheidet.');
}
public function leave(Request $request, Group $group): RedirectResponse
{
$this->groups->leave($group, $request->user());
return $group->privacy === 'open' ? back()->with('status', 'Gruppe verlassen.') : to_route('gruppen.index')->with('status', 'Gruppe verlassen.');
}
public function invite(Request $request, Group $group): RedirectResponse
{
$data = $request->validate(['users' => ['required', 'array', 'max:100'], 'users.*' => ['integer']]);
$count = $this->groups->invite($group, $request->user(), $data['users']);
return back()->with('status', $count === 1 ? '1 Person eingeladen.' : "{$count} Personen eingeladen.");
}
public function decide(Request $request, Group $group, User $user): RedirectResponse
{
$data = $request->validate(['accept' => ['required', 'boolean']]);
$this->groups->decide($group, $request->user(), $user, $data['accept']);
return back()->with('status', $data['accept'] ? "{$user->name} ist jetzt Mitglied." : 'Anfrage abgelehnt.');
}
public function role(Request $request, Group $group, User $user): RedirectResponse
{
$data = $request->validate(['role' => ['required', Rule::in(array_keys(Member::ROLES))]]);
$this->groups->setRole($group, $request->user(), $user, $data['role']);
return back()->with('status', 'Rolle geändert.');
}
public function remove(Request $request, Group $group, User $user): RedirectResponse
{
$this->groups->removeMember($group, $request->user(), $user);
return back()->with('status', "{$user->name} entfernt.");
}
public function notifications(Request $request, Group $group): RedirectResponse
{
$data = $request->validate(['notify' => ['required', 'in:all,off']]);
$group->memberships()->where('user_id', $request->user()->id)->update(['notify' => $data['notify']]);
return back()->with('status', $data['notify'] === 'all' ? 'Sie werden über neue Beiträge benachrichtigt.' : 'Keine Benachrichtigungen mehr zu neuen Beiträgen.');
}
public function cover(Request $request, Group $group): StreamedResponse
{
abort_unless($group->cover_path && $this->groups->access($group, $request->user())['see'], 404);
return Storage::disk(Files::DISK)->response($group->cover_path, null, ['Content-Type' => 'image/webp', 'Cache-Control' => 'private, max-age=604800', 'X-Content-Type-Options' => 'nosniff']);
}
/**
* @return array<string, mixed>
*/
private function members(Group $group, bool $moderate): array
{
$all = $group->memberships()->with('user')->get()->filter(fn (Member $m) => $m->user);
$map = fn (Member $m) => [...Presenter::person($m->user), 'role' => $m->role, 'status' => $m->status];
return [
'active' => $all->where('status', 'active')->sortBy(fn (Member $m) => [array_search($m->role, ['admin', 'moderator', 'member'], true), $m->user->name])->map($map)->values()->all(),
'pending' => $moderate ? $all->where('status', 'pending')->map($map)->values()->all() : [],
'invited' => $moderate ? $all->where('status', 'invited')->map($map)->values()->all() : [],
];
}
/**
* @return array<string, mixed>
*/
private function validated(Request $request): array
{
return $request->validate([
'name' => ['required', 'string', 'max:100'],
'description' => ['nullable', 'string', 'max:2000'],
'privacy' => ['required', Rule::in(array_keys(Group::PRIVACY))],
'cover' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:15360'],
], [], ['name' => 'Name', 'description' => 'Beschreibung', 'privacy' => 'Art', 'cover' => 'Titelbild']);
}
}

View file

@ -0,0 +1,162 @@
<?php
namespace Inhaus\Plugins\Gruppen\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Gruppen\Files;
use Inhaus\Plugins\Gruppen\Groups;
use Inhaus\Plugins\Gruppen\Models\Attachment;
use Inhaus\Plugins\Gruppen\Models\Comment;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Post;
use Inhaus\Plugins\Gruppen\Presenter;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PostController extends Controller
{
public function __construct(private readonly Groups $groups) {}
/** Einzelner Beitrag (Link aus Benachrichtigungen), mit allen Kommentaren */
public function show(Request $request, Group $group, Post $post): Response
{
abort_unless($post->group_id === $group->id, 404);
$access = $this->groups->access($group, $request->user());
abort_unless($access['read'], 404);
$post->load(['user', 'attachments', 'group']);
return Inertia::render('gruppen::Post', [
'group' => Presenter::group($group, $access['member']?->status),
'post' => Presenter::posts(collect([$post]), $request->user(), $this->groups)[0],
'comments' => $this->allComments($post, $request, $access['moderate']),
'reactions' => Post::REACTIONS,
'reports' => $access['moderate'] ? DB::table('gruppen_reports')->where('post_id', $post->id)->whereNull('resolved_at')->get(['id', 'comment_id', 'reason'])->all() : [],
]);
}
public function store(Request $request, Group $group): JsonResponse
{
$data = $request->validate([
'body' => ['nullable', 'string', 'max:'.Post::MAX_LENGTH],
'files' => ['nullable', 'array', 'max:'.Groups::MAX_FILES],
'files.*' => ['file', 'max:25600'],
'poll' => ['nullable', 'array', 'max:10'],
'poll.*' => ['nullable', 'string', 'max:120'],
'multiple' => ['boolean'],
], ['files.*.max' => 'Eine Datei ist größer als 25 MB.'], ['body' => 'Beitrag']);
$post = $this->groups->post($group, $request->user(), $data['body'] ?? null, $request->file('files', []), $data['poll'] ?? null, (bool) ($data['multiple'] ?? false));
$post->load(['user', 'attachments', 'group']);
return response()->json(['post' => Presenter::posts(collect([$post]), $request->user(), $this->groups)[0]], 201);
}
public function update(Request $request, Post $post): JsonResponse
{
abort_unless($post->user_id === $request->user()->id && $this->groups->access($post->group, $request->user())['post'], 403);
$data = $request->validate(['body' => ['nullable', 'string', 'max:'.Post::MAX_LENGTH]]);
$post->update(['body' => filled($data['body'] ?? null) ? trim($data['body']) : null, 'edited_at' => now()]);
return response()->json(['ok' => true]);
}
public function destroy(Request $request, Post $post): JsonResponse
{
$this->groups->deletePost($post, $request->user());
return response()->json(['ok' => true]);
}
public function pin(Request $request, Post $post): JsonResponse
{
$this->groups->pin($post, $request->user(), $request->boolean('pinned'));
return response()->json(['ok' => true]);
}
public function react(Request $request, Post $post): JsonResponse
{
$data = $request->validate(['emoji' => ['nullable', 'string', 'max:16']]);
$this->groups->react($post, $request->user(), $data['emoji'] ?? null);
return response()->json(['ok' => true]);
}
public function vote(Request $request, Post $post): JsonResponse
{
$data = $request->validate(['options' => ['present', 'array', 'max:10'], 'options.*' => ['integer']]);
$this->groups->vote($post, $request->user(), $data['options']);
$post->load(['user', 'attachments', 'group']);
return response()->json(['poll' => Presenter::posts(collect([$post]), $request->user(), $this->groups)[0]['poll']]);
}
public function comments(Request $request, Post $post): JsonResponse
{
$access = $this->groups->access($post->group, $request->user());
abort_unless($access['read'], 404);
return response()->json(['comments' => $this->allComments($post, $request, $access['moderate'])]);
}
public function comment(Request $request, Post $post): JsonResponse
{
$data = $request->validate(['body' => ['required', 'string', 'max:'.Comment::MAX_LENGTH], 'parent_id' => ['nullable', 'integer']], [], ['body' => 'Kommentar']);
$this->groups->comment($post, $request->user(), $data['body'], $data['parent_id'] ?? null);
return $this->comments($request, $post->fresh());
}
public function deleteComment(Request $request, Comment $comment): JsonResponse
{
$this->groups->deleteComment($comment, $request->user());
return response()->json(['ok' => true]);
}
public function report(Request $request, Post $post): JsonResponse
{
$data = $request->validate(['reason' => ['required', 'string', 'max:500'], 'comment_id' => ['nullable', 'integer']]);
$comment = isset($data['comment_id']) ? $post->comments()->findOrFail($data['comment_id']) : null;
$this->groups->report($post, $comment, $request->user(), trim($data['reason']));
return response()->json(['message' => 'Danke – die Gruppenmoderation sieht es sich an.']);
}
public function resolveReports(Request $request, Post $post): JsonResponse
{
abort_unless($this->groups->access($post->group, $request->user())['moderate'], 403);
DB::table('gruppen_reports')->where('post_id', $post->id)->whereNull('resolved_at')->update(['resolved_at' => now()]);
return response()->json(['ok' => true]);
}
public function file(Request $request, Attachment $attachment, string $size): StreamedResponse
{
$post = $attachment->post;
abort_unless($this->groups->access($post->group, $request->user())['read'], 404);
$disk = Storage::disk(Files::DISK);
$path = $size === 'thumb' && $attachment->thumb_path ? $attachment->thumb_path : $attachment->path;
abort_unless($disk->exists($path), 404);
$headers = ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, max-age=604800', 'Content-Security-Policy' => "default-src 'none'; img-src 'self'; sandbox"];
return $attachment->isImage()
? $disk->response($path, $attachment->name, [...$headers, 'Content-Type' => $attachment->mime], 'inline')
: $disk->download($path, $attachment->name, [...$headers, 'Content-Type' => 'application/octet-stream']);
}
/**
* @return list<array<string, mixed>>
*/
private function allComments(Post $post, Request $request, bool $moderate): array
{
$all = $post->comments()->with('user')->orderBy('id')->limit(1000)->get();
return Presenter::comments($all->whereNull('parent_id')->values(), $request->user(), $moderate, $all->whereNotNull('parent_id')->groupBy('parent_id'));
}
}

28
src/Models/Attachment.php Normal file
View file

@ -0,0 +1,28 @@
<?php
namespace Inhaus\Plugins\Gruppen\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['post_id', 'path', 'thumb_path', 'name', 'mime', 'size', 'width', 'height', 'sort'])]
class Attachment extends Model
{
protected $table = 'gruppen_attachments';
public $timestamps = false;
/**
* @return BelongsTo<Post, $this>
*/
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
public function isImage(): bool
{
return $this->thumb_path !== null;
}
}

37
src/Models/Comment.php Normal file
View file

@ -0,0 +1,37 @@
<?php
namespace Inhaus\Plugins\Gruppen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['post_id', 'user_id', 'parent_id', 'body', 'edited_at'])]
class Comment extends Model
{
public const MAX_LENGTH = 3000;
protected $table = 'gruppen_comments';
protected function casts(): array
{
return ['edited_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Post, $this>
*/
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
}

81
src/Models/Group.php Normal file
View file

@ -0,0 +1,81 @@
<?php
namespace Inhaus\Plugins\Gruppen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['name', 'slug', 'description', 'cover_path', 'privacy', 'created_by', 'members_count', 'posts_count', 'last_activity_at'])]
class Group extends Model
{
public const PRIVACY = [
'open' => 'Offen',
'closed' => 'Geschlossen',
'secret' => 'Privat',
];
public const PRIVACY_HINTS = [
'open' => 'Alle sehen die Beiträge und können sofort beitreten.',
'closed' => 'Alle finden die Gruppe; Beiträge sehen nur Mitglieder. Beitritt auf Anfrage.',
'secret' => 'Nur Mitglieder finden die Gruppe. Beitritt nur auf Einladung.',
];
protected $table = 'gruppen_groups';
protected function casts(): array
{
return ['last_activity_at' => 'datetime'];
}
public function getRouteKeyName(): string
{
return 'slug';
}
/**
* @return HasMany<Member, $this>
*/
public function memberships(): HasMany
{
return $this->hasMany(Member::class);
}
/**
* @return HasMany<Post, $this>
*/
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function membership(?User $user): ?Member
{
return $user ? $this->memberships()->where('user_id', $user->id)->first() : null;
}
/**
* Auffindbar: offene und geschlossene Gruppen, private nur für Mitglieder bzw. Eingeladene.
*
* @param Builder<Group> $query
*/
public function scopeDiscoverableBy(Builder $query, User $user): void
{
if ($user->can('gruppen.manage')) {
return;
}
$query->where(fn ($q) => $q->where('privacy', '!=', 'secret')
->orWhereHas('memberships', fn ($m) => $m->where('user_id', $user->id)->whereIn('status', ['active', 'invited'])));
}
public function refreshCounts(): void
{
$this->forceFill([
'members_count' => $this->memberships()->where('status', 'active')->count(),
'posts_count' => $this->posts()->count(),
])->saveQuietly();
}
}

74
src/Models/Member.php Normal file
View file

@ -0,0 +1,74 @@
<?php
namespace Inhaus\Plugins\Gruppen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['group_id', 'user_id', 'role', 'status', 'invited_by', 'notify', 'joined_at', 'last_seen_at', 'notified_at'])]
class Member extends Model
{
public const ROLES = ['admin' => 'Admin', 'moderator' => 'Moderation', 'member' => 'Mitglied'];
protected $table = 'gruppen_members';
public $incrementing = false;
protected $primaryKey = null;
protected function casts(): array
{
return ['joined_at' => 'datetime', 'last_seen_at' => 'datetime', 'notified_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Group, $this>
*/
public function group(): BelongsTo
{
return $this->belongsTo(Group::class);
}
public function isActive(): bool
{
return $this->status === 'active';
}
/** Admin oder Moderation: pinnen, löschen, Anfragen annehmen */
public function canModerate(): bool
{
return $this->isActive() && in_array($this->role, ['admin', 'moderator'], true);
}
public function isAdmin(): bool
{
return $this->isActive() && $this->role === 'admin';
}
protected function setKeysForSaveQuery($query): Builder
{
return $query->where('group_id', $this->group_id)->where('user_id', $this->user_id);
}
protected function setKeysForSelectQuery($query): Builder
{
return $this->setKeysForSaveQuery($query);
}
/** Zusammengesetzter Schlüssel: Löschen nur genau dieser Mitgliedschaft */
public function delete(): ?bool
{
return (bool) static::query()->where('group_id', $this->group_id)->where('user_id', $this->user_id)->delete();
}
}

56
src/Models/Post.php Normal file
View file

@ -0,0 +1,56 @@
<?php
namespace Inhaus\Plugins\Gruppen\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['group_id', 'user_id', 'body', 'poll', 'pinned_at', 'edited_at', 'comments_count'])]
class Post extends Model
{
public const MAX_LENGTH = 10000;
public const REACTIONS = ['👍', '❤️', '😂', '😮', '😢', '👏'];
protected $table = 'gruppen_posts';
protected function casts(): array
{
return ['poll' => 'array', 'pinned_at' => 'datetime', 'edited_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Group, $this>
*/
public function group(): BelongsTo
{
return $this->belongsTo(Group::class);
}
/**
* @return HasMany<Attachment, $this>
*/
public function attachments(): HasMany
{
return $this->hasMany(Attachment::class)->orderBy('sort');
}
/**
* @return HasMany<Comment, $this>
*/
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}

112
src/Presenter.php Normal file
View file

@ -0,0 +1,112 @@
<?php
namespace Inhaus\Plugins\Gruppen;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Inhaus\Plugins\Gruppen\Models\Attachment;
use Inhaus\Plugins\Gruppen\Models\Comment;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Post;
class Presenter
{
/**
* @return array<string, mixed>|null
*/
public static function person(?User $user): ?array
{
return $user ? ['id' => $user->id, 'name' => $user->name, 'initials' => $user->initials, 'avatar_url' => $user->avatarUrl(96), 'job_title' => $user->job_title] : null;
}
/**
* @return array<string, mixed>
*/
public static function group(Group $group, ?string $status = null): array
{
return [
'id' => $group->id,
'slug' => $group->slug,
'name' => $group->name,
'description' => $group->description,
'privacy' => $group->privacy,
'privacy_label' => Group::PRIVACY[$group->privacy],
'privacy_hint' => Group::PRIVACY_HINTS[$group->privacy],
'cover_url' => $group->cover_path ? route('gruppen.cover', [$group, 'v' => substr(md5($group->cover_path), 0, 8)]) : null,
'members_count' => $group->members_count,
'posts_count' => $group->posts_count,
'last_activity_at' => $group->last_activity_at?->toIso8601String(),
'status' => $status,
'url' => route('gruppen.show', $group),
];
}
/**
* @param Collection<int, Post> $posts mit user, attachments, group
* @return list<array<string, mixed>>
*/
public static function posts(Collection $posts, User $me, Groups $groups): array
{
$ids = $posts->pluck('id')->all();
$reactions = DB::table('gruppen_reactions')->whereIn('post_id', $ids ?: [0])->get()->groupBy('post_id');
$votes = DB::table('gruppen_poll_votes')->whereIn('post_id', $ids ?: [0])->get()->groupBy('post_id');
$comments = Comment::query()->with('user')->whereIn('post_id', $ids ?: [0])->whereNull('parent_id')
->orderByDesc('id')->get()->groupBy('post_id');
$access = [];
return $posts->map(function (Post $post) use ($me, $groups, $reactions, $votes, $comments, &$access) {
$rights = $access[$post->group_id] ??= $groups->access($post->group, $me);
$mineReaction = $reactions->get($post->id)?->firstWhere('user_id', $me->id)?->emoji;
$postVotes = $votes->get($post->id) ?? collect();
return [
'id' => $post->id,
'group' => ['slug' => $post->group->slug, 'name' => $post->group->name],
'user' => self::person($post->user),
'body' => $post->body,
'pinned' => $post->pinned_at !== null,
'edited' => $post->edited_at !== null,
'created_at' => $post->created_at?->toIso8601String(),
'url' => route('gruppen.post', [$post->group, $post]),
'images' => $post->attachments->filter->isImage()->map(fn (Attachment $a) => [
'id' => $a->id, 'url' => route('gruppen.file', [$a, 'full']), 'thumb_url' => route('gruppen.file', [$a, 'thumb']), 'width' => $a->width, 'height' => $a->height, 'name' => $a->name,
])->values()->all(),
'files' => $post->attachments->reject->isImage()->map(fn (Attachment $a) => [
'id' => $a->id, 'url' => route('gruppen.file', [$a, 'full']), 'name' => $a->name, 'size' => $a->size,
])->values()->all(),
'poll' => $post->poll ? [
'multiple' => (bool) $post->poll['multiple'],
'voters' => $postVotes->pluck('user_id')->unique()->count(),
'mine' => $postVotes->where('user_id', $me->id)->pluck('option')->map(fn ($o) => (int) $o)->values()->all(),
'options' => collect($post->poll['options'])->map(fn ($label, $i) => ['label' => $label, 'votes' => $postVotes->where('option', $i)->count()])->all(),
] : null,
'reactions' => ($reactions->get($post->id) ?? collect())->countBy('emoji')->map(fn ($count, $emoji) => ['emoji' => $emoji, 'count' => $count])->sortByDesc('count')->values()->all(),
'reactions_total' => ($reactions->get($post->id) ?? collect())->count(),
'my_reaction' => $mineReaction,
'comments_count' => $post->comments_count,
'comments' => self::comments(($comments->get($post->id) ?? collect())->take(2)->reverse()->values(), $me, $rights['moderate']),
'can_comment' => $rights['post'],
'can_delete' => $post->user_id === $me->id || $rights['moderate'],
'can_edit' => $post->user_id === $me->id,
'can_pin' => $rights['moderate'],
];
})->values()->all();
}
/**
* @param Collection<int, Comment> $comments
* @return list<array<string, mixed>>
*/
public static function comments(Collection $comments, User $me, bool $moderate, ?Collection $replies = null): array
{
return $comments->map(fn (Comment $c) => [
'id' => $c->id,
'user' => self::person($c->user),
'body' => $c->body,
'created_at' => $c->created_at?->toIso8601String(),
'can_delete' => $c->user_id === $me->id || $moderate,
'replies' => $replies ? self::comments($replies->get($c->id) ?? collect(), $me, $moderate) : [],
])->values()->all();
}
}

161
tests/GruppenTest.php Normal file
View file

@ -0,0 +1,161 @@
<?php
namespace Tests\Plugins\Gruppen;
use App\Models\User;
use App\Notifications\PortalNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Gruppen\Models\Group;
use Inhaus\Plugins\Gruppen\Models\Post;
use Tests\TestCase;
/**
* Läuft innerhalb einer Inhaus-Installation mit dem Plugin unter plugins/gruppen:
* vendor-dev/bin/phpunit plugins/gruppen/tests
*/
class GruppenTest extends TestCase
{
use RefreshDatabase;
private ?string $previousState = null;
protected function setUp(): void
{
$file = getcwd().'/storage/app/plugins.json';
$this->previousState = is_file($file) ? file_get_contents($file) : null;
$state = json_decode($this->previousState ?? '{}', true) ?: [];
$state['gruppen'] = ['enabled' => true];
file_put_contents($file, json_encode($state));
parent::setUp();
Storage::fake('local');
}
protected function tearDown(): void
{
$file = storage_path('app/plugins.json');
$this->previousState === null ? @unlink($file) : file_put_contents($file, $this->previousState);
parent::tearDown();
}
private function group(User $creator, string $privacy, string $name = 'Laufgruppe'): Group
{
$this->actingAs($creator)->post('/gruppen', ['name' => $name, 'privacy' => $privacy, 'description' => 'Wir laufen mittwochs.'])->assertRedirect();
return Group::query()->latest('id')->firstOrFail();
}
public function test_open_groups_everyone_can_read_and_join(): void
{
[$ada, $bob] = User::factory()->count(2)->create()->all();
$group = $this->group($ada, 'open');
$this->assertSame('laufgruppe', $group->slug);
$this->assertSame(1, $group->members_count);
$this->actingAs($ada)->postJson("/gruppen/{$group->slug}/beitraege", ['body' => 'Mittwoch 17 Uhr am Haupteingang?'])->assertCreated();
// Nicht-Mitglieder lesen mit, dürfen aber nicht schreiben
$this->actingAs($bob)->get("/gruppen/{$group->slug}")->assertInertia(fn (Assert $p) => $p->has('posts', 1)->where('can.post', false)->where('can.read', true));
$this->actingAs($bob)->postJson("/gruppen/{$group->slug}/beitraege", ['body' => 'Hallo'])->assertForbidden();
$this->actingAs($bob)->post("/gruppen/{$group->slug}/beitreten")->assertSessionHas('status', 'Willkommen in der Gruppe!');
$this->assertSame(2, $group->fresh()->members_count);
$this->actingAs($bob)->get('/gruppen')->assertInertia(fn (Assert $p) => $p->has('groups', 1)->has('posts', 1));
}
public function test_closed_groups_need_approval_and_hide_posts(): void
{
Notification::fake();
[$ada, $bob] = User::factory()->count(2)->create()->all();
$group = $this->group($ada, 'closed', 'MAV-Austausch');
$this->actingAs($ada)->postJson("/gruppen/{$group->slug}/beitraege", ['body' => 'Intern']);
$this->actingAs($bob)->get("/gruppen/{$group->slug}")->assertInertia(fn (Assert $p) => $p->has('posts', 0)->where('can.read', false)->where('members', null));
$this->actingAs($bob)->post("/gruppen/{$group->slug}/beitreten")->assertSessionHas('status', 'Anfrage gesendet – die Gruppe entscheidet.');
Notification::assertSentTo($ada, PortalNotification::class, fn ($n) => str_contains($n->title, 'Beitrittsanfrage'));
$this->actingAs($ada)->get("/gruppen/{$group->slug}")->assertInertia(fn (Assert $p) => $p->where('members.pending.0.id', $bob->id));
$this->actingAs($ada)->post("/gruppen/{$group->slug}/anfragen/{$bob->id}", ['accept' => true]);
$this->actingAs($bob)->get("/gruppen/{$group->slug}")->assertInertia(fn (Assert $p) => $p->has('posts', 1)->where('can.post', true));
}
public function test_secret_groups_are_invisible_and_invite_only(): void
{
Notification::fake();
[$ada, $bob, $eve] = User::factory()->count(3)->create()->all();
$group = $this->group($ada, 'secret', 'Projekt Umzug');
$this->actingAs($eve)->get("/gruppen/{$group->slug}")->assertNotFound();
$this->actingAs($eve)->post("/gruppen/{$group->slug}/beitreten")->assertNotFound();
$this->actingAs($eve)->get('/gruppen/entdecken')->assertInertia(fn (Assert $p) => $p->has('groups', 0));
$this->actingAs($ada)->post("/gruppen/{$group->slug}/einladen", ['users' => [$bob->id]])->assertSessionHas('status');
Notification::assertSentTo($bob, PortalNotification::class, fn ($n) => str_contains($n->title, 'Einladung'));
$this->actingAs($bob)->get('/gruppen')->assertInertia(fn (Assert $p) => $p->has('invitations', 1));
$this->actingAs($bob)->post("/gruppen/{$group->slug}/beitreten")->assertSessionHas('status', 'Willkommen in der Gruppe!');
// Nur Admins/Moderation laden in nicht offene Gruppen ein
$this->actingAs($bob)->post("/gruppen/{$group->slug}/einladen", ['users' => [$eve->id]])->assertForbidden();
}
public function test_posts_with_photos_polls_reactions_comments_and_moderation(): void
{
Notification::fake();
[$ada, $bob, $cem] = User::factory()->count(3)->create()->all();
$group = $this->group($ada, 'open');
$this->actingAs($bob)->post("/gruppen/{$group->slug}/beitreten");
$this->actingAs($cem)->post("/gruppen/{$group->slug}/beitreten");
$post = $this->actingAs($ada)->post("/gruppen/{$group->slug}/beitraege", [
'body' => 'Welcher Tag passt?',
'poll' => ['Mittwoch', 'Donnerstag', ''],
'files' => [UploadedFile::fake()->image('strecke.jpg', 2000, 1500), UploadedFile::fake()->create('plan.pdf', 20, 'application/pdf')],
], ['Accept' => 'application/json'])->assertCreated()->json('post');
$this->assertCount(1, $post['images']);
$this->assertSame(1600, $post['images'][0]['width']);
$this->assertSame('plan.pdf', $post['files'][0]['name']);
$this->assertCount(2, $post['poll']['options']);
Notification::assertSentTo([$bob, $cem], PortalNotification::class, fn ($n) => str_contains($n->title, 'Neu in'));
$this->actingAs($bob)->postJson("/gruppen/beitraege/{$post['id']}/abstimmen", ['options' => [1]])->assertJsonPath('poll.options.1.votes', 1);
$this->actingAs($cem)->postJson("/gruppen/beitraege/{$post['id']}/reaktion", ['emoji' => '❤️'])->assertOk();
$this->actingAs($bob)->postJson("/gruppen/beitraege/{$post['id']}/kommentare", ['body' => 'Donnerstag!'])->assertOk();
Notification::assertSentTo($ada, PortalNotification::class, fn ($n) => str_contains($n->title, 'kommentiert'));
// Melden → Gruppen-Admin erfährt es; Admin pinnt und löscht
$this->actingAs($cem)->postJson("/gruppen/beitraege/{$post['id']}/melden", ['reason' => 'Test'])->assertOk();
Notification::assertSentTo($ada, PortalNotification::class, fn ($n) => str_contains($n->title, 'gemeldet'));
$this->actingAs($bob)->postJson("/gruppen/beitraege/{$post['id']}/anpinnen", ['pinned' => true])->assertForbidden();
$this->actingAs($ada)->postJson("/gruppen/beitraege/{$post['id']}/anpinnen", ['pinned' => true])->assertOk();
$this->actingAs($bob)->get("/gruppen/{$group->slug}")->assertInertia(fn (Assert $p) => $p
->where('posts.0.pinned', true)->where('posts.0.poll.mine', [1])->where('posts.0.reactions.0.emoji', '❤️')
->where('posts.0.comments.0.body', 'Donnerstag!')->where('posts.0.comments_count', 1));
// Fotos nur für Berechtigte (offen: alle), gelöschte weg
$this->actingAs($cem)->get($post['images'][0]['thumb_url'])->assertOk();
$this->actingAs($bob)->deleteJson("/gruppen/beitraege/{$post['id']}")->assertForbidden();
$this->actingAs($ada)->deleteJson("/gruppen/beitraege/{$post['id']}")->assertOk();
$this->assertSame(0, Post::query()->count());
$this->assertSame([], Storage::disk('local')->allFiles("gruppen/{$group->id}/{$post['id']}"));
}
public function test_roles_and_last_admin_handover(): void
{
[$ada, $bob] = User::factory()->count(2)->create()->all();
$group = $this->group($ada, 'open');
$this->actingAs($bob)->post("/gruppen/{$group->slug}/beitreten");
$this->actingAs($bob)->put("/gruppen/{$group->slug}/mitglieder/{$ada->id}", ['role' => 'member'])->assertForbidden();
$this->actingAs($ada)->put("/gruppen/{$group->slug}/mitglieder/{$ada->id}", ['role' => 'member'])->assertSessionHasErrors('role');
$this->actingAs($ada)->post("/gruppen/{$group->slug}/verlassen");
$this->assertSame('admin', $group->membership($bob)->role);
}
}

5
vite.config.js Normal file
View file

@ -0,0 +1,5 @@
import { defineConfig } from 'vite';
import { inhausPlugin } from './inhaus-sdk/vite.js';
// Baut resources/js/{pages,widgets,blocks,…} nach dist/ (siehe inhaus-sdk/vite.js)
export default defineConfig(inhausPlugin());