Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
annarhughes committed Jun 4, 2024
1 parent e0470ad commit cd5ffab
Show file tree
Hide file tree
Showing 13 changed files with 146 additions and 116 deletions.
4 changes: 2 additions & 2 deletions src/api/crisp/crisp-api.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export interface CrispProfileCustomFields {
course_dbr_sessions?: string;
course_iaro?: string;
course_iaro_sessions?: string;
course_rtr?: string;
course_rtr_sessions?: string;
course_rtar?: string;
course_rtar_sessions?: string;
course_rryts?: string;
course_rryts_sessions?: string;
course_ma?: string;
Expand Down
4 changes: 2 additions & 2 deletions src/api/mailchimp/mailchimp-api.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export interface ListMemberCustomFields {
C_DBR_S?: string;
C_IARO?: string;
C_IARO_S?: string;
C_RTR?: string;
C_RTR_S?: string;
C_RTAR?: string;
C_RTAR_S?: string;
C_RRYTS?: string;
C_RRYTS_S?: string;
C_MA?: string;
Expand Down
18 changes: 12 additions & 6 deletions src/api/mailchimp/mailchimp-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ mailchimp.setConfig({
server: mailchimpServerPrefix,
});

export async function getEmailMD5Hash(email: string) {
export function getEmailMD5Hash(email: string) {
return createHash('md5').update(email).digest('hex');
}

Expand All @@ -22,13 +22,15 @@ export async function ping() {
console.log(response);
}

export async function createMailchimpProfile(profileData: Partial<UpdateListMemberRequest>) {
export const createMailchimpProfile = async (
profileData: Partial<UpdateListMemberRequest>,
): Promise<ListMember> => {
try {
return await mailchimp.lists.addListMember(mailchimpAudienceId, profileData);
} catch (error) {
throw new Error(`Create mailchimp profile API call failed: ${error}`);
}
}
};

// Note getMailchimpProfile is not currently used
export const getMailchimpProfile = async (email: string): Promise<ListMember> => {
Expand All @@ -44,21 +46,25 @@ export const updateMailchimpProfile = async (
email: string,
): Promise<ListMember> => {
try {
return await mailchimp.lists.updateListMember(mailchimpAudienceId, getEmailMD5Hash(email), {
return await mailchimp.lists.updateListMember(
mailchimpAudienceId,
getEmailMD5Hash(email),
newProfileData,
});
);
} catch (error) {
throw new Error(`Update mailchimp profile API call failed: ${error}`);
}
};

export const createMailchimpMergeField = async (
name: string,
tag: string,
type: MAILCHIMP_MERGE_FIELD_TYPES,
): Promise<ListMember> => {
try {
return await mailchimp.lists.addListMergeField(mailchimpAudienceId, {
name,
tag,
type,
required: false,
});
Expand All @@ -79,7 +85,7 @@ export const deleteCypressMailchimpProfiles = async () => {
try {
const cypressProfiles = (await mailchimp.lists.getSegmentMembersList(
mailchimpAudienceId,
'874073',
'5101590',
)) as { members: ListMember[] };

cypressProfiles.members.forEach(async (profile: ListMember) => {
Expand Down
4 changes: 2 additions & 2 deletions src/partner-access/partner-access.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class PartnerAccessService {
async validatePartnerAutomaticAccessCode(partnerId: string) {
const partner = await this.partnerRepository.findOne({
where: { id: partnerId },
relations: { partnerFeature: true },
relations: { partnerFeature: { feature: true } },
});

if (!partner) {
Expand All @@ -109,7 +109,7 @@ export class PartnerAccessService {
(pf) => pf.feature.name === FEATURES.AUTOMATIC_ACCESS_CODE,
);

if (!automaticAccessCodePartnerFeature) {
if (!automaticAccessCodePartnerFeature || !partner.partnerFeature) {
throw new HttpException(
'Partner does not have automatic access code Feature',
HttpStatus.BAD_REQUEST,
Expand Down
11 changes: 7 additions & 4 deletions src/session-user/session-user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ export class SessionUserService {
courseUser: CourseUserEntity,
course: CourseEntity,
): Promise<CourseUserEntity> {
const userSessionIds = courseUser.sessionUser.map((sessionUser) => {
const userSessionIds = courseUser.sessionUser?.map((sessionUser) => {
if (sessionUser.completed) return sessionUser.sessionId;
});

const courseSessionIds = course.session.map((session) => {
const courseSessionIds = course.session?.map((session) => {
if (session.status === STORYBLOK_STORY_STATUS_ENUM.PUBLISHED) return session.id;
});

Expand Down Expand Up @@ -178,7 +178,7 @@ export class SessionUserService {
sessionUser.completedAt = completed ? new Date() : null;
await this.sessionUserRepository.save(sessionUser);

courseUser.sessionUser.map((su) => {
courseUser.sessionUser?.map((su) => {
if (su.sessionId === id) {
su.completed = completed;
}
Expand All @@ -195,7 +195,10 @@ export class SessionUserService {
}

// Attach data to object to be serialized for response
const course = await this.courseRepository.findOneBy({ id: courseId });
const course = await this.courseRepository.findOne({
where: { id: courseId },
relations: { session: true },
});
courseUser = await this.checkCourseIsComplete(courseUser, course);
courseUser.course = course;
const formattedResponse = formatCourseUserObjects([courseUser])[0];
Expand Down
35 changes: 1 addition & 34 deletions src/user/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { HttpException, HttpStatus } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { createCrispProfile, updateCrispProfile } from 'src/api/crisp/crisp-api';
import { createMailchimpProfile } from 'src/api/mailchimp/mailchimp-api';
import { PartnerAccessEntity } from 'src/entities/partner-access.entity';
import { PartnerEntity } from 'src/entities/partner.entity';
import { SubscriptionUserService } from 'src/subscription-user/subscription-user.service';
Expand Down Expand Up @@ -134,19 +133,7 @@ describe('UserService', () => {
person: { nickname: user.user.name, locales: [user.user.signUpLanguage] },
segments: ['public'],
});
expect(createMailchimpProfile).toHaveBeenCalledWith({
email_address: user.user.email,
language: user.user.signUpLanguage,
status: 'subscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
enabled: false,
},
],
merge_fields: { NAME: user.user.name },
});
expect(updateCrispProfile).toHaveBeenCalled();
});

it('when supplied with user dto and partner access code, it should return a new partner user', async () => {
Expand Down Expand Up @@ -191,26 +178,6 @@ describe('UserService', () => {
},
'user@email.com',
);
expect(createMailchimpProfile).toHaveBeenCalledWith({
email_address: user.user.email,
language: 'en',
status: 'subscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
enabled: true,
},
],
merge_fields: {
NAME: 'name',
PARTNERS: 'bumble',
THERREMAIN: 5,
THERREDEEM: 1,
FEATTHER: 'true',
FEATCHAT: 'true',
},
});
});

it('when supplied with user dto and partner access that has already been used, it should return an error', async () => {
Expand Down
13 changes: 7 additions & 6 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,17 @@ export class UserService {
? SIGNUP_TYPE.PARTNER_USER_WITHOUT_CODE
: SIGNUP_TYPE.PUBLIC_USER;

let partnerAccess: PartnerAccessEntity | null = null;
const partner = partnerId ? await this.partnerRepository.findOneBy({ id: partnerId }) : null;

try {
let partnerAccess: PartnerAccessEntity;
let partner: PartnerEntity;

if (signUpType === SIGNUP_TYPE.PARTNER_USER_WITHOUT_CODE) {
await this.partnerAccessService.validatePartnerAutomaticAccessCode(partnerId);
partner = await this.partnerRepository.findOneBy({ id: partnerId });
}
if (signUpType === SIGNUP_TYPE.PARTNER_USER_WITH_CODE) {
partnerAccess = await this.partnerAccessService.getPartnerAccessByCode(partnerAccessCode);
partner = partnerAccess.partner;
}

const firebaseUser = await this.authService.createFirebaseUser(email, password);
Expand All @@ -73,6 +75,7 @@ export class UserService {
null,
user.id,
);

this.logger.log(`Create user: (no access code) created partner user in db. User: ${email}`);
} else if (signUpType === SIGNUP_TYPE.PARTNER_USER_WITH_CODE) {
// Assign the existing partner access to new user
Expand All @@ -85,13 +88,11 @@ export class UserService {
this.logger.log(`Create user: created public user in db. User: ${email}`);
}

// Create profiles for external services
createServiceUserProfiles(user, partner, partnerAccess);
this.logger.log(`Create user: updated crisp profile ${email}`);

const userDto = formatUserObject({
...user,
...(partnerAccess && { partnerAccess: [partnerAccess] }),
...(partnerAccess && { partnerAccess: [{ ...partnerAccess, partner }] }),
});
return userDto;
} catch (error) {
Expand Down
4 changes: 4 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ export const respondIoDeleteContactWebhook = getEnv(
);

export const mailchimpApiKey = getEnv(process.env.MAILCHIMP_API_KEY, 'MAILCHIMP_API_KEY');
export const mailchimpMarketingPermissionId = getEnv(
process.env.MAILCHIMP_MARKETING_PERMISSION_ID,
'MAILCHIMP_MARKETING_PERMISSION_ID',
);
export const mailchimpAudienceId = getEnv(
process.env.MAILCHIMP_AUDIENCE_ID,
'MAILCHIMP_AUDIENCE_ID',
Expand Down
2 changes: 1 addition & 1 deletion src/utils/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const formatPartnerAccessObjects = (partnerAccessObjects: PartnerAccessEn
therapySessionsRedeemed: partnerAccess.therapySessionsRedeemed,
partner: partnerAccess.partner ? formatPartnerObject(partnerAccess.partner) : null,
therapySessions:
partnerAccess.therapySession.length === 0
partnerAccess.therapySession?.length === 0
? []
: partnerAccess.therapySession?.map((ts) => {
return {
Expand Down
43 changes: 32 additions & 11 deletions src/utils/serviceUserProfiles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
mockPartnerEntity,
mockUserEntity,
} from 'test/utils/mockData';
import { SIMPLYBOOK_ACTION_ENUM } from './constants';
import { SIMPLYBOOK_ACTION_ENUM, mailchimpMarketingPermissionId } from './constants';
import {
createMailchimpCourseMergeField,
createServiceUserProfiles,
Expand Down Expand Up @@ -50,6 +50,11 @@ describe('Service user profiles', () => {
marketing_permission: mockUserEntity.contactPermission,
service_emails_permission: mockUserEntity.serviceEmailsPermission,
signed_up_at: mockUserEntity.createdAt.toISOString(),
feature_live_chat: true,
feature_therapy: false,
partners: '',
therapy_sessions_redeemed: 0,
therapy_sessions_remaining: 0,
},
mockUserEntity.email,
);
Expand All @@ -60,14 +65,19 @@ describe('Service user profiles', () => {
status: 'subscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
marketing_permission_id: mailchimpMarketingPermissionId,
text: 'Email',
enabled: mockUserEntity.contactPermission,
},
],
merge_fields: {
SIGNUPD: mockUserEntity.createdAt.toISOString(),
NAME: mockUserEntity.name,
FEATCHAT: 'true',
FEATTHER: 'false',
PARTNERS: '',
THERREMAIN: 0,
THERREDEEM: 0,
},
});
});
Expand Down Expand Up @@ -103,8 +113,8 @@ describe('Service user profiles', () => {
status: 'subscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
marketing_permission_id: mailchimpMarketingPermissionId,
text: 'Email',
enabled: mockUserEntity.contactPermission,
},
],
Expand Down Expand Up @@ -138,8 +148,8 @@ describe('Service user profiles', () => {
status: 'subscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
marketing_permission_id: mailchimpMarketingPermissionId,
text: 'Email',
enabled: mockUserEntity.contactPermission,
},
],
Expand Down Expand Up @@ -172,8 +182,8 @@ describe('Service user profiles', () => {
status: 'unsubscribed',
marketing_permissions: [
{
marketing_permission_id: '874073',
text: 'Marketing Permissions',
marketing_permission_id: mailchimpMarketingPermissionId,
text: 'Email',
enabled: false,
},
],
Expand Down Expand Up @@ -478,10 +488,21 @@ describe('Service user profiles', () => {
});

describe('createMailchimpCourseMergeField', () => {
it('should update crisp and mailchimp profile course data', async () => {
it('should create mailchimp course merge field', async () => {
await createMailchimpCourseMergeField('Full course name');

expect(createMailchimpMergeField).toHaveBeenNthCalledWith(1, 'C_FCN', 'text');
expect(createMailchimpMergeField).toHaveBeenNthCalledWith(
1,
'Course FCN Status',
'C_FCN',
'text',
);
expect(createMailchimpMergeField).toHaveBeenNthCalledWith(
2,
'Course FCN Sessions',
'C_FCN_S',
'text',
);
});
});
});
Loading

0 comments on commit cd5ffab

Please sign in to comment.