Skip to content

Commit

Permalink
Merge pull request #32 from cap-js/fine-tuning
Browse files Browse the repository at this point in the history
Fine-tuning implementation
  • Loading branch information
danjoa authored Oct 27, 2023
2 parents ad48792 + ca4c8a7 commit 4045d06
Show file tree
Hide file tree
Showing 16 changed files with 330 additions and 385 deletions.
265 changes: 117 additions & 148 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,169 +7,162 @@ The `@cap-js/notifications` package is a [CDS plugin](https://cap.cloud.sap/docs
### Table of Contents

- [Setup](#setup)
- [Usage](#usage)
- [Update Notification Configuration](#update-notification-configuration)
- [Notification Types Path](#notification-types-path)
- [Notification Type Prefix](#notification-type-prefix)
- [Add Notification Types](#add-notification-types)
- [Add code to send notifications](#add-code-to-send-notifications)
- [Simple Notification with title](#simple-notification-with-title)
- [Simple Notification with title and description](#simple-notification-with-title-and-description)
- [Custom Notifications](#custom-notifications)
- [With standard parameters](#with-standard-parameters)
- [Passing the whole notification object](#passing-the-whole-notification-object)
- [Sample Application with notifications](#sample-application-with-notifications)
- [In Local Environment](#in-local-environment)
- [In Production Environment](#in-production-environment)
- [Notification Destination](#notification-destination)
- [Integrate with SAP Build Work Zone](#integrate-with-sap-build-work-zone)
- [Send Notifications](#send-notifications)
- [Use Notification Types](#use-notification-types)
- [API Reference](#api-reference)
- [Test-drive Locally](#test-drive-locally)
- [Run in Production](#run-in-production)
- [Advanced Usage](#advanced-usage)
- [Contributing](#contributing)
- [Code of Conduct](#code-of-conduct)
- [Code of Conduct](#code-of-conduct)
- [Licensing](#licensing)

## Setup

To enable notifications, simply add this self-configuring plugin package to your project:

```sh
cds add notifications
npm add @cap-js/notifications
```

<img width="1300" alt="cds add notifications" style="border-radius:0.5rem" src="_assets/cdsAddNotifications.gif">

## Usage

In this guide, we use the [Incidents Management reference sample app](https://github.com/cap-js/incidents-app) as the base, to publish notifications.

### Update Notification Configuration
## Send Notifications

`cds add notifications` will add default configurations for notifications in the `package.json` file.
With that you can use the NotificationService as any other CAP Service like so in you event handlers:

<img width="1300" alt="Default Notification config" style="border-radius:0.5rem" src="_assets/packageJsonConfig.gif">
```js
const alert = await cds.connect.to('notifications');
```

#### Notification Types Path
You can use the following signature to send the simple notification with title and description

When you run `cds add notifications`, it will add `notificationstype.json` file with template for a notification type in the project root folder. You can add the notification types in the `notificationtype.json` file for sending the custom notification types.
```js
alert.notify({
recipients: [ ...supporters() ],
priority: "HIGH",
title: "New high priority incident is assigned to you!",
description: "Incident titled 'Engine overheating' created by 'customer X' with priority high is assigned to you!"
});
```

#### Notification Type Prefix
* **priority** - Priority of the notification, this argument is optional, it defaults to NEUTRAL
* **description** - Subtitle for the notification, this argument is optional

To make notification types unique to the application, prefix is added to the type key. By default, `application name` is added as the prefix. You can update the `prefix` if required.
## Use Notification Types

### Add Notification Types
### 1. Add notification types

If you want to send custom notifications in your application, you can add the notification types in the `notificationtype.json` file.
If you want to send custom notifications in your application, you can add the notification types in the `srv/notification-types.json` file.

Sample: If you want to send the notification when the new incident is reported, you can modify the `notificationtypes.json` as below:
Sample: If you want to send the notification when the incident is resolved, you can modify the `srv/notification-types.json` as below:

```jsonc
[
{
"NotificationTypeKey": "IncidentReported",
"NotificationTypeVersion": "1",
"Templates": [
{
"Language": "en",
"TemplatePublic": "Incident Reported",
"TemplateSensitive": "Incident '{{name}}' Reported",
"TemplateGrouped": "New Incidents",
"TemplateLanguage": "mustache",
"Subtitle": "Incident '{{name}}' reported by '{{customer}}'."
}
]
}
]
```json
[
{
"NotificationTypeKey": "IncidentResolved",
"NotificationTypeVersion": "1",
"Templates": [
{
"Language": "en",
"TemplatePublic": "Incident Resolved",
"TemplateSensitive": "Incident '{{title}}' Resolved",
"TemplateGrouped": "Incident Status Update",
"TemplateLanguage": "mustache",
"Subtitle": "Incident from '{{customer}}' resolved by {{user}}."
}
]
}
]
```

### Add code to send notifications
### 2. Use pre-defined types in your code like that:

In the handler files, connect to the notifications plugin by:

```js
const alert = await cds.connect.to('notifications');
await alert.notify ('IncidentResolved', {
recipients: [ customer.id ],
data: {
customer: customer.info,
title: incident.title,
user: cds.context.user.id,
}
})
```

#### Simple Notification with title
You can use the following signature to send the simple notification with title
```js
alert.notify({
recipients: ["[email protected]","[email protected]"],
priority: "HIGH",
title: "New incident is reported!"
});
```
#### Simple Notification with title and description
You can use the following signature to send the simple notification with title and description
```js
alert.notify({
recipients: ["[email protected]"],
priority: "HIGH",
title: "New high priority incident is assigned to you!",
description: "Incident titled 'Engine overheating' created by 'customer X' with priority high is assigned to you!"
});
```
## API Reference

* **recipients** - List of the recipients, this argument is mandatory
* **type** - Notification type key, this argument is mandatory
* **priority** - Priority of the notification, this argument is optional, it defaults to NEUTRAL
* **data** - A key-value pair that is used to fill a placeholder of the notification type template, this argument is optional

## Test-drive Locally
In local environment, when you publish notification, it is mocked to publish the nofication to the console.

<img width="700" alt="Notify to console" style="border-radius:0.5rem" src="_assets/notifyToConsole.png">

## Run in Production

#### Notification Destination

As a pre-requisite to publish the notification, you need to have a [destination](https://help.sap.com/docs/build-work-zone-standard-edition/sap-build-work-zone-standard-edition/enabling-notifications-for-custom-apps-on-sap-btp-cloud-foundry#configure-the-destination-to-the-notifications-service) configured to publish the notification. In the `package.json` by default destination name `SAP_Notifications` is added, you can modify the destination name that you are configuring.

#### Integrate with SAP Build Work Zone

Once application is deployed and [integrated with SAP Build Work Zone](https://github.com/cap-js/calesi/tree/main/samples/notifications), you can see the notification under fiori notifications icon!

<img width="1300" alt="Sample Application Demo" style="border-radius:0.5rem;" src="_assets/incidentsNotificationDemo.gif">



## Advanced Usage

### Custom Notification Types Path

Notifications plugin configures `srv/notification-types.json` as default notification types file. If you are using different file, you can update the file path in `cds.env.requires.notifications.types`

### Custom Notification Type Prefix

To make notification types unique to the application, prefix is added to the type key. By default, `application name` is added as the prefix. You can update the `cds.env.requires.notifications.prefix` if required.

### Low-level Notifications API

#### Custom Notifications
You can use these two signature to send the custom notification with pre-defined notification types.

##### With standard parameters
#### With pre-defined parameters

By using this approach you can send notifications with the predefined parameters - recipients, data, priority, type and other parameters listed in the [API documentation](https://help.sap.com/docs/build-work-zone-standard-edition/sap-build-work-zone-standard-edition/developing-cloud-foundry-applications-with-notifications)

By using this approach you can post a notification by providing different parts of the notification object grouped in related units
```js
alert.notify({
recipients: ["[email protected]","[email protected]"],
type: "IncidentCreated"
recipients: [...supporters()],
type: "IncidentResolved",
priority: 'NEUTRAL',
properties: [
data: {
customer: customer.info,
title: incident.title,
user: cds.context.user.id,
},
OriginId: "Example Origin Id",
NotificationTypeVersion: "1",
ProviderId: "/SAMPLEPROVIDER",
ActorId: "BACKENDACTORID",
ActorDisplayText: "ActorName",
ActorImageURL: "https://some-url",
NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z",
TargetParameters: [
{
Key: 'name',
IsSensitive: false,
Language: 'en',
Value: 'Engine overheating',
Type: 'String'
},
{
Key: 'customer',
IsSensitive: false,
Language: 'en',
Value: 'John',
Type: 'String'
"Key": "string",
"Value": "string"
}
],
navigation: {
NavigationTargetAction: "displayInbox",
NavigationTargetObject: "WorkflowTask",
}
payload: {
Id: "01234567-89ab-cdef-0123-456789abcdef",
OriginId: "Example Origin Id",
NotificationTypeId: "01234567-89ab-cdef-0123-456789abcdef",
NotificationTypeVersion: "1",
ProviderId: "/SAMPLEPROVIDER",
ActorId: "BACKENDACTORID",
ActorDisplayText: "ActorName",
ActorImageURL: "https://some-url",
NotificationTypeTimestamp: "2022-03-15T09:58:42.807Z",
TargetParameters: [
{
"Key": "string",
"Value": "string"
}
]
}
});
});
```

Possible parameters:
* **recipients** - List of the recipients, this argument is mandatory
* **type** - Notification type key, this argument is mandatory
* **priority** - Priority of the notification, this argument is optional, it defaults to NEUTRAL
* **properties** - A key-value pair that is used to fill a placeholder of the notification type template, this argument is optional
* **navigation** - All navigation related parameters, this argument is optional
* **payload** - The rest parameters that can be passed, this argument is optional
#### Passing the whole notification object

##### Passing the whole notification object
By using this approach you need to pass the whole notification object as described in the [API documentation](https://help.sap.com/docs/build-work-zone-standard-edition/sap-build-work-zone-standard-edition/developing-cloud-foundry-applications-with-notifications)

By using this approach you need to pass the whole notification object as described in the API documentation
```js
alert.notify({
NotificationTypeKey: 'IncidentCreated',
Expand All @@ -187,46 +180,22 @@ alert.notify({
Key: 'customer',
IsSensitive: false,
Language: 'en',
Value: 'John',
Value: 'Dave',
Type: 'String'
}
],
Recipients: ["admin1@test.com","admin2@test.com"]
Recipients: [{ RecipientId: "supportuser1@mycompany.com" },{ RecipientId: "supportuser2@mycompany.com" }]
});
```

### Sample Application with notifications

#### In Local Environment
In local environment, when you publish notification, it is mocked to publish the nofication to the console.

<img width="1300" alt="Notify to console" style="border-radius:0.5rem;padding:1rem;background:rgb(24 24 24)" src="_assets/notifyToConsole.png">

#### In Production Environment

##### Notification Destination

As a pre-requisite to publish the notification, you need to have a [destination](https://help.sap.com/docs/build-work-zone-standard-edition/sap-build-work-zone-standard-edition/enabling-notifications-for-custom-apps-on-sap-btp-cloud-foundry#configure-the-destination-to-the-notifications-service) configured to publish the notification. In the `package.json` by default destination name `SAP_Notification` is added, you can modify the destination name that you are configuring.

##### Integrate with SAP Build Work Zone

Once application is deployed and [integrated with SAP Build Work Zone](https://github.com/cap-js/calesi/tree/main/samples/notifications), you can see the notification under fiori notifications icon!

<img width="1300" alt="Sample Application Demo" style="border-radius:0.5rem;" src="_assets/incidentsNotificationDemo.gif">

## Contributing

This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-js/change-tracking/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md).


### Code of Conduct
## Code of Conduct

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone. By participating in this project, you agree to abide by its [Code of Conduct](CODE_OF_CONDUCT.md) at all times.


## Licensing

Copyright 2023 SAP SE or an SAP affiliate company and contributors. Please see our [LICENSE](LICENSE) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available [via the REUSE tool](https://api.reuse.software/info/github.com/cap-js/change-tracking).



Binary file removed _assets/cdsAddNotifications.gif
Binary file not shown.
Binary file modified _assets/incidentsNotificationDemo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified _assets/notifyToConsole.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions lib/notificationTypes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { executeHttpRequest } = require("@sap-cloud-sdk/http-client");
const { buildHeadersForDestination } = require("@sap-cloud-sdk/connectivity");
const { getNotificationDestination, doesKeyExist, getPrefix, getNotificationTypesKeyWithPrefix } = require("./utils");
const { getNotificationDestination, getPrefix, getNotificationTypesKeyWithPrefix } = require("./utils");
const _ = require("lodash");
const NOTIFICATION_TYPES_API_ENDPOINT = "v2/NotificationType.svc";
const cds = require("@sap/cds");
Expand Down Expand Up @@ -49,7 +49,7 @@ function createNotificationTypesMap(notificationTypesJSON, isLocal = false) {
// update the notification type key with prefix
notificationType.NotificationTypeKey = notificationTypeKeyWithPrefix;

if (!doesKeyExist(types, notificationTypeKeyWithPrefix)) {
if (!(notificationTypeKeyWithPrefix in types)) {
types[notificationTypeKeyWithPrefix] = {};
}

Expand Down
37 changes: 0 additions & 37 deletions lib/notifications.js

This file was deleted.

Loading

0 comments on commit 4045d06

Please sign in to comment.