Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add actor to system variables #4278

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
d615902
feat: add actor to system variables
ainouzgali Oct 1, 2023
f94de85
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 1, 2023
1913c8c
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 2, 2023
bc4f4b6
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 2, 2023
1e6a2a0
test: add test for actor variables
ainouzgali Oct 2, 2023
db2791f
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 2, 2023
28882c0
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 2, 2023
01635c0
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 3, 2023
7313f9b
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 3, 2023
9dc75b1
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 5, 2023
2fe1066
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 8, 2023
7788adc
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 10, 2023
5d80ded
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 12, 2023
a49f37d
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 15, 2023
9cdfc3e
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 16, 2023
69c5a47
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
scopsy Oct 19, 2023
b1c57c0
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 22, 2023
7a69d83
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
scopsy Oct 22, 2023
6170039
chore: update lock file
scopsy Oct 22, 2023
72b334c
Merge branch 'next' into nv-2864-actor-variables-are-not-working-in-s…
ainouzgali Oct 23, 2023
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
3 changes: 3 additions & 0 deletions apps/api/src/app/events/dtos/trigger-event-request.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ export class TriggerEventRequestDto {
],
})
@IsOptional()
@ValidateIf((_, value) => typeof value !== 'string')
@ValidateNested()
@Type(() => SubscriberPayloadDto)
actor?: TriggerRecipientSubscriber;

@ApiProperty({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ export class TriggerEventToAllRequestDto {
],
})
@IsOptional()
@ValidateIf((_, value) => typeof value !== 'string')
@ValidateNested()
@Type(() => SubscriberPayloadDto)
actor?: TriggerRecipientSubscriber;

