]> BookStack Code Mirror - bookstack/commitdiff
Completed webhook management interface
authorDan Brown <redacted>
Wed, 8 Dec 2021 17:35:58 +0000 (17:35 +0000)
committerDan Brown <redacted>
Wed, 8 Dec 2021 17:35:58 +0000 (17:35 +0000)
Got webhook CRUD actions in place within the interface.
Quick manual test pass done, Needs automated tests.

12 files changed:
app/Actions/Webhook.php
app/Actions/WebhookTrackedEvent.php [new file with mode: 0644]
app/Http/Controllers/WebhookController.php
database/migrations/2021_12_07_111343_create_webhooks_table.php
resources/js/components/webhook-events.js
resources/lang/en/settings.php
resources/views/form/errors.blade.php [new file with mode: 0644]
resources/views/settings/webhooks/create.blade.php
resources/views/settings/webhooks/delete.blade.php
resources/views/settings/webhooks/edit.blade.php
resources/views/settings/webhooks/index.blade.php
resources/views/settings/webhooks/parts/form.blade.php

index 2d11584e63875ad3fb34294cb453863df2fb0295..55bc855cedeaea45c203e3730cd9f52154f3e113 100644 (file)
@@ -3,18 +3,67 @@
 namespace BookStack\Actions;
 
 use BookStack\Interfaces\Loggable;
+use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\HasMany;
 
 /**
  * @property int $id
  * @property string $name
  * @property string $endpoint
+ * @property Collection $trackedEvents
  */
 class Webhook extends Model implements Loggable
 {
+    protected $fillable = ['name', 'endpoint'];
+
     use HasFactory;
 
+    /**
+     * Define the tracked event relation a webhook.
+     */
+    public function trackedEvents(): HasMany
+    {
+        return $this->hasMany(WebhookTrackedEvent::class);
+    }
+
+    /**
+     * Update the tracked events for a webhook from the given list of event types.
+     */
+    public function updateTrackedEvents(array $events): void
+    {
+        $this->trackedEvents()->delete();
+
+        $eventsToStore = array_intersect($events, array_values(ActivityType::all()));
+        if (in_array('all', $events)) {
+            $eventsToStore = ['all'];
+        }
+
+        $trackedEvents = [];
+        foreach ($eventsToStore as $event) {
+            $trackedEvents[] = new WebhookTrackedEvent(['event' => $event]);
+        }
+
+        $this->trackedEvents()->saveMany($trackedEvents);
+    }
+
+    /**
+     * Check if this webhook tracks the given event.
+     */
+    public function tracksEvent(string $event): bool
+    {
+        return $this->trackedEvents->pluck('event')->contains($event);
+    }
+
+    /**
+     * Get a URL for this webhook within the settings interface.
+     */
+    public function getUrl(string $path = ''): string
+    {
+        return url('/settings/webhooks/' . $this->id . '/' . ltrim($path, '/'));
+    }
+
     /**
      * Get the string descriptor for this item.
      */
diff --git a/app/Actions/WebhookTrackedEvent.php b/app/Actions/WebhookTrackedEvent.php
new file mode 100644 (file)
index 0000000..a053062
--- /dev/null
@@ -0,0 +1,18 @@
+<?php
+
+namespace BookStack\Actions;
+
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * @property int $id
+ * @property int $webhook_id
+ * @property string $event
+ */
+class WebhookTrackedEvent extends Model
+{
+    protected $fillable = ['event'];
+
+    use HasFactory;
+}
index 15a31f312fd02a185af5dc52781150e7971320de..497d623b20afc8141533a3b4b74b8adbf4d64cb7 100644 (file)
@@ -20,8 +20,11 @@ class WebhookController extends Controller
      */
     public function index()
     {
-        // TODO - Get and pass webhooks
-        return view('settings.webhooks.index');
+        $webhooks = Webhook::query()
+            ->orderBy('name', 'desc')
+            ->with('trackedEvents')
+            ->get();
+        return view('settings.webhooks.index', ['webhooks' => $webhooks]);
     }
 
     /**
@@ -37,7 +40,16 @@ class WebhookController extends Controller
      */
     public function store(Request $request)
     {
-        // TODO - Create webhook
+        $validated = $this->validate($request, [
+            'name' => ['required', 'max:150'],
+            'endpoint' => ['required', 'url', 'max:500'],
+            'events' => ['required', 'array']
+        ]);
+
+        $webhook = new Webhook($validated);
+        $webhook->save();
+        $webhook->updateTrackedEvents(array_values($validated['events']));
+
         $this->logActivity(ActivityType::WEBHOOK_CREATE, $webhook);
         return redirect('/settings/webhooks');
     }
@@ -48,7 +60,9 @@ class WebhookController extends Controller
     public function edit(string $id)
     {
         /** @var Webhook $webhook */
-        $webhook = Webhook::query()->findOrFail($id);
+        $webhook = Webhook::query()
+            ->with('trackedEvents')
+            ->findOrFail($id);
 
         return view('settings.webhooks.edit', ['webhook' => $webhook]);
     }
@@ -58,10 +72,17 @@ class WebhookController extends Controller
      */
     public function update(Request $request, string $id)
     {
+        $validated = $this->validate($request, [
+            'name' => ['required', 'max:150'],
+            'endpoint' => ['required', 'url', 'max:500'],
+            'events' => ['required', 'array']
+        ]);
+
         /** @var Webhook $webhook */
         $webhook = Webhook::query()->findOrFail($id);
 
-        // TODO - Update
+        $webhook->fill($validated)->save();
+        $webhook->updateTrackedEvents($validated['events']);
 
         $this->logActivity(ActivityType::WEBHOOK_UPDATE, $webhook);
         return redirect('/settings/webhooks');
@@ -85,7 +106,7 @@ class WebhookController extends Controller
         /** @var Webhook $webhook */
         $webhook = Webhook::query()->findOrFail($id);
 
-        // TODO - Delete event type relations
+        $webhook->trackedEvents()->delete();
         $webhook->delete();
 
         $this->logActivity(ActivityType::WEBHOOK_DELETE, $webhook);
index 7ccfe693d8acf475614202239b312d99a298afb4..2ded0b9495e8c22f35aed37385cceed9035d1d64 100644 (file)
@@ -18,6 +18,18 @@ class CreateWebhooksTable extends Migration
             $table->string('name', 150);
             $table->string('endpoint', 500);
             $table->timestamps();
+
+            $table->index('name');
+        });
+
+        Schema::create('webhook_tracked_events', function (Blueprint $table) {
+            $table->increments('id');
+            $table->integer('webhook_id');
+            $table->string('event', 50);
+            $table->timestamps();
+
+            $table->index('event');
+            $table->index('webhook_id');
         });
     }
 
