Skip to content

Уведомления в телеграмме #442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ DATABASE_PORT=5432
DATABASE_NAME='databaseName'
DATABASE_USERNAME='user'
DATABASE_PASSWORD='password'
BOT_TOKEN='IGNORE'

POSTGRES_USER=postgres
POSTGRES_PW=postgres
Expand Down
2 changes: 2 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"dependencies": {
"@diary-spo/crypto": "workspace:*",
"@elysiajs/cors": "^1.1.1",
"@types/node-telegram-bot-api": "^0.64.7",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove

"cache-manager": "^5.7.6",
"elysia": "1.1.21",
"elysia-compression": "^0.0.7",
Expand All @@ -25,6 +26,7 @@
"node-rsa": "^1.1.1",
"pg": "^8.13.1",
"pg-hstore": "^2.3.4",
"puregram": "^2.26.8",
"rand-token": "^1.0.1",
"sequelize": "^6.37.5",
"sequelize-simple-cache": "^1.3.5"
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ export const {
DATABASE_USERNAME,
DATABASE_PASSWORD,
TIMEZONE,
KEY_SCAN_PATH
KEY_SCAN_PATH,
BOT_TOKEN
} = PARAMS_INIT
3 changes: 2 additions & 1 deletion apps/api/src/config/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ export const PARAMS_INIT: ParamsInit = {
DATABASE_USERNAME: '',
DATABASE_PASSWORD: '',
TIMEZONE: getTimezone(),
KEY_SCAN_PATH: './'
KEY_SCAN_PATH: './',
BOT_TOKEN: ''
}
1 change: 1 addition & 0 deletions apps/api/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface StringParams {
DATABASE_PASSWORD: string
TIMEZONE: string
KEY_SCAN_PATH: string
BOT_TOKEN: string
}

export type ParamsKeys = StringKeys<ParamsInit>
Expand Down
12 changes: 9 additions & 3 deletions apps/api/src/helpers/generateToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,33 @@ import { API_CODES, ApiError } from '@api'
import { formatDate } from '@utils'
import { suid } from 'rand-token'
import { AuthModel } from '../models/Auth'
import type { TokenInfo } from '../types'

/**
* Генерирует токен и вставляет в базу
* В случае успеха возвращает токен, иначе выбрасывает ошибку
* @param diaryUserId
* @returns {string} token
*/
export const generateToken = async (diaryUserId: bigint): Promise<string> => {
export const generateToken = async (
diaryUserId: bigint
): Promise<TokenInfo> => {
// Генерируем токен
const token = suid(16)

const formattedDate = formatDate(new Date().toISOString())

// TODO: сделать метод рядом с моделью для создания и использовать тут
await AuthModel.create({
const auth = await AuthModel.create({
diaryUserId,
token,
lastUsedDate: formattedDate
}).catch(() => {
throw new ApiError('Error insert token!', API_CODES.INTERNAL_SERVER_ERROR)
})

return token
return {
token,
tokenId: auth.id
}
}
5 changes: 5 additions & 0 deletions apps/api/src/helpers/workerDetector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
let isWorker = false

export const setIsWorker = (value: boolean) => (isWorker = value)

export const getIsWorker = () => isWorker
2 changes: 1 addition & 1 deletion apps/api/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Elysia } from 'elysia'
import { compression } from 'elysia-compression'
import { helmet } from 'elysia-helmet'

import { TIMEZONE } from '@config'
import { BOT_TOKEN, TIMEZONE } from '@config'
import { sequelize } from '@db'

import { getTimezone } from './config/getTimeZone'
Expand Down
10 changes: 8 additions & 2 deletions apps/api/src/models/Auth/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@ import { DataTypes } from 'sequelize'
import { sequelize } from '@db'

import { DiaryUserModel } from '../DiaryUser'
import type { IModelPrototypeNoId } from '../types'
import type { IModelPrototype, IModelPrototypeNoId } from '../types'

export type AuthModelType = {
id: bigint
diaryUserId: bigint
token: string
lastUsedDate: string
}

export type IAuthModel = IModelPrototypeNoId<AuthModelType>
export type IAuthModel = IModelPrototype<AuthModelType, 'id'>

export const AuthModel = sequelize.define<IAuthModel>('auth', {
id: {
type: DataTypes.BIGINT,
autoIncrement: true,
primaryKey: true
},
diaryUserId: {
type: DataTypes.BIGINT,
allowNull: false,
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/models/DiaryUser/methods.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ResponseLogin } from '@diary-spo/shared'
import type { TokenInfo } from '../../types'
import type { IGroupModel } from '../Group'
import type { ISPOModel } from '../SPO'
import type { IDiaryUserModel } from './model'
Expand All @@ -7,7 +8,7 @@ export const getFormattedDiaryUserData = (
diaryUser: IDiaryUserModel,
spo: ISPOModel,
group: IGroupModel,
token: string
token: TokenInfo
): ResponseLogin => ({
id: diaryUser.id,
groupId: diaryUser.groupId,
Expand All @@ -23,5 +24,6 @@ export const getFormattedDiaryUserData = (
lastName: diaryUser.lastName,
middleName: diaryUser.middleName,
spoId: spo.id,
token
token: token.token,
tokenId: token.tokenId
})
1 change: 1 addition & 0 deletions apps/api/src/models/Mark/actions/get/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './markGetByData'
10 changes: 10 additions & 0 deletions apps/api/src/models/Mark/actions/get/markGetByData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { ICacheData } from '@helpers'
import { MarkModel } from '../../model'

export const markGetByData = async (taskId: bigint, authData: ICacheData) =>
MarkModel.findOne({
where: {
taskId,
diaryUserId: authData.localUserId
}
})
1 change: 1 addition & 0 deletions apps/api/src/models/Mark/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './save'
export * from './delete'
export * from './get'
22 changes: 20 additions & 2 deletions apps/api/src/models/Mark/actions/save/markSaveOrGet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MarkKeys } from '@diary-spo/shared'
import type { MarkKeys, Task } from '@diary-spo/shared'
import { type ICacheData, retriesForError } from '@helpers'
import { formatDate } from '@utils'
import { addNewMarkEvent } from '../../../../worker/notificator/bot'
import { markValueSaveOrGet } from '../../../MarkValue'
import type { IScheduleModel } from '../../../Schedule'
import { markSaveOrGetUnSafe } from './markSaveOrGetUnSafe'
Expand All @@ -10,7 +11,9 @@ export const markSaveOrGet = async (
schedule: IScheduleModel,
taskId: bigint,
termId: bigint | null,
authData: ICacheData
authData: ICacheData,
task: Task | null,
systemInitiator = false
) => {
// Не сохраняем текущий семестр для предыдущих семестров
if (authData.termStartDate && authData.termLastUpdate) {
Expand All @@ -35,11 +38,26 @@ export const markSaveOrGet = async (
authData
])

const previousMarkId = markDB[0].markValueId

// Если есть изменения, то он потом сохранит
markDB[0].markValueId = markValueId
if (termId) {
markDB[0].termId = termId
}

// Сохраняем событие добавления/обновления оценки
if (task && systemInitiator)
if (markDB[0].markValueId !== previousMarkId || markDB[1])
addNewMarkEvent({
mark,
previousMarkId:
markDB[0].markValueId !== previousMarkId ? previousMarkId : null,
task,
diaryUserId: authData.localUserId,
status: markDB[1] ? 'ADD' : 'UPDATE',
eventDatetime: new Date()
})

return markDB[0].save()
}
8 changes: 8 additions & 0 deletions apps/api/src/models/MarkValue/actions/get/markValueGetById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { MarkValueModel } from '../../model'

export const markValueGetById = async (markValueId: number) =>
MarkValueModel.findOne({
where: {
id: markValueId
}
})
1 change: 1 addition & 0 deletions apps/api/src/models/Required/actions/get/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './requiredGetByData'
9 changes: 9 additions & 0 deletions apps/api/src/models/Required/actions/get/requiredGetByData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { RequiredModel } from '../../model'

export const requiredGetByData = (diaryUserId: bigint, taskId: bigint) =>
RequiredModel.findOne({
where: {
diaryUserId,
taskId
}
})
1 change: 1 addition & 0 deletions apps/api/src/models/Required/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './save'
export * from './get'
1 change: 1 addition & 0 deletions apps/api/src/models/Schedule/actions/get/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './scheduleGetFromDB'
export * from './scheduleGetFromDBById'
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ScheduleModel } from '../../model'

export const scheduleGetFromDBById = async (scheduleId: bigint) =>
ScheduleModel.findOne({
where: {
id: scheduleId
}
})
5 changes: 3 additions & 2 deletions apps/api/src/models/Schedule/actions/save/daySave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { lessonSave } from './lessonSave'
export const daySave = async (
day: Day,
authData: ICacheData,
termPromise?: ITermDetectP
termPromise?: ITermDetectP,
systemInitiator = false
) => {
if (!day.lessons) {
return
Expand All @@ -19,7 +20,7 @@ export const daySave = async (
for (const lesson of day.lessons) {
const promise = retriesForError(
lessonSave,
[new Date(day.date), lesson, authData, termPromise],
[new Date(day.date), lesson, authData, termPromise, systemInitiator],
3,
1000
) //lessonSave(day.date, lesson, authData, termPromise)
Expand Down
8 changes: 5 additions & 3 deletions apps/api/src/models/Schedule/actions/save/lessonSave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ import type { ScheduleWhere } from '../types'
* @param lesson - Занятие для сохранения
* @param authData - Данные, предоставленные клиентом для авторизации
* @param termPromise
* @param systemInitiator
* @returns Promise<IScheduleModel | null>
*/
export const lessonSave = async (
date: Date,
lesson: Lesson,
authData: ICacheData,
termPromise?: ITermDetectP
termPromise?: ITermDetectP,
systemInitiator = false
): Promise<IScheduleModel | null> => {
/**
* Пропускаем пустые занятия типа:
Expand Down Expand Up @@ -124,7 +126,7 @@ export const lessonSave = async (

/**
* Если расписание есть в базе, то
* пробуем поменять поля и если они поменялись, то
* пробуем сравнить поля и если они поменялись, то
* он (метод save) сделает запрос для сохранения
*/
if (!isCreated) {
Expand Down Expand Up @@ -165,7 +167,7 @@ export const lessonSave = async (
const schedule = await promiseToReturn
retriesForError(
tasksSaveOrGet,
[gradebook.tasks, schedule, authData, termPromise],
[gradebook.tasks, schedule, authData, termPromise, systemInitiator],
2
)
}
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/models/Subject/actions/get/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './subjectGetFromDBById'
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { SubjectModel } from '../../model'

export const subjectGetFromDBById = (subjectId: bigint) =>
SubjectModel.findOne({
where: {
id: subjectId
}
})
1 change: 1 addition & 0 deletions apps/api/src/models/Subject/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './save'
export * from './get'
1 change: 1 addition & 0 deletions apps/api/src/models/Subscribe/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './model'
41 changes: 41 additions & 0 deletions apps/api/src/models/Subscribe/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { DataTypes } from 'sequelize'

import { cache, enableCache, sequelize } from '@db'

import { DiaryUserModel } from '../DiaryUser'
import type { IModelPrototypeNoId } from '../types'

export type SubscribeModelType = {
diaryUserId: bigint
tgId: bigint
preActionsIsSuccess: boolean
}

export type ISubscribeModelType = IModelPrototypeNoId<SubscribeModelType>

const subscribeModel = sequelize.define<ISubscribeModelType>('subscribe', {
diaryUserId: {
type: DataTypes.BIGINT,
primaryKey: true,
references: {
model: DiaryUserModel,
key: 'id'
}
},
tgId: {
type: DataTypes.BIGINT,
primaryKey: true,
allowNull: false,
unique: true
},
preActionsIsSuccess: {
type: DataTypes.BOOLEAN,
primaryKey: false,
allowNull: false,
unique: false
}
})

export const SubscribeModel = enableCache
? cache.init<ISubscribeModelType>(subscribeModel)
: subscribeModel
1 change: 1 addition & 0 deletions apps/api/src/models/Task/actions/get/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './taskGetFromDB'
8 changes: 8 additions & 0 deletions apps/api/src/models/Task/actions/get/taskGetFromDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { TaskModel } from '../../model'

export const taskGetFromDB = async (taskIdFromDiary: number) =>
TaskModel.findOne({
where: {
idFromDiary: taskIdFromDiary
}
})
1 change: 1 addition & 0 deletions apps/api/src/models/Task/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './delete'
export * from './get'
export * from './save'
Loading