5 Commits
Author SHA1 Message Date
Daan Meijer 64d771e34c added actions back to mutation single
linter / quality (push) Failing after 1m5s
tests / ci (8.3) (push) Failing after 49s
tests / ci (8.4) (push) Failing after 1m6s
tests / ci (8.5) (push) Failing after 1m8s
2026-07-06 17:55:31 +02:00
Daan Meijer 2ab1acf040 mutations hebben single
linter / quality (push) Failing after 1m6s
tests / ci (8.3) (push) Failing after 50s
tests / ci (8.4) (push) Failing after 1m6s
tests / ci (8.5) (push) Failing after 1m6s
2026-07-06 17:47:14 +02:00
Daan Meijer 3d6a5362e6 notificationtest gerepareerd
linter / quality (push) Failing after 1m4s
tests / ci (8.3) (push) Failing after 51s
tests / ci (8.4) (push) Failing after 1m7s
tests / ci (8.5) (push) Failing after 1m6s
2026-07-06 17:31:47 +02:00
Daan Meijer dc94c2252c juiste view policy voor een mutation
linter / quality (push) Failing after 1m6s
tests / ci (8.3) (push) Failing after 49s
tests / ci (8.4) (push) Failing after 1m6s
tests / ci (8.5) (push) Failing after 1m8s
2026-07-06 17:11:43 +02:00
Daan Meijer 1be49133a0 users worden nu beter geresolved
linter / quality (push) Failing after 1m5s
tests / ci (8.3) (push) Failing after 49s
tests / ci (8.4) (push) Failing after 1m7s
tests / ci (8.5) (push) Failing after 1m6s
2026-07-06 16:51:34 +02:00
19 changed files with 605 additions and 428 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ During this session, we successfully built out and verified several core archite
* Created a dynamic user detail page (`dynamics.users.show`) scoped to each dynamic. It displays a participant's role, custom display name, fallback real name, and a clean chronological listing of their 10 most recent mutations (activities) in that dynamic. * Created a dynamic user detail page (`dynamics.users.show`) scoped to each dynamic. It displays a participant's role, custom display name, fallback real name, and a clean chronological listing of their 10 most recent mutations (activities) in that dynamic.
8. **Polymorphic System Message placeholders & Dynamic Client-Side Linking**: 8. **Polymorphic System Message placeholders & Dynamic Client-Side Linking**:
* Refactored system log activity messages to use native `<user:userId>` placeholders and associated them with polymorphic `subject_id` and `subject_type` objects. * Refactored system log activity messages to use native `<user:userUuid>` placeholders and associated them with polymorphic `subject_id` and `subject_type` objects.
* On the client-side, the chat component parses these placeholders into rich, clickable links to User Profiles, and dynamically matches and wraps referenced ledger names into links pointing directly to the ledger show page. * On the client-side, the chat component parses these placeholders into rich, clickable links to User Profiles, and dynamically matches and wraps referenced ledger names into links pointing directly to the ledger show page.
* Added backend-side placeholder resolution inside `ActivityService` for the dashboard, ensuring unread system logs translate cleanly to real names across multiple dynamics. * Added backend-side placeholder resolution inside `ActivityService` for the dashboard, ensuring unread system logs translate cleanly to real names across multiple dynamics.
@@ -118,7 +118,7 @@ class DynamicInvitationController extends Controller
// Log to Dynamic chat activity log! // Log to Dynamic chat activity log!
$dynamic->chat->messages()->create([ $dynamic->chat->messages()->create([
'user_id' => null, 'user_id' => null,
'content' => "<user:{$request->user()->id}> joined the Dynamic as a ".strtoupper($invitation->role), 'content' => "<user:{$request->user()->uuid}> joined the Dynamic as a ".strtoupper($invitation->role),
'subject_id' => $request->user()->id, 'subject_id' => $request->user()->id,
'subject_type' => User::class, 'subject_type' => User::class,
]); ]);
+31 -81
View File
@@ -19,30 +19,10 @@ class MutationController extends Controller
{ {
use AuthorizesRequests; use AuthorizesRequests;
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(StoreMutationRequest $request, Dynamic $dynamic, Ledger $ledger) public function store(StoreMutationRequest $request, Dynamic $dynamic, Ledger $ledger)
{ {
$this->authorize('create', [Mutation::class, $ledger]); $this->authorize('create', [Mutation::class, $ledger]);
// If the user is an owner, default status to 'approved'. Otherwise default to 'pending'.
$status = $request->user()->can('update', $ledger) ? 'approved' : 'pending'; $status = $request->user()->can('update', $ledger) ? 'approved' : 'pending';
$mutation = DB::transaction(function () use ($request, $ledger, $status) { $mutation = DB::transaction(function () use ($request, $ledger, $status) {
@@ -70,7 +50,6 @@ class MutationController extends Controller
} }
} }
// Only increment score if the status is approved!
if ($status === 'approved') { if ($status === 'approved') {
$ledger->increment('score', $request->validated('amount')); $ledger->increment('score', $request->validated('amount'));
} }
@@ -78,48 +57,46 @@ class MutationController extends Controller
return $mutation; return $mutation;
}); });
// Notify all other participants
$recipients = $dynamic->participants()->where('users.id', '!=', $request->user()->id)->get(); $recipients = $dynamic->participants()->where('users.id', '!=', $request->user()->id)->get();
$message = $status === 'approved' $message = $status === 'approved'
? "{$request->user()->name} added a new entry: \"{$mutation->description}\"." ? "{$request->user()->name} added a new entry: \"{$mutation->description}\"."
: "{$request->user()->name} suggested a new entry: \"{$mutation->description}\"."; : "{$request->user()->name} suggested a new entry: \"{$mutation->description}\".";
if ($recipients->isNotEmpty()) {
Notification::send($recipients, new NewActivityNotification([ Notification::send($recipients, new NewActivityNotification([
'content' => $message, 'content' => $message,
'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]), 'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]),
])); ]));
}
return redirect()->route('dynamics.ledgers.show', [$dynamic, $ledger]); return redirect()->route('dynamics.ledgers.show', [$dynamic, $ledger]);
} }
/** public function show(Request $request, Dynamic $dynamic, Ledger $ledger, Mutation $mutation)
* Display the specified resource.
*/
public function show(Dynamic $dynamic, Ledger $ledger, Mutation $mutation)
{ {
$this->authorize('view', $mutation); $this->authorize('view', $mutation);
return $mutation; $mutation->load('user', 'ledger', 'media', 'chat.messages.user');
$dynamic = $mutation->ledger->dynamic;
$dynamic->load('participants');
$user = $request->user();
return inertia('Mutations/Show', [
'mutation' => $mutation,
'dynamic' => $dynamic,
'can' => [
'update' => $user->can('update', $dynamic),
],
]);
} }
/**
* Show the form for editing the specified resource.
*/
public function edit(Dynamic $dynamic, Ledger $ledger, Mutation $mutation)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Dynamic $dynamic, Ledger $ledger, Mutation $mutation) public function update(Request $request, Dynamic $dynamic, Ledger $ledger, Mutation $mutation)
{ {
$this->authorize('update', $mutation); $this->authorize('update', $mutation);
$request->validate([ $request->validate(['status' => ['required', 'string', 'in:approved,rejected']]);
'status' => ['required', 'string', 'in:approved,rejected'],
]);
$oldStatus = $mutation->status; $oldStatus = $mutation->status;
$newStatus = $request->input('status'); $newStatus = $request->input('status');
@@ -127,7 +104,6 @@ class MutationController extends Controller
DB::transaction(function () use ($mutation, $ledger, $oldStatus, $newStatus) { DB::transaction(function () use ($mutation, $ledger, $oldStatus, $newStatus) {
$mutation->update(['status' => $newStatus]); $mutation->update(['status' => $newStatus]);
// Adjust the ledger score if status transitions to approved or from approved!
if ($oldStatus !== 'approved' && $newStatus === 'approved') { if ($oldStatus !== 'approved' && $newStatus === 'approved') {
$ledger->increment('score', $mutation->amount); $ledger->increment('score', $mutation->amount);
} elseif ($oldStatus === 'approved' && $newStatus !== 'approved') { } elseif ($oldStatus === 'approved' && $newStatus !== 'approved') {
@@ -135,41 +111,17 @@ class MutationController extends Controller
} }
}); });
// Log to Mutation and Dynamic chats
$user = $request->user(); $user = $request->user();
$statusText = strtoupper($newStatus); $statusText = strtoupper($newStatus);
$mutationMsg = $mutation->chat->messages()->create([ // Notify the suggester
'user_id' => null, $suggester = $mutation->user;
'content' => "Suggestion was {$statusText} by <user:{$user->id}>.", if ($suggester && $suggester->id !== $user->id) {
'subject_id' => $mutation->id, Notification::send($suggester, new NewActivityNotification([
'subject_type' => Mutation::class, 'content' => "Your suggestion \"{$mutation->description}\" was {$statusText} by {$user->name}.",
]);
broadcast(new MessageSent($mutationMsg));
if ($newStatus === 'approved') {
$dynamicMsg = $dynamic->chat->messages()->create([
'user_id' => null,
'content' => "<user:{$user->id}> APPROVED the suggestion \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
'subject_id' => $mutation->id,
'subject_type' => Mutation::class,
]);
} else {
$dynamicMsg = $dynamic->chat->messages()->create([
'user_id' => null,
'content' => "<user:{$user->id}> REJECTED the suggestion \"{$mutation->description}\" on \"{$ledger->name}\" ledger.",
'subject_id' => $mutation->id,
'subject_type' => Mutation::class,
]);
}
broadcast(new MessageSent($dynamicMsg));
// Notify all other participants
$recipients = $dynamic->participants()->where('users.id', '!=', $request->user()->id)->get();
Notification::send($recipients, new NewActivityNotification([
'content' => "{$user->name} {$statusText} the suggestion: \"{$mutation->description}\".",
'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]), 'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]),
])); ]));
}
return redirect()->back(); return redirect()->back();
} }
@@ -178,23 +130,21 @@ class MutationController extends Controller
{ {
$this->authorize('void', $mutation); $this->authorize('void', $mutation);
DB::transaction(function() use ($mutation, $ledger) {
if ($mutation->status === 'approved') {
$ledger->decrement('score', $mutation->amount);
}
$mutation->update(['status' => 'voided']); $mutation->update(['status' => 'voided']);
});
// Notify all other participants
$recipients = $dynamic->participants()->where('users.id', '!=', $request->user()->id)->get(); $recipients = $dynamic->participants()->where('users.id', '!=', $request->user()->id)->get();
if ($recipients->isNotEmpty()) {
Notification::send($recipients, new NewActivityNotification([ Notification::send($recipients, new NewActivityNotification([
'content' => "{$request->user()->name} voided an entry: \"{$mutation->description}\".", 'content' => "{$request->user()->name} voided an entry: \"{$mutation->description}\".",
'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]), 'url' => route('dynamics.ledgers.show', [$dynamic, $ledger]),
])); ]));
}
return redirect()->route('dynamics.ledgers.show', [$dynamic, $ledger]); return redirect()->route('dynamics.ledgers.show', [$dynamic, $ledger]);
} }
/**
* Remove the specified resource from storage.
*/
public function destroy(Dynamic $dynamic, Ledger $ledger, Mutation $mutation)
{
//
}
} }
+25 -4
View File
@@ -70,8 +70,8 @@ class Mutation extends Model
$mutationMsg = $mutation->chat->messages()->create([ $mutationMsg = $mutation->chat->messages()->create([
'user_id' => null, 'user_id' => null,
'content' => $status === 'approved' 'content' => $status === 'approved'
? "Entry was created by <user:{$user->id}>." ? "Entry was created by <user:{$user->uuid}>."
: "Suggestion was created by <user:{$user->id}>.", : "Suggestion was created by <user:{$user->uuid}>.",
'subject_id' => $mutation->id, 'subject_id' => $mutation->id,
'subject_type' => Mutation::class, 'subject_type' => Mutation::class,
]); ]);
@@ -80,14 +80,14 @@ class Mutation extends Model
if ($status === 'approved') { if ($status === 'approved') {
$dynamicMsg = $dynamic->chat->messages()->create([ $dynamicMsg = $dynamic->chat->messages()->create([
'user_id' => null, 'user_id' => null,
'content' => "<user:{$user->id}> added entry \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.", 'content' => "<user:{$user->uuid}> added entry \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
'subject_id' => $mutation->id, 'subject_id' => $mutation->id,
'subject_type' => Mutation::class, 'subject_type' => Mutation::class,
]); ]);
} else { } else {
$dynamicMsg = $dynamic->chat->messages()->create([ $dynamicMsg = $dynamic->chat->messages()->create([
'user_id' => null, 'user_id' => null,
'content' => "<user:{$user->id}> suggested \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.", 'content' => "<user:{$user->uuid}> suggested \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
'subject_id' => $mutation->id, 'subject_id' => $mutation->id,
'subject_type' => Mutation::class, 'subject_type' => Mutation::class,
]); ]);
@@ -100,6 +100,27 @@ class Mutation extends Model
static::updated(function (Mutation $mutation) { static::updated(function (Mutation $mutation) {
if ($mutation->wasChanged('status')) { if ($mutation->wasChanged('status')) {
$status = $mutation->getAttribute('status');
$user = request()->user();
$ledger = $mutation->ledger;
$mutationMsg = $mutation->chat->messages()->create([
'user_id' => null,
'content' => $status === 'approved'
? "<user:{$user->uuid}> APPROVED the suggestion \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger."
: "<user:{$user->uuid}> DENIED the suggestion \"{$mutation->description}\" for ".($mutation->amount >= 0 ? '+' : '')."{$mutation->amount} points on \"{$ledger->name}\" ledger.",
'subject_id' => $mutation->id,
'subject_type' => Mutation::class,
]);
$dynamic = $ledger->dynamic;
$dynamic->chat->messages()->create([
'user_id' => null,
'content' => $mutationMsg->content,
'subject_id' => $mutation->id,
'subject_type' => Mutation::class,
]);
broadcast(new \App\Events\MutationUpdated($mutation)); broadcast(new \App\Events\MutationUpdated($mutation));
} }
}); });
+4 -25
View File
@@ -2,8 +2,6 @@
namespace App\Notifications; namespace App\Notifications;
use App\Models\Chat;
use App\Models\Message;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use NotificationChannels\WebPush\WebPushChannel; use NotificationChannels\WebPush\WebPushChannel;
@@ -13,47 +11,28 @@ class NewActivityNotification extends Notification
{ {
use Queueable; use Queueable;
public $activity; public array $activity;
/** public function __construct(array $activity)
* Create a new notification instance.
*/
public function __construct($activity)
{ {
$this->activity = $activity; $this->activity = $activity;
} }
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array public function via(object $notifiable): array
{ {
return ['database', WebPushChannel::class]; return [WebPushChannel::class, 'database'];
} }
/**
* Get the web push representation of the notification.
*/
public function toWebPush(object $notifiable): WebPushMessage public function toWebPush(object $notifiable): WebPushMessage
{ {
return (new WebPushMessage)
$result = (new WebPushMessage)
->title('New Activity') ->title('New Activity')
->icon('/apple-touch-icon.png') ->icon('/apple-touch-icon.png')
->body($this->activity['content']) ->body($this->activity['content'])
->action('View', 'view') ->action('View', 'view')
->data(['url' => $this->activity['url']]); ->data(['url' => $this->activity['url']]);
return $result;
} }
/**
* Get the array representation of the notification.
*
* @return array<string, mixed>
*/
public function toArray(object $notifiable): array public function toArray(object $notifiable): array
{ {
return [ return [
+8
View File
@@ -8,6 +8,14 @@ use App\Models\User;
class MutationPolicy class MutationPolicy
{ {
/**
* Determine whether the user can view the mutation.
*/
public function view(User $user, Mutation $mutation): bool
{
return $user->can('view', $mutation->ledger);
}
/** /**
* Determine whether the user can create mutations. * Determine whether the user can create mutations.
*/ */
+2 -2
View File
@@ -100,7 +100,7 @@ class ActivityService
$participants = $dynamic->participants()->withPivot('display_name')->get(); $participants = $dynamic->participants()->withPivot('display_name')->get();
$participantsMap = $participants->reduce(function ($acc, $p) { $participantsMap = $participants->reduce(function ($acc, $p) {
$acc[$p->id] = $p->pivot->display_name ?? $p->name; $acc[$p->uuid] = $p->pivot->display_name ?? $p->name;
return $acc; return $acc;
}, []); }, []);
@@ -115,7 +115,7 @@ class ActivityService
$messageData['url'] = $this->getUrlForMessage($message); $messageData['url'] = $this->getUrlForMessage($message);
// Resolve <user:id> placeholders to actual names/display names // Resolve <user:id> placeholders to actual names/display names
$messageData['content'] = preg_replace_callback('/<user:(\d+)>/', function ($matches) use ($participantsMap) { $messageData['content'] = preg_replace_callback('/<user:([0-9a-f-]+)>/', function ($matches) use ($participantsMap) {
$userId = $matches[1]; $userId = $matches[1];
return $participantsMap[$userId] ?? "User #{$userId}"; return $participantsMap[$userId] ?? "User #{$userId}";
@@ -0,0 +1,42 @@
<?php
use App\Models\Message;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\App\Models\Message::all()->each(function (Message $message) {
$msg = $message->content;
$msg = preg_replace_callback('/<user:([0-9]+)>/', function ($matches) {
$userId = $matches[1];
$user = \App\Models\User::find($userId);
if($user){
$userId = $user->uuid;
}
return "<user:$userId>";
}, $msg);
if($msg != $message->content) {
$message->update(['content' => $msg]);
}
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('uuid_base', function (Blueprint $table) {
//
});
}
};
+1 -1
View File
@@ -149,7 +149,7 @@ const participantsById = computed(() => {
{} as Record< {} as Record<
number, number,
{ {
id: number; id: string;
name: string; name: string;
pivot?: { display_name: string | null } | null; pivot?: { display_name: string | null } | null;
} }
+5 -2
View File
@@ -19,10 +19,13 @@ const props = defineProps<{
}>(); }>();
const processedContent = computed(() => { const processedContent = computed(() => {
return props.message.content.replace(/<user:(\d+)>/g, (match, userId) => { return props.message.content.replace(
/<user:([0-9a-f-]+)>/g,
(match, userId) => {
// This is a placeholder for a more robust user lookup // This is a placeholder for a more robust user lookup
return `<a href="${route('users.show', userId)}" class="text-blue-500 hover:underline">@user${userId}</a>`; return `<a href="${route('users.show', userId)}" class="text-blue-500 hover:underline">@user${userId}</a>`;
}); },
);
}); });
</script> </script>
+19 -186
View File
@@ -1,64 +1,22 @@
<script setup lang="ts"> <script setup lang="ts">
import { useForm } from '@inertiajs/vue3'; import { Link } from '@inertiajs/vue3';
import { route } from 'ziggy-js'; import { route } from 'ziggy-js';
import Chat from '@/components/Chat.vue';
const props = defineProps<{ const props = defineProps<{
dynamicId: string; dynamicId: string;
ledgerId: string; ledgerId: string;
ledgerAlignment?: string; ledgerAlignment?: string;
mutations: Array<{ mutations: Array<{
id: number; id: string; // Now a UUID
user_id: number; user_id: number;
user: { name: string }; user: { name: string };
amount: number; amount: number;
description: string; description: string;
status: string; status: string;
created_at: string; created_at: string;
chat: any;
media?: Array<{ id: number; url: string; mime_type: string }>;
can: {
update: boolean;
void: boolean;
};
}>;
participants?: Array<{
id: number;
name: string;
pivot?: { role: string };
}>; }>;
}>(); }>();
const emit = defineEmits<{
(e: 'open-lightbox', url: string, mimeType: string): void;
}>();
function updateStatus(mutationId: number, status: 'approved' | 'rejected') {
useForm({ status }).put(
route('dynamics.ledgers.mutations.update', {
dynamic: props.dynamicId,
ledger: props.ledgerId,
mutation: mutationId,
}),
);
}
function voidMutation(mutationId: number) {
useForm({}).put(
route('dynamics.ledgers.mutations.void', {
dynamic: props.dynamicId,
ledger: props.ledgerId,
mutation: mutationId,
}),
);
}
function isOwnerUser(userId: number): boolean {
const participant = props.participants?.find((p) => p.id === userId);
return participant?.pivot?.role === 'owner';
}
function getAmountClass(amount: number): string { function getAmountClass(amount: number): string {
const alignment = props.ledgerAlignment || 'neutral'; const alignment = props.ledgerAlignment || 'neutral';
@@ -87,18 +45,15 @@ function getAmountClass(amount: number): string {
<li <li
v-for="mutation in mutations" v-for="mutation in mutations"
:key="mutation.id" :key="mutation.id"
class="c-mutation-list__item"
> >
<div class="c-mutation-list__item-header"> <Link
<div> :href="route('dynamics.ledgers.mutations.show', { dynamic: dynamicId, ledger: ledgerId, mutation: mutation.id })"
<span class="c-mutation-list__item-author"> class="c-mutation-list__item-link"
{{ >
isOwnerUser(mutation.user_id) <div class="c-mutation-list__item-content">
? 'Added by' <p class="c-mutation-list__item-desc">
: 'Suggested by' {{ mutation.description }}
}} </p>
{{ mutation.user.name }}
</span>
<div class="c-mutation-list__item-meta"> <div class="c-mutation-list__item-meta">
<span <span
:class="getAmountClass(mutation.amount)" :class="getAmountClass(mutation.amount)"
@@ -107,9 +62,7 @@ function getAmountClass(amount: number): string {
{{ mutation.amount > 0 ? '+' : '' {{ mutation.amount > 0 ? '+' : ''
}}{{ mutation.amount }} }}{{ mutation.amount }}
</span> </span>
<!-- Only show status badge if mutation was NOT auto-approved by an owner -->
<span <span
v-if="!isOwnerUser(mutation.user_id)"
:class="{ :class="{
'c-mutation-list__item-status--pending': 'c-mutation-list__item-status--pending':
mutation.status === 'pending', mutation.status === 'pending',
@@ -124,79 +77,7 @@ function getAmountClass(amount: number): string {
</span> </span>
</div> </div>
</div> </div>
<div class="c-mutation-list__item-time"> </Link>
{{ new Date(mutation.created_at).toLocaleString() }}
</div>
</div>
<p class="c-mutation-list__item-desc">
{{ mutation.description }}
</p>
<!-- Attached Mutation Proof Media -->
<div
v-if="mutation.media && mutation.media.length > 0"
class="c-mutation-list__media-list"
>
<div
v-for="item in mutation.media"
:key="item.id"
class="c-mutation-list__media-item"
>
<img
v-if="item.mime_type.startsWith('image/')"
:src="item.url"
class="c-mutation-list__media-img"
@click="
emit('open-lightbox', item.url, item.mime_type)
"
/>
<div
v-else-if="item.mime_type.startsWith('video/')"
class="c-mutation-list__media-video-wrapper"
@click="
emit('open-lightbox', item.url, item.mime_type)
"
>
<video
:src="item.url"
class="c-mutation-list__media-video"
></video>
<div class="c-mutation-list__media-video-overlay">
</div>
</div>
</div>
</div>
<!-- Owner Approve/Reject Actions -->
<div
v-if="mutation.can?.update || mutation.can?.void"
class="c-mutation-list__actions"
>
<button
v-if="mutation.can?.update"
@click="updateStatus(mutation.id, 'approved')"
class="c-mutation-list__approve-btn"
>
Approve
</button>
<button
v-if="mutation.can?.update"
@click="updateStatus(mutation.id, 'rejected')"
class="c-mutation-list__reject-btn"
>
Reject
</button>
<button
v-if="mutation.can?.void"
@click="voidMutation(mutation.id)"
class="c-mutation-list__void-btn"
>
Void
</button>
</div>
<Chat v-if="mutation.chat" :chat="mutation.chat" :dynamic-id="dynamicId" :participants="participants" />
</li> </li>
</ul> </ul>
<div v-if="mutations.length === 0" class="c-mutation-list__empty"> <div v-if="mutations.length === 0" class="c-mutation-list__empty">
@@ -217,23 +98,23 @@ function getAmountClass(amount: number): string {
} }
.c-mutation-list__list { .c-mutation-list__list {
@apply mt-4 space-y-4; @apply mt-4 space-y-2;
} }
.c-mutation-list__item { .c-mutation-list__item-link {
@apply overflow-hidden bg-white p-4 shadow-sm sm:rounded-lg dark:bg-gray-800; @apply block overflow-hidden bg-white p-4 shadow-sm sm:rounded-lg dark:bg-gray-800 transition-all duration-200 hover:shadow-md hover:bg-gray-50 dark:hover:bg-gray-700;
} }
.c-mutation-list__item-header { .c-mutation-list__item-content {
@apply flex items-start justify-between; @apply flex items-center justify-between;
} }
.c-mutation-list__item-author { .c-mutation-list__item-desc {
@apply font-semibold; @apply text-sm text-gray-600 dark:text-gray-400;
} }
.c-mutation-list__item-meta { .c-mutation-list__item-meta {
@apply mt-1 flex items-center gap-2; @apply flex items-center gap-2;
} }
.c-mutation-list__item-amount { .c-mutation-list__item-amount {
@@ -268,54 +149,6 @@ function getAmountClass(amount: number): string {
@apply bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400; @apply bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400;
} }
.c-mutation-list__item-time {
@apply text-xs text-gray-500;
}
.c-mutation-list__item-desc {
@apply mt-3 text-sm text-gray-600 dark:text-gray-400;
}
.c-mutation-list__media-list {
@apply mt-3 flex flex-wrap gap-2;
}
.c-mutation-list__media-item {
@apply max-w-[200px] overflow-hidden rounded-md border border-neutral-200 bg-black dark:border-neutral-700;
}
.c-mutation-list__media-img {
@apply h-auto max-h-[150px] w-full cursor-pointer object-cover transition-opacity hover:opacity-90;
}
.c-mutation-list__media-video-wrapper {
@apply relative cursor-pointer transition-opacity hover:opacity-90;
}
.c-mutation-list__media-video {
@apply h-auto max-h-[150px] w-full;
}
.c-mutation-list__media-video-overlay {
@apply absolute inset-0 flex items-center justify-center bg-black/40 text-2xl font-bold text-white;
}
.c-mutation-list__actions {
@apply mt-3 flex gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-700;
}
.c-mutation-list__approve-btn {
@apply inline-flex cursor-pointer items-center rounded bg-green-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-green-500;
}
.c-mutation-list__reject-btn {
@apply inline-flex cursor-pointer items-center rounded bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-500;
}
.c-mutation-list__void-btn {
@apply inline-flex cursor-pointer items-center rounded bg-gray-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-gray-500;
}
.c-mutation-list__empty { .c-mutation-list__empty {
@apply mt-4 text-gray-500; @apply mt-4 text-gray-500;
} }
@@ -39,11 +39,11 @@ const parsedContent = computed(() => {
let content = props.message.content; let content = props.message.content;
// 1. Replace <user:id> placeholders with links to their dynamic profile // 1. Replace <user:id> placeholders with links to their dynamic profile
const userRegex = /<user:(\d+)>/g; const userRegex = /<user:([0-9a-f-]+)>/g;
content = content.replace(userRegex, (match, userId) => { content = content.replace(userRegex, (match, userId) => {
const user = props.participantsById[Number(userId)]; const user = props.participantsById[(userId)];
if (user) { if (user) {
const url = route('dynamics.users.show', [props.dynamicId, Number(userId)]); const url = route('dynamics.users.show', [props.dynamicId, (userId)]);
return `<a href="${url}" class="c-chat__user-link font-semibold text-blue-500 hover:underline">${ return `<a href="${url}" class="c-chat__user-link font-semibold text-blue-500 hover:underline">${
user.pivot?.display_name ?? user.name user.pivot?.display_name ?? user.name
}</a>`; }</a>`;
@@ -49,15 +49,21 @@ const parsedContent = computed(() => {
let content = props.message.content; let content = props.message.content;
// 1. Replace <user:id> placeholders with links to their dynamic profile // 1. Replace <user:id> placeholders with links to their dynamic profile
const userRegex = /<user:(\d+)>/g; const userRegex = /<user:([0-9a-f-]+)>/g;
content = content.replace(userRegex, (match, userId) => { content = content.replace(userRegex, (match, userId) => {
const user = props.participantsById[Number(userId)]; const user = props.participantsById[(userId)];
if (user) { if (user) {
const url = route('dynamics.users.show', [props.dynamicId, Number(userId)]); const url = route('dynamics.users.show', [
props.dynamicId,
(userId),
]);
return `<a href="${url}" class="c-chat__user-link font-semibold text-blue-500 hover:underline">${ return `<a href="${url}" class="c-chat__user-link font-semibold text-blue-500 hover:underline">${
user.pivot?.display_name ?? user.name user.pivot?.display_name ?? user.name
}</a>`; }</a>`;
} }
return `User #${userId}`; return `User #${userId}`;
}); });
@@ -104,9 +110,7 @@ const parsedContent = computed(() => {
<template> <template>
<div> <div>
<div class="c-chat__message-header"> <div class="c-chat__message-header">
<span class="c-chat__message-author">{{ <span class="c-chat__message-author">{{ message.user?.name }}</span>
message.user?.name
}}</span>
<span <span
class="c-chat__message-time" class="c-chat__message-time"
:title="formatTimestamp(message.created_at).full" :title="formatTimestamp(message.created_at).full"
@@ -138,10 +142,7 @@ const parsedContent = computed(() => {
class="relative cursor-pointer transition-opacity hover:opacity-90" class="relative cursor-pointer transition-opacity hover:opacity-90"
@click="emit('open-lightbox', item.url, item.mime_type)" @click="emit('open-lightbox', item.url, item.mime_type)"
> >
<video <video :src="item.url" class="c-chat__video"></video>
:src="item.url"
class="c-chat__video"
></video>
<div class="c-chat__play-overlay"></div> <div class="c-chat__play-overlay"></div>
</div> </div>
</div> </div>
+308
View File
@@ -0,0 +1,308 @@
<script setup lang="ts">
import Chat from '@/components/Chat.vue';
import { defineOptions } from 'vue';
import { useForm } from '@inertiajs/vue3';
import { route } from 'ziggy-js';
const props = defineProps<{
mutation: {
id: string; // Updated to match serialization
user_id: number;
user: { name: string };
amount: number;
description: string;
status: string;
created_at: string;
chat: any;
media?: Array<{ id: number; url: string; mime_type: string }>;
can: {
update: boolean;
void: boolean;
};
ledger: {
id: string;
name: string;
dynamic_id: string;
alignment?: string;
dynamic: {
id: string;
name: string;
}
}
};
dynamic: {
id: string;
participants: any[];
};
can: {
update: boolean;
};
}>();
const dynamicId = props.dynamic.id;
function updateStatus(mutationId: string, status: 'approved' | 'rejected') {
useForm({ status }).put(
route('dynamics.ledgers.mutations.update', {
dynamic: props.dynamic.id,
ledger: props.mutation.ledger.id,
mutation: mutationId,
}),
);
}
function voidMutation(mutationId: string) {
useForm({}).put(
route('dynamics.ledgers.mutations.void', {
dynamic: props.dynamic.id,
ledger: props.mutation.ledger.id,
mutation: mutationId,
}),
);
}
function isOwnerUser(userId: number): boolean {
const participant = props.dynamic.participants?.find((p) => p.id === userId);
return participant?.pivot?.role === 'owner';
}
function getAmountClass(amount: number): string {
const alignment = props.mutation.ledger.alignment || 'neutral';
if (alignment === 'positive') {
return amount > 0
? 'c-mutation-list__item-amount--positive'
: 'c-mutation-list__item-amount--negative';
}
if (alignment === 'negative') {
return amount < 0
? 'c-mutation-list__item-amount--positive'
: 'c-mutation-list__item-amount--negative';
}
return 'c-mutation-list__item-amount--neutral';
}
defineOptions({
layout: (props: any) => ({
breadcrumbs: [
{ title: 'Dynamics', href: route('dynamics.index') },
{ title: props.mutation.ledger.dynamic.name, href: route('dynamics.show', props.mutation.ledger.dynamic.id) },
{ title: props.mutation.ledger.name, href: route('dynamics.ledgers.show', [props.mutation.ledger.dynamic.id, props.mutation.ledger.id]) },
{ title: 'Mutation Details', href: '' },
]
})
});
</script>
<template>
<div class="c-mutation-list__item">
<div class="c-mutation-list__item-header">
<div>
<span class="c-mutation-list__item-author">
{{
isOwnerUser(mutation.user_id)
? 'Added by'
: 'Suggested by'
}}
{{ mutation.user.name }}
</span>
<div class="c-mutation-list__item-meta">
<span
:class="getAmountClass(mutation.amount)"
class="c-mutation-list__item-amount"
>
{{ mutation.amount > 0 ? '+' : ''
}}{{ mutation.amount }}
</span>
<span
v-if="!isOwnerUser(mutation.user_id)"
:class="{
'c-mutation-list__item-status--pending':
mutation.status === 'pending',
'c-mutation-list__item-status--approved':
mutation.status === 'approved',
'c-mutation-list__item-status--rejected':
mutation.status === 'rejected',
}"
class="c-mutation-list__item-status"
>
{{ mutation.status }}
</span>
</div>
</div>
<div class="c-mutation-list__item-time">
{{ new Date(mutation.created_at).toLocaleString() }}
</div>
</div>
<p class="c-mutation-list__item-desc">
{{ mutation.description }}
</p>
<div
v-if="mutation.media && mutation.media.length > 0"
class="c-mutation-list__media-list"
>
<div
v-for="item in mutation.media"
:key="item.id"
class="c-mutation-list__media-item"
>
<img
v-if="item.mime_type.startsWith('image/')"
:src="item.url"
class="c-mutation-list__media-img"
/>
<div
v-else-if="item.mime_type.startsWith('video/')"
class="c-mutation-list__media-video-wrapper"
>
<video
:src="item.url"
class="c-mutation-list__media-video"
></video>
<div class="c-mutation-list__media-video-overlay">
</div>
</div>
</div>
</div>
<!-- Owner Approve/Reject/Void Actions -->
<div
v-if="mutation.can?.update || mutation.can?.void"
class="c-mutation-list__actions"
>
<button
v-if="mutation.can?.update"
@click="updateStatus(mutation.id, 'approved')"
class="c-mutation-list__approve-btn"
>
Approve
</button>
<button
v-if="mutation.can?.update"
@click="updateStatus(mutation.id, 'rejected')"
class="c-mutation-list__reject-btn"
>
Reject
</button>
<button
v-if="mutation.can?.void"
@click="voidMutation(mutation.id)"
class="c-mutation-list__void-btn"
>
Void
</button>
</div>
<Chat v-if="mutation.chat"
:chat="mutation.chat"
:participants="dynamic.participants"
:dynamic-id="dynamicId"
/>
</div>
</template>
<style scoped>
@reference "../../../css/app.css";
.c-mutation-list__item {
@apply overflow-hidden bg-white p-4 shadow-sm sm:rounded-lg dark:bg-gray-800;
}
.c-mutation-list__item-header {
@apply flex items-start justify-between;
}
.c-mutation-list__item-author {
@apply font-semibold;
}
.c-mutation-list__item-meta {
@apply mt-1 flex items-center gap-2;
}
.c-mutation-list__item-amount {
@apply text-sm font-bold;
}
.c-mutation-list__item-amount--positive {
@apply text-green-500;
}
.c-mutation-list__item-amount--negative {
@apply text-red-500;
}
.c-mutation-list__item-amount--neutral {
@apply text-gray-500 dark:text-gray-400;
}
.c-mutation-list__item-status {
@apply rounded px-1.5 py-0.5 text-[10px] font-medium tracking-wider uppercase;
}
.c-mutation-list__item-status--pending {
@apply bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400;
}
.c-mutation-list__item-status--approved {
@apply bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400;
}
.c-mutation-list__item-status--rejected {
@apply bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400;
}
.c-mutation-list__item-time {
@apply text-xs text-gray-500;
}
.c-mutation-list__item-desc {
@apply mt-3 text-sm text-gray-600 dark:text-gray-400;
}
.c-mutation-list__media-list {
@apply mt-3 flex flex-wrap gap-2;
}
.c-mutation-list__media-item {
@apply max-w-[200px] overflow-hidden rounded-md border border-neutral-200 bg-black dark:border-neutral-700;
}
.c-mutation-list__media-img {
@apply h-auto max-h-[150px] w-full cursor-pointer object-cover transition-opacity hover:opacity-90;
}
.c-mutation-list__media-video-wrapper {
@apply relative cursor-pointer transition-opacity hover:opacity-90;
}
.c-mutation-list__media-video {
@apply h-auto max-h-[150px] w-full;
}
.c-mutation-list__media-video-overlay {
@apply absolute inset-0 flex items-center justify-center bg-black/40 text-2xl font-bold text-white;
}
.c-mutation-list__actions {
@apply mt-3 mb-3 flex gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-700;
}
.c-mutation-list__approve-btn {
@apply inline-flex cursor-pointer items-center rounded bg-green-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-green-500;
}
.c-mutation-list__reject-btn {
@apply inline-flex cursor-pointer items-center rounded bg-red-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-red-500;
}
.c-mutation-list__void-btn {
@apply inline-flex cursor-pointer items-center rounded bg-gray-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-gray-500;
}
</style>
-78
View File
@@ -1,78 +0,0 @@
<?php
namespace Tests\Browser;
use App\Models\Dynamic;
use App\Models\Ledger;
use App\Models\Mutation;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class NotificationTest extends DuskTestCase
{
use DatabaseMigrations;
protected function setUp(): void
{
parent::setUp();
$this->artisan('migrate:fresh', ['--seed' => true]);
}
/**
* A basic browser test example.
*/
public function test_it_shows_notifications_on_mutation_activity(): void
{
$owner = User::factory()->create();
$participant = User::factory()->create();
$dynamic = Dynamic::factory()->create();
$dynamic->chat()->create();
$dynamic->participants()->attach($owner->id, ['role' => 'owner']);
$dynamic->participants()->attach($participant->id, ['role' => 'participant']);
$ledger = Ledger::factory()->create(['dynamic_id' => $dynamic->id]);
$this->browse(function (Browser $ownerBrowser, Browser $participantBrowser) use ($owner, $participant, $dynamic, $ledger) {
$ownerBrowser->loginAs($owner)
->visit(route('dynamics.ledgers.show', [$dynamic, $ledger]))
->waitForText($ledger->name)
->assertSee($ledger->name)
->script([
"window.notifications = [];",
"window.Notification = function(title, options) { window.notifications.push({title, options}); };",
]);
$participantBrowser->loginAs($participant)
->visit(route('dynamics.ledgers.show', [$dynamic, $ledger]))
->waitForText('Add Mutation')
->type('[data-test="description-input"]', 'A new task suggestion')
->type('[data-test="amount-input"]', 10)
->press('[data-test="add-mutation-button"]')
->waitForText('A new task suggestion');
$ownerBrowser->pause(1000);
$lastNotification = $ownerBrowser->script("return window.notifications.pop();")[0] ?? null;
$this->assertNotNull($lastNotification, "Owner did not receive the 'new suggestion' notification.");
$this->assertEquals('New Activity', $lastNotification['title']);
$this->assertStringContainsString('suggested a new entry', $lastNotification['options']['body']);
$mutation = Mutation::where('description', 'A new task suggestion')->first();
$ownerBrowser->press("#mutation-{$mutation->id}-approve")
->waitForText('APPROVED');
$participantBrowser->script([
"window.notifications = [];",
"window.Notification = function(title, options) { window.notifications.push({title, options}); };",
]);
$ownerBrowser->pause(1000);
$participantBrowser->pause(1000);
$lastNotification = $participantBrowser->script("return window.notifications.pop();")[0] ?? null;
$this->assertNotNull($lastNotification, "Participant did not receive the 'approved' notification.");
$this->assertEquals('New Activity', $lastNotification['title']);
$this->assertStringContainsString('APPROVED the suggestion', $lastNotification['options']['body']);
});
}
}
+8 -8
View File
@@ -18,7 +18,7 @@ test('authenticated users can visit the dashboard', function () {
$response = $this->get(route('dashboard')); $response = $this->get(route('dashboard'));
$response->assertOk(); $response->assertOk();
$response->assertInertia(fn ($page) => $page->component('Dashboard')->has('unreadEntities')); $response->assertInertia(fn ($page) => $page->component('Dashboard')->has('unreadDynamics'));
}); });
test('visiting dynamic updates the read cursor', function () { test('visiting dynamic updates the read cursor', function () {
@@ -100,12 +100,12 @@ test('dashboard groups and filters unread entities correctly based on cursor', f
// Verify unread grouping structure // Verify unread grouping structure
$response->assertInertia(fn ($page) => $page $response->assertInertia(fn ($page) => $page
->component('Dashboard') ->component('Dashboard')
->where('unreadEntities.0.name', 'Testing Dynamic') ->where('unreadDynamics.0.name', 'Testing Dynamic')
->where('unreadEntities.0.unread_count', 1) ->where('unreadDynamics.0.unread_count', 1)
->has('unreadEntities.0.context_activities', 1) // Should have old message as context ->has('unreadDynamics.0.context_activities', 1) // Should have old message as context
->where('unreadEntities.0.context_activities.0.content', 'Old message context') ->where('unreadDynamics.0.context_activities.0.content', 'Old message context')
->has('unreadEntities.0.new_activities', 1) // Should have unread message ->has('unreadDynamics.0.new_activities', 1) // Should have unread message
->where('unreadEntities.0.new_activities.0.content', 'New unread message alert') ->where('unreadDynamics.0.new_activities.0.content', 'New unread message alert')
); );
// Now visit the Dynamic, which clears the unread count // Now visit the Dynamic, which clears the unread count
@@ -116,7 +116,7 @@ test('dashboard groups and filters unread entities correctly based on cursor', f
$response2->assertOk(); $response2->assertOk();
$response2->assertInertia(fn ($page) => $page $response2->assertInertia(fn ($page) => $page
->component('Dashboard') ->component('Dashboard')
->has('unreadEntities', 0) ->has('unreadDynamics', 0)
); );
Carbon::setTestNow(); // Reset test time Carbon::setTestNow(); // Reset test time
+1 -1
View File
@@ -99,5 +99,5 @@ test('only the user with the specified email address can accept the link', funct
// Verify system notification is added to Dynamic activity chat // Verify system notification is added to Dynamic activity chat
$chatMessages = $dynamic->chat->messages; $chatMessages = $dynamic->chat->messages;
expect($chatMessages)->not->toBeEmpty(); expect($chatMessages)->not->toBeEmpty();
expect($chatMessages->last()->content)->toBe("<user:{$invitee->id}> joined the Dynamic as a EDITOR"); expect($chatMessages->last()->content)->toBe("<user:{$invitee->uuid}> joined the Dynamic as a EDITOR");
}); });
+6 -6
View File
@@ -33,12 +33,12 @@ test('owner can create a mutation which is automatically approved and does not s
$mutationChatMessages = $mutation->chat->messages; $mutationChatMessages = $mutation->chat->messages;
expect($mutationChatMessages)->toHaveCount(1); expect($mutationChatMessages)->toHaveCount(1);
expect($mutationChatMessages->first()->user_id)->toBeNull(); expect($mutationChatMessages->first()->user_id)->toBeNull();
expect($mutationChatMessages->first()->content)->toBe("Entry was created by <user:{$owner->id}>."); expect($mutationChatMessages->first()->content)->toBe("Entry was created by <user:{$owner->uuid}>.");
$dynamicChatMessages = $dynamic->chat->messages; $dynamicChatMessages = $dynamic->chat->messages;
expect($dynamicChatMessages)->toHaveCount(1); expect($dynamicChatMessages)->toHaveCount(1);
expect($dynamicChatMessages->first()->user_id)->toBeNull(); expect($dynamicChatMessages->first()->user_id)->toBeNull();
expect($dynamicChatMessages->first()->content)->toBe("<user:{$owner->id}> added entry \"Direct point reward\" for +15 points on \"{$ledger->name}\" ledger."); expect($dynamicChatMessages->first()->content)->toBe("<user:{$owner->uuid}> added entry \"Direct point reward\" for +15 points on \"{$ledger->name}\" ledger.");
}); });
test('non-owner participant creates a suggestion which defaults to pending and says suggested', function () { test('non-owner participant creates a suggestion which defaults to pending and says suggested', function () {
@@ -71,12 +71,12 @@ test('non-owner participant creates a suggestion which defaults to pending and s
$mutationChatMessages = $mutation->chat->messages; $mutationChatMessages = $mutation->chat->messages;
expect($mutationChatMessages)->toHaveCount(1); expect($mutationChatMessages)->toHaveCount(1);
expect($mutationChatMessages->first()->user_id)->toBeNull(); expect($mutationChatMessages->first()->user_id)->toBeNull();
expect($mutationChatMessages->first()->content)->toBe("Suggestion was created by <user:{$participant->id}>."); expect($mutationChatMessages->first()->content)->toBe("Suggestion was created by <user:{$participant->uuid}>.");
$dynamicChatMessages = $dynamic->chat->messages; $dynamicChatMessages = $dynamic->chat->messages;
expect($dynamicChatMessages)->toHaveCount(1); expect($dynamicChatMessages)->toHaveCount(1);
expect($dynamicChatMessages->first()->user_id)->toBeNull(); expect($dynamicChatMessages->first()->user_id)->toBeNull();
expect($dynamicChatMessages->first()->content)->toBe("<user:{$participant->id}> suggested \"Suggested point reward\" for +10 points on \"{$ledger->name}\" ledger."); expect($dynamicChatMessages->first()->content)->toBe("<user:{$participant->uuid}> suggested \"Suggested point reward\" for +10 points on \"{$ledger->name}\" ledger.");
}); });
test('owner can approve a pending suggestion and it is updated and logged', function () { test('owner can approve a pending suggestion and it is updated and logged', function () {
@@ -115,11 +115,11 @@ test('owner can approve a pending suggestion and it is updated and logged', func
// Note: one from boot created (empty or via seeder, but in our factory it starts with 0 messages if not manually logged, // Note: one from boot created (empty or via seeder, but in our factory it starts with 0 messages if not manually logged,
// actually our model booted hook creates the chat but doesn't log on boot, the update method creates 1 message) // actually our model booted hook creates the chat but doesn't log on boot, the update method creates 1 message)
expect($mutationChatMessages->last()->user_id)->toBeNull(); expect($mutationChatMessages->last()->user_id)->toBeNull();
expect($mutationChatMessages->last()->content)->toBe("Suggestion was APPROVED by <user:{$owner->id}>."); expect($mutationChatMessages->last()->content)->toBe("<user:{$owner->uuid}> APPROVED the suggestion \"Polished dungeon floors\" for +20 points on \"{$ledger->name}\" ledger.");
$dynamicChatMessages = $dynamic->chat->messages; $dynamicChatMessages = $dynamic->chat->messages;
expect($dynamicChatMessages->last()->user_id)->toBeNull(); expect($dynamicChatMessages->last()->user_id)->toBeNull();
expect($dynamicChatMessages->last()->content)->toBe("<user:{$owner->id}> APPROVED the suggestion \"Polished dungeon floors\" for +20 points on \"{$ledger->name}\" ledger."); expect($dynamicChatMessages->last()->content)->toBe("<user:{$owner->uuid}> APPROVED the suggestion \"Polished dungeon floors\" for +20 points on \"{$ledger->name}\" ledger.");
}); });
test('creating a mutation with 0 points fails validation', function () { test('creating a mutation with 0 points fails validation', function () {
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace Tests\Feature;
use App\Models\Dynamic;
use App\Models\Ledger;
use App\Models\Mutation;
use App\Models\User;
use App\Notifications\NewActivityNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;
class NotificationDispatchTest extends TestCase
{
use RefreshDatabase;
public function test_notification_is_sent_on_mutation_suggestion()
{
Notification::fake();
$owner = User::factory()->create();
$participant = User::factory()->create();
$dynamic = Dynamic::factory()->create();
$dynamic->participants()->attach($owner->id, ['role' => 'owner']);
$dynamic->participants()->attach($participant->id, ['role' => 'participant']);
$ledger = Ledger::factory()->create(['dynamic_id' => $dynamic->id]);
$this->actingAs($participant)
->post(route('dynamics.ledgers.mutations.store', [$dynamic, $ledger]), [
'description' => 'A test suggestion',
'amount' => 10,
]);
Notification::assertSentTo($owner, NewActivityNotification::class);
Notification::assertNotSentTo($participant, NewActivityNotification::class);
}
public function test_notification_is_sent_on_mutation_approval()
{
Notification::fake();
$owner = User::factory()->create();
$participant = User::factory()->create();
$dynamic = Dynamic::factory()->create();
$dynamic->participants()->attach($owner->id, ['role' => 'owner']);
$dynamic->participants()->attach($participant->id, ['role' => 'participant']);
$ledger = Ledger::factory()->create(['dynamic_id' => $dynamic->id]);
$mutation = Mutation::factory()->create([
'ledger_id' => $ledger->id,
'user_id' => $participant->id,
'status' => 'pending',
]);
$this->actingAs($owner)
->put(route('dynamics.ledgers.mutations.update', [$dynamic, $ledger, $mutation]), [
'status' => 'approved',
]);
Notification::assertSentTo($participant, NewActivityNotification::class);
Notification::assertNotSentTo($owner, NewActivityNotification::class);
}
public function test_notification_is_sent_on_mutation_void()
{
Notification::fake();
$owner = User::factory()->create();
$participant = User::factory()->create();
$dynamic = Dynamic::factory()->create();
$dynamic->participants()->attach($owner->id, ['role' => 'owner']);
$dynamic->participants()->attach($participant->id, ['role' => 'participant']);
$ledger = Ledger::factory()->create(['dynamic_id' => $dynamic->id]);
$mutation = Mutation::factory()->create([
'ledger_id' => $ledger->id,
'user_id' => $participant->id,
'status' => 'approved',
]);
$this->actingAs($owner)
->put(route('dynamics.ledgers.mutations.void', [$dynamic, $ledger, $mutation]));
Notification::assertSentTo($participant, NewActivityNotification::class);
Notification::assertNotSentTo($owner, NewActivityNotification::class);
}
public function test_notification_is_sent_to_other_participants_when_owner_adds_mutation()
{
Notification::fake();
$owner = User::factory()->create();
$participant1 = User::factory()->create();
$participant2 = User::factory()->create();
$dynamic = Dynamic::factory()->create();
$dynamic->participants()->attach($owner->id, ['role' => 'owner']);
$dynamic->participants()->attach($participant1->id, ['role' => 'participant']);
$dynamic->participants()->attach($participant2->id, ['role' => 'participant']);
$ledger = Ledger::factory()->create(['dynamic_id' => $dynamic->id]);
$this->actingAs($owner)
->post(route('dynamics.ledgers.mutations.store', [$dynamic, $ledger]), [
'description' => 'A test mutation from owner',
'amount' => 25,
]);
Notification::assertSentTo($participant1, NewActivityNotification::class);
Notification::assertSentTo($participant2, NewActivityNotification::class);
Notification::assertNotSentTo($owner, NewActivityNotification::class);
}
}