Skip to content

Commit

Permalink
fix: try to fix scheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
Fedorrychkov committed Jan 21, 2024
1 parent 49491af commit 44d058d
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 40 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { Injectable } from '@nestjs/common'
import { Injectable, Logger } from '@nestjs/common'
import TelegramBot from 'node-telegram-bot-api'
import { baseCommands } from '../../commands'
import { TelegramService } from '../../telegram.service'

@Injectable()
export class MealNotification {
private logger = new Logger(MealNotification.name)

constructor(private readonly telegramService: TelegramService) {}

public async mealNotificationSend(chatId: string, message: string, options?: TelegramBot.SendMessageOptions) {
this.logger.log(`[mealNotificationSend]: Сообщение отправлено в chatId: ${chatId}`, { message })

this.telegramService.sendMessage({ id: chatId, message, options: options || baseCommands })
}
}
124 changes: 85 additions & 39 deletions src/modules/telegram/scenarios/mealEvent/mealEvent.schedule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export class MealEventsSchedule {
private readonly mealNotification: MealNotification,
) {}

@Cron(CronExpression.EVERY_HOUR)
// @Cron(CronExpression.EVERY_HOUR)
@Cron(CronExpression.EVERY_MINUTE)
async checkMealsByUsersToday() {
const users = await this.userEntity.findAll()

Expand All @@ -37,6 +38,14 @@ export class MealEventsSchedule {

const { isNeedToPushNotification, currentDate, currentDateInstance } = getTimeInfoForNotifications()

this.logger.log(
`[checkMealsByUsersToday]: Пользователь ${user.id} с ником ${user.username} пока не может получать уведомления`,
{
isNeedToPushNotification,
isNotificationEnabled: settings?.isNotificationEnabled,
},
)

// Если время еще не 10 утра (по мск по сути) или нотификации выключены, то уведомления не посылаем.
if (!isNeedToPushNotification || !settings?.isNotificationEnabled) {
return
Expand Down Expand Up @@ -88,27 +97,36 @@ export class MealEventsSchedule {
])

if (!settings?.isNotificationEnabled) {
this.logger.log(`Пользователь ${user.id} с ником ${user.username} отключил уведомления`)
this.logger.log(`[getMealEvents]: Пользователь ${user.id} с ником ${user.username} отключил уведомления`)

return
}

if (!settings?.mealsCountPerDay) {
this.logger.log(`Пользователь ${user.id} с ником ${user.username} не установил количество приемов пищи`)
this.logger.log(
`[getMealEvents]: Пользователь ${user.id} с ником ${user.username} не установил количество приемов пищи`,
)

// TODO: Добавить уведомления 1 раз в день об установке количества приемов пищи (начать уведомлять через день после регистрации)
return
}

if (events?.length >= settings?.mealsCountPerDay) {
this.logger.log(`Пользователь ${user.id} с ником ${user.username} уже выполнил план за день`)
this.logger.log(`[getMealEvents]: Пользователь ${user.id} с ником ${user.username} уже выполнил план за день`)

return
}

const { isNeedToPushNotification } = getTimeInfoForNotifications()

if (!isNeedToPushNotification) {
this.logger.log(
`[getMealEvents]: Пользователь ${user.id} с ником ${user.username} пока не может получать уведомления`,
{
isNeedToPushNotification,
},
)

return
}

Expand All @@ -121,6 +139,13 @@ export class MealEventsSchedule {
const isSended = this.notificationMealSended.get(key) || false

if (isSended) {
this.logger.log(
`[getMealEvents]: Пользователь ${user.id} с ником ${user.username} уже получал уведомление о следующем приеме пищи`,
{
key,
},
)

return
}

Expand All @@ -134,6 +159,17 @@ export class MealEventsSchedule {

const isNeedToSend = minutes - -reminderPeriodInMinutes < 30

if (!isNeedToSend) {
this.logger.log(
`[getMealEvents]: Пользователю ${user.id} с ником ${user.username} пока рано отправлять уведомление`,
{
minutes,
reminderPeriodInMinutes,
diff: minutes - -reminderPeriodInMinutes,
},
)
}

if (isNeedToSend) {
await this.mealNotification.mealNotificationSend(
user.chatId,
Expand All @@ -146,94 +182,104 @@ export class MealEventsSchedule {
)
}

private async sendMealsCountPerDayNotification({
private async sendMealStartNotification({
user,
settings,
events,
currentDate,
currentDateInstance,
}: {
user: UserDocument
settings: SettingsDocument
events: MealEventDocument[]
currentDate: string
currentDateInstance: Dayjs
}) {
const isToday = time
.unix((user.createdAt as any)?._seconds)
.tz('Europe/Moscow')
.isToday()
const key = `${user.id}-${currentDate}`

// Не нужно отправлять уведомления о напоминании еды, если прием пищи уже был зарегистрирован
if (events?.length > 0) {
this.logger.log(
`[sendMealStartNotification]: Пользователь ${user.id} с ником ${user.username} уже зарегистрировал ${events.length} приемов пищи за сегодня ${currentDate}`,
)

if ((settings?.mealsCountPerDay && settings?.mealsCountPerDay > 0) || isToday) {
return false
}

const key = `${user.id}-${currentDate}`

const lastTodayNotification = this.notificationMealCountPerDatSended.get(key)
const lastTodayNotification = this.notificationMealStartSended.get(key)

if (lastTodayNotification) {
this.logger.log(
`Пользователь ${user.id} с ником ${user.username} уже получал уведомления о необходимости настроить интервалы еды`,
`[sendMealStartNotification]: Пользователь ${user.id} с ником ${user.username} уже получал уведомления о начале еды`,
)

return false
}

const countSettingsText =
'Для корректной работы, вам нужно настроить количество приемов еды, чтобы я мог уведомлять вас заблоговременно!\n\n'
const mealsCountPerDay = settings?.mealsCountPerDay

const remindsInfoText = `${countSettingsText}Обратите внимание, я начинаю уведомления от последнего зарегестрированного приема пищи`
const mealCountInfo = !!mealsCountPerDay
? `\n\nСегодня вас ждет ${mealsCountPerDay} приемов пищи, удачи, с соблюдеием графика!`
: ''

await this.mealNotification.mealNotificationSend(user.chatId, `${remindsInfoText}`, settingsCommands)
await this.mealNotification.mealNotificationSend(
user.chatId,
`Приветствую! Вы сегодня еще не кушали, постарайтесь сделать это в ближайшее время!${mealCountInfo}`,
)

this.notificationMealCountPerDatSended.set(key, currentDateInstance.valueOf())
this.notificationMealStartSended.set(key, currentDateInstance.valueOf())

return true
}

private async sendMealStartNotification({
private async sendMealsCountPerDayNotification({
user,
settings,
events,
currentDate,
currentDateInstance,
}: {
user: UserDocument
settings: SettingsDocument
events: MealEventDocument[]
currentDate: string
currentDateInstance: Dayjs
}) {
const key = `${user.id}-${currentDate}`
const isToday = time
.unix((user.createdAt as any)?._seconds)
.tz('Europe/Moscow')
.isToday()

// Не нужно отправлять уведомления о напоминании еды, если прием пищи уже был зарегистрирован
if (events?.length > 0) {
this.logger.log(
`Пользователь ${user.id} с ником ${user.username} уже зарегистрировал ${events.length} приемов пищи за сегодня ${currentDate}`,
)
this.logger.log(
`[sendMealsCountPerDayNotification]: Пользователь ${user.id} с ником ${user.username} пока не может получать уведомления`,
{
isToday,
mealsCountPerDay: settings?.mealsCountPerDay,
},
)

if ((settings?.mealsCountPerDay && settings?.mealsCountPerDay > 0) || isToday) {
return false
}

const lastTodayNotification = this.notificationMealStartSended.get(key)
const key = `${user.id}-${currentDate}`

const lastTodayNotification = this.notificationMealCountPerDatSended.get(key)

if (lastTodayNotification) {
this.logger.log(`Пользователь ${user.id} с ником ${user.username} уже получал уведомления о начале еды`)
this.logger.log(
`[sendMealsCountPerDayNotification]: Пользователь ${user.id} с ником ${user.username} уже получал уведомления о необходимости настроить интервалы еды`,
)

return false
}

const mealsCountPerDay = settings?.mealsCountPerDay
const countSettingsText =
'Для корректной работы, вам нужно настроить количество приемов еды, чтобы я мог уведомлять вас заблоговременно!\n\n'

const mealCountInfo = !!mealsCountPerDay
? `\n\nСегодня вас ждет ${mealsCountPerDay} приемов пищи, удачи, с соблюдеием графика!`
: ''
const remindsInfoText = `${countSettingsText}Обратите внимание, я начинаю уведомления от последнего зарегестрированного приема пищи`

await this.mealNotification.mealNotificationSend(
user.chatId,
`Приветствую! Вы сегодня еще не кушали, постарайтесь сделать это в ближайшее время!${mealCountInfo}`,
)
await this.mealNotification.mealNotificationSend(user.chatId, `${remindsInfoText}`, settingsCommands)

this.notificationMealStartSended.set(key, currentDateInstance.valueOf())
this.notificationMealCountPerDatSended.set(key, currentDateInstance.valueOf())

return true
}
Expand Down

0 comments on commit 44d058d

Please sign in to comment.