Skip to content

Commit

Permalink
Merge pull request #184 from RJ-SMTR/hotfix/#172-dev-daily-user-mail
Browse files Browse the repository at this point in the history
Hotfix/#172 (dev) Emails diferentes para usuários não cadastrados
  • Loading branch information
williamfl2007 committed Feb 15, 2024
2 parents c14a16d + f5aa0eb commit 599eb52
Show file tree
Hide file tree
Showing 24 changed files with 672 additions and 67 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ npm run seed:run user mailhistory
```
> O comando não diferencia maiúsculas de minúsculas
Rodar seed com todos os módulos exceto alguns
```
npm run seed:run __exclude user mailhistory
> A ordem dos parâmetros não influencia a execução
```

## Links

- Swagger: http://localhost:3000/docs
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { SettingsModule } from './settings/settings.module';
import { MailCountModule } from './mail-count/mail-count.module';
import { CronJobsModule } from './cron-jobs/cron-jobs.module';
import { BigqueryModule } from './bigquery/bigquery.module';
import { TestModule } from './test/test.module';

@Module({
imports: [
Expand Down Expand Up @@ -104,6 +105,7 @@ import { BigqueryModule } from './bigquery/bigquery.module';
MailCountModule,
CronJobsModule,
BigqueryModule,
TestModule,
],
})
export class AppModule {}
2 changes: 1 addition & 1 deletion src/config/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
Min,
} from 'class-validator';

enum Environment {
export enum Environment {
Development = 'development',
Production = 'production',
Local = 'local',
Expand Down
1 change: 1 addition & 0 deletions src/cron-jobs/cron-jobs.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ import { MailCountModule } from 'src/mail-count/mail-count.module';
MailCountModule,
],
providers: [CronJobsService],
exports: [CronJobsService],
})
export class CronJobsModule {}
82 changes: 82 additions & 0 deletions src/cron-jobs/cron-jobs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { HttpStatus, Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SchedulerRegistry } from '@nestjs/schedule';
import { CronJob, CronJobParameters } from 'cron';
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 @@ -10,6 +11,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 @@ -24,6 +26,7 @@ export enum CrobJobsEnum {
bulkSendInvites = 'bulkSendInvites',
sendStatusReport = 'sendStatusReport',
pollDb = 'pollDb',
bulkResendInvites = 'bulkResendInvites',
}

interface ICronJob {
Expand Down Expand Up @@ -95,6 +98,15 @@ export class CronJobsService implements OnModuleInit {
onTick: () => this.pollDb(),
},
},
{
name: CrobJobsEnum.bulkResendInvites,
cronJobParameters: {
cronTime: '45 14 * * *', // 14:45 GMT = 11:45BRT (GMT-3)
onTick: async () => {
await this.bulkResendInvites();
},
},
},
);

for (const jobConfig of this.jobsConfig) {
Expand Down Expand Up @@ -556,4 +568,74 @@ export class CronJobsService implements OnModuleInit {
isSettingValid: true,
};
}

async bulkResendInvites(): Promise<HttpStatus> {
const THIS_METHOD = `${this.bulkResendInvites.name}()`;
const notRegisteredUsers = await this.usersService.getNotRegisteredUsers();

if (notRegisteredUsers.length === 0) {
this.logger.log(
formatLog('Não há usuários para enviar, abortando...', THIS_METHOD),
);
return HttpStatus.NOT_FOUND;
}
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);
}
return HttpStatus.OK;
}

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 para ${mailSentInfo.envelope.to}.`,
THIS_METHOD,
),
);
}