index 54080d36e22693ed61e47abac0f5454ccdd856b0..aa50aa9d883f1541cbf08eed3d9865b65c252789 100644 (file)
@@ -8,7 +8,7 @@ class WebhookEvents {
 
     setup() {
         this.checkboxes = this.$el.querySelectorAll('input[type="checkbox"]');
-        this.allCheckbox = this.$refs.all;
+        this.allCheckbox = this.$el.querySelector('input[type="checkbox"][value="all"]');
 
         this.$el.addEventListener('change', event => {
             if (event.target.checked && event.target === this.allCheckbox) {
index 6812075b35edf60aef98ed2c8d237bb79c155b82..209702d0e68e1010244c1bfdedb6227aaaa071ce 100755 (executable)
@@ -246,6 +246,7 @@ return [
     'webhooks_events_all' => 'All system events',
     'webhooks_name' => 'Webhook Name',
     'webhooks_endpoint' => 'Webhook Endpoint',
+    'webhook_events_table_header' => 'Events',
     'webhooks_delete' => 'Delete Webhook',
     'webhooks_delete_warning' => 'This will fully delete this webhook, with the name \':webhookName\', from the system.',
     'webhooks_delete_confirm' => 'Are you sure you want to delete this webhook?',
diff --git a/resources/views/form/errors.blade.php b/resources/views/form/errors.blade.php
new file mode 100644 (file)
index 0000000..03cd4be
--- /dev/null
@@ -0,0 +1,3 @@
+@if($errors->has($name))
+    <div class="text-neg text-small">{{ $errors->first($name) }}</div>
+@endif
\ No newline at end of file
index b49afe4156f98dda29ad296611c9e508445d0d91..d5fd1d38d799fb47e04846787aadebb0ac3999c3 100644 (file)
@@ -8,7 +8,7 @@
             @include('settings.parts.navbar', ['selected' => 'webhooks'])
         </div>
 
-        <form action="{{ url("/settings/webhooks/new") }}" method="POST">
+        <form action="{{ url("/settings/webhooks/create") }}" method="POST">
             @include('settings.webhooks.parts.form', ['title' => trans('settings.webhooks_create')])
         </form>
     </div>
index a89b011711f72843f751fe0a49f892aa75d42560..65560f65fc02e7f3e10725c6e27f37c864d3d4bc 100644 (file)
@@ -13,7 +13,7 @@
             <p>{{ trans('settings.webhooks_delete_warning', ['webhookName' => $webhook->name]) }}</p>
 
 
-            <form action="{{ url("/settings/webhooks/{$role->id}") }}" method="POST">
+            <form action="{{ $webhook->getUrl() }}" method="POST">
                 {!! csrf_field() !!}
                 {!! method_field('DELETE') !!}
 
@@ -25,7 +25,7 @@
                     </div>
                     <div>
                         <div class="form-group text-right">
-                            <a href="{{ url("/settings/webhooks/{$role->id}") }}" class="button outline">{{ trans('common.cancel') }}</a>
+                            <a href="{{ $webhook->getUrl() }}" class="button outline">{{ trans('common.cancel') }}</a>
                             <button type="submit" class="button">{{ trans('common.confirm') }}</button>
                         </div>
                     </div>
index d4e60cc14189798f1c85923b533a15a6c27088d1..a221b4ce7fb3b55dd4d93968ec511263b96cc610 100644 (file)
@@ -7,7 +7,7 @@
             @include('settings.parts.navbar', ['selected' => 'webhooks'])
         </div>
 
-        <form action="{{ url("/settings/webhooks/{$webhook->id}") }}" method="POST">
+        <form action="{{ $webhook->getUrl() }}" method="POST">
             {!! method_field('PUT') !!}
             @include('settings.webhooks.parts.form', ['model' => $webhook, 'title' => trans('settings.webhooks_edit')])
         </form>
index 8adf60835db6123c7a67ead5b9b1824709781334..999a458ec15057251840ddbcc5fbaacb33d88bb6 100644 (file)
                 <h1 class="list-heading">{{ trans('settings.webhooks') }}</h1>
 
                 <div class="text-right">
-                    <a href="{{ url("/settings/webhooks/create") }}" class="button outline">{{ trans('settings.webhooks_create') }}</a>
+                    <a href="{{ url("/settings/webhooks/create") }}"
+                       class="button outline">{{ trans('settings.webhooks_create') }}</a>
                 </div>
             </div>
 
+            @if(count($webhooks) > 0)
+
+                <table class="table">
+                    <tr>
+                        <th>{{ trans('common.name') }}</th>
+                        <th>{{ trans('settings.webhook_events_table_header') }}</th>
+                    </tr>
+                    @foreach($webhooks as $webhook)
+                        <tr>
+                            <td>
+                                <a href="{{ $webhook->getUrl() }}">{{ $webhook->name }}</a> <br>
+                                <span class="small text-muted italic">{{ $webhook->endpoint }}</span>
+                            </td>
+                            <td>
+                                @if($webhook->tracksEvent('all'))
+                                    {{ trans('settings.webhooks_events_all') }}
+                                @else
+                                    {{ $webhook->trackedEvents->count() }}
+                                @endif
+                            </td>
+                        </tr>
+                    @endforeach
+                </table>
+            @else
+                <p class="text-muted empty-text">
+                    {{ trans('common.no_items') }}
+                </p>
+            @endif
+
 
         </div>
     </div>
index 935b01992fa5185fe1caecdf9bec8bccbc1be993..e2b3fc34d7d8fb13544d9c0111ce0c472f37236e 100644 (file)
 
         <div component="webhook-events">
             <label class="setting-list-label">{{ trans('settings.webhooks_events') }}</label>
+            @include('form.errors', ['name' => 'events'])
+
             <p class="small">{{ trans('settings.webhooks_events_desc') }}</p>
             <p class="text-warn small">{{ trans('settings.webhooks_events_warning') }}</p>
 
-            <div>
-                <label><input type="checkbox"
-                              name="events[]"
-                              value="all"
-                              refs="webhook-events@all">
-                    {{ trans('settings.webhooks_events_all') }}</label>
+            <div class="toggle-switch-list">
+                @include('form.custom-checkbox', [
+                    'name' => 'events[]',
+                    'value' => 'all',
+                    'label' => trans('settings.webhooks_events_all'),
+                    'checked' => old('events') ? in_array('all', old('events')) : (isset($webhook) ? $webhook->tracksEvent('all') : false),
+                ])
             </div>
 
-            <hr class="my-m">
+            <hr class="my-s">
 
-            <div class="dual-column-content">
+            <div class="dual-column-content toggle-switch-list">
                 @foreach(\BookStack\Actions\ActivityType::all() as $activityType)
-                    <label><input type="checkbox" name="events[]" value="{{ $activityType }}">{{ $activityType }}</label>
+                    <div>
+                        @include('form.custom-checkbox', [
+                           'name' => 'events[]',
+                           'value' => $activityType,
+                           'label' => $activityType,
+                           'checked' => old('events') ? in_array($activityType, old('events')) : (isset($webhook) ? $webhook->tracksEvent($activityType) : false),
+                       ])
+                    </div>
                 @endforeach
             </div>
         </div>
@@ -49,7 +59,7 @@
     <div class="form-group text-right">
         <a href="{{ url("/settings/webhooks") }}" class="button outline">{{ trans('common.cancel') }}</a>
         @if ($webhook->id ?? false)
-            <a href="{{ url("/settings/roles/delete/{$webhook->id}") }}" class="button outline">{{ trans('settings.webhooks_delete') }}</a>
+            <a href="{{ $webhook->getUrl('/delete') }}" class="button outline">{{ trans('settings.webhooks_delete') }}</a>
         @endif
         <button type="submit" class="button">{{ trans('settings.webhooks_save') }}</button>
     </div>