feat(scheduler): add publishing exit discount withdraw requested event

This commit is contained in:
Karol Sójko
2022-11-03 10:08:52 +01:00
parent f127241857
commit d66f784538
10 changed files with 172 additions and 0 deletions
@@ -36,6 +36,7 @@ import { PredicateVerifiedEventHandler } from '../Domain/Handler/PredicateVerifi
import { VerifyPredicates } from '../Domain/UseCase/VerifyPredicates/VerifyPredicates'
import { UserRegisteredEventHandler } from '../Domain/Handler/UserRegisteredEventHandler'
import { SubscriptionCancelledEventHandler } from '../Domain/Handler/SubscriptionCancelledEventHandler'
import { ExitDiscountAppliedEventHandler } from '../Domain/Handler/ExitDiscountAppliedEventHandler'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const newrelicFormatter = require('@newrelic/winston-enricher')
@@ -124,6 +125,9 @@ export class ContainerConfigLoader {
container
.bind<SubscriptionCancelledEventHandler>(TYPES.SubscriptionCancelledEventHandler)
.to(SubscriptionCancelledEventHandler)
container
.bind<ExitDiscountAppliedEventHandler>(TYPES.ExitDiscountAppliedEventHandler)
.to(ExitDiscountAppliedEventHandler)
// Services
container.bind<DomainEventFactory>(TYPES.DomainEventFactory).to(DomainEventFactory)
@@ -146,6 +150,7 @@ export class ContainerConfigLoader {
['PREDICATE_VERIFIED', container.get(TYPES.PredicateVerifiedEventHandler)],
['USER_REGISTERED', container.get(TYPES.UserRegisteredEventHandler)],
['SUBSCRIPTION_CANCELLED', container.get(TYPES.SubscriptionCancelledEventHandler)],
['EXIT_DISCOUNT_APPLIED', container.get(TYPES.ExitDiscountAppliedEventHandler)],
])
if (env.get('SQS_QUEUE_URL', true)) {
@@ -24,6 +24,7 @@ const TYPES = {
PredicateVerifiedEventHandler: Symbol.for('PredicateVerifiedEventHandler'),
UserRegisteredEventHandler: Symbol.for('UserRegisteredEventHandler'),
SubscriptionCancelledEventHandler: Symbol.for('SubscriptionCancelledEventHandler'),
ExitDiscountAppliedEventHandler: Symbol.for('ExitDiscountAppliedEventHandler'),
// Services
DomainEventPublisher: Symbol.for('DomainEventPublisher'),
DomainEventSubscriberFactory: Symbol.for('DomainEventSubscriberFactory'),
@@ -65,6 +65,29 @@ describe('DomainEventFactory', () => {
})
})
it('should create a EXIT_DISCOUNT_WITHDRAW_REQUESTED event', () => {
expect(
createFactory().createExitDiscountWithdrawRequestedEvent({
userEmail: '[email protected]',
discountCode: 'exit-20',
}),
).toEqual({
createdAt: expect.any(Date),
meta: {
correlation: {
userIdentifier: '[email protected]',
userIdentifierType: 'email',
},
origin: 'scheduler',
},
payload: {
userEmail: '[email protected]',
discountCode: 'exit-20',
},
type: 'EXIT_DISCOUNT_WITHDRAW_REQUESTED',
})
})
it('should create a EMAIL_MESSAGE_REQUESTED event', () => {
expect(
createFactory().createEmailMessageRequestedEvent({
@@ -4,6 +4,7 @@ import {
DiscountWithdrawRequestedEvent,
DomainEventService,
EmailMessageRequestedEvent,
ExitDiscountWithdrawRequestedEvent,
PredicateVerificationRequestedEvent,
} from '@standardnotes/domain-events'
import { PredicateAuthority } from '@standardnotes/predicates'
@@ -51,6 +52,24 @@ export class DomainEventFactory implements DomainEventFactoryInterface {
}
}
createExitDiscountWithdrawRequestedEvent(dto: {
userEmail: string
discountCode: string
}): ExitDiscountWithdrawRequestedEvent {
return {
type: 'EXIT_DISCOUNT_WITHDRAW_REQUESTED',
createdAt: this.timer.getUTCDate(),
meta: {
correlation: {
userIdentifier: dto.userEmail,
userIdentifierType: 'email',
},
origin: DomainEventService.Scheduler,
},
payload: dto,
}
}
createEmailMessageRequestedEvent(dto: {
userEmail: string
messageIdentifier: EmailMessageIdentifier
@@ -3,6 +3,7 @@ import {
DiscountApplyRequestedEvent,
DiscountWithdrawRequestedEvent,
EmailMessageRequestedEvent,
ExitDiscountWithdrawRequestedEvent,
PredicateVerificationRequestedEvent,
} from '@standardnotes/domain-events'
@@ -18,4 +19,8 @@ export interface DomainEventFactoryInterface {
}): EmailMessageRequestedEvent
createDiscountApplyRequestedEvent(dto: { userEmail: string; discountCode: string }): DiscountApplyRequestedEvent
createDiscountWithdrawRequestedEvent(dto: { userEmail: string; discountCode: string }): DiscountWithdrawRequestedEvent
createExitDiscountWithdrawRequestedEvent(dto: {
userEmail: string
discountCode: string
}): ExitDiscountWithdrawRequestedEvent
}
@@ -0,0 +1,40 @@
import 'reflect-metadata'
import { ExitDiscountAppliedEvent } from '@standardnotes/domain-events'
import { TimerInterface } from '@standardnotes/time'
import { JobRepositoryInterface } from '../Job/JobRepositoryInterface'
import { ExitDiscountAppliedEventHandler } from './ExitDiscountAppliedEventHandler'
describe('ExitDiscountAppliedEventHandler', () => {
let timer: TimerInterface
let jobRepository: JobRepositoryInterface
const createHandler = () => new ExitDiscountAppliedEventHandler(timer, jobRepository)
beforeEach(() => {
timer = {} as jest.Mocked<TimerInterface>
timer.getUTCDateNHoursAhead = jest.fn().mockReturnValue(new Date(2))
timer.convertDateToMicroseconds = jest.fn().mockReturnValue(123)
timer.getTimestampInMicroseconds = jest.fn().mockReturnValue(1)
jobRepository = {} as jest.Mocked<JobRepositoryInterface>
jobRepository.save = jest.fn()
})
it('should schedule a job to do an exit discount withdrawal', async () => {
await createHandler().handle({
payload: { userEmail: '[email protected]', discountRate: 20 },
} as jest.Mocked<ExitDiscountAppliedEvent>)
expect(jobRepository.save).toHaveBeenNthCalledWith(1, {
createdAt: 1,
name: 'withdraw-subscription-exit-discount',
scheduledAt: 123,
status: 'pending',
userIdentifier: '[email protected]',
userIdentifierType: 'email',
})
})
})
@@ -0,0 +1,33 @@
import { DomainEventHandlerInterface, ExitDiscountAppliedEvent } from '@standardnotes/domain-events'
import { inject, injectable } from 'inversify'
import { TimerInterface } from '@standardnotes/time'
import TYPES from '../../Bootstrap/Types'
import { Job } from '../Job/Job'
import { JobName } from '../Job/JobName'
import { JobRepositoryInterface } from '../Job/JobRepositoryInterface'
import { JobStatus } from '../Job/JobStatus'
@injectable()
export class ExitDiscountAppliedEventHandler implements DomainEventHandlerInterface {
constructor(
@inject(TYPES.Timer) private timer: TimerInterface,
@inject(TYPES.JobRepository) private jobRepository: JobRepositoryInterface,
) {}
async handle(event: ExitDiscountAppliedEvent): Promise<void> {
await this.scheduleExitDiscountWithdraw(event)
}
private async scheduleExitDiscountWithdraw(event: ExitDiscountAppliedEvent): Promise<void> {
const job = new Job()
job.name = JobName.WITHDRAW_SUBSCRIPTION_EXIT_DISCOUNT
job.scheduledAt = this.timer.convertDateToMicroseconds(this.timer.getUTCDateNHoursAhead(24))
job.createdAt = this.timer.getTimestampInMicroseconds()
job.status = JobStatus.Pending
job.userIdentifier = event.payload.userEmail
job.userIdentifierType = 'email'
await this.jobRepository.save(job)
}
}
@@ -253,6 +253,35 @@ describe('JobDoneInterpreter', () => {
expect(domainEventPublisher.publish).not.toHaveBeenCalled()
})
it('should request exit discount withdraw', async () => {
jobRepository.findOneByUuid = jest.fn().mockReturnValue({
name: JobName.WITHDRAW_SUBSCRIPTION_EXIT_DISCOUNT,
userIdentifier: '[email protected]',
userIdentifierType: 'email',
} as jest.Mocked<Job>)
await createInterpreter().interpret('1-2-3')
expect(domainEventFactory.createExitDiscountWithdrawRequestedEvent).toHaveBeenCalledWith({
userEmail: '[email protected]',
discountCode: 'exit-20',
})
expect(domainEventPublisher.publish).toHaveBeenCalled()
})
it('should not request exit discount withdraw if email is missing', async () => {
jobRepository.findOneByUuid = jest.fn().mockReturnValue({
name: JobName.WITHDRAW_SUBSCRIPTION_EXIT_DISCOUNT,
userIdentifier: '2-3-4',
userIdentifierType: 'uuid',
} as jest.Mocked<Job>)
await createInterpreter().interpret('1-2-3')
expect(domainEventFactory.createExitDiscountWithdrawRequestedEvent).not.toHaveBeenCalled()
expect(domainEventPublisher.publish).not.toHaveBeenCalled()
})
it('should do nothing if there is no interpretation for a given job', async () => {
jobRepository.findOneByUuid = jest.fn().mockReturnValue({
name: 'foobar' as JobName,
@@ -65,6 +65,11 @@ export class JobDoneInterpreter implements JobDoneInterpreterInterface {
await this.requestDiscountWithdraw(job)
}
return
case JobName.WITHDRAW_SUBSCRIPTION_EXIT_DISCOUNT:
if (job.userIdentifierType === 'email') {
await this.requestExitDiscountWithdraw(job)
}
return
default:
this.logger.warn(`[${jobUuid}]${job.name}: job is not interpretable.`)
@@ -132,6 +137,17 @@ export class JobDoneInterpreter implements JobDoneInterpreterInterface {
)
}
private async requestExitDiscountWithdraw(job: Job): Promise<void> {
this.logger.debug(`[${job.uuid}]${job.name}: requesting exit discount withdraw.`)
await this.domainEventPublisher.publish(
this.domainEventFactory.createExitDiscountWithdrawRequestedEvent({
userEmail: job.userIdentifier,
discountCode: 'exit-20',
}),
)
}
private async predicatesAreFulfilled(job: Job): Promise<boolean> {
const predicates = await this.predicateRepository.findByJobUuid(job.uuid)
@@ -5,4 +5,5 @@ export enum JobName {
EXIT_INTERVIEW = 'exit-interview',
APPLY_SUBSCRIPTION_DISCOUNT = 'apply-subscription-discount',
WITHDRAW_SUBSCRIPTION_DISCOUNT = 'withdraw-subscription-discount',
WITHDRAW_SUBSCRIPTION_EXIT_DISCOUNT = 'withdraw-subscription-exit-discount',
}