// SMTP error
else {
this.logger.error(
formatErrorLog(
'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,
),
);
}
}
}
16 changes: 16 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,21 @@ export class MailHistorySeedDataService {
inviteStatus: new InviteStatus(InviteStatusEnum.used),
} as IMailSeedData),
);
for (let i = 0; i < mailSeedData.length; i++) {
const mail = mailSeedData[i];
if (
[
'sent.user@example.com',
'used.user@example.com',
'registered.user@example.com',
].includes(mail.email as string)
) {
mail[i] = {
...mail,
sentAt: subDays(new Date(), 16),
} as IMailSeedData;
}
}
return mailSeedData;
}
}
81 changes: 59 additions & 22 deletions src/database/seeds/mail-history/mail-history-seed.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { UserSeedDataService } from '../user/user-seed-data.service';
@Injectable()
export class MailHistorySeedService {
private logger = new Logger('MailHistorySeedService', { timestamp: true });
private newMails: any[] = [];

constructor(
@InjectRepository(MailHistory)
Expand All @@ -27,39 +28,64 @@ export class MailHistorySeedService {
}

async run() {
for (const item of await this.mhSeedDataService.getDataFromConfig()) {
const itemUser = await this.getHistoryUser(item);
for (const mailFixture of await this.mhSeedDataService.getDataFromConfig()) {
const itemUser = await this.getHistoryUser(mailFixture);
const itemSeedUser = (
await this.userSeedDataService.getDataFromConfig()
).find((i) => i.email === itemUser.email);
const foundItem = await this.mailHistoryRepository.findOne({
const foundMail = await this.mailHistoryRepository.findOne({
where: {
user: { email: itemUser.email as string },
},
});

if (!foundItem) {
const newItem = { ...item };
newItem.user = itemUser;
newItem.email = itemUser.email as string;
newItem.hash = await this.generateInviteHash();
if (itemSeedUser?.inviteStatus) {
newItem.inviteStatus = itemSeedUser.inviteStatus;
}
this.logger.log(`Creating mail history: ${JSON.stringify(newItem)}`);
await this.mailHistoryRepository.save(
this.mailHistoryRepository.create(newItem),
);
await this.usersRepository.save(
this.usersRepository.create({
id: itemUser.id,
hash: newItem.hash,
}),
);
const hash = await this.generateInviteHash();
const newItem = { ...mailFixture };
newItem.user = itemUser;
newItem.email = itemUser.email as string;
newItem.hash = hash;
if (itemSeedUser?.inviteStatus) {
newItem.inviteStatus = itemSeedUser.inviteStatus;
}
await this.saveMailHistory(newItem, itemUser, foundMail);
this.pushNewMail(newItem, foundMail);
}

if (this.newMails.length) {
this.printResults();
} else {
this.logger.log('No new mails changed.');
}
}

pushNewMail(mail: IMailSeedData, foundMail: MailHistory | null) {
this.newMails.push({
status: foundMail ? 'updated' : 'created',
email: mail.email,
hash: mail.hash,
inviteStatus: mail.inviteStatus,
sentAt: mail.sentAt,
});
}

async saveMailHistory(
mail: IMailSeedData,
itemUser: User,
foundMail: MailHistory | null,
) {
await this.mailHistoryRepository.save(
this.mailHistoryRepository.create({
...mail,
id: foundMail?.id || mail.id,
}),
);
await this.usersRepository.save(
this.usersRepository.create({
id: itemUser.id,
hash: mail.hash,
}),
);
}

async generateInviteHash(): Promise<string> {
let hash = crypto
.createHash('sha256')
Expand All @@ -80,4 +106,15 @@ export class MailHistorySeedService {
});
return users[0];
}

printResults() {
this.logger.log('NEW USERS:');
this.logger.warn(
'The passwords shown are always new but if user exists the current password in DB wont be updated.\n' +
'Save these passwords in the first run or remove these users before seed',
);
for (const item of this.newMails) {
this.logger.log(item);
}
}
}
37 changes: 25 additions & 12 deletions src/database/seeds/user/user-seed-data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ export class UserSeedDataService {
await this.bigqueryService.runQuery(
BQSInstances.smtr,
`
SELECT
DISTINCT o.documento,
FROM \`rj-smtr-dev.cadastro.operadoras\` o
LEFT JOIN \`rj-smtr-dev.br_rj_riodejaneiro_bilhetagem_cct.transacao\` t ON t.id_operadora = o.id_operadora
WHERE t.modo = 'Van'
LIMIT 5
SELECT
DISTINCT o.documento,
FROM \`rj-smtr-dev.cadastro.operadoras\` o
LEFT JOIN \`rj-smtr-dev.br_rj_riodejaneiro_bilhetagem_cct.transacao\` t ON t.id_operadora = o.id_operadora
WHERE t.modo = 'Van'
LIMIT 5
`,
)
).reduce((l: string[], i) => [...l, i['documento']], []);
Expand All @@ -45,12 +45,12 @@ export class UserSeedDataService {
await this.bigqueryService.runQuery(
BQSInstances.smtr,
`
SELECT
DISTINCT c.cnpj,
FROM \`rj-smtr-dev.cadastro.consorcios\` c
LEFT JOIN \`rj-smtr-dev.br_rj_riodejaneiro_bilhetagem_cct.transacao\` t ON t.id_consorcio = c.id_consorcio
WHERE t.modo != 'Van' AND c.cnpj IS NOT NULL
LIMIT 5
SELECT
DISTINCT c.cnpj,
FROM \`rj-smtr-dev.cadastro.consorcios\` c
LEFT JOIN \`rj-smtr-dev.br_rj_riodejaneiro_bilhetagem_cct.transacao\` t ON t.id_consorcio = c.id_consorcio
WHERE t.modo != 'Van' AND c.cnpj IS NOT NULL
LIMIT 5
`,
)
).reduce((l: string[], i) => [...l, i['cnpj']], []);
Expand Down Expand Up @@ -205,6 +205,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
Loading

0 comments on commit 599eb52

Please sign in to comment.