通知插件
这个 @cap-js/notifications 软件包是一个 CDS 插件 支持在SAP建设工作区内发布业务通知.
目录
设置
所需经费: 节点.js... 20, @sap/cds >=八.
要启用通知, 只需在您的工程中添加此自配置插件包 :
npm add @cap-js/notifications
开始
安装插件后,您可以通过两种方式发送通知:
快速启动: 直接通知
使用 notify()数字 :
const alert = await cds.connect.to("notifications")
await alert.notify({
recipients: ["[email protected]"],
title: "Book Order Received",
description: 'Your order for "Wuthering Heights" is being processed.'
})
建议: 界定通知类型
在服务模式中定义通知事件 @notification数字 :
using { CatalogService } from './cat-service';
extend service CatalogService with {
@notification: {
title: 'Book {{title}} Ordered',
subtitle: '{{buyer}} ordered {{title}}'
}
event BookOrdered {
title : String;
buyer : String;
}
}
从您的服务处理器中释放事件 :
this.on("submitOrder", async req => {
// ... process order ...
await this.emit("BookOrdered", {
title: book.title,
buyer: req.user.id,
recipients: ["[email protected]"]
})
})
插件拦截事件并自动发送通知. 在当地开发期间,通知会被打印到控制台. 不需要 BTP 连接 .
运行样本
本节使用本寄存器中包含的书店样本.
1. 启动样本应用
cd tests/bookshop
npm install
cds watch
服务器开始于 http://localhost:4004 (英语)。在本地开发过程中,插件将通知打印到控制台,因此尚不需要BTP账户.
2. 触发通知
书店 submitOrder 动作减少账本存量并输出 a BookOrderedNotify 活动。 插件截取该事件并发送通知 .
打开 tests/bookshop/test/http/CatalogService.http 在VS代码中并单击 发送请求 上层 submitOrder 块。 此文件有服务器 URL 和预配置的证书 .
在服务器控制台中, 您可以看到打印的通知, 以确认通知成功 .
3. 自定义通知类型
打开 tests/bookshop/srv/notifications.cds此文件定义了 BookOrderedNotify 及其所有活动 @notification 说明。 更改字幕模板以包含数量 :
// Before
subtitle: '{i18n>BOOK_ORDERED_SUBTITLE}',
// After
subtitle: '{{buyer}} ordered {{quantity}}x {{title}}',
保存文件并 cds watch 自动重装。 再次发送请求,更新后字幕出现在控制台输出中. 从这里开始,尝试调整优先级表达式,添加一个 @description,或探索活动的其他说明.
4. 连接SAP建设区
要看到通知出现在工作区,需要配置SAP建设工作区的BTP子账户和SAP警报通知服务.
- 跟着 SAP 构建工作区设置指南 以订阅服务并配置所需的
SAP_Notifications目标在您的子账户中 . - 用 CF 将本地环境绑入目的服务实例
cds bind运行cds watch --profile hybrid从本地机器连接到 BTP 目的地.
启动时, 插件自动注册您的通知类型 。 提交命令后,将向工作区内的铃声发送通知,通知接收者.
[!注] 书店样本默认使用程序内通知. 工作区铃声图标显示由SAP BTP全球用户ID(UUID)识别的收件人的通知. 为了测试电子邮件的发送,还需要额外的设置。 关于启用,见 电子邮件发送 财务报告和审定财务报表 默认邮件发送。关于所需的BTP配置,请参见 SMTP 邮件目的地指南。 。 。 .
定义通知类型
通知的依据是: 通知类型:定义通知外观的模板,包括标题、字幕和电子邮件内容。 这些类型可以有两种方式定义,两种类型都可以一起使用,并在启动时被合并.
备选案文A:CDS说明(建议)
建议的做法是,在服务模式中直接界定通知类型,对事件进行注解 @notification。插件在启动时自动发现并注册它们.
在您定义一个事件 srv/ 模式 :
using { CatalogService } from './cat-service';
extend service CatalogService with {
@description: 'Sent when a book is ordered'
@notification: {
title : 'Book {{title}} Ordered',
publicTitle : 'Book Ordered',
subtitle : '{{buyer}} ordered {{title}}',
groupedTitle : 'Bookshop Updates'
}
@Common.SemanticObject: 'Books'
@Common.SemanticObjectAction: 'display'
event BookOrdered {
title : String;
buyer : String;
}
}
至少有一个事件 @notification 注释(赤色) @notification 旗帜或任何 @notification.* 正在取回。 通知类型密钥取自事件名称. 命名空间前缀被剥去, my.bookshop.BookOrdered 变成 BookOrdered。 。 。 .
[!注] 插件自动注入 a
recipients元素在模型装入时间进入每个通知事件;您不需要亲自声明.
[重要] 事件必须包含在服务中,要么直接在服务中定义事件
service或通过使用extend service编号 :using将它纳入现有的一个.
[!注] 说明也可以使用标准 CDS 放在单独的文件中
annotate指令.
共同说明:
@notification: {
title : 'Book {{title}} Ordered',
publicTitle : 'Book Ordered',
subtitle : '{{buyer}} ordered {{title}}',
groupedTitle : 'Bookshop Updates', // Group header for multiple notifications
email: {
subject: 'Your order: {{title}}',
html : './email-template.html' // Path to HTML template or inline HTML
},
priority: #HIGH // Priority: LOW, NEUTRAL, MEDIUM, HIGH
}
event BookOrdered { ... }
关于支持的说明及其绘图的完整清单,见 注释。 。 。 .
交付渠道(仅选择A)
使用 @notification.channels 指定通过下列方式发送通知类型的渠道:
@notification: {
title : 'Book Ordered',
channels: ['email']
}
event BookOrdered { ... }
支持的值为: email (SAP邮件)和 workzone (SAP 建设工作区). 如果没有指定频道,频道默认值为 cds.env.requires.notifications.channels,或 workzone 如果没有设置.
i18n 支持(仅选项A)
这个 @notification 注释值支持 {i18n>key} 语法. 在启动时, 密钥会自动解决您的项目的 i18n 捆绑 。 在至少一个翻译与默认语言不同的地方,每个语言都会生成模板.
@notification.title: '{i18n>BOOK_ORDERED_TITLE}'
@notification.subtitle: '{i18n>BOOK_ORDERED_SUBTITLE}'
event BookOrdered { ... }
HTML 电子邮件模板( 只有选项 A)
这个 email.html 注释接受内含的 HTML 字符串或路径 .html 文件相对 .cds 来源文件. 文件在启动时被读取,其中的i18n占位符被解决.
@notification: {
email: {
subject: 'Your order: {{title}}',
html : './book-ordered-email.html'
}
}
event BookOrdered { ... }
优先权(仅选择A)
通知可分配不同的优先级别: LOW, (中文(简体) ), NEUTRAL (违约), MEDIUM,或 HIGH这些优先事项影响在SAP建设区如何显示和排序通知.
优先事项可以静态设定,使用 # enum值,或动态使用 CDS 表达式语言( CXL) 在运行时评估条件.
静态优先 :
@notification.priority: #HIGH
event BookOrdered { ... }
动态优先级 :
优先级可以在运行时从使用根据数据库评估的 CDS 三进制表达式的事件数据中计算:
@notification.priority: (quantity > 5 ? #HIGH : #LOW)
event BookOrdered {
quantity : Integer;
title : String;
}
使用 CDS 函数的复杂表达式也被支持:
@notification.priority: (days_between(orderDate, deliveryDate) > 7 ? #HIGH : #LOW)
event LateDelivery {
orderDate : Date;
deliveryDate : Date;
}
动态优先级需要通过 this.emit(...) 因此插件可以截取并评价.
建立一体化
运行 cds build 全部进程 @notification 附加说明的事件并生成合并 notification-types.json 转到构建输出,将CDS注释中的类型与JSON文件中的任何类型合并.
备选案文B:JSON文件
另一种办法是静态地在 srv/notification-types.json 或自定义路径(参见 自定义通知类型路径:
[
{
"NotificationTypeKey": "BookOrdered",
"NotificationTypeVersion": "1",
"Templates": [
{
"Language": "en",
"TemplatePublic": "Book Ordered",
"TemplateSensitive": "Book '{{title}}' Ordered",
"TemplateGrouped": "Bookshop Updates",
"TemplateLanguage": "mustache",
"Subtitle": "{{buyer}} ordered {{title}}."
}
]
}
]
[!注] i18n 分辨率、 HTML 文件路径和优先级说明(
@notification.priority),只有在使用CDS说明(备选A)时才可用. JSON文件格式使用预解字符串.
电子邮件发送
在这两种方法中,电子邮件发送都可以用于通知类型。 它要求SAP警报通知处与 business-notifications 计划和配置 SMTP 邮件目的地。 。 。 .
[! 警告] 这个
business-notifications计划验证 全部 您在注册时间的通知类型, 不仅仅是有电子邮件的。 这意味着你的应用程序中的每一个通知类型,即使是纯粹的应用程序,都必须有TemplatePublic(从publicTitle和TemplateGrouped(从groupedTitle)设置,或启动注册会失败.
Via CDS 说明 :
@notification: {
title : 'Book {{title}} Ordered',
publicTitle : 'Book Ordered',
subtitle : '{{buyer}} ordered {{title}}',
groupedTitle : 'Bookshop Updates',
email: {
subject: 'Your order: {{title}}',
html : './book-ordered-email.html'
},
channels: ['email']
}
event BookOrdered { ... }
维娅·杰森:
{
"NotificationTypeKey": "BookOrdered",
"Templates": [
{
"Language": "en",
"TemplatePublic": "Book Ordered",
"TemplateSensitive": "Book '{{title}}' Ordered",
"TemplateGrouped": "Bookshop Updates",
"TemplateLanguage": "mustache",
"EmailSubject": "Your order: {{title}}",
"EmailHtml": "<p>Thanks for ordering <b>{{title}}</b>!</p>"
}
],
"DeliveryChannels": [{ "Type": "MAIL", "Enabled": true, "DefaultPreference": true, "EditablePreference": true }]
}
说明:
Enabled, (中文(简体) ),DefaultPreference,以及EditablePreference需要ANS字段。 使用上面显示的数值而不更改它们 .
发送通知
发送通知有两种模式.
图案1:释放CDS事件(建议)
如果您将您的通知类型定义为带有 CDS 事件的 CDS @notification 注释,插件自动勾入您的服务。 从你的服务管理者那里释放这个事件.
this.on("submitOrder", async req => {
const book = await SELECT.one.from("Books").where({ ID: req.data.book })
await this.emit("BookOrdered", {
title: book.title,
buyer: req.user.id,
recipients: ["[email protected]"]
})
})
插件注册事件处理器, 将通知转发给 ANS 。 如果您需要自己处理事件, 您仍然可以注册自己的事件处理器 。 插件的处理器和它们一起运行 .
图案2:呼叫通知( )
您也可以连接到通知服务并拨打 notify() 直接说 这与预先确定的通知类型或不存在.
简单通知 (不需要预先定义的类型):
const alert = await cds.connect.to("notifications")
await alert.notify({
recipients: [...readers()],
priority: "HIGH",
title: "New book arrived!",
description: "Book 'Wuthering Heights' has been added to the catalog."
})
[!注] 简单的 API 只支持
recipients, (中文(简体) ),priority, (中文(简体) ),title,以及description对于高级属性,使用命名的通知类型或 低级 API。 。 。 .
命名的通知类型 :
await alert.notify("BookOrdered", {
recipients: [buyer.id],
data: {
title: book.title,
buyer: buyer.name
}
})
批量通知
可以通过数组 notify() 在一个呼叫中发出多个通知。 这只触发一个发件箱事件,在通知许多收件人时减少交易次数. 如果有些项目失败,成功的项目仍然交付。 失败者会被记录为警告,只有 全部 项目失败.
alert.notify("BookOrdered", [
{ recipients: [buyer1.id], data: { title: book.title, buyer: buyer1.name } },
{ recipients: [buyer2.id], data: { title: book.title, buyer: buyer2.name } }
])
[! 警告] 批次发送只能通过
notify([...]). CDS事件的排放发送一次呼叫.
或者,可以使用默认的通知模板:
await alert.notify([
{ type: "BookOrdered", recipients: [buyer1.id], data: { title: book1.title, buyer: buyer1.name } },
{ type: "BookOrdered", recipients: [buyer2.id], data: { title: book2.title, buyer: buyer2.name } }
])
实体通知
当实体数据被读取或更改时,实体通知允许您声明火灾通知,而不写任何处理器代码. 添加一个 @notifications 直接给一个CDS实体的注释,数组中的每个条目定义一个通知:
service CatalogService {
@notifications: [{
type : 'BookOrdered',
on : ['READ'],
recipients: ($self.createdBy),
where : ($self.stock < 5),
priority : #High
}]
entity Books as projection on my.Books;
}
注释属性
| 财产 | 需求 | 说明 |
|---|---|---|
type | 对 | 此通知类型的名称( 如“ BookOrdered ”) 。 插件自动注册 . |
on | 对 | 需要收听的 CDS 事件列表 : 'READ', (中文(简体) ), 'CREATE', (中文(简体) ), 'UPDATE' |
recipients | 对 | 实地参考(例如:. $self.createdBy)或字面收件人标识符 |
where | 没有 | 过滤表达式: 只有匹配此条件的实体点出通知 |
priority | 没有 | #Low, (中文(简体) ), #Neutral, (中文(简体) ), #Medium,或 #High |
parameters | 没有 | 明确将通知模板占位符映射到实体域 |
通知属性
默认情况下,所有实体字段都转到通知模板. 使用 parameters 仅映射特定字段:
@notifications: [{
type : 'BookOrdered',
on : ['READ'],
recipients: ($self.createdBy),
parameters: { bookTitle: $self.title, bookId: $self.ID }
}]
entity Books as projection on my.Books;
由此产生一份通知,其中只有 bookTitle 财务报告和审定财务报表 bookId 属性设置,匹配通知类型模板中的占位符.
API 参考
简单通知
对于 notify({ recipients, title, ... }),不需要预先定义的通知类型。 插件使用内置 Default 模板.
| 参数 | 需求 | 说明 |
|---|---|---|
recipients | 对 | 接收者标识符组:电子邮件地址或SAP BTP 全球用户ID(UUID) |
title | 对 | 通知标题字符串 |
priority | 没有 | LOW, (中文(简体) ), NEUTRAL (违约), MEDIUM,或 HIGH |
description | 没有 | 副标题文本 |
命名的通知类型
对于 notify('TypeKey', payload) 或者说 notify({ type: 'TypeKey', ... }),则使用预定义的通知类型发送通知.
| 参数 | 需求 | 说明 |
|---|---|---|
recipients | 对 | 接收者标识符组:电子邮件地址或SAP BTP 全球用户ID(UUID) |
type | 对 | 通知类型密钥( 如 ). 'BookOrdered'(中文(简体) ) |
data | 没有 | 用于在类型模板中填充胡子占位符的密钥值配对 |
priority | 没有 | LOW, (中文(简体) ), NEUTRAL (违约), MEDIUM,或 HIGH |
说明: 收件人可以是电子邮件地址(例如.
[email protected])或SAP BTP Global用户ID(UUID格式,例如.a1b2c3d4-...) (中文(简体) ). 单位auto模式(默认),插件检测每个收件人的格式并自动使用正确的密钥。 见 认证标识符 详细情况.
验证
- 财产价值 不得超过 255 个字符。更长的数值导致通知被拒绝.
- 目标参数值 长于 250个字符 默然放弃.
- 事件元素名称 不得超过 128个字符被抓到的侵权行为
cds build时间.
注释
对通知字段的 CDS 说明的完整映射 :
| 注释 | ANS 战地 | 说明 |
|---|---|---|
@description | Description | 通知类型说明 |
@notification.title | TemplateSensitive | 主要通知标题( 支持占位符) |
@notification.publicTitle | TemplatePublic | 公共退职头衔 |
@notification.subtitle | Subtitle | 副标题文本 |
@notification.groupedTitle | TemplateGrouped | 多个通知的组头 |
@notification.email.subject | EmailSubject | 电子邮件主题行 |
@notification.email.html | EmailHtml | 内嵌 HTML 或路径到 .html 文件 |
@Common.SemanticObject | NavigationTargetObject | 导航目标对象 |
@Common.SemanticObjectAction | NavigationTargetAction | 导航动作 |
@notification.priority | Priority | LOW, (中文(简体) ), NEUTRAL, (中文(简体) ), MEDIUM,或 HIGH |
本地测试驱动
在当地开发期间,通知被嘲笑并被印刷到控制台. 不需要外部服务.
在生产中运行
通知目标
作为先决条件,配置 目标 名称 SAP_Notifications 在您的 BTP 子账户中。 该插件默认使用此目的地在混合和生产环境中连接到通知服务.
通知类型登记
通知类型在每次申请启动时都会自动注册,并与通知服务同步. 通知类型的任何添加、更改或清除,无论是从CDS说明还是JSON文件中,都应用在下次启动时。 无手册 cds build 或内容部署步骤.
与SAP建设区一体化
一旦应用程序被部署并融入SAP建设工作区,通知就会出现在Fiori通知图标下.
高级使用
自定义通知类型路径
插件读取 srv/notification-types.json 作为默认 JSON 类型文件。 要使用不同的路径 :
"cds": {
"requires": {
"notifications": {
"types": "srv/my-notification-types.json"
}
}
}
自定义通知类型前缀
要让每个应用程序都独有通知类型密钥,插件会用应用程序名前缀它们 package.json 默认。 要使用自定义前缀 :
"cds": {
"requires": {
"notifications": {
"prefix": "my-custom-prefix"
}
}
}
自定义目标名称
覆盖默认值 SAP_Notifications 目标名称 :
"cds": {
"requires": {
"notifications": {
"destination": "MY_CUSTOM_DESTINATION"
}
}
}
认证标识符
cds.env.requires.notifications.authenticationIdentifier 控制在发布通知时使用的收件人密钥.
auto(默认):每个收件人选择收件人的密钥. UUID格式的值作为SAP BTP Global User ID处理并发布GlobalUserId; 其它所有内容都与RecipientId。如果一个值既不是UUID,也不是电子邮件地址,则会登录警告。 这样可以将UUID和电子邮件地址混合在同一处recipients没有配置的阵列.UserUUID: 总是使用GlobalUserId。当工作区认证标识符设定为User ID。 。 。 .RecipientId: 总是使用RecipientId。当收件人通过电子邮件或登录名称识别时使用此选项.
[注] 对于使用用户ID发送的电子邮件通知,必须配置身份目录服务(IDS)的目的地,用于电子邮件地址查询.
关于工作区认证标识符配置,见 工作区子账户设置。 。 。 .
默认通道
默认情况下,所有通知类型都使用工作区通道. 更改所有类型的默认值 channels 注释, 设定 channels 在配置中:
"cds": {
"requires": {
"notifications": {
"channels": ["email"]
}
}
}
还支持多个频道:
"notifications": {
"channels": ["email", "workzone"]
}
每起事件 channels 说明总是优先于这一全球缺省.
发件箱行为
默认情况下,通知服务使用发件箱(outbox: true: notify() 将信件排入队列后立即解析,而不是发送到 ANS 时。 这意味着ANS的HTTP响应没有被返回. 要同步发送并接收 HTTP 响应 :
"cds": {
"requires": {
"notifications": {
"outbox": false
}
}
}
关闭插件
要禁用插件而不移除, 设置 enabled: false数字 :
"cds": {
"requires": {
"notifications": {
"enabled": false
}
}
}
这阻止了插件注册其不会自动生成的钩子 this.emit() 拦截,没有通知类型的注册,也没有建造任务. 直接电话: cds.connect.to('notifications').notify() 不受此旗帜的影响.
低级通知 API
为全面控制起见,可直接通过该附件所述的完整通知对象 ANS API 文档。 。 。 .
有个别参数
alert.notify({
recipients: [...readers()],
type: "BookOrdered",
priority: "NEUTRAL",
data: {
title: book.title,
buyer: buyer.name
},
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: "string", Value: "string" }] //tell Work Zone which record to open when the user clicks on the notification
})
传递全部通知对象
alert.notify({
NotificationTypeKey: "BookOrdered",
NotificationTypeVersion: "1",
Priority: "NEUTRAL",
Properties: [
{ Key: "title", IsSensitive: false, Language: "en", Value: "Wuthering Heights", Type: "String" },
{ Key: "buyer", IsSensitive: false, Language: "en", Value: "[email protected]", Type: "String" }
],
Recipients: [{ RecipientId: "[email protected]" }, { RecipientId: "[email protected]" }]
})
捐款
此项目可通过下列方式对特性请求/建议、错误报告等开放: GitHub 问题鼓励并始终欢迎各方作出贡献和反馈。 关于如何作出贡献的更多信息,项目结构以及额外贡献信息见我们 贡献准则。 。 。 .
行为守则
作为成员、贡献者和领导人,我们保证使参加我们的社区成为每个人不受骚扰的经历。 通过参与这个项目,你同意遵守 行为守则 在任何时间.
许可证发放
版权2026 SAP SE或SAP下属公司和贡献者. 请看我们的 自由主义 版权和许可证信息。 详细信息,包括第三方组成部分及其许可证/版权信息 通过REUSE工具。 。 。 .