@ApiProperty({
Expand Down
42 changes: 41 additions & 1 deletion apps/api/src/app/events/e2e/trigger-event.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,44 @@ describe(`Trigger event - ${eventTriggerPath} (POST)`, function () {
expect(message!.subject).to.equal('Test email a subject nested');
});

it('should trigger E-Mail notification with actor data', async function () {
const newSubscriberId = SubscriberRepository.createObjectId();
const channelType = ChannelTypeEnum.EMAIL;
const actorSubscriber = await subscriberService.createSubscriber({ firstName: 'Actor' });

template = await session.createTemplate({
steps: [
{
name: 'Message Name',
subject: 'Test email',
type: StepTypeEnum.EMAIL,
content: [
{
type: EmailBlockTypeEnum.TEXT,
content: 'Hello {{actor.firstName}}, Welcome to {{organizationName}}' as string,
},
],
},
],
});

await sendTrigger(session, template, newSubscriberId, {}, {}, '', actorSubscriber.subscriberId);

await session.awaitRunningJobs(template._id);

const createdSubscriber = await subscriberRepository.findBySubscriberId(session.environment._id, newSubscriberId);

const message = await messageRepository.findOne({
_environmentId: session.environment._id,
_subscriberId: createdSubscriber?._id,
channel: channelType,
});

const block = message!.content[0] as IEmailBlock;

expect(block.content).to.equal('Hello Actor, Welcome to Umbrella Corp');
});

it('should not trigger notification with subscriber data if integration is inactive', async function () {
const newSubscriberIdInAppNotification = SubscriberRepository.createObjectId();
const channelType = ChannelTypeEnum.SMS;
Expand Down Expand Up @@ -2442,7 +2480,8 @@ export async function sendTrigger(
newSubscriberIdInAppNotification: string,
payload: Record<string, unknown> = {},
overrides: Record<string, unknown> = {},
tenant?: string
tenant?: string,
actor?: string
): Promise<AxiosResponse> {
return await axiosInstance.post(
`${session.serverUrl}${eventTriggerPath}`,
Expand All @@ -2456,6 +2495,7 @@ export async function sendTrigger(
},
overrides,
tenant,
actor,
},
{
headers: {
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/app/events/events.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export class EventsController {
@Body() body: TriggerEventRequestDto
): Promise<TriggerEventResponseDto> {
const mappedTenant = body.tenant ? this.mapTenant(body.tenant) : null;
const mappedActor = body.actor ? this.mapActor(body.actor) : null;

const result = await this.parseEventRequest.execute(
ParseEventRequestCommand.create({
Expand All @@ -70,7 +71,7 @@ export class EventsController {
payload: body.payload || {},
overrides: body.overrides || {},
to: body.to,
actor: body.actor,
actor: mappedActor,
tenant: mappedTenant,
transactionId: body.transactionId,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class ParseEventRequestCommand extends EnvironmentWithUserCommand {
transactionId?: string;

@IsOptional()
@ValidateNested()
actor?: TriggerRecipientSubscriber | null;

@IsOptional()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export class ProcessBulkTrigger {
for (const event of command.events) {
let result: TriggerEventResponseDto;
const mappedTenant = event.tenant ? this.parseEventRequest.mapTenant(event.tenant) : null;
const mappedActor = event.actor ? this.mapTriggerRecipients.mapSubscriber(event.actor) : null;

try {
result = (await this.parseEventRequest.execute(
Expand All @@ -29,7 +30,7 @@ export class ProcessBulkTrigger {
payload: event.payload,
overrides: event.overrides || {},
to: event.to,
actor: event.actor,
actor: mappedActor,
tenant: mappedTenant,
transactionId: event.transactionId,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ const TriggerTitle = styled(Text)`
`;

export const ExecutionDetailTrigger = ({ identifier, step, subscriberVariables }) => {
const { payload, overrides, tenant } = step || {};
const { payload, overrides, tenant, actorId } = step || {};

const curlSnippet = getCurlTriggerSnippet(identifier, subscriberVariables, payload, overrides, { tenant });
const curlSnippet = getCurlTriggerSnippet(identifier, subscriberVariables, payload, overrides, {
...(tenant && { tenant }),
...(actorId && { actor: { subscriberId: actorId } }),
});

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
IntegrationEntity,
IChannelSettings,
TenantRepository,
SubscriberEntity,
} from '@novu/dal';
import {
ChannelTypeEnum,
Expand Down Expand Up @@ -75,6 +76,13 @@ export class SendMessageChat extends SendMessageBase {
if (!chatChannel?.template) throw new PlatformException('Chat channel template not found');

const tenant = await this.handleTenantExecution(command.job);
let actor: SubscriberEntity | null = null;
if (command.job.actorId) {
actor = await this.getSubscriberBySubscriberId({
subscriberId: command.job.actorId,
_environmentId: command.environmentId,
});
}

let content = '';
const data = {
Expand All @@ -85,6 +93,7 @@ export class SendMessageChat extends SendMessageBase {
total_count: command.events?.length,
},
...(tenant && { tenant }),
...(actor && { actor }),
...command.payload,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
MessageEntity,
LayoutRepository,
TenantRepository,
SubscriberEntity,
} from '@novu/dal';
import {
ChannelTypeEnum,
Expand Down Expand Up @@ -135,6 +136,14 @@ export class SendMessageEmail extends SendMessageBase {
return;
}

let actor: SubscriberEntity | null = null;
if (command.job.actorId) {
actor = await this.getSubscriberBySubscriberId({
subscriberId: command.job.actorId,
_environmentId: command.environmentId,
});
}

const [tenant, overrideLayoutId] = await Promise.all([
this.handleTenantExecution(command.job),
this.getOverrideLayoutId(command),
Expand Down Expand Up @@ -167,6 +176,7 @@ export class SendMessageEmail extends SendMessageBase {
total_count: command.events?.length,
},
...(tenant && { tenant }),
...(actor && { actor }),
subscriber,
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,14 @@ export class SendMessageInApp extends SendMessageBase {

const { actor } = command.step.template;

let actorSubscriber: SubscriberEntity | null = null;
if (command.job.actorId) {
actorSubscriber = await this.getSubscriberBySubscriberId({
subscriberId: command.job.actorId,
_environmentId: command.environmentId,
});
}

const [tenant, organization] = await Promise.all([
this.handleTenantExecution(command.job),
this.organizationRepository.findById(command.organizationId, 'branding'),
Expand All @@ -125,7 +133,8 @@ export class SendMessageInApp extends SendMessageBase {
subscriber,
command,
organization,
tenant
tenant,
actorSubscriber
);

if (inAppChannel.template.cta?.data?.url) {
Expand All @@ -135,7 +144,8 @@ export class SendMessageInApp extends SendMessageBase {
subscriber,
command,
organization,
tenant
tenant,
actorSubscriber
);
}

Expand All @@ -149,7 +159,8 @@ export class SendMessageInApp extends SendMessageBase {
subscriber,
command,
organization,
tenant
tenant,
actorSubscriber
);
ctaButtons.push({ type: action.type, content: buttonContent });
}
Expand Down Expand Up @@ -286,7 +297,8 @@ export class SendMessageInApp extends SendMessageBase {
subscriber: SubscriberEntity,
command: SendMessageCommand,
organization: OrganizationEntity | null,
tenant: TenantEntity | null
tenant: TenantEntity | null,
actor: SubscriberEntity | null
): Promise<string> {
return await this.compileTemplate.execute(
CompileTemplateCommand.create({
Expand All @@ -303,6 +315,7 @@ export class SendMessageInApp extends SendMessageBase {
color: organization?.branding?.color || '#f47373',
},
...(tenant && { tenant }),
...(actor && { actor }),
...payload,
},
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
MessageEntity,
IntegrationEntity,
TenantRepository,
SubscriberEntity,
JobEntity,
} from '@novu/dal';
import {
Expand Down Expand Up @@ -86,11 +87,19 @@ export class SendMessagePush extends SendMessageBase {
total_count: command.events?.length,
};
const tenant = await this.handleTenantExecution(command.job);
let actor: SubscriberEntity | null = null;
if (command.job.actorId) {
actor = await this.getSubscriberBySubscriberId({
subscriberId: command.job.actorId,
_environmentId: command.environmentId,
});
}

const data = {
subscriber: subscriber,
step: stepData,
...(tenant && { tenant }),
...(actor && { actor }),
...command.payload,
};
let content = '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
MessageEntity,
IntegrationEntity,
TenantRepository,
SubscriberEntity,
} from '@novu/dal';
import { ChannelTypeEnum, LogCodeEnum, ExecutionDetailsSourceEnum, ExecutionDetailsStatusEnum } from '@novu/shared';
import {
Expand Down Expand Up @@ -79,6 +80,13 @@ export class SendMessageSms extends SendMessageBase {
const smsChannel: NotificationStepEntity = command.step;
if (!smsChannel.template) throw new PlatformException(`Unexpected error: SMS template is missing`);

let actor: SubscriberEntity | null = null;
if (command.job.actorId) {
actor = await this.getSubscriberBySubscriberId({
subscriberId: command.job.actorId,
_environmentId: command.environmentId,
});
}
const tenant = await this.handleTenantExecution(command.job);

const payload = {
Expand All @@ -89,6 +97,7 @@ export class SendMessageSms extends SendMessageBase {
total_count: command.events?.length,
},
...(tenant && { tenant }),
...(actor && { actor }),
...command.payload,
};

Expand Down
1 change: 1 addition & 0 deletions libs/dal/src/repositories/job/job.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export class JobEntity {
};
type?: StepTypeEnum;
_actorId?: string;
actorId?: string;
}

export type JobDBModel = ChangePropsValueType<
Expand Down
3 changes: 3 additions & 0 deletions libs/dal/src/repositories/job/job.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ const jobSchema = new Schema<JobDBModel>(
type: Schema.Types.ObjectId,
ref: 'Subscriber',
},
actorId: {
type: Schema.Types.String,
},
expireAt: Schema.Types.Date,
},
schemaOptions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export class NotificationRepository extends BaseRepository<
$nin: [StepTypeEnum.TRIGGER],
},
},
select: 'createdAt digest payload overrides to tenant providerId step status type updatedAt',
select: 'createdAt digest payload overrides to tenant actorId providerId step status type updatedAt',
populate: [
{
path: 'executionDetails',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export interface IMessageTemplate {
}

// eslint-disable-next-line @typescript-eslint/naming-convention
export const TemplateSystemVariables = ['subscriber', 'step', 'branding', 'tenant', 'preheader'];
export const TemplateSystemVariables = ['subscriber', 'step', 'branding', 'tenant', 'preheader', 'actor'];

// eslint-disable-next-line @typescript-eslint/naming-convention
export const SystemVariablesWithTypes = {
Expand All @@ -51,6 +51,15 @@ export const SystemVariablesWithTypes = {
locale: 'string',
subscriberId: 'string',
},
actor: {
firstName: 'string',
lastName: 'string',
email: 'string',
phone: 'string',
avatar: 'string',
locale: 'string',
subscriberId: 'string',
},
step: {
digest: 'boolean',
events: 'array',
Expand All @@ -67,9 +76,10 @@ export const SystemVariablesWithTypes = {
};

// eslint-disable-next-line @typescript-eslint/naming-convention
export const TriggerReservedVariables = ['tenant'];
export const TriggerReservedVariables = ['tenant', 'actor'];

// eslint-disable-next-line @typescript-eslint/naming-convention
export const ReservedVariablesMap = {
[TriggerContextTypeEnum.TENANT]: [{ name: 'identifier', type: TemplateVariableTypeEnum.STRING }],
[TriggerContextTypeEnum.ACTOR]: [{ name: 'subscriberId', type: TemplateVariableTypeEnum.STRING }],
};
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export interface INotificationTrigger {

export enum TriggerContextTypeEnum {
TENANT = 'tenant',
ACTOR = 'actor',
}

export interface ITriggerReservedVariable {
Expand Down
Loading
Loading