Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions addon/components/modals/create-notification-channel.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@
<div class="input-group">
<Checkbox @value={{value}} @label={{humanize key}} @onToggle={{fn @options.setConfigKey key}} />
</div>
{{else if (eq key "environment")}}
<InputGroup @name={{humanize key}} @helpText={{t "storefront.component.modals.create-notification-channel.environment-help-text"}}>
<Select
class="w-full"
@options={{array "auto" "production" "sandbox"}}
@value={{value}}
@onSelect={{fn @options.setConfigKey key}}
@humanize={{true}}
/>
</InputGroup>
{{else if (eq key "android_channel_id")}}
<InputGroup @name={{humanize key}} @helpText={{t "storefront.component.modals.create-notification-channel.android-channel-id-help-text"}}>
<Input class="form-input w-full" placeholder={{humanize key}} @value={{value}} {{on "blur" (fn @options.setConfigKey key)}} />
</InputGroup>
{{else if (or (eq key "private_key_content") (eq key "firebase_credentials_json"))}}
<InputGroup @name={{humanize key}}>
<Textarea class="form-input w-full" rows="6" placeholder={{humanize key}} @value={{value}} {{on "blur" (fn @options.setConfigKey key)}} />
Expand Down
33 changes: 33 additions & 0 deletions addon/components/modals/test-notification-channel.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Modal::Default @modalIsOpened={{@modalIsOpened}} @options={{@options}} @confirm={{@onConfirm}} @decline={{@onDecline}}>
<div class="modal-body-container">
<InputGroup @name={{t "storefront.component.modals.test-notification-channel.token"}} @helpText={{t "storefront.component.modals.test-notification-channel.token-text"}}>
<Textarea class="form-input w-full" rows="3" @value={{@options.token}} {{on "blur" @options.setToken}} />
</InputGroup>

