Skip to content

Commit

Permalink
fix: show different mails for non registered users
Browse files Browse the repository at this point in the history
  • Loading branch information
yxuo committed Feb 2, 2024
1 parent 4e2ab9f commit 4fed666
Show file tree
Hide file tree
Showing 13 changed files with 271 additions and 108 deletions.
1 change: 1 addition & 0 deletions src/config/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
enum Environment {
Development = 'development',
Production = 'production',
Local = 'local',
Test = 'test',
}

Expand Down
114 changes: 63 additions & 51 deletions src/cron-jobs/cron-jobs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { CronJob, CronJobParameters } from 'cron';
import { CoreBankService } from 'src/core-bank/core-bank.service';
import { JaeService } from 'src/jae/jae.service';
import { InviteStatus } from 'src/mail-history-statuses/entities/mail-history-status.entity';
import { InviteStatusEnum } from 'src/mail-history-statuses/mail-history-status.enum';
import { MailHistory } from 'src/mail-history/entities/mail-history.entity';
import { MailHistoryService } from 'src/mail-history/mail-history.service';
Expand All @@ -12,6 +13,7 @@ import { appSettings } from 'src/settings/app.settings';
import { SettingEntity } from 'src/settings/entities/setting.entity';
import { ISettingData } from 'src/settings/interfaces/setting-data.interface';
import { SettingsService } from 'src/settings/settings.service';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import {
formatErrorMessage as formatErrorLog,
Expand All @@ -28,7 +30,7 @@ export enum CrobJobsEnum {
updateCoreBankMockedData = 'updateCoreBankMockedData',
sendStatusReport = 'sendStatusReport',
pollDb = 'pollDb',
bulkReSendInvites = 'bulkReSendInvites',
bulkResendInvites = 'bulkResendInvites',
}

interface ICronJob {
Expand Down Expand Up @@ -57,7 +59,7 @@ export class CronJobsService implements OnModuleInit {
private jaeService: JaeService,
private coreBankService: CoreBankService,
private usersService: UsersService,
) { }
) {}

onModuleInit() {
const THIS_CLASS_WITH_METHOD = `${CronJobsService.name}.${this.onModuleInit.name}`;
Expand Down Expand Up @@ -117,10 +119,10 @@ export class CronJobsService implements OnModuleInit {
},
},
{
name: CrobJobsEnum.bulkReSendInvites,
name: CrobJobsEnum.bulkResendInvites,
cronJobParameters: {
cronTime: '45 14 * * *', // 14:45 GMT = 11:45BRT (GMT-3)
onTick: async () => this.bulkReSendInvites(),
cronTime: '* * * * *', //'45 14 * * *', // 14:45 GMT = 11:45BRT (GMT-3)
onTick: async () => this.bulkResendInvites(),
},
},
);
Expand Down Expand Up @@ -177,7 +179,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Tarefa cancelada pois 'setting.${appSettings.any__activate_auto_send_invite.name}' = 'false'.` +
` Para ativar, altere na tabela 'setting'`,
` Para ativar, altere na tabela 'setting'`,
THIS_METHOD,
),
);
Expand All @@ -193,8 +195,8 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Iniciando tarefa - a enviar: ${unsent.length},` +
` enviado: ${sentToday.length}/${dailyQuota()},` +
` falta enviar: ${remainingQuota}`,
` enviado: ${sentToday.length}/${dailyQuota()},` +
` falta enviar: ${remainingQuota}`,
THIS_METHOD,
),
);
Expand Down Expand Up @@ -354,7 +356,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Tarefa cancelada pois 'setting.${appSettings.any__mail_report_enabled.name}' = 'false'.` +
` Para ativar, altere na tabela 'setting'`,
` Para ativar, altere na tabela 'setting'`,
THIS_METHOD,
),
);
Expand All @@ -373,7 +375,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Tarefa cancelada pois 'setting.${appSettings.any__mail_report_enabled.name}' = 'false'.` +
` Para ativar, altere na tabela 'setting'`,
` Para ativar, altere na tabela 'setting'`,
THIS_METHOD,
),
);
Expand All @@ -389,7 +391,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.error(
formatLog(
`Tarefa cancelada pois a configuração 'mail.statusReportRecipients'` +
` não foi encontrada (retornou: ${mailRecipients}).`,
` não foi encontrada (retornou: ${mailRecipients}).`,
'sendStatusReport()',
),
);
Expand All @@ -400,7 +402,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.error(
formatLog(
`Tarefa cancelada pois a configuração 'mail.statusReportRecipients'` +
` não contém uma lista de emails válidos. Retornou: ${mailRecipients}.`,
` não contém uma lista de emails válidos. Retornou: ${mailRecipients}.`,
THIS_METHOD,
),
);
Expand Down Expand Up @@ -474,7 +476,7 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Tarefa cancelada pois setting.${appSettings.any__poll_db_enabled.name}' = 'false'` +
` Para ativar, altere na tabela 'setting'`,
` Para ativar, altere na tabela 'setting'`,
THIS_METHOD,
),
);
Expand Down Expand Up @@ -531,8 +533,8 @@ export class CronJobsService implements OnModuleInit {
this.logger.log(
formatLog(
`Alteração encontrada em` +
` setting.'${args.setting.name}': ` +
`${job?.cronJobParameters.cronTime} --> ${setting}.`,
` setting.'${args.setting.name}': ` +
`${job?.cronJobParameters.cronTime} --> ${setting}.`,
thisMethod,
),
);
Expand Down Expand Up @@ -597,57 +599,67 @@ export class CronJobsService implements OnModuleInit {
};
}