{{#if (eq @options.channel.scheme "apn")}}
<InputGroup @name={{t "storefront.component.modals.test-notification-channel.environment"}} @helpText={{t "storefront.component.modals.test-notification-channel.environment-text"}}>
<Select
class="w-full"
@options={{array "production" "sandbox"}}
@value={{@options.environment}}
@placeholder={{t "storefront.component.modals.test-notification-channel.environment"}}
@onSelect={{@options.setEnvironment}}
@humanize={{true}}
/>
</InputGroup>
{{/if}}

{{#if @options.results}}
<div class="p-2 rounded-md my-2 border border-gray-200 dark:border-gray-800">
<h4 class="mb-2 font-semibold text-sm dark:text-white">{{t "storefront.component.modals.test-notification-channel.result"}}</h4>
{{#each @options.results as |result|}}
<div class="text-xs font-mono dark:text-gray-200 mb-1">
{{#if result.environment}}[{{result.environment}}]{{/if}}
{{result.status}}
{{#if result.reason}}- {{result.reason}}{{/if}}
</div>
{{/each}}
</div>
{{/if}}
</div>
</Modal::Default>
10 changes: 10 additions & 0 deletions addon/controllers/networks/index/network/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,16 @@ export default class NetworksIndexNetworkIndexController extends Controller {
return this.notificationsController.deleteChannel(...arguments);
}

/**
* Send a test push notification through a notification channel.
*
* @method testChannel
* @public
*/
@action testChannel() {
return this.notificationsController.testChannel(...arguments);
}

/**
* Make an alertable action.
*
Expand Down
39 changes: 39 additions & 0 deletions addon/controllers/settings/notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default class SettingsNotificationsController extends Controller {
@service crud;
@service storefront;
@service hostRouter;
@service fetch;
@alias('storefront.activeStore') activeStore;
queryParams = ['query'];

Expand Down Expand Up @@ -88,6 +89,44 @@ export default class SettingsNotificationsController extends Controller {
});
}

@action testChannel(channel) {
this.modalsManager.show('modals/test-notification-channel', {
title: this.intl.t('storefront.settings.notification.send-test-push'),
acceptButtonText: this.intl.t('storefront.settings.notification.send-test-push-button'),
acceptButtonIcon: 'paper-plane',
channel,
token: '',
environment: null,
results: null,
setToken: (event) => {
this.modalsManager.setOption('token', event.target.value);
},
setEnvironment: (environment) => {
this.modalsManager.setOption('environment', environment);
},
keepOpen: true,
confirm: async (modal) => {
const { token, environment } = this.modalsManager.getOptions(['token', 'environment']);
modal.startLoading();

try {
const response = await this.fetch.post(`notification-channels/${channel.id}/test`, { token, environment }, { namespace: 'storefront/int/v1' });
this.modalsManager.setOption('results', response.results);

if (response.status === 'OK') {
this.notifications.success(this.intl.t('storefront.settings.notification.test-push-sent'));
} else {
this.notifications.warning(this.intl.t('storefront.settings.notification.test-push-failed'));
}
} catch (error) {
this.notifications.serverError(error);
} finally {
modal.stopLoading();
}
},
});
}

@action deleteChannel(channel) {
this.modalsManager.confirm({
title: this.intl.t('storefront.settings.notification.remove-this-notification-channel'),
Expand Down
1 change: 1 addition & 0 deletions addon/templates/networks/index/network/index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@
<span class="dark:text-gray-50">{{notificationChannel.name}}</span>
</div>
<div class="flex items-center">
<Button @size="xs" @type="default" @text={{t "storefront.settings.notification.send-test"}} @wrapperClass="mr-2" @onClick={{fn this.testChannel notificationChannel}} />
<Button @size="xs" @type="default" @text={{t "storefront.common.edit"}} @wrapperClass="mr-2" @onClick={{fn this.editChannel notificationChannel}} />
<Button @size="xs" @type="danger" @text={{t "storefront.common.delete"}} @onClick={{fn this.deleteChannel notificationChannel}} />
</div>
Expand Down
1 change: 1 addition & 0 deletions addon/templates/settings/notifications.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<span class="dark:text-gray-50">{{notificationChannel.name}}</span>
</div>
<div class="flex items-center">
<Button @size="xs" @type="default" @text={{t "storefront.settings.notification.send-test"}} @wrapperClass="mr-2" @onClick={{fn this.testChannel notificationChannel}} />
<Button @size="xs" @type="default" @text={{t "storefront.common.edit"}} @wrapperClass="mr-2" @onClick={{fn this.editChannel notificationChannel}} />
<Button @size="xs" @type="danger" @text={{t "storefront.common.delete"}} @onClick={{fn this.deleteChannel notificationChannel}} />
</div>
Expand Down
5 changes: 2 additions & 3 deletions addon/utils/get-notification-schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ export default function getNotificationSchemas() {
team_id: '',
app_bundle_id: '',
private_key_content: '',
production: true,
environment: 'auto',
},
fcm: {
firebase_credentials_json: '',
firebase_database_url: '',
firebase_project_name: '',
android_channel_id: '',
},
};

Expand Down
1 change: 1 addition & 0 deletions app/components/modals/test-notification-channel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from '@fleetbase/storefront-engine/components/modals/test-notification-channel';
13 changes: 13 additions & 0 deletions server/config/storefront.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@
))),
],

/*
|--------------------------------------------------------------------------
| Push Notifications
|--------------------------------------------------------------------------
|
| android_channel_id: the Android notification channel storefront pushes are
| posted to. Leave empty to use the app's default FCM channel. A notification
| channel's own `android_channel_id` setting takes precedence.
*/
'push' => [
'android_channel_id' => env('STOREFRONT_PUSH_ANDROID_CHANNEL_ID'),
],

/*
|--------------------------------------------------------------------------
| Database Connection
Expand Down
62 changes: 62 additions & 0 deletions server/src/Http/Controllers/NotificationChannelController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

namespace Fleetbase\Storefront\Http\Controllers;

use Fleetbase\Storefront\Models\NotificationChannel;
use Fleetbase\Storefront\Push\ApnClientFactory;
use Fleetbase\Storefront\Push\PushMessage;
use Fleetbase\Storefront\Push\Transports\ApnTransport;
use Fleetbase\Storefront\Push\Transports\FcmTransport;
use Illuminate\Http\Request;

class NotificationChannelController extends StorefrontController
{
/**
Expand All @@ -10,4 +17,59 @@ class NotificationChannelController extends StorefrontController
* @var string
*/
public $resource = 'notification_channel';

/**
* Send a test push to a single device token through a notification channel and report
* the provider's raw outcome, so credential or token problems can be diagnosed.
*
* @return \Illuminate\Http\JsonResponse
*/
public function testPush(string $id, Request $request, FcmTransport $fcm, ApnTransport $apn)
{
$token = trim((string) $request->input('token'));
if ($token === '') {
return response()->error('A device token is required.');
}

$channel = NotificationChannel::where(function ($query) use ($id) {
$query->where('uuid', $id)->orWhere('app_key', $id);
})->where('company_uuid', session('company'))->first();

if (!$channel) {
return response()->error('Notification channel not found.', 404);
}

$message = PushMessage::create(
$request->input('title', 'Test notification'),
$request->input('body', 'Push notifications from ' . ($channel->name ?? 'your storefront') . ' are working.'),
['type' => 'test']
);

$results = [];
try {
if ($channel->scheme === 'fcm') {
$outcome = $fcm->send($channel, $message, [$token])[$token] ?? null;
$results[] = ['environment' => null, 'status' => $outcome?->status ?? 'error', 'reason' => $outcome?->reason];
} else {
$environments = $request->filled('environment') ? [$request->input('environment')] : ApnClientFactory::environments($channel);
foreach ($environments as $environment) {
$outcome = $apn->send($channel, $environment, $message, [$token])[$token] ?? null;
$results[] = ['environment' => $environment, 'status' => $outcome?->status ?? 'error', 'reason' => $outcome?->reason];
if ($outcome?->status === 'sent') {
break;
}
}
}
} catch (\Throwable $e) {
$results[] = ['environment' => null, 'status' => 'error', 'reason' => $e->getMessage()];
}

$sent = collect($results)->contains('status', 'sent');

return response()->json([
'status' => $sent ? 'OK' : 'FAILED',
'scheme' => $channel->scheme,
'results' => $results,
]);
}
}
94 changes: 82 additions & 12 deletions server/src/Http/Controllers/v1/CustomerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Fleetbase\Storefront\Http\Requests\CreateCustomerRequest;
use Fleetbase\Storefront\Http\Requests\VerifyCreateCustomerRequest;
use Fleetbase\Storefront\Http\Resources\Customer;
use Fleetbase\Storefront\Push\StorefrontPushChannel;
use Fleetbase\Storefront\Support\Storefront;
use Fleetbase\Support\Utils;
use Illuminate\Database\Eloquent\ModelNotFoundException;
Expand Down Expand Up @@ -48,25 +49,94 @@ public function registerDevice(Request $request)
return response()->apiError('Not authorized to register device for cutomer');
}

$device = UserDevice::firstOrCreate(
[
'token' => $request->input('token'),
'platform' => $request->or(['platform', 'os']),
],
[
'user_uuid' => $customer->user_uuid,
'platform' => $request->or(['platform', 'os']),
'token' => $request->input('token'),
'status' => 'active',
]
);
$token = trim((string) $request->input('token'));
$platform = StorefrontPushChannel::normalizePlatform($request->or(['platform', 'os']));

if ($token === '') {
return response()->apiError('A device token is required.');
}

if (!$platform) {
return response()->apiError('Device platform must be either ios or android.');
}

if (!$customer->user_uuid) {
return response()->apiError('Unable to register device for customer without a user account.');
}

// A token identifies one app install, so it always belongs to the customer who
// registered it most recently (e.g. after logging out and in as someone else).
$devices = UserDevice::withTrashed()->where('token', $token)->orderByDesc('updated_at')->get();
$device = $devices->shift() ?? new UserDevice();
$devices->each(fn (UserDevice $duplicate) => $duplicate->forceDelete());

if ($device->exists && $device->trashed()) {
$device->restore();
}

$device->fill([
'user_uuid' => $customer->user_uuid,
'platform' => $platform,
'token' => $token,
'status' => 'active',
]);

$optionalAttributes = [
'environment' => in_array($request->input('environment'), ['production', 'sandbox'], true) ? $request->input('environment') : null,
'app_identifier' => session('storefront_store') ?? session('storefront_network'),
'last_seen_at' => now(),
];
$columns = static::userDeviceColumns();
foreach ($optionalAttributes as $column => $value) {
if (in_array($column, $columns, true)) {
$device->forceFill([$column => $value]);
}
}

$device->save();

return response()->json([
'status' => 'OK',
'device' => $device->public_id,
]);
}

/**
* Unregister a device token for the authenticated customer, e.g. on logout.
*
* @return \Illuminate\Http\JsonResponse
*/
public function unregisterDevice(Request $request)
{
$customer = Storefront::getCustomerFromToken();

if (!$customer) {
return response()->apiError('Not authorized to unregister device for customer');
}

$token = trim((string) $request->input('token'));
if ($token === '') {
return response()->apiError('A device token is required.');
}

$deleted = UserDevice::where('token', $token)->where('user_uuid', $customer->user_uuid)->get()->each(fn (UserDevice $device) => $device->delete())->count();

return response()->json([
'status' => 'OK',
'deleted' => $deleted,
]);
}

/**
* Newer core-api versions add push metadata columns to user_devices.
*
* @return string[]
*/
protected static function userDeviceColumns(): array
{
return (new UserDevice())->getConnection()->getSchemaBuilder()->getColumnListing('user_devices');
}

/**
* Query for Storefront Customer orders.
*
Expand Down
5 changes: 4 additions & 1 deletion server/src/Listeners/HandleOrderCompleted.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ public function handle(OrderCompleted $event)
// if storefront order notify customer driver has been addigned
if ($order->hasMeta('storefront_id')) {
$order->load(['customer']);
$order->customer->notify(new StorefrontOrderCompleted($order));

if ($order->customer) {
$order->customer->notify(new StorefrontOrderCompleted($order));
}
}
}
}
5 changes: 4 additions & 1 deletion server/src/Listeners/HandleOrderDriverAssigned.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ public function handle(OrderDriverAssigned $event)
// if storefront order notify customer driver has been addigned
if ($order->hasMeta('storefront_id')) {
$order->load(['customer']);
$order->customer->notify(new StorefrontOrderDriverAssigned($order));

if ($order->customer) {
$order->customer->notify(new StorefrontOrderDriverAssigned($order));
}
}
}
}
Loading
Loading