async getEmail() {
return await this.mailHistoryService.emailsNaoCadastrados();
}

async bulkReSendInvites() {
const THIS_METHOD = `${this.bulkReSendInvites.name}()`;
const emails: string[] = (
await this.mailHistoryService.emailsNaoCadastrados()
).reduce((emails: string[], user) => [...emails, String(user.email)], []);
async bulkResendInvites() {
const THIS_METHOD = `${this.bulkResendInvites.name}()`;
const notRegisteredUsers = await this.usersService.getNotRegisteredUsers();

if (emails.length === 0) {
if (notRegisteredUsers.length === 0) {
this.logger.log(
formatLog('Não há usuários para enviar, abortando...', THIS_METHOD),
);
return;
}
this.logger.log(
formatLog(
String(
'Enviando emails específicos para ' +
`${notRegisteredUsers.length} usuários não totalmente registrados`,
),
THIS_METHOD,
),
);
for (const user of notRegisteredUsers) {
await this.resendInvite(user, THIS_METHOD);
}
}

for (const email of emails) {
try {
const mailSentInfo = await this.mailService.reSendEmailBank({
to: email,
data: null,
});
async resendInvite(user: User, outerMethod: string) {
const THIS_METHOD = `${outerMethod} > ${this.resendInvite.name}`;
try {
const mailSentInfo = await this.mailService.reSendEmailBank({
to: user.email as string,
data: {
hash: user.aux_inviteHash as string,
inviteStatus: user.aux_inviteStatus as InviteStatus,
},
});

// Success
if (mailSentInfo.success) {
this.logger.log(formatLog('Email enviado com sucesso.', THIS_METHOD));
}
// Success
if (mailSentInfo.success) {
this.logger.log(formatLog('Email enviado com sucesso.', THIS_METHOD));
}

// SMTP error
else {
this.logger.error(
formatErrorLog(
'Email enviado retornou erro.',
mailSentInfo,
new Error(),
THIS_METHOD,
),
);
}
} catch (httpException) {
// API error
// SMTP error
else {
this.logger.error(
formatErrorLog(
'Email falhou ao enviar.',
httpException,
httpException as Error,
'Email enviado retornou erro.',
mailSentInfo,
new Error(),
THIS_METHOD,
),
);
}
} catch (httpException) {
// API error
this.logger.error(
formatErrorLog(
'Email falhou ao enviar.',
httpException,
httpException as Error,
THIS_METHOD,
),
);
}
}
}
10 changes: 10 additions & 0 deletions src/database/seeds/mail-history/mail-history-seed-data.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { subDays } from 'date-fns';
import { InviteStatus } from 'src/mail-history-statuses/entities/mail-history-status.entity';
import { InviteStatusEnum } from 'src/mail-history-statuses/mail-history-status.enum';
import { IMailSeedData } from 'src/mail-history/interfaces/mail-history-data.interface';
Expand All @@ -22,6 +23,15 @@ export class MailHistorySeedDataService {
inviteStatus: new InviteStatus(InviteStatusEnum.used),
} as IMailSeedData),
);
for (let i = 0; i < mailSeedData.length; i++) {
const mail = mailSeedData[i];
if (mail.email === 'registered.user@example.com') {
mail[i] = {
...mail,
sentAt: subDays(new Date(), 16),
} as IMailSeedData;
}
}
return mailSeedData;
}
}
13 changes: 13 additions & 0 deletions src/database/seeds/user/user-seed-data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,19 @@ export class UserSeedDataService {
status: { id: StatusEnum.active } as Status,
inviteStatus: new InviteStatus(InviteStatusEnum.used),
},
{
fullName: 'Used registered user',
email: 'registered.user@example.com',
password: 'secret',
permitCode: '319274392832024',
role: { id: RoleEnum.user } as Role,
status: { id: StatusEnum.active } as Status,
inviteStatus: new InviteStatus(InviteStatusEnum.used),
bankCode: 104,
bankAgency: '1234',
bankAccount: '12345',
bankAccountDigit: '1',
},
] as UserDataInterface[])
: []),
];
Expand Down
18 changes: 4 additions & 14 deletions src/database/seeds/user/user-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,8 @@ export class UserSeedService {
) {}

async run() {
if (!(await this.validateRun())) {
this.logger.log('Database is not empty. Aborting seed...');
return;
}
this.logger.log(
`run() ${this.userSeedDataService.getDataFromConfig().length} items`,
);
for (const item of this.userSeedDataService.getDataFromConfig()) {
const userFixtures = await this.userSeedDataService.getDataFromConfig();
for (const item of userFixtures) {
const foundItem = await this.userSeedRepository.findOne({
where: {
email: item.email,
Expand All @@ -35,13 +29,13 @@ export class UserSeedService {
let createdItem: User;
if (foundItem) {
const newItem = new User(foundItem);
newItem.update(item);
newItem.update(item, true);
await this.userSeedRepository.save(
this.userSeedRepository.create(newItem),
);
createdItem = (await this.userSeedRepository.findOne({
where: {
email: newItem.email as string,
email: item.email as string,
},
})) as User;
} else {
Expand Down Expand Up @@ -89,8 +83,4 @@ export class UserSeedService {
}
return hash;
}

async validateRun() {
return global.force || (await this.userSeedRepository.count()) === 0;
}
}
Loading

0 comments on commit 4fed666

Please sign in to comment.