From 7185d94e757946980d3da73f03693a00d0155066 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 10:50:15 -0300 Subject: [PATCH 001/113] Moving api and creating graphQL APi --- .../src/services/GetDailyCommitsService.ts | 2 +- backend/src/services/GetDailyEventsService.ts | 2 +- backend/src/services/GetLanguagesService.ts | 2 +- .../src/services/GetRepositoriesService.ts | 2 +- backend/src/services/GetUserService.ts | 2 +- backend/src/services/githubApi/GraphQLApi.ts | 27 +++++++++++++++++++ .../services/{api.ts => githubApi/RestApi.ts} | 2 +- 7 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 backend/src/services/githubApi/GraphQLApi.ts rename backend/src/services/{api.ts => githubApi/RestApi.ts} (90%) diff --git a/backend/src/services/GetDailyCommitsService.ts b/backend/src/services/GetDailyCommitsService.ts index 2da1e23..bb81c95 100644 --- a/backend/src/services/GetDailyCommitsService.ts +++ b/backend/src/services/GetDailyCommitsService.ts @@ -1,4 +1,4 @@ -import api from './api'; +import api from './githubApi/RestApi'; import Event from '../entities/Event'; import { catchGitHubNotFound } from '../utils/exceptions'; import AppError from '../errors/AppError'; diff --git a/backend/src/services/GetDailyEventsService.ts b/backend/src/services/GetDailyEventsService.ts index e93de1c..07f934e 100644 --- a/backend/src/services/GetDailyEventsService.ts +++ b/backend/src/services/GetDailyEventsService.ts @@ -1,4 +1,4 @@ -import api from './api'; +import api from './githubApi/RestApi'; import { catchGitHubNotFound } from '../utils/exceptions'; import Event from '../entities/Event'; import GetRepositoriesService from './GetRepositoriesService'; diff --git a/backend/src/services/GetLanguagesService.ts b/backend/src/services/GetLanguagesService.ts index 05b35cf..126855e 100644 --- a/backend/src/services/GetLanguagesService.ts +++ b/backend/src/services/GetLanguagesService.ts @@ -1,7 +1,7 @@ import GetRepositoriesService from './GetRepositoriesService'; import Repository from '../entities/Repository'; import AppError from '../errors/AppError'; -import api from './api'; +import api from './githubApi/RestApi'; interface Response { top_language: string; diff --git a/backend/src/services/GetRepositoriesService.ts b/backend/src/services/GetRepositoriesService.ts index 51dd0de..92a5ac3 100644 --- a/backend/src/services/GetRepositoriesService.ts +++ b/backend/src/services/GetRepositoriesService.ts @@ -1,4 +1,4 @@ -import api from './api'; +import api from './githubApi/RestApi'; import { catchGitHubNotFound } from '../utils/exceptions'; import Repository from '../entities/Repository'; diff --git a/backend/src/services/GetUserService.ts b/backend/src/services/GetUserService.ts index ee67df5..83b9367 100644 --- a/backend/src/services/GetUserService.ts +++ b/backend/src/services/GetUserService.ts @@ -1,4 +1,4 @@ -import api from './api'; +import api from './githubApi/RestApi'; import { catchGitHubNotFound } from '../utils/exceptions'; import AppError from '../errors/AppError'; diff --git a/backend/src/services/githubApi/GraphQLApi.ts b/backend/src/services/githubApi/GraphQLApi.ts new file mode 100644 index 0000000..d5e3a21 --- /dev/null +++ b/backend/src/services/githubApi/GraphQLApi.ts @@ -0,0 +1,27 @@ +import axios from 'axios'; +import GetTeacherTokenService from '../GetTeacherTokenService'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const useGlobal: any = global; + +const api = axios.create({ + baseURL: 'https://api.github.com/graphql', +}); + +api.interceptors.request.use(async config => { + if (!useGlobal.teacherToken) { + const getTeacherToken = new GetTeacherTokenService(); + const token = await getTeacherToken.execute(); + + if (token) { + useGlobal.teacherToken = token; + } + } + if (useGlobal.teacherToken) { + config.headers.authorization = `token ${useGlobal.teacherToken}`; + } + + return config; +}); + +export default api; diff --git a/backend/src/services/api.ts b/backend/src/services/githubApi/RestApi.ts similarity index 90% rename from backend/src/services/api.ts rename to backend/src/services/githubApi/RestApi.ts index 7c4ee33..22f9952 100644 --- a/backend/src/services/api.ts +++ b/backend/src/services/githubApi/RestApi.ts @@ -1,5 +1,5 @@ import axios from 'axios'; -import GetTeacherTokenService from './GetTeacherTokenService'; +import GetTeacherTokenService from '../GetTeacherTokenService'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const useGlobal: any = global; From 041d81b2c980d3d5d85ab90ebe20f49af9e1d0ca Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:06:30 -0300 Subject: [PATCH 002/113] v1 routes --- backend/src/routes/index.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index 6b99246..0019a23 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -9,13 +9,13 @@ import userRouter from './user.routes'; const routes = Router(); -routes.use('/user', userRouter); -routes.use('/teacher', teacherRouter); -routes.use('/session', sessionRouter); +routes.use('v1/user', userRouter); +routes.use('v1/teacher', teacherRouter); +routes.use('v1/session', sessionRouter); routes.use(authMiddleware); -routes.use('/student', studentRouter); -routes.use('/class', classRouter); +routes.use('v1/student', studentRouter); +routes.use('v1/class', classRouter); export default routes; From 6c0d43cf746f0bcf22d5a2bb5f27d11ff7029436 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:08:24 -0300 Subject: [PATCH 003/113] Moving services to v1 --- backend/src/models/v2/Manager.ts | 42 +++++++++++++++++++ .../{ => v1}/AuthenticateTeacherService.ts | 4 +- .../services/{ => v1}/CreateCommitService.ts | 0 .../{ => v1}/CreateRepositoryService.ts | 0 .../CreateStudentDailyReportService.ts | 0 .../services/{ => v1}/CreateStudentService.ts | 0 .../services/{ => v1}/CreateTeacherService.ts | 0 .../services/{ => v1}/EditTeacherService.ts | 0 .../src/services/{ => v1}/GetClassReport.ts | 0 .../{ => v1}/GetDailyCommitsService.ts | 0 .../{ => v1}/GetDailyEventsService.ts | 0 .../{ => v1}/GetInteractionsVolumeService.ts | 0 .../services/{ => v1}/GetLanguagesService.ts | 0 .../services/{ => v1}/GetLinesGrowthVolume.ts | 0 .../GetPeriodStudentDailyReportsService.ts | 0 .../services/{ => v1}/GetProfileService.ts | 0 .../{ => v1}/GetRepositoriesService.ts | 0 .../{ => v1}/GetTeacherTokenService.ts | 0 .../{ => v1}/GetUserDailyReportService.ts | 0 .../src/services/{ => v1}/GetUserService.ts | 0 .../{ => v1}/RegisterTeacherGithubService.ts | 4 +- .../src/services/v2/CreateManagerService.ts | 5 +++ 22 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 backend/src/models/v2/Manager.ts rename backend/src/services/{ => v1}/AuthenticateTeacherService.ts (91%) rename backend/src/services/{ => v1}/CreateCommitService.ts (100%) rename backend/src/services/{ => v1}/CreateRepositoryService.ts (100%) rename backend/src/services/{ => v1}/CreateStudentDailyReportService.ts (100%) rename backend/src/services/{ => v1}/CreateStudentService.ts (100%) rename backend/src/services/{ => v1}/CreateTeacherService.ts (100%) rename backend/src/services/{ => v1}/EditTeacherService.ts (100%) rename backend/src/services/{ => v1}/GetClassReport.ts (100%) rename backend/src/services/{ => v1}/GetDailyCommitsService.ts (100%) rename backend/src/services/{ => v1}/GetDailyEventsService.ts (100%) rename backend/src/services/{ => v1}/GetInteractionsVolumeService.ts (100%) rename backend/src/services/{ => v1}/GetLanguagesService.ts (100%) rename backend/src/services/{ => v1}/GetLinesGrowthVolume.ts (100%) rename backend/src/services/{ => v1}/GetPeriodStudentDailyReportsService.ts (100%) rename backend/src/services/{ => v1}/GetProfileService.ts (100%) rename backend/src/services/{ => v1}/GetRepositoriesService.ts (100%) rename backend/src/services/{ => v1}/GetTeacherTokenService.ts (100%) rename backend/src/services/{ => v1}/GetUserDailyReportService.ts (100%) rename backend/src/services/{ => v1}/GetUserService.ts (100%) rename backend/src/services/{ => v1}/RegisterTeacherGithubService.ts (94%) create mode 100644 backend/src/services/v2/CreateManagerService.ts diff --git a/backend/src/models/v2/Manager.ts b/backend/src/models/v2/Manager.ts new file mode 100644 index 0000000..b381902 --- /dev/null +++ b/backend/src/models/v2/Manager.ts @@ -0,0 +1,42 @@ +import { + Column, + CreateDateColumn, + UpdateDateColumn, + Entity, + PrimaryGeneratedColumn, +} from 'typeorm'; + +@Entity('teachers') +class Teacher { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column('varchar') + github_login: string; + + @Column('varchar') + name: string; + + @Column('varchar') + email: string; + + @Column('varchar') + password: string; + + @Column('varchar') + github_token: string; + + @Column('varchar') + avatar_url: string; + + @Column('varchar') + github_id: string; + + @CreateDateColumn() + created_at: Date; + + @UpdateDateColumn() + updated_at: Date; +} + +export default Teacher; diff --git a/backend/src/services/AuthenticateTeacherService.ts b/backend/src/services/v1/AuthenticateTeacherService.ts similarity index 91% rename from backend/src/services/AuthenticateTeacherService.ts rename to backend/src/services/v1/AuthenticateTeacherService.ts index 567b6cb..7dd649e 100644 --- a/backend/src/services/AuthenticateTeacherService.ts +++ b/backend/src/services/v1/AuthenticateTeacherService.ts @@ -1,8 +1,8 @@ import { getRepository } from 'typeorm'; import { compare } from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import Teacher from '../models/Teacher'; -import AppError from '../errors/AppError'; +import Teacher from '../../models/Teacher'; +import AppError from '../../errors/AppError'; interface Response { teacher: Teacher; diff --git a/backend/src/services/CreateCommitService.ts b/backend/src/services/v1/CreateCommitService.ts similarity index 100% rename from backend/src/services/CreateCommitService.ts rename to backend/src/services/v1/CreateCommitService.ts diff --git a/backend/src/services/CreateRepositoryService.ts b/backend/src/services/v1/CreateRepositoryService.ts similarity index 100% rename from backend/src/services/CreateRepositoryService.ts rename to backend/src/services/v1/CreateRepositoryService.ts diff --git a/backend/src/services/CreateStudentDailyReportService.ts b/backend/src/services/v1/CreateStudentDailyReportService.ts similarity index 100% rename from backend/src/services/CreateStudentDailyReportService.ts rename to backend/src/services/v1/CreateStudentDailyReportService.ts diff --git a/backend/src/services/CreateStudentService.ts b/backend/src/services/v1/CreateStudentService.ts similarity index 100% rename from backend/src/services/CreateStudentService.ts rename to backend/src/services/v1/CreateStudentService.ts diff --git a/backend/src/services/CreateTeacherService.ts b/backend/src/services/v1/CreateTeacherService.ts similarity index 100% rename from backend/src/services/CreateTeacherService.ts rename to backend/src/services/v1/CreateTeacherService.ts diff --git a/backend/src/services/EditTeacherService.ts b/backend/src/services/v1/EditTeacherService.ts similarity index 100% rename from backend/src/services/EditTeacherService.ts rename to backend/src/services/v1/EditTeacherService.ts diff --git a/backend/src/services/GetClassReport.ts b/backend/src/services/v1/GetClassReport.ts similarity index 100% rename from backend/src/services/GetClassReport.ts rename to backend/src/services/v1/GetClassReport.ts diff --git a/backend/src/services/GetDailyCommitsService.ts b/backend/src/services/v1/GetDailyCommitsService.ts similarity index 100% rename from backend/src/services/GetDailyCommitsService.ts rename to backend/src/services/v1/GetDailyCommitsService.ts diff --git a/backend/src/services/GetDailyEventsService.ts b/backend/src/services/v1/GetDailyEventsService.ts similarity index 100% rename from backend/src/services/GetDailyEventsService.ts rename to backend/src/services/v1/GetDailyEventsService.ts diff --git a/backend/src/services/GetInteractionsVolumeService.ts b/backend/src/services/v1/GetInteractionsVolumeService.ts similarity index 100% rename from backend/src/services/GetInteractionsVolumeService.ts rename to backend/src/services/v1/GetInteractionsVolumeService.ts diff --git a/backend/src/services/GetLanguagesService.ts b/backend/src/services/v1/GetLanguagesService.ts similarity index 100% rename from backend/src/services/GetLanguagesService.ts rename to backend/src/services/v1/GetLanguagesService.ts diff --git a/backend/src/services/GetLinesGrowthVolume.ts b/backend/src/services/v1/GetLinesGrowthVolume.ts similarity index 100% rename from backend/src/services/GetLinesGrowthVolume.ts rename to backend/src/services/v1/GetLinesGrowthVolume.ts diff --git a/backend/src/services/GetPeriodStudentDailyReportsService.ts b/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts similarity index 100% rename from backend/src/services/GetPeriodStudentDailyReportsService.ts rename to backend/src/services/v1/GetPeriodStudentDailyReportsService.ts diff --git a/backend/src/services/GetProfileService.ts b/backend/src/services/v1/GetProfileService.ts similarity index 100% rename from backend/src/services/GetProfileService.ts rename to backend/src/services/v1/GetProfileService.ts diff --git a/backend/src/services/GetRepositoriesService.ts b/backend/src/services/v1/GetRepositoriesService.ts similarity index 100% rename from backend/src/services/GetRepositoriesService.ts rename to backend/src/services/v1/GetRepositoriesService.ts diff --git a/backend/src/services/GetTeacherTokenService.ts b/backend/src/services/v1/GetTeacherTokenService.ts similarity index 100% rename from backend/src/services/GetTeacherTokenService.ts rename to backend/src/services/v1/GetTeacherTokenService.ts diff --git a/backend/src/services/GetUserDailyReportService.ts b/backend/src/services/v1/GetUserDailyReportService.ts similarity index 100% rename from backend/src/services/GetUserDailyReportService.ts rename to backend/src/services/v1/GetUserDailyReportService.ts diff --git a/backend/src/services/GetUserService.ts b/backend/src/services/v1/GetUserService.ts similarity index 100% rename from backend/src/services/GetUserService.ts rename to backend/src/services/v1/GetUserService.ts diff --git a/backend/src/services/RegisterTeacherGithubService.ts b/backend/src/services/v1/RegisterTeacherGithubService.ts similarity index 94% rename from backend/src/services/RegisterTeacherGithubService.ts rename to backend/src/services/v1/RegisterTeacherGithubService.ts index 97e5d1d..02e2548 100644 --- a/backend/src/services/RegisterTeacherGithubService.ts +++ b/backend/src/services/v1/RegisterTeacherGithubService.ts @@ -1,6 +1,6 @@ import axios from 'axios'; -import AppError from '../errors/AppError'; -import { encrypt } from '../utils/crypto'; +import AppError from '../../errors/AppError'; +import { encrypt } from '../../utils/crypto'; import EditTeacherService from './EditTeacherService'; class RegisterTeacherGithubService { diff --git a/backend/src/services/v2/CreateManagerService.ts b/backend/src/services/v2/CreateManagerService.ts new file mode 100644 index 0000000..c6ff3f8 --- /dev/null +++ b/backend/src/services/v2/CreateManagerService.ts @@ -0,0 +1,5 @@ +class CreateManagerService { + public execute({}): Promise<> {} +} + +export default CreateManagerService; From 42e7a81f3f8e6b3716b8f39445a25fd84ac45e7f Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:09:50 -0300 Subject: [PATCH 004/113] Moving services to v1 --- backend/src/controllers/ClassController.ts | 4 ++-- backend/src/controllers/DailyReportController.ts | 4 ++-- backend/src/controllers/GithubTokenController.ts | 2 +- backend/src/controllers/InteractionsController.ts | 2 +- backend/src/controllers/LinesController.ts | 2 +- backend/src/controllers/SessionController.ts | 2 +- backend/src/controllers/StudentController.ts | 10 +++++----- backend/src/controllers/TeacherController.ts | 4 ++-- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/backend/src/controllers/ClassController.ts b/backend/src/controllers/ClassController.ts index 4d1f9b1..6a7027a 100644 --- a/backend/src/controllers/ClassController.ts +++ b/backend/src/controllers/ClassController.ts @@ -2,8 +2,8 @@ import { Request, Response } from 'express'; import { getRepository } from 'typeorm'; import * as yup from 'yup'; import Student from '../models/Student'; -import GetClassReport from '../services/GetClassReport'; -import GetPeriodStudentDailyReportsService from '../services/GetPeriodStudentDailyReportsService'; +import GetClassReport from '../services/v1/GetClassReport'; +import GetPeriodStudentDailyReportsService from '../services/v1/GetPeriodStudentDailyReportsService'; class ClassController { static async index(request: Request, response: Response): Promise { diff --git a/backend/src/controllers/DailyReportController.ts b/backend/src/controllers/DailyReportController.ts index 31ae421..23d0225 100644 --- a/backend/src/controllers/DailyReportController.ts +++ b/backend/src/controllers/DailyReportController.ts @@ -3,8 +3,8 @@ import { getRepository } from 'typeorm'; import * as yup from 'yup'; import AppError from '../errors/AppError'; import Student from '../models/Student'; -import GetPeriodStudentDailyReportsService from '../services/GetPeriodStudentDailyReportsService'; -import GetUserService from '../services/GetUserService'; +import GetPeriodStudentDailyReportsService from '../services/v1/GetPeriodStudentDailyReportsService'; +import GetUserService from '../services/v1/GetUserService'; class DailyReportController { static async show(request: Request, response: Response): Promise { diff --git a/backend/src/controllers/GithubTokenController.ts b/backend/src/controllers/GithubTokenController.ts index 0f1371b..db65ce6 100644 --- a/backend/src/controllers/GithubTokenController.ts +++ b/backend/src/controllers/GithubTokenController.ts @@ -1,5 +1,5 @@ import { Request, Response } from 'express'; -import RegisterTeacherGithubService from '../services/RegisterTeacherGithubService'; +import RegisterTeacherGithubService from '../services/v1/RegisterTeacherGithubService'; class GithubTokenController { static async store(request: Request, response: Response): Promise { diff --git a/backend/src/controllers/InteractionsController.ts b/backend/src/controllers/InteractionsController.ts index 3678a48..a1b0e55 100644 --- a/backend/src/controllers/InteractionsController.ts +++ b/backend/src/controllers/InteractionsController.ts @@ -2,7 +2,7 @@ import { Request, Response } from 'express'; import * as yup from 'yup'; import { getRepository } from 'typeorm'; import AppError from '../errors/AppError'; -import GetInteractionsVolume from '../services/GetInteractionsVolumeService'; +import GetInteractionsVolume from '../services/v1/GetInteractionsVolumeService'; import Student from '../models/Student'; class InteractionsController { diff --git a/backend/src/controllers/LinesController.ts b/backend/src/controllers/LinesController.ts index 1b9928d..dfa3f30 100644 --- a/backend/src/controllers/LinesController.ts +++ b/backend/src/controllers/LinesController.ts @@ -3,7 +3,7 @@ import * as yup from 'yup'; import { getRepository } from 'typeorm'; import AppError from '../errors/AppError'; import Student from '../models/Student'; -import GetLinesGrowthVolume from '../services/GetLinesGrowthVolume'; +import GetLinesGrowthVolume from '../services/v1/GetLinesGrowthVolume'; class LinesController { static async index(request: Request, response: Response): Promise { diff --git a/backend/src/controllers/SessionController.ts b/backend/src/controllers/SessionController.ts index ff7250e..22a65ed 100644 --- a/backend/src/controllers/SessionController.ts +++ b/backend/src/controllers/SessionController.ts @@ -1,7 +1,7 @@ import { Request, Response } from 'express'; import * as yup from 'yup'; -import AuthenticateTeacherService from '../services/AuthenticateTeacherService'; +import AuthenticateTeacherService from '../services/v1/AuthenticateTeacherService'; class SessionController { static async store(request: Request, response: Response): Promise { diff --git a/backend/src/controllers/StudentController.ts b/backend/src/controllers/StudentController.ts index 467cb40..db45925 100644 --- a/backend/src/controllers/StudentController.ts +++ b/backend/src/controllers/StudentController.ts @@ -2,11 +2,11 @@ import { Request, Response } from 'express'; import { getRepository } from 'typeorm'; import * as yup from 'yup'; -import GetUserService from '../services/GetUserService'; -import GetProfileService from '../services/GetProfileService'; -import GetLanguagesService from '../services/GetLanguagesService'; -import CreateStudentService from '../services/CreateStudentService'; -import CreateRepositoryService from '../services/CreateRepositoryService'; +import GetUserService from '../services/v1/GetUserService'; +import GetProfileService from '../services/v1/GetProfileService'; +import GetLanguagesService from '../services/v1/GetLanguagesService'; +import CreateStudentService from '../services/v1/CreateStudentService'; +import CreateRepositoryService from '../services/v1/CreateRepositoryService'; import Student from '../models/Student'; import AppError from '../errors/AppError'; import Repository from '../models/Repository'; diff --git a/backend/src/controllers/TeacherController.ts b/backend/src/controllers/TeacherController.ts index ea7ce18..7d647b7 100644 --- a/backend/src/controllers/TeacherController.ts +++ b/backend/src/controllers/TeacherController.ts @@ -1,8 +1,8 @@ import { Request, Response } from 'express'; import * as yup from 'yup'; -import GetUserService from '../services/GetUserService'; -import CreateTeacherService from '../services/CreateTeacherService'; +import GetUserService from '../services/v1/GetUserService'; +import CreateTeacherService from '../services/v1/CreateTeacherService'; class TeacherController { static async store(request: Request, response: Response): Promise { From 16958e0fde2a1320832f2a152bf08ef97b263348 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:12:30 -0300 Subject: [PATCH 005/113] Moving v1 routes --- backend/src/app.ts | 4 ++-- backend/src/routes/{ => v1}/class.routes.ts | 0 backend/src/routes/{ => v1}/index.ts | 12 ++++++------ backend/src/routes/{ => v1}/session.routes.ts | 0 backend/src/routes/{ => v1}/student.routes.ts | 0 backend/src/routes/{ => v1}/teacher.routes.ts | 0 backend/src/routes/{ => v1}/user.routes.ts | 6 +++--- 7 files changed, 11 insertions(+), 11 deletions(-) rename backend/src/routes/{ => v1}/class.routes.ts (100%) rename backend/src/routes/{ => v1}/index.ts (56%) rename backend/src/routes/{ => v1}/session.routes.ts (100%) rename backend/src/routes/{ => v1}/student.routes.ts (100%) rename backend/src/routes/{ => v1}/teacher.routes.ts (100%) rename backend/src/routes/{ => v1}/user.routes.ts (83%) diff --git a/backend/src/app.ts b/backend/src/app.ts index f7d4e69..40ce3ec 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -7,7 +7,7 @@ import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; -import routes from './routes'; +import v1 from './routes/v1'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; import RequestStudentsProcessProcessor from './workers/RequestStudentsProcess/RequestStudentsProcessProcessor'; @@ -79,7 +79,7 @@ class App { } private routes(): void { - this.express.use(routes); + this.express.use('/v1', v1); } } diff --git a/backend/src/routes/class.routes.ts b/backend/src/routes/v1/class.routes.ts similarity index 100% rename from backend/src/routes/class.routes.ts rename to backend/src/routes/v1/class.routes.ts diff --git a/backend/src/routes/index.ts b/backend/src/routes/v1/index.ts similarity index 56% rename from backend/src/routes/index.ts rename to backend/src/routes/v1/index.ts index 0019a23..c08eaa3 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/v1/index.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; -import authMiddleware from '../middlewares/authMiddleware'; +import authMiddleware from '../../middlewares/authMiddleware'; import sessionRouter from './session.routes'; import teacherRouter from './teacher.routes'; import studentRouter from './student.routes'; @@ -9,13 +9,13 @@ import userRouter from './user.routes'; const routes = Router(); -routes.use('v1/user', userRouter); -routes.use('v1/teacher', teacherRouter); -routes.use('v1/session', sessionRouter); +routes.use('/user', userRouter); +routes.use('/teacher', teacherRouter); +routes.use('/session', sessionRouter); routes.use(authMiddleware); -routes.use('v1/student', studentRouter); -routes.use('v1/class', classRouter); +routes.use('/student', studentRouter); +routes.use('/class', classRouter); export default routes; diff --git a/backend/src/routes/session.routes.ts b/backend/src/routes/v1/session.routes.ts similarity index 100% rename from backend/src/routes/session.routes.ts rename to backend/src/routes/v1/session.routes.ts diff --git a/backend/src/routes/student.routes.ts b/backend/src/routes/v1/student.routes.ts similarity index 100% rename from backend/src/routes/student.routes.ts rename to backend/src/routes/v1/student.routes.ts diff --git a/backend/src/routes/teacher.routes.ts b/backend/src/routes/v1/teacher.routes.ts similarity index 100% rename from backend/src/routes/teacher.routes.ts rename to backend/src/routes/v1/teacher.routes.ts diff --git a/backend/src/routes/user.routes.ts b/backend/src/routes/v1/user.routes.ts similarity index 83% rename from backend/src/routes/user.routes.ts rename to backend/src/routes/v1/user.routes.ts index 0193258..beec591 100644 --- a/backend/src/routes/user.routes.ts +++ b/backend/src/routes/v1/user.routes.ts @@ -1,8 +1,8 @@ import { Router, Request, Response } from 'express'; -import GetProfileService from '../services/GetProfileService'; -import GetLanguagesService from '../services/GetLanguagesService'; -import GetUserDailyReportService from '../services/GetUserDailyReportService'; +import GetProfileService from '../../services/v1/GetProfileService'; +import GetLanguagesService from '../../services/v1/GetLanguagesService'; +import GetUserDailyReportService from '../../services/v1/GetUserDailyReportService'; const userRouter = Router(); From 770dea42d22140a7261f3969e1409ed883150d4f Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:16:08 -0300 Subject: [PATCH 006/113] Moving v1 routes --- backend/src/models/v2/Manager.ts | 4 ++-- backend/src/routes/v1/session.routes.ts | 2 +- backend/src/routes/v2/index.ts | 8 ++++++++ backend/src/routes/v2/manager.routes.ts | 7 +++++++ 4 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 backend/src/routes/v2/index.ts create mode 100644 backend/src/routes/v2/manager.routes.ts diff --git a/backend/src/models/v2/Manager.ts b/backend/src/models/v2/Manager.ts index b381902..e963535 100644 --- a/backend/src/models/v2/Manager.ts +++ b/backend/src/models/v2/Manager.ts @@ -7,7 +7,7 @@ import { } from 'typeorm'; @Entity('teachers') -class Teacher { +class Manager { @PrimaryGeneratedColumn('uuid') id: string; @@ -39,4 +39,4 @@ class Teacher { updated_at: Date; } -export default Teacher; +export default Manager; diff --git a/backend/src/routes/v1/session.routes.ts b/backend/src/routes/v1/session.routes.ts index f852af7..e1b143b 100644 --- a/backend/src/routes/v1/session.routes.ts +++ b/backend/src/routes/v1/session.routes.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; -import SessionController from '../controllers/SessionController'; +import SessionController from '../../controllers/SessionController'; const sessionRouter = Router(); diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts new file mode 100644 index 0000000..04661fd --- /dev/null +++ b/backend/src/routes/v2/index.ts @@ -0,0 +1,8 @@ +import { Router } from 'express'; +import manangerRouter from './manager.routes'; + +const routes = Router(); + +routes.use('/manager', manangerRouter); + +export default routes; diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/v2/manager.routes.ts new file mode 100644 index 0000000..6a98df5 --- /dev/null +++ b/backend/src/routes/v2/manager.routes.ts @@ -0,0 +1,7 @@ +import { Router } from 'express'; + +const manangerRouter = Router(); + +manangerRouter.post('/'); + +export default manangerRouter; From 02b1af0269143a16936a7c9ec0d2e72285ea0a44 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:32:19 -0300 Subject: [PATCH 007/113] Moving v1 routes --- backend/src/app.ts | 2 ++ backend/src/routes/v1/teacher.routes.ts | 4 +-- backend/src/routes/v2/manager.routes.ts | 15 ++++++++- .../src/services/v1/CreateCommitService.ts | 2 +- .../services/v1/CreateRepositoryService.ts | 2 +- .../v1/CreateStudentDailyReportService.ts | 2 +- .../src/services/v1/CreateStudentService.ts | 4 +-- .../src/services/v1/CreateTeacherService.ts | 4 +-- backend/src/services/v1/EditTeacherService.ts | 4 +-- backend/src/services/v1/GetClassReport.ts | 2 +- .../src/services/v1/GetDailyCommitsService.ts | 8 ++--- .../src/services/v1/GetDailyEventsService.ts | 6 ++-- .../v1/GetInteractionsVolumeService.ts | 2 +- .../src/services/v1/GetLanguagesService.ts | 6 ++-- .../src/services/v1/GetLinesGrowthVolume.ts | 2 +- .../v1/GetPeriodStudentDailyReportsService.ts | 4 +-- backend/src/services/v1/GetProfileService.ts | 2 +- .../src/services/v1/GetRepositoriesService.ts | 6 ++-- .../src/services/v1/GetTeacherTokenService.ts | 4 +-- backend/src/services/v1/GetUserService.ts | 6 ++-- .../src/services/v2/CreateManagerService.ts | 32 ++++++++++++++++++- 21 files changed, 82 insertions(+), 37 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index 40ce3ec..f98122a 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -8,6 +8,7 @@ import { router } from 'bull-board'; import { Worker } from 'bullmq'; import v1 from './routes/v1'; +import v2 from './routes/v2/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; import RequestStudentsProcessProcessor from './workers/RequestStudentsProcess/RequestStudentsProcessProcessor'; @@ -80,6 +81,7 @@ class App { private routes(): void { this.express.use('/v1', v1); + this.express.use('/v2', v2); } } diff --git a/backend/src/routes/v1/teacher.routes.ts b/backend/src/routes/v1/teacher.routes.ts index 5b8ae5c..699156c 100644 --- a/backend/src/routes/v1/teacher.routes.ts +++ b/backend/src/routes/v1/teacher.routes.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; -import TeacherController from '../controllers/TeacherController'; -import GithubTokenController from '../controllers/GithubTokenController'; +import TeacherController from '../../controllers/TeacherController'; +import GithubTokenController from '../../controllers/GithubTokenController'; const teacherRouter = Router(); diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/v2/manager.routes.ts index 6a98df5..b88dafb 100644 --- a/backend/src/routes/v2/manager.routes.ts +++ b/backend/src/routes/v2/manager.routes.ts @@ -1,7 +1,20 @@ import { Router } from 'express'; +import CreateManagerService from '../../services/v2/CreateManagerService'; const manangerRouter = Router(); -manangerRouter.post('/'); +manangerRouter.post('/', async (request, response) => { + const { github_login, email, password } = request.body; + + const createManagerService = new CreateManagerService(); + + const manager = await createManagerService.execute({ + github_login, + email, + password, + }); + + return response.json(manager); +}); export default manangerRouter; diff --git a/backend/src/services/v1/CreateCommitService.ts b/backend/src/services/v1/CreateCommitService.ts index 1b465c0..ca5ff24 100644 --- a/backend/src/services/v1/CreateCommitService.ts +++ b/backend/src/services/v1/CreateCommitService.ts @@ -1,5 +1,5 @@ import { getRepository } from 'typeorm'; -import Commit from '../models/Commit'; +import Commit from '../../models/Commit'; interface Request { repository_id: string | null; diff --git a/backend/src/services/v1/CreateRepositoryService.ts b/backend/src/services/v1/CreateRepositoryService.ts index 33e2179..e52eb1b 100644 --- a/backend/src/services/v1/CreateRepositoryService.ts +++ b/backend/src/services/v1/CreateRepositoryService.ts @@ -1,5 +1,5 @@ import { getRepository } from 'typeorm'; -import Repository from '../models/Repository'; +import Repository from '../../models/Repository'; interface Request { student_id: string; diff --git a/backend/src/services/v1/CreateStudentDailyReportService.ts b/backend/src/services/v1/CreateStudentDailyReportService.ts index 0e6b6c9..ab679ec 100644 --- a/backend/src/services/v1/CreateStudentDailyReportService.ts +++ b/backend/src/services/v1/CreateStudentDailyReportService.ts @@ -1,5 +1,5 @@ import { getRepository } from 'typeorm'; -import StudentDailyReport from '../models/StudentDailyReport'; +import StudentDailyReport from '../../models/StudentDailyReport'; interface Request { student_id: string; diff --git a/backend/src/services/v1/CreateStudentService.ts b/backend/src/services/v1/CreateStudentService.ts index ffd4717..047d4aa 100644 --- a/backend/src/services/v1/CreateStudentService.ts +++ b/backend/src/services/v1/CreateStudentService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; -import AppError from '../errors/AppError'; -import Student from '../models/Student'; +import AppError from '../../errors/AppError'; +import Student from '../../models/Student'; interface Request { github_id: string; diff --git a/backend/src/services/v1/CreateTeacherService.ts b/backend/src/services/v1/CreateTeacherService.ts index 97ad58e..f6794c9 100644 --- a/backend/src/services/v1/CreateTeacherService.ts +++ b/backend/src/services/v1/CreateTeacherService.ts @@ -1,7 +1,7 @@ import { getRepository } from 'typeorm'; import { hash } from 'bcryptjs'; -import AppError from '../errors/AppError'; -import Teacher from '../models/Teacher'; +import AppError from '../../errors/AppError'; +import Teacher from '../../models/Teacher'; import GetUserService from './GetUserService'; interface CreateTeacherRequest { diff --git a/backend/src/services/v1/EditTeacherService.ts b/backend/src/services/v1/EditTeacherService.ts index e4b1c0a..4e18f0c 100644 --- a/backend/src/services/v1/EditTeacherService.ts +++ b/backend/src/services/v1/EditTeacherService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; -import AppError from '../errors/AppError'; -import Teacher from '../models/Teacher'; +import AppError from '../../errors/AppError'; +import Teacher from '../../models/Teacher'; interface RequestOptions { name?: string; diff --git a/backend/src/services/v1/GetClassReport.ts b/backend/src/services/v1/GetClassReport.ts index 838e412..eb1d344 100644 --- a/backend/src/services/v1/GetClassReport.ts +++ b/backend/src/services/v1/GetClassReport.ts @@ -1,5 +1,5 @@ import { getRepository } from 'typeorm'; -import Student from '../models/Student'; +import Student from '../../models/Student'; import GetPeriodStudentDailyReportsService from './GetPeriodStudentDailyReportsService'; interface Response { diff --git a/backend/src/services/v1/GetDailyCommitsService.ts b/backend/src/services/v1/GetDailyCommitsService.ts index bb81c95..84eb59a 100644 --- a/backend/src/services/v1/GetDailyCommitsService.ts +++ b/backend/src/services/v1/GetDailyCommitsService.ts @@ -1,7 +1,7 @@ -import api from './githubApi/RestApi'; -import Event from '../entities/Event'; -import { catchGitHubNotFound } from '../utils/exceptions'; -import AppError from '../errors/AppError'; +import api from '../githubApi/RestApi'; +import Event from '../../entities/Event'; +import { catchGitHubNotFound } from '../../utils/exceptions'; +import AppError from '../../errors/AppError'; interface Commit { repository: { diff --git a/backend/src/services/v1/GetDailyEventsService.ts b/backend/src/services/v1/GetDailyEventsService.ts index 07f934e..bca41fa 100644 --- a/backend/src/services/v1/GetDailyEventsService.ts +++ b/backend/src/services/v1/GetDailyEventsService.ts @@ -1,6 +1,6 @@ -import api from './githubApi/RestApi'; -import { catchGitHubNotFound } from '../utils/exceptions'; -import Event from '../entities/Event'; +import api from '../githubApi/RestApi'; +import { catchGitHubNotFound } from '../../utils/exceptions'; +import Event from '../../entities/Event'; import GetRepositoriesService from './GetRepositoriesService'; interface EventsCounter { diff --git a/backend/src/services/v1/GetInteractionsVolumeService.ts b/backend/src/services/v1/GetInteractionsVolumeService.ts index 57069bc..0238302 100644 --- a/backend/src/services/v1/GetInteractionsVolumeService.ts +++ b/backend/src/services/v1/GetInteractionsVolumeService.ts @@ -1,5 +1,5 @@ import { Between, getRepository } from 'typeorm'; -import StudentDailyReport from '../models/StudentDailyReport'; +import StudentDailyReport from '../../models/StudentDailyReport'; interface Request { since: string; diff --git a/backend/src/services/v1/GetLanguagesService.ts b/backend/src/services/v1/GetLanguagesService.ts index 126855e..0c98b87 100644 --- a/backend/src/services/v1/GetLanguagesService.ts +++ b/backend/src/services/v1/GetLanguagesService.ts @@ -1,7 +1,7 @@ import GetRepositoriesService from './GetRepositoriesService'; -import Repository from '../entities/Repository'; -import AppError from '../errors/AppError'; -import api from './githubApi/RestApi'; +import Repository from '../../entities/Repository'; +import AppError from '../../errors/AppError'; +import api from '../githubApi/RestApi'; interface Response { top_language: string; diff --git a/backend/src/services/v1/GetLinesGrowthVolume.ts b/backend/src/services/v1/GetLinesGrowthVolume.ts index 70f0d46..34003af 100644 --- a/backend/src/services/v1/GetLinesGrowthVolume.ts +++ b/backend/src/services/v1/GetLinesGrowthVolume.ts @@ -1,5 +1,5 @@ import { Between, getRepository } from 'typeorm'; -import StudentDailyReport from '../models/StudentDailyReport'; +import StudentDailyReport from '../../models/StudentDailyReport'; interface Request { since: string; diff --git a/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts b/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts index 23cf602..84ddde1 100644 --- a/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts +++ b/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts @@ -1,6 +1,6 @@ import { getCustomRepository, getRepository } from 'typeorm'; -import StudentDailyReportsRepository from '../repositories/StudentDailyReportsRepository'; -import Commit from '../models/Commit'; +import StudentDailyReportsRepository from '../../repositories/StudentDailyReportsRepository'; +import Commit from '../../models/Commit'; interface CommitResponse { repository?: { diff --git a/backend/src/services/v1/GetProfileService.ts b/backend/src/services/v1/GetProfileService.ts index 92dc9a8..63658b7 100644 --- a/backend/src/services/v1/GetProfileService.ts +++ b/backend/src/services/v1/GetProfileService.ts @@ -1,6 +1,6 @@ import GetUserService from './GetUserService'; import GetRepositoriesService from './GetRepositoriesService'; -import Profile from '../entities/Profile'; +import Profile from '../../entities/Profile'; class GetProfileService { public async execute(username: string): Promise { diff --git a/backend/src/services/v1/GetRepositoriesService.ts b/backend/src/services/v1/GetRepositoriesService.ts index 92a5ac3..b929719 100644 --- a/backend/src/services/v1/GetRepositoriesService.ts +++ b/backend/src/services/v1/GetRepositoriesService.ts @@ -1,6 +1,6 @@ -import api from './githubApi/RestApi'; -import { catchGitHubNotFound } from '../utils/exceptions'; -import Repository from '../entities/Repository'; +import api from '../githubApi/RestApi'; +import { catchGitHubNotFound } from '../../utils/exceptions'; +import Repository from '../../entities/Repository'; class GetRepositoriesService { public async execute(username: string): Promise { diff --git a/backend/src/services/v1/GetTeacherTokenService.ts b/backend/src/services/v1/GetTeacherTokenService.ts index 630401c..81a485d 100644 --- a/backend/src/services/v1/GetTeacherTokenService.ts +++ b/backend/src/services/v1/GetTeacherTokenService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; -import Teacher from '../models/Teacher'; -import { decrypt } from '../utils/crypto'; +import Teacher from '../../models/Teacher'; +import { decrypt } from '../../utils/crypto'; class GetTeacherTokenService { public async execute(): Promise { diff --git a/backend/src/services/v1/GetUserService.ts b/backend/src/services/v1/GetUserService.ts index 83b9367..344e852 100644 --- a/backend/src/services/v1/GetUserService.ts +++ b/backend/src/services/v1/GetUserService.ts @@ -1,6 +1,6 @@ -import api from './githubApi/RestApi'; -import { catchGitHubNotFound } from '../utils/exceptions'; -import AppError from '../errors/AppError'; +import api from '../githubApi/RestApi'; +import { catchGitHubNotFound } from '../../utils/exceptions'; +import AppError from '../../errors/AppError'; interface Request { username?: string; diff --git a/backend/src/services/v2/CreateManagerService.ts b/backend/src/services/v2/CreateManagerService.ts index c6ff3f8..778b20d 100644 --- a/backend/src/services/v2/CreateManagerService.ts +++ b/backend/src/services/v2/CreateManagerService.ts @@ -1,5 +1,35 @@ +import { getRepository } from 'typeorm'; +import Manager from '../../models/v2/Manager'; +import api from '../githubApi/RestApi'; + +interface Request { + github_login: string; + email: string; + password: string; +} + +interface Response { + id: string; + github_login: string; + email: string; + avatar_url: string; + name: string; +} + class CreateManagerService { - public execute({}): Promise<> {} + public async execute({ + github_login, + email, + password, + }: Request): Promise { + const managerRepository = getRepository(Manager); + + const githubData = await api.post(`/user/${github_login}`); + + console.log(githubData.data); + + return null; + } } export default CreateManagerService; From 1449777d110581d228185fb33b1331c153d0a3af Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 11:35:20 -0300 Subject: [PATCH 008/113] Moving to v2 versions --- backend/src/routes/v1/class.routes.ts | 2 +- backend/src/routes/v1/student.routes.ts | 8 ++++---- backend/src/services/githubApi/RestApi.ts | 2 +- .../src/workers/ProcessStudent/ProcessStudentProcessor.ts | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/backend/src/routes/v1/class.routes.ts b/backend/src/routes/v1/class.routes.ts index 3bf94a7..39101cc 100644 --- a/backend/src/routes/v1/class.routes.ts +++ b/backend/src/routes/v1/class.routes.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; -import ClassController from '../controllers/ClassController'; +import ClassController from '../../controllers/ClassController'; const classRouter = Router(); diff --git a/backend/src/routes/v1/student.routes.ts b/backend/src/routes/v1/student.routes.ts index 507b2bc..bb89010 100644 --- a/backend/src/routes/v1/student.routes.ts +++ b/backend/src/routes/v1/student.routes.ts @@ -1,9 +1,9 @@ import { Router } from 'express'; -import StudentController from '../controllers/StudentController'; -import DailyReportController from '../controllers/DailyReportController'; -import InteractionsController from '../controllers/InteractionsController'; -import LinesController from '../controllers/LinesController'; +import StudentController from '../../controllers/StudentController'; +import DailyReportController from '../../controllers/DailyReportController'; +import InteractionsController from '../../controllers/InteractionsController'; +import LinesController from '../../controllers/LinesController'; const studentRouter = Router(); diff --git a/backend/src/services/githubApi/RestApi.ts b/backend/src/services/githubApi/RestApi.ts index 22f9952..d3a3be1 100644 --- a/backend/src/services/githubApi/RestApi.ts +++ b/backend/src/services/githubApi/RestApi.ts @@ -1,5 +1,5 @@ import axios from 'axios'; -import GetTeacherTokenService from '../GetTeacherTokenService'; +import GetTeacherTokenService from '../v1/GetTeacherTokenService'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const useGlobal: any = global; diff --git a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts b/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts index 4ec8aa8..e97b8e9 100644 --- a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts +++ b/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts @@ -4,10 +4,10 @@ import Student from '../../models/Student'; import Repository from '../../models/Repository'; import { StudentRequest } from '../../providers/queue/QueueProvider'; -import GetUserService from '../../services/GetUserService'; -import GetUserDailyReportService from '../../services/GetUserDailyReportService'; -import CreateStudentDailyReportService from '../../services/CreateStudentDailyReportService'; -import CreateCommitService from '../../services/CreateCommitService'; +import GetUserService from '../../services/v1/GetUserService'; +import GetUserDailyReportService from '../../services/v1/GetUserDailyReportService'; +import CreateStudentDailyReportService from '../../services/v1/CreateStudentDailyReportService'; +import CreateCommitService from '../../services/v1/CreateCommitService'; const processStudentProcessor = async ( job: Job, From 1bd1b5d83791a9962d14811b5246e62b015e404e Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:12:21 -0300 Subject: [PATCH 009/113] removing v1 services and routes --- backend/src/routes/v1/class.routes.ts | 11 -- backend/src/routes/v1/index.ts | 21 ---- backend/src/routes/v1/session.routes.ts | 9 -- backend/src/routes/v1/student.routes.ts | 21 ---- backend/src/routes/v1/teacher.routes.ts | 10 -- backend/src/routes/v1/user.routes.ts | 49 -------- .../services/{v2 => }/CreateManagerService.ts | 8 +- .../services/v1/AuthenticateTeacherService.ts | 42 ------- .../src/services/v1/CreateCommitService.ts | 41 ------- .../services/v1/CreateRepositoryService.ts | 38 ------- .../v1/CreateStudentDailyReportService.ts | 50 -------- .../src/services/v1/CreateStudentService.ts | 48 -------- .../src/services/v1/CreateTeacherService.ts | 52 --------- backend/src/services/v1/EditTeacherService.ts | 37 ------ backend/src/services/v1/GetClassReport.ts | 48 -------- .../src/services/v1/GetDailyCommitsService.ts | 94 --------------- .../src/services/v1/GetDailyEventsService.ts | 87 -------------- .../v1/GetInteractionsVolumeService.ts | 48 -------- .../src/services/v1/GetLanguagesService.ts | 62 ---------- .../src/services/v1/GetLinesGrowthVolume.ts | 51 --------- .../v1/GetPeriodStudentDailyReportsService.ts | 107 ------------------ backend/src/services/v1/GetProfileService.ts | 23 ---- .../src/services/v1/GetRepositoriesService.ts | 41 ------- .../src/services/v1/GetTeacherTokenService.ts | 16 --- .../services/v1/GetUserDailyReportService.ts | 88 -------------- backend/src/services/v1/GetUserService.ts | 46 -------- .../v1/RegisterTeacherGithubService.ts | 62 ---------- 27 files changed, 4 insertions(+), 1206 deletions(-) delete mode 100644 backend/src/routes/v1/class.routes.ts delete mode 100644 backend/src/routes/v1/index.ts delete mode 100644 backend/src/routes/v1/session.routes.ts delete mode 100644 backend/src/routes/v1/student.routes.ts delete mode 100644 backend/src/routes/v1/teacher.routes.ts delete mode 100644 backend/src/routes/v1/user.routes.ts rename backend/src/services/{v2 => }/CreateManagerService.ts (68%) delete mode 100644 backend/src/services/v1/AuthenticateTeacherService.ts delete mode 100644 backend/src/services/v1/CreateCommitService.ts delete mode 100644 backend/src/services/v1/CreateRepositoryService.ts delete mode 100644 backend/src/services/v1/CreateStudentDailyReportService.ts delete mode 100644 backend/src/services/v1/CreateStudentService.ts delete mode 100644 backend/src/services/v1/CreateTeacherService.ts delete mode 100644 backend/src/services/v1/EditTeacherService.ts delete mode 100644 backend/src/services/v1/GetClassReport.ts delete mode 100644 backend/src/services/v1/GetDailyCommitsService.ts delete mode 100644 backend/src/services/v1/GetDailyEventsService.ts delete mode 100644 backend/src/services/v1/GetInteractionsVolumeService.ts delete mode 100644 backend/src/services/v1/GetLanguagesService.ts delete mode 100644 backend/src/services/v1/GetLinesGrowthVolume.ts delete mode 100644 backend/src/services/v1/GetPeriodStudentDailyReportsService.ts delete mode 100644 backend/src/services/v1/GetProfileService.ts delete mode 100644 backend/src/services/v1/GetRepositoriesService.ts delete mode 100644 backend/src/services/v1/GetTeacherTokenService.ts delete mode 100644 backend/src/services/v1/GetUserDailyReportService.ts delete mode 100644 backend/src/services/v1/GetUserService.ts delete mode 100644 backend/src/services/v1/RegisterTeacherGithubService.ts diff --git a/backend/src/routes/v1/class.routes.ts b/backend/src/routes/v1/class.routes.ts deleted file mode 100644 index 39101cc..0000000 --- a/backend/src/routes/v1/class.routes.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Router } from 'express'; - -import ClassController from '../../controllers/ClassController'; - -const classRouter = Router(); - -classRouter.get('/', ClassController.index); -classRouter.get('/below_average', ClassController.index); -classRouter.get('/report', ClassController.show); - -export default classRouter; diff --git a/backend/src/routes/v1/index.ts b/backend/src/routes/v1/index.ts deleted file mode 100644 index c08eaa3..0000000 --- a/backend/src/routes/v1/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Router } from 'express'; - -import authMiddleware from '../../middlewares/authMiddleware'; -import sessionRouter from './session.routes'; -import teacherRouter from './teacher.routes'; -import studentRouter from './student.routes'; -import classRouter from './class.routes'; -import userRouter from './user.routes'; - -const routes = Router(); - -routes.use('/user', userRouter); -routes.use('/teacher', teacherRouter); -routes.use('/session', sessionRouter); - -routes.use(authMiddleware); - -routes.use('/student', studentRouter); -routes.use('/class', classRouter); - -export default routes; diff --git a/backend/src/routes/v1/session.routes.ts b/backend/src/routes/v1/session.routes.ts deleted file mode 100644 index e1b143b..0000000 --- a/backend/src/routes/v1/session.routes.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Router } from 'express'; - -import SessionController from '../../controllers/SessionController'; - -const sessionRouter = Router(); - -sessionRouter.post('/', SessionController.store); - -export default sessionRouter; diff --git a/backend/src/routes/v1/student.routes.ts b/backend/src/routes/v1/student.routes.ts deleted file mode 100644 index bb89010..0000000 --- a/backend/src/routes/v1/student.routes.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Router } from 'express'; - -import StudentController from '../../controllers/StudentController'; -import DailyReportController from '../../controllers/DailyReportController'; -import InteractionsController from '../../controllers/InteractionsController'; -import LinesController from '../../controllers/LinesController'; - -const studentRouter = Router(); - -studentRouter.post('/', StudentController.store); -studentRouter.get('/:username', StudentController.show); -studentRouter.get( - '/:username/interactions/volume', - InteractionsController.index, -); - -studentRouter.get('/:username/lines/volume', LinesController.index); - -studentRouter.get('/:username/report', DailyReportController.show); - -export default studentRouter; diff --git a/backend/src/routes/v1/teacher.routes.ts b/backend/src/routes/v1/teacher.routes.ts deleted file mode 100644 index 699156c..0000000 --- a/backend/src/routes/v1/teacher.routes.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Router } from 'express'; -import TeacherController from '../../controllers/TeacherController'; -import GithubTokenController from '../../controllers/GithubTokenController'; - -const teacherRouter = Router(); - -teacherRouter.post('/', TeacherController.store); -teacherRouter.get('/callback', GithubTokenController.store); - -export default teacherRouter; diff --git a/backend/src/routes/v1/user.routes.ts b/backend/src/routes/v1/user.routes.ts deleted file mode 100644 index beec591..0000000 --- a/backend/src/routes/v1/user.routes.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Router, Request, Response } from 'express'; - -import GetProfileService from '../../services/v1/GetProfileService'; -import GetLanguagesService from '../../services/v1/GetLanguagesService'; -import GetUserDailyReportService from '../../services/v1/GetUserDailyReportService'; - -const userRouter = Router(); - -userRouter.get('/:username', async (request: Request, response: Response) => { - const { username } = request.params; - - if (!username) - return response - .status(400) - .json({ error: 'GitHub username does not provided.' }); - - const getProfileService = new GetProfileService(); - const getLanguagesService = new GetLanguagesService(); - - const profileInfo = await getProfileService.execute(username); - const languages = await getLanguagesService.execute(username); - - return response.json({ - ...profileInfo, - ...languages, - }); -}); - -userRouter.get( - '/daily/:username', - async (request: Request, response: Response) => { - const { username } = request.params; - - if (!username) - return response - .status(400) - .json({ error: 'GitHub username does not provided.' }); - - const getUserDailyReportService = new GetUserDailyReportService(); - - const dailyInfo = await getUserDailyReportService.execute(username); - - return response.json({ - ...dailyInfo, - }); - }, -); - -export default userRouter; diff --git a/backend/src/services/v2/CreateManagerService.ts b/backend/src/services/CreateManagerService.ts similarity index 68% rename from backend/src/services/v2/CreateManagerService.ts rename to backend/src/services/CreateManagerService.ts index 778b20d..ca3e32c 100644 --- a/backend/src/services/v2/CreateManagerService.ts +++ b/backend/src/services/CreateManagerService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; -import Manager from '../../models/v2/Manager'; import api from '../githubApi/RestApi'; +import Teacher from '../../models/Teacher'; interface Request { github_login: string; @@ -22,11 +22,11 @@ class CreateManagerService { email, password, }: Request): Promise { - const managerRepository = getRepository(Manager); + const managerRepository = getRepository(Teacher); - const githubData = await api.post(`/user/${github_login}`); + const githubData = await api.get(`/users/${github_login}`); - console.log(githubData.data); + const { login, name, avatar_url, id } = githubData.data; return null; } diff --git a/backend/src/services/v1/AuthenticateTeacherService.ts b/backend/src/services/v1/AuthenticateTeacherService.ts deleted file mode 100644 index 7dd649e..0000000 --- a/backend/src/services/v1/AuthenticateTeacherService.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { getRepository } from 'typeorm'; -import { compare } from 'bcryptjs'; -import jwt from 'jsonwebtoken'; -import Teacher from '../../models/Teacher'; -import AppError from '../../errors/AppError'; - -interface Response { - teacher: Teacher; - token: string; -} - -class AuthenticateTeacherService { - public async execute(email: string, password: string): Promise { - const teachersRepository = getRepository(Teacher); - - const teacher = await teachersRepository.findOne({ email }); - - if (!teacher) { - throw new AppError('E-mail not found.', 404); - } - - const passwordMatched = await compare(password, teacher.password); - - if (!passwordMatched) { - throw new AppError('Incorrect password.', 401); - } - - const secret = process.env.JWT_SECRET; - if (!secret) { - throw new AppError('Internal server error.', 500); - } - - const token = jwt.sign({}, secret, { - subject: teacher.id, - expiresIn: '7d', - }); - - return { teacher, token }; - } -} - -export default AuthenticateTeacherService; diff --git a/backend/src/services/v1/CreateCommitService.ts b/backend/src/services/v1/CreateCommitService.ts deleted file mode 100644 index ca5ff24..0000000 --- a/backend/src/services/v1/CreateCommitService.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { getRepository } from 'typeorm'; -import Commit from '../../models/Commit'; - -interface Request { - repository_id: string | null; - student_id: string; - student_daily_report_id: string; - message: string; - additions: number; - deletions: number; - sha: string; -} - -class CreateCommitService { - async execute({ - student_id, - repository_id, - student_daily_report_id, - message, - additions, - deletions, - sha, - }: Request): Promise { - const commitsRepository = getRepository(Commit); - - const commit = commitsRepository.create({ - student_id, - repository_id, - student_daily_report_id, - message, - additions, - deletions, - sha, - }); - await commitsRepository.save(commit); - - return commit; - } -} - -export default CreateCommitService; diff --git a/backend/src/services/v1/CreateRepositoryService.ts b/backend/src/services/v1/CreateRepositoryService.ts deleted file mode 100644 index e52eb1b..0000000 --- a/backend/src/services/v1/CreateRepositoryService.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { getRepository } from 'typeorm'; -import Repository from '../../models/Repository'; - -interface Request { - student_id: string; - github_id: string; - name: string; - full_name: string; - description: string; - html_url: string; -} - -class CreateRepositoryService { - async execute({ - student_id, - github_id, - name, - full_name, - description, - html_url, - }: Request): Promise { - const repositoriesRepository = getRepository(Repository); - - const repository = repositoriesRepository.create({ - student_id, - github_id, - name, - full_name, - description, - html_url, - }); - await repositoriesRepository.save(repository); - - return repository; - } -} - -export default CreateRepositoryService; diff --git a/backend/src/services/v1/CreateStudentDailyReportService.ts b/backend/src/services/v1/CreateStudentDailyReportService.ts deleted file mode 100644 index ab679ec..0000000 --- a/backend/src/services/v1/CreateStudentDailyReportService.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { getRepository } from 'typeorm'; -import StudentDailyReport from '../../models/StudentDailyReport'; - -interface Request { - student_id: string; - new_forks: number; - new_issues: number; - new_prs: number; - new_stars: number; - new_repositories: number; - new_interactions: number; - new_commits: number; - additions: number; - deletions: number; -} - -class CreateStudentDailyReportService { - async execute({ - student_id, - new_forks, - new_issues, - new_prs, - new_stars, - new_repositories, - new_interactions, - new_commits, - additions, - deletions, - }: Request): Promise { - const studentDailyReportsRepository = getRepository(StudentDailyReport); - - const studentDailyReport = studentDailyReportsRepository.create({ - student_id, - new_forks, - new_issues, - new_prs, - new_stars, - new_repositories, - new_interactions, - new_commits, - additions, - deletions, - }); - await studentDailyReportsRepository.save(studentDailyReport); - - return studentDailyReport; - } -} - -export default CreateStudentDailyReportService; diff --git a/backend/src/services/v1/CreateStudentService.ts b/backend/src/services/v1/CreateStudentService.ts deleted file mode 100644 index 047d4aa..0000000 --- a/backend/src/services/v1/CreateStudentService.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { getRepository } from 'typeorm'; -import AppError from '../../errors/AppError'; -import Student from '../../models/Student'; - -interface Request { - github_id: string; - teacher_id: string; - name: string; - github_login: string; - avatar_url: string; - top_language: string; -} - -class CreateStudentService { - async execute({ - github_id, - teacher_id, - name, - github_login, - avatar_url, - top_language, - }: Request): Promise { - const studentsRepository = getRepository(Student); - - const searchedStudent = await studentsRepository.findOne({ - where: { - github_id, - }, - }); - if (searchedStudent) { - throw new AppError('Student already exists.'); - } - - const student = studentsRepository.create({ - teacher_id, - github_id, - name, - github_login, - avatar_url, - top_language, - }); - await studentsRepository.save(student); - - return student; - } -} - -export default CreateStudentService; diff --git a/backend/src/services/v1/CreateTeacherService.ts b/backend/src/services/v1/CreateTeacherService.ts deleted file mode 100644 index f6794c9..0000000 --- a/backend/src/services/v1/CreateTeacherService.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { getRepository } from 'typeorm'; -import { hash } from 'bcryptjs'; -import AppError from '../../errors/AppError'; -import Teacher from '../../models/Teacher'; -import GetUserService from './GetUserService'; - -interface CreateTeacherRequest { - github_id: string; - email: string; - github_login: string; - password: string; -} - -class CreateTeacherService { - async execute({ - github_id, - email, - github_login, - password, - }: CreateTeacherRequest): Promise { - const teachersRepository = getRepository(Teacher); - - const userExists = await teachersRepository.findOne({ - email, - }); - - if (userExists) { - throw new AppError('E-mail address already used'); - } - - const getUser = new GetUserService(); - const { avatar_url, name } = await getUser.execute({ - username: github_login, - }); - - const hashedPassword = await hash(password, 8); - - const teacher = teachersRepository.create({ - github_id, - avatar_url, - email, - github_login, - name, - password: hashedPassword, - }); - await teachersRepository.save(teacher); - - return teacher; - } -} - -export default CreateTeacherService; diff --git a/backend/src/services/v1/EditTeacherService.ts b/backend/src/services/v1/EditTeacherService.ts deleted file mode 100644 index 4e18f0c..0000000 --- a/backend/src/services/v1/EditTeacherService.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { getRepository } from 'typeorm'; -import AppError from '../../errors/AppError'; -import Teacher from '../../models/Teacher'; - -interface RequestOptions { - name?: string; - password?: string; - github_token?: string; - avatar_url?: string; -} - -class EditTeacherService { - async execute( - username: string, - { name, password, avatar_url, github_token }: RequestOptions, - ): Promise { - const teachersRepository = getRepository(Teacher); - - const teacher = await teachersRepository.findOne({ - github_login: username, - }); - if (!teacher) { - throw new AppError('Teacher not found.', 404); - } - - if (name) teacher.name = name; - if (password) teacher.password = password; - if (github_token) teacher.github_token = github_token; - if (avatar_url) teacher.avatar_url = avatar_url; - - await teachersRepository.save(teacher); - - return teacher; - } -} - -export default EditTeacherService; diff --git a/backend/src/services/v1/GetClassReport.ts b/backend/src/services/v1/GetClassReport.ts deleted file mode 100644 index eb1d344..0000000 --- a/backend/src/services/v1/GetClassReport.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { getRepository } from 'typeorm'; -import Student from '../../models/Student'; -import GetPeriodStudentDailyReportsService from './GetPeriodStudentDailyReportsService'; - -interface Response { - all_new_interactions: number; - all_new_commits: number; - new_interactions_average: number; - new_commits_average: number; -} - -class GetClassReport { - async execute(since: string, until: string): Promise { - const classInformation: Response = { - all_new_interactions: 0, - all_new_commits: 0, - new_interactions_average: 0, - new_commits_average: 0, - }; - - const studentsRepository = getRepository(Student); - const students = await studentsRepository.find(); - - for (const student of students) { - const getPeriodStudentDailyReport = new GetPeriodStudentDailyReportsService(); - const currentDailyReport = await getPeriodStudentDailyReport.execute( - student.id, - since, - until, - ); - - classInformation.all_new_commits += currentDailyReport.new_commits; - classInformation.all_new_interactions += - currentDailyReport.new_interactions; - } - - if (students.length !== 0) { - classInformation.new_commits_average = - classInformation.all_new_commits / students.length; - classInformation.new_interactions_average = - classInformation.all_new_interactions / students.length; - } - - return classInformation; - } -} - -export default GetClassReport; diff --git a/backend/src/services/v1/GetDailyCommitsService.ts b/backend/src/services/v1/GetDailyCommitsService.ts deleted file mode 100644 index 84eb59a..0000000 --- a/backend/src/services/v1/GetDailyCommitsService.ts +++ /dev/null @@ -1,94 +0,0 @@ -import api from '../githubApi/RestApi'; -import Event from '../../entities/Event'; -import { catchGitHubNotFound } from '../../utils/exceptions'; -import AppError from '../../errors/AppError'; - -interface Commit { - repository: { - id: string; - name: string; - url: string; - }; - sha: string; - message: string; - additions: number; - deletions: number; -} - -interface Response { - new_commits: number; - commits: Commit[]; -} - -function isToday(a: Date, b: Date) { - return ( - a.getDate() === b.getDate() && - a.getMonth() === b.getMonth() && - a.getFullYear() === b.getFullYear() - ); -} - -class GetDailyCommitsService { - public async execute(username: string): Promise { - let response; - try { - response = await api.get(`/users/${username}/events`); - } catch (error) { - throw catchGitHubNotFound(error); - } - let events: Event[] = response.data; - - events = events.filter(item => { - const eventDate = new Date(item.created_at); - const today = new Date(); - - return isToday(today, eventDate) && item.payload.commits; - }); - - let commits: Commit[] = []; - - const eventPromise = async (item: Event) => { - const currentRepository = item.repo; - - if (item.payload.commits) { - const newCommits: Commit[] = []; - - const commitPromises = item.payload.commits.map(commit => { - const commitPromise = async () => { - try { - response = await api.get( - `/repos/${currentRepository.name}/commits/${commit.sha}`, - ); - } catch (error) { - throw new AppError('Unable to obtain stats commit', 500); - } - const { stats, sha } = response.data; - - newCommits.push({ - sha, - repository: item.repo, - message: commit.message, - additions: stats.additions, - deletions: stats.deletions, - }); - }; - - return commitPromise(); - }); - await Promise.all(commitPromises); - - commits = [...commits, ...newCommits]; - } - }; - - const eventPromises = events.map(item => eventPromise(item)); - await Promise.all(eventPromises); - - return { - new_commits: commits.length, - commits, - }; - } -} - -export default GetDailyCommitsService; diff --git a/backend/src/services/v1/GetDailyEventsService.ts b/backend/src/services/v1/GetDailyEventsService.ts deleted file mode 100644 index bca41fa..0000000 --- a/backend/src/services/v1/GetDailyEventsService.ts +++ /dev/null @@ -1,87 +0,0 @@ -import api from '../githubApi/RestApi'; -import { catchGitHubNotFound } from '../../utils/exceptions'; -import Event from '../../entities/Event'; -import GetRepositoriesService from './GetRepositoriesService'; - -interface EventsCounter { - [type: string]: number; -} - -interface Response { - new_interactions: number; - new_forks: number; - new_stars: number; - new_repositories: number; - new_prs: number; - new_issues: number; -} - -function isToday(a: Date, b: Date) { - return ( - a.getDate() === b.getDate() && - a.getMonth() === b.getMonth() && - a.getFullYear() === b.getFullYear() - ); -} - -class GetDailyEventsService { - public async execute(username: string): Promise { - let response; - try { - response = await api.get(`/users/${username}/events`); - } catch (error) { - throw catchGitHubNotFound(error); - } - let events: Event[] = response.data; - - events = events.filter(item => { - const eventDate = new Date(item.created_at); - const today = new Date(); - - return isToday(today, eventDate); - }); - - const eventsCounter: EventsCounter = { - ForkEvent: 0, - IssueEvent: 0, - PullRequestEvent: 0, - WatchEvent: 0, - }; - - events.forEach(item => { - if (eventsCounter[item.type]) { - eventsCounter[item.type] += 1; - } else { - eventsCounter[item.type] = 1; - } - }); - - const getRepositoriesService = new GetRepositoriesService(); - let repositories = await getRepositoriesService.execute(username); - - repositories = repositories.filter(item => { - const eventDate = new Date(item.created_at); - const today = new Date(); - - return isToday(today, eventDate); - }); - - const totalInteractions = - eventsCounter.ForkEvent + - eventsCounter.IssueEvent + - eventsCounter.PullRequestEvent + - eventsCounter.WatchEvent + - repositories.length; - - return { - new_forks: eventsCounter.ForkEvent, - new_issues: eventsCounter.IssueEvent, - new_prs: eventsCounter.PullRequestEvent, - new_stars: eventsCounter.WatchEvent, - new_repositories: repositories.length, - new_interactions: totalInteractions, - }; - } -} - -export default GetDailyEventsService; diff --git a/backend/src/services/v1/GetInteractionsVolumeService.ts b/backend/src/services/v1/GetInteractionsVolumeService.ts deleted file mode 100644 index 0238302..0000000 --- a/backend/src/services/v1/GetInteractionsVolumeService.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Between, getRepository } from 'typeorm'; -import StudentDailyReport from '../../models/StudentDailyReport'; - -interface Request { - since: string; - until: string; - student_id: string; -} - -interface Data { - date: Date; - value: number; -} - -interface DataBaseRequest { - created_at: Date; - new_interactions: number; -} - -class GetInteractionsVolume { - async execute({ since, until, student_id }: Request): Promise { - const dailyReportRepository = getRepository(StudentDailyReport); - - const dailyReports = await dailyReportRepository.find({ - where: { - created_at: Between(since, until), - student_id, - }, - select: ['created_at', 'new_interactions'], - order: { - created_at: 'ASC', - }, - }); - - const parsedData = dailyReports.map( - ({ created_at, new_interactions }: DataBaseRequest) => { - return { - value: new_interactions, - date: created_at, - }; - }, - ); - - return parsedData; - } -} - -export default GetInteractionsVolume; diff --git a/backend/src/services/v1/GetLanguagesService.ts b/backend/src/services/v1/GetLanguagesService.ts deleted file mode 100644 index 0c98b87..0000000 --- a/backend/src/services/v1/GetLanguagesService.ts +++ /dev/null @@ -1,62 +0,0 @@ -import GetRepositoriesService from './GetRepositoriesService'; -import Repository from '../../entities/Repository'; -import AppError from '../../errors/AppError'; -import api from '../githubApi/RestApi'; - -interface Response { - top_language: string; - top_5_languages: string[]; -} - -interface LanguagesDictionary { - [language: string]: number; -} - -class GetLanguagesService { - public async execute(username: string): Promise { - const getRepositoriesService = new GetRepositoriesService(); - const repositories: Repository[] = await getRepositoriesService.execute( - username, - ); - - const languageCounter: LanguagesDictionary = {}; - - const countRepositoryLanguages = async (repository: Repository) => { - const { full_name } = repository; - - let response; - try { - response = await api.get(`/repos/${full_name}/languages`); - } catch (error) { - throw new AppError(`Unable to obtain ${full_name} languages.`, 500); - } - const languages = response.data; - - Object.keys(languages).forEach(language => { - if (languageCounter[language]) { - languageCounter[language] += languages[language]; - } else { - languageCounter[language] = languages[language]; - } - }); - }; - - const promises = repositories.map(repository => - countRepositoryLanguages(repository), - ); - await Promise.all(promises); - - let topLanguages = Object.keys(languageCounter).sort((a, b) => { - return languageCounter[a] > languageCounter[b] ? -1 : 1; - }); - - topLanguages = topLanguages.slice(0, 5); - - return { - top_language: topLanguages[0], - top_5_languages: topLanguages, - }; - } -} - -export default GetLanguagesService; diff --git a/backend/src/services/v1/GetLinesGrowthVolume.ts b/backend/src/services/v1/GetLinesGrowthVolume.ts deleted file mode 100644 index 34003af..0000000 --- a/backend/src/services/v1/GetLinesGrowthVolume.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Between, getRepository } from 'typeorm'; -import StudentDailyReport from '../../models/StudentDailyReport'; - -interface Request { - since: string; - until: string; - student_id: string; -} - -interface Data { - date: Date; - gains: number; - loss: number; -} - -interface DataBaseRequest { - created_at: Date; - additions: number; - deletions: number; -} - -class GetLinesGrowthVolume { - async execute({ since, until, student_id }: Request): Promise { - const dailyReportRepository = getRepository(StudentDailyReport); - - const dailyReports = await dailyReportRepository.find({ - where: { - created_at: Between(since, until), - student_id, - }, - select: ['created_at', 'additions', 'deletions'], - order: { - created_at: 'ASC', - }, - }); - - const parsedData = dailyReports.map( - ({ created_at, additions, deletions }: DataBaseRequest) => { - return { - gains: additions, - loss: deletions, - date: created_at, - }; - }, - ); - - return parsedData; - } -} - -export default GetLinesGrowthVolume; diff --git a/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts b/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts deleted file mode 100644 index 84ddde1..0000000 --- a/backend/src/services/v1/GetPeriodStudentDailyReportsService.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { getCustomRepository, getRepository } from 'typeorm'; -import StudentDailyReportsRepository from '../../repositories/StudentDailyReportsRepository'; -import Commit from '../../models/Commit'; - -interface CommitResponse { - repository?: { - name: string; - url: string; - }; - sha: string; - message: string; - additions: number; - deletions: number; -} - -interface Response { - new_interactions: number; - new_forks: number; - new_stars: number; - new_repositories: number; - new_prs: number; - new_issues: number; - new_commits: number; - additions: number; - deletions: number; - created_at: string; - commits: CommitResponse[]; -} - -class GetPeriodStudentDailyReportsService { - public async execute( - student_id: string, - since: string, - until: string, - ): Promise { - const sinceDate = new Date(since); - const untilDate = new Date(until); - - const reportsRepository = getCustomRepository( - StudentDailyReportsRepository, - ); - const commitRepository = getRepository(Commit); - - const finalPeriodReport: Response = { - additions: 0, - deletions: 0, - created_at: new Date().toISOString(), - new_commits: 0, - new_forks: 0, - new_interactions: 0, - new_issues: 0, - new_prs: 0, - new_repositories: 0, - new_stars: 0, - commits: [], - }; - - const reports = await reportsRepository.findByPeriod( - student_id, - sinceDate, - untilDate, - ); - - for (const report of reports) { - finalPeriodReport.additions += report.additions; - finalPeriodReport.deletions += report.deletions; - finalPeriodReport.new_commits += report.new_commits; - finalPeriodReport.new_forks += report.new_forks; - finalPeriodReport.new_interactions += report.new_interactions; - finalPeriodReport.new_issues += report.new_issues; - finalPeriodReport.new_prs += report.new_prs; - finalPeriodReport.new_repositories += report.new_repositories; - finalPeriodReport.new_stars += report.new_stars; - - const commits = await commitRepository.find({ - student_daily_report_id: report.id, - }); - - const commitsResponse: CommitResponse[] = commits.map(commit => { - const response: CommitResponse = { - sha: commit.sha, - additions: commit.additions, - deletions: commit.deletions, - message: commit.message, - }; - - if (commit.repository) { - response.repository = { - name: commit.repository.name, - url: commit.repository.html_url, - }; - } - - return response; - }); - - finalPeriodReport.commits = [ - ...finalPeriodReport.commits, - ...commitsResponse, - ]; - } - - return finalPeriodReport; - } -} - -export default GetPeriodStudentDailyReportsService; diff --git a/backend/src/services/v1/GetProfileService.ts b/backend/src/services/v1/GetProfileService.ts deleted file mode 100644 index 63658b7..0000000 --- a/backend/src/services/v1/GetProfileService.ts +++ /dev/null @@ -1,23 +0,0 @@ -import GetUserService from './GetUserService'; -import GetRepositoriesService from './GetRepositoriesService'; -import Profile from '../../entities/Profile'; - -class GetProfileService { - public async execute(username: string): Promise { - const getUserService = new GetUserService(); - const getRepositoriesService = new GetRepositoriesService(); - - const { avatar_url, github_login } = await getUserService.execute({ - username, - }); - const repositories = await getRepositoriesService.execute(username); - - return { - github_login, - avatar_url, - repositories, - }; - } -} - -export default GetProfileService; diff --git a/backend/src/services/v1/GetRepositoriesService.ts b/backend/src/services/v1/GetRepositoriesService.ts deleted file mode 100644 index b929719..0000000 --- a/backend/src/services/v1/GetRepositoriesService.ts +++ /dev/null @@ -1,41 +0,0 @@ -import api from '../githubApi/RestApi'; -import { catchGitHubNotFound } from '../../utils/exceptions'; -import Repository from '../../entities/Repository'; - -class GetRepositoriesService { - public async execute(username: string): Promise { - let response; - try { - response = await api.get(`/users/${username}/repos`); - } catch (error) { - throw catchGitHubNotFound(error); - } - let repositories: Repository[] = response.data; - - repositories = repositories.map(item => { - const { - id, - name, - full_name, - description, - html_url, - language, - created_at, - } = item; - - return { - id: String(id), - name, - full_name, - description, - html_url, - created_at, - language, - }; - }); - - return repositories; - } -} - -export default GetRepositoriesService; diff --git a/backend/src/services/v1/GetTeacherTokenService.ts b/backend/src/services/v1/GetTeacherTokenService.ts deleted file mode 100644 index 81a485d..0000000 --- a/backend/src/services/v1/GetTeacherTokenService.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { getRepository } from 'typeorm'; -import Teacher from '../../models/Teacher'; -import { decrypt } from '../../utils/crypto'; - -class GetTeacherTokenService { - public async execute(): Promise { - const teachersRepository = getRepository(Teacher); - - const teacher = await teachersRepository.findOne(); - if (!teacher || !teacher.github_token) return ''; - - return decrypt(teacher.github_token); - } -} - -export default GetTeacherTokenService; diff --git a/backend/src/services/v1/GetUserDailyReportService.ts b/backend/src/services/v1/GetUserDailyReportService.ts deleted file mode 100644 index 52f50cc..0000000 --- a/backend/src/services/v1/GetUserDailyReportService.ts +++ /dev/null @@ -1,88 +0,0 @@ -import GetUserService from './GetUserService'; -import GetDailyCommitsService from './GetDailyCommitsService'; -import GetDailyEventsService from './GetDailyEventsService'; - -interface Commit { - repository: { - id: string; - name: string; - url: string; - }; - sha: string; - message: string; - additions: number; - deletions: number; -} - -interface Response { - user: { - github_login: string; - avatar_url: string; - }; - payload: { - new_interactions: number; - new_forks: number; - new_stars: number; - new_repositories: number; - new_prs: number; - new_issues: number; - new_commits: number; - additions: number; - deletions: number; - commits: Commit[]; - created_at: string; - }; -} - -class GetUserDaily { - public async execute(username: string): Promise { - const getUserService = new GetUserService(); - const { github_login, avatar_url } = await getUserService.execute({ - username, - }); - - const getDailyCommitsService = new GetDailyCommitsService(); - const { new_commits, commits } = await getDailyCommitsService.execute( - username, - ); - - let additions = 0; - let deletions = 0; - commits.forEach(item => { - additions += item.additions; - deletions += item.deletions; - }); - - const getDailyEventsService = new GetDailyEventsService(); - const { - new_forks, - new_interactions, - new_issues, - new_prs, - new_repositories, - new_stars, - } = await getDailyEventsService.execute(username); - - return { - user: { - github_login, - avatar_url, - }, - payload: { - new_forks, - new_interactions: new_interactions + new_commits, - new_issues, - new_prs, - new_repositories, - new_stars, - new_commits, - additions, - deletions, - commits, - created_at: new Date().toISOString(), - }, - }; - } -} - -export default GetUserDaily; diff --git a/backend/src/services/v1/GetUserService.ts b/backend/src/services/v1/GetUserService.ts deleted file mode 100644 index 344e852..0000000 --- a/backend/src/services/v1/GetUserService.ts +++ /dev/null @@ -1,46 +0,0 @@ -import api from '../githubApi/RestApi'; -import { catchGitHubNotFound } from '../../utils/exceptions'; -import AppError from '../../errors/AppError'; - -interface Request { - username?: string; - github_id?: string; -} - -interface Response { - github_id: string; - github_login: string; - avatar_url: string; - name: string; -} - -class GetUserService { - public async execute({ username, github_id }: Request): Promise { - let response; - if (username) { - try { - response = await api.get(`/users/${username}`); - } catch (error) { - throw catchGitHubNotFound(error); - } - } else if (github_id) { - try { - response = await api.get(`/user/${github_id}`); - } catch (error) { - throw catchGitHubNotFound(error); - } - } else { - throw new AppError('Github Login or Github ID is missing', 400); - } - const { id, login, avatar_url, name } = response.data; - - return { - github_id: String(id), - github_login: login, - avatar_url, - name, - }; - } -} - -export default GetUserService; diff --git a/backend/src/services/v1/RegisterTeacherGithubService.ts b/backend/src/services/v1/RegisterTeacherGithubService.ts deleted file mode 100644 index 02e2548..0000000 --- a/backend/src/services/v1/RegisterTeacherGithubService.ts +++ /dev/null @@ -1,62 +0,0 @@ -import axios from 'axios'; -import AppError from '../../errors/AppError'; -import { encrypt } from '../../utils/crypto'; -import EditTeacherService from './EditTeacherService'; - -class RegisterTeacherGithubService { - async execute(code: string): Promise { - const clientId = process.env.GITHUB_APP_CLIENT_ID; - const clientSecret = process.env.GITHUB_APP_CLIENT_SECRET; - - if (!clientId || !clientSecret) { - throw new AppError('Internal server error.', 500); - } - - let tokenRequest; - try { - tokenRequest = await axios.post( - 'https://github.com/login/oauth/access_token', - { - client_id: clientId, - client_secret: clientSecret, - code, - }, - { - headers: { - Accept: 'application/json', - }, - }, - ); - } catch (error) { - throw new AppError('Not able to get github access token.', 401); - } - - const accessToken = tokenRequest.data.access_token; - if (!accessToken) { - throw new AppError('Not able to get github access token.', 401); - } - - let response; - try { - response = await axios.get('https://api.github.com/user', { - headers: { - Authorization: `token ${accessToken}`, - }, - }); - } catch (error) { - throw new AppError('Unable to get user information on GitHub api.', 500); - } - const { name, login, avatar_url } = response.data; - - const encryptedToken = encrypt(accessToken); - - const editTeacher = new EditTeacherService(); - await editTeacher.execute(login, { - name, - avatar_url, - github_token: encryptedToken, - }); - } -} - -export default RegisterTeacherGithubService; From 3b701b84f34943e84b9819a1774768f95d283a8b Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:13:08 -0300 Subject: [PATCH 010/113] Removing v1 --- backend/src/app.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index f98122a..8d5fe5c 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -7,7 +7,6 @@ import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; -import v1 from './routes/v1'; import v2 from './routes/v2/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; @@ -80,7 +79,6 @@ class App { } private routes(): void { - this.express.use('/v1', v1); this.express.use('/v2', v2); } } From 45142ca9e3f615588806a3943575fdd9dd7ed844 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:13:12 -0300 Subject: [PATCH 011/113] Removing v1 --- backend/src/controllers/ClassController.ts | 76 --------------- .../src/controllers/DailyReportController.ts | 49 ---------- .../src/controllers/GithubTokenController.ts | 21 ----- .../src/controllers/InteractionsController.ts | 44 --------- backend/src/controllers/LinesController.ts | 44 --------- backend/src/controllers/SessionController.ts | 31 ------- backend/src/controllers/StudentController.ts | 92 ------------------- backend/src/controllers/TeacherController.ts | 36 -------- backend/src/routes/v2/manager.routes.ts | 2 +- backend/src/services/CreateManagerService.ts | 4 +- 10 files changed, 3 insertions(+), 396 deletions(-) delete mode 100644 backend/src/controllers/ClassController.ts delete mode 100644 backend/src/controllers/DailyReportController.ts delete mode 100644 backend/src/controllers/GithubTokenController.ts delete mode 100644 backend/src/controllers/InteractionsController.ts delete mode 100644 backend/src/controllers/LinesController.ts delete mode 100644 backend/src/controllers/SessionController.ts delete mode 100644 backend/src/controllers/StudentController.ts delete mode 100644 backend/src/controllers/TeacherController.ts diff --git a/backend/src/controllers/ClassController.ts b/backend/src/controllers/ClassController.ts deleted file mode 100644 index 6a7027a..0000000 --- a/backend/src/controllers/ClassController.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Request, Response } from 'express'; -import { getRepository } from 'typeorm'; -import * as yup from 'yup'; -import Student from '../models/Student'; -import GetClassReport from '../services/v1/GetClassReport'; -import GetPeriodStudentDailyReportsService from '../services/v1/GetPeriodStudentDailyReportsService'; - -class ClassController { - static async index(request: Request, response: Response): Promise { - const studentsRepository = getRepository(Student); - const students = await studentsRepository.find({ - loadEagerRelations: false, - }); - - if (request.path === '/below_average') { - const schema = yup.object().shape({ - since: yup.string().required('Since date string is required.'), - until: yup.string(), - }); - await schema.validate(request.query); - - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; - - const getClassReport = new GetClassReport(); - const classInformation = await getClassReport.execute( - String(since), - String(until), - ); - - const belowAverageStudents: Student[] = []; - - for (const student of students) { - const getPeriodStudentDailyReport = new GetPeriodStudentDailyReportsService(); - const studentDailyReport = await getPeriodStudentDailyReport.execute( - student.id, - String(since), - String(until), - ); - - if ( - studentDailyReport.new_interactions < - classInformation.new_interactions_average - ) { - belowAverageStudents.push(student); - } - } - - return response.json(belowAverageStudents); - } - - return response.json(students); - } - - static async show(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - since: yup.string().required('Since date string is required.'), - until: yup.string(), - }); - await schema.validate(request.query); - - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; - - const getClassReport = new GetClassReport(); - const classInformation = await getClassReport.execute( - String(since), - String(until), - ); - return response.json(classInformation); - } -} - -export default ClassController; diff --git a/backend/src/controllers/DailyReportController.ts b/backend/src/controllers/DailyReportController.ts deleted file mode 100644 index 23d0225..0000000 --- a/backend/src/controllers/DailyReportController.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Request, Response } from 'express'; -import { getRepository } from 'typeorm'; -import * as yup from 'yup'; -import AppError from '../errors/AppError'; -import Student from '../models/Student'; -import GetPeriodStudentDailyReportsService from '../services/v1/GetPeriodStudentDailyReportsService'; -import GetUserService from '../services/v1/GetUserService'; - -class DailyReportController { - static async show(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - since: yup.string().required('Since date string is required.'), - until: yup.string(), - }); - await schema.validate(request.query); - - const { username } = request.params; - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; - - if (!username) { - throw new AppError('Github username in params is required.', 400); - } - - const getUser = new GetUserService(); - const { github_id } = await getUser.execute({ - username, - }); - - const studentsRepository = getRepository(Student); - const student = await studentsRepository.findOne({ - where: { - github_id, - }, - }); - - const getPeriodStudentDailyReport = new GetPeriodStudentDailyReportsService(); - const studentDailyReport = await getPeriodStudentDailyReport.execute( - student.id, - String(since), - String(until), - ); - - return response.json(studentDailyReport); - } -} - -export default DailyReportController; diff --git a/backend/src/controllers/GithubTokenController.ts b/backend/src/controllers/GithubTokenController.ts deleted file mode 100644 index db65ce6..0000000 --- a/backend/src/controllers/GithubTokenController.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Request, Response } from 'express'; -import RegisterTeacherGithubService from '../services/v1/RegisterTeacherGithubService'; - -class GithubTokenController { - static async store(request: Request, response: Response): Promise { - const { code } = request.query; - - if (!code) { - return response.status(401).json({ - message: 'Not able to get github login code.', - }); - } - - const registerTeacherGithub = new RegisterTeacherGithubService(); - await registerTeacherGithub.execute(code as string); - - return response.json({ message: 'Github Token registered.' }); - } -} - -export default GithubTokenController; diff --git a/backend/src/controllers/InteractionsController.ts b/backend/src/controllers/InteractionsController.ts deleted file mode 100644 index a1b0e55..0000000 --- a/backend/src/controllers/InteractionsController.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Request, Response } from 'express'; -import * as yup from 'yup'; -import { getRepository } from 'typeorm'; -import AppError from '../errors/AppError'; -import GetInteractionsVolume from '../services/v1/GetInteractionsVolumeService'; -import Student from '../models/Student'; - -class InteractionsController { - static async index(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - since: yup.string().required('Since date string is required.'), - until: yup.string(), - }); - await schema.validate(request.query); - - const { username } = request.params; - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; - - if (!username) { - throw new AppError('Github username in params is required.', 400); - } - - const getInteractions = new GetInteractionsVolume(); - const studentRepository = getRepository(Student); - - const { id } = await studentRepository.findOne({ - where: { - github_login: username, - }, - }); - - const volumeData = await getInteractions.execute({ - since: since.toString(), - until: until.toString(), - student_id: id, - }); - - return response.json(volumeData); - } -} - -export default InteractionsController; diff --git a/backend/src/controllers/LinesController.ts b/backend/src/controllers/LinesController.ts deleted file mode 100644 index dfa3f30..0000000 --- a/backend/src/controllers/LinesController.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Request, Response } from 'express'; -import * as yup from 'yup'; -import { getRepository } from 'typeorm'; -import AppError from '../errors/AppError'; -import Student from '../models/Student'; -import GetLinesGrowthVolume from '../services/v1/GetLinesGrowthVolume'; - -class LinesController { - static async index(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - since: yup.string().required('Since date string is required.'), - until: yup.string(), - }); - await schema.validate(request.query); - - const { username } = request.params; - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; - - if (!username) { - throw new AppError('Github username in params is required.', 400); - } - - const getLines = new GetLinesGrowthVolume(); - const studentRepository = getRepository(Student); - - const { id } = await studentRepository.findOne({ - where: { - github_login: username, - }, - }); - - const volumeData = await getLines.execute({ - since: since.toString(), - until: until.toString(), - student_id: id, - }); - - return response.json(volumeData); - } -} - -export default LinesController; diff --git a/backend/src/controllers/SessionController.ts b/backend/src/controllers/SessionController.ts deleted file mode 100644 index 22a65ed..0000000 --- a/backend/src/controllers/SessionController.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Request, Response } from 'express'; -import * as yup from 'yup'; - -import AuthenticateTeacherService from '../services/v1/AuthenticateTeacherService'; - -class SessionController { - static async store(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - email: yup.string().required('E-mail is required.'), - password: yup.string().required('Password is required.'), - }); - - await schema.validate(request.body); - - const { email, password } = request.body; - - const authenticateTeacher = new AuthenticateTeacherService(); - const { teacher, token } = await authenticateTeacher.execute( - email, - password, - ); - - delete teacher.password; - const hasGithubToken = !!teacher.github_token; - delete teacher.github_token; - - return response.json({ teacher, token, hasGithubToken }); - } -} - -export default SessionController; diff --git a/backend/src/controllers/StudentController.ts b/backend/src/controllers/StudentController.ts deleted file mode 100644 index db45925..0000000 --- a/backend/src/controllers/StudentController.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Request, Response } from 'express'; -import { getRepository } from 'typeorm'; -import * as yup from 'yup'; - -import GetUserService from '../services/v1/GetUserService'; -import GetProfileService from '../services/v1/GetProfileService'; -import GetLanguagesService from '../services/v1/GetLanguagesService'; -import CreateStudentService from '../services/v1/CreateStudentService'; -import CreateRepositoryService from '../services/v1/CreateRepositoryService'; -import Student from '../models/Student'; -import AppError from '../errors/AppError'; -import Repository from '../models/Repository'; - -class StudentController { - static async store(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - github_login: yup.string().required('Student github_login is required.'), - }); - - await schema.validate(request.body); - - const { github_login } = request.body; - const { teacher } = request; - - const getProfile = new GetProfileService(); - const { avatar_url, repositories } = await getProfile.execute(github_login); - - const getLanguages = new GetLanguagesService(); - const { top_language } = await getLanguages.execute(github_login); - - const getUser = new GetUserService(); - const { github_id, name } = await getUser.execute({ - username: github_login, - }); - - const createStudentService = new CreateStudentService(); - const student = await createStudentService.execute({ - github_id, - name, - github_login, - avatar_url, - teacher_id: teacher.id, - top_language, - }); - - const createRepository = new CreateRepositoryService(); - for (const repository of repositories) { - await createRepository.execute({ - description: repository.description, - full_name: repository.full_name, - github_id: repository.id, - html_url: repository.html_url, - name: repository.name, - student_id: student.id, - }); - } - - return response.json(student); - } - - static async show(request: Request, response: Response): Promise { - const studentRepository = getRepository(Student); - const repositoriesRepository = getRepository(Repository); - - const { username } = request.params; - if (!username) { - throw new AppError('Github username in params is required.', 400); - } - - const getUser = new GetUserService(); - const user = await getUser.execute({ - username, - }); - - const student = await studentRepository.findOne({ - where: { github_id: user.github_id }, - loadEagerRelations: false, - }); - - const repositories = await repositoriesRepository.find({ - where: { student_id: student.id }, - loadEagerRelations: false, - }); - - return response.json({ - student, - repositories, - }); - } -} - -export default StudentController; diff --git a/backend/src/controllers/TeacherController.ts b/backend/src/controllers/TeacherController.ts deleted file mode 100644 index 7d647b7..0000000 --- a/backend/src/controllers/TeacherController.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Request, Response } from 'express'; -import * as yup from 'yup'; - -import GetUserService from '../services/v1/GetUserService'; -import CreateTeacherService from '../services/v1/CreateTeacherService'; - -class TeacherController { - static async store(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - github_login: yup.string().required('Github Login is required.'), - email: yup.string().required('E-mail is required.'), - password: yup.string().required('Password is required.'), - }); - - await schema.validate(request.body); - - const { github_login, email, password } = request.body; - - const getUser = new GetUserService(); - const { github_id } = await getUser.execute({ username: github_login }); - - const createTeacher = new CreateTeacherService(); - const teacher = await createTeacher.execute({ - github_id, - email, - github_login, - password, - }); - - delete teacher.password; - - return response.json(teacher); - } -} - -export default TeacherController; diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/v2/manager.routes.ts index b88dafb..712ca04 100644 --- a/backend/src/routes/v2/manager.routes.ts +++ b/backend/src/routes/v2/manager.routes.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; -import CreateManagerService from '../../services/v2/CreateManagerService'; +import CreateManagerService from '../../services/CreateManagerService'; const manangerRouter = Router(); diff --git a/backend/src/services/CreateManagerService.ts b/backend/src/services/CreateManagerService.ts index ca3e32c..1fee7b8 100644 --- a/backend/src/services/CreateManagerService.ts +++ b/backend/src/services/CreateManagerService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; -import api from '../githubApi/RestApi'; -import Teacher from '../../models/Teacher'; +import api from './githubApi/RestApi'; +import Teacher from '../models/Teacher'; interface Request { github_login: string; From 7d72a8f4e3021665421e8b0d367446d39ce79685 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:18:17 -0300 Subject: [PATCH 012/113] refactor passes --- backend/src/app.ts | 40 +++++++++---------- backend/src/services/GetGithubTokenService.ts | 16 ++++++++ backend/src/services/githubApi/GraphQLApi.ts | 6 +-- backend/src/services/githubApi/RestApi.ts | 6 +-- 4 files changed, 42 insertions(+), 26 deletions(-) create mode 100644 backend/src/services/GetGithubTokenService.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 8d5fe5c..5b853e6 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -50,32 +50,32 @@ class App { } private defineCron(): void { - cron.schedule('00 23 * * *', async () => - this.queueProvider.add({ - jobName: 'request students process', - queueName: 'students-process-requester', - opts: { - removeOnComplete: false, - }, - }), - ); + // cron.schedule('00 23 * * *', async () => + // this.queueProvider.add({ + // jobName: 'request students process', + // queueName: 'students-process-requester', + // opts: { + // removeOnComplete: false, + // }, + // }), + // ); } private queues(): void { - this.queueProvider.register({ queueName: 'students-process-requester' }); - this.queueProvider.register({ queueName: 'student-processor' }); - this.queueProvider.setUI(); + // this.queueProvider.register({ queueName: 'students-process-requester' }); + // this.queueProvider.register({ queueName: 'student-processor' }); + // this.queueProvider.setUI(); } private workers(): void { - this.studentsProcessRequester = new Worker( - 'students-process-requester', - RequestStudentsProcessProcessor, - ); - this.studentProcessor = new Worker( - 'student-processor', - ProcessStudentProcessor, - ); + // this.studentsProcessRequester = new Worker( + // 'students-process-requester', + // RequestStudentsProcessProcessor, + // ); + // this.studentProcessor = new Worker( + // 'student-processor', + // ProcessStudentProcessor, + // ); } private routes(): void { diff --git a/backend/src/services/GetGithubTokenService.ts b/backend/src/services/GetGithubTokenService.ts new file mode 100644 index 0000000..c4199e3 --- /dev/null +++ b/backend/src/services/GetGithubTokenService.ts @@ -0,0 +1,16 @@ +import { getRepository } from 'typeorm'; +import Teacher from '../models/Teacher'; +import { decrypt } from '../utils/crypto'; + +class GetGithubTokenService { + async execute(): Promise { + const teachersRepository = getRepository(Teacher); + + const teacher = await teachersRepository.findOne(); + if (!teacher || !teacher.github_token) return ''; + + return decrypt(teacher.github_token); + } +} + +export default GetGithubTokenService; diff --git a/backend/src/services/githubApi/GraphQLApi.ts b/backend/src/services/githubApi/GraphQLApi.ts index d5e3a21..f84fa01 100644 --- a/backend/src/services/githubApi/GraphQLApi.ts +++ b/backend/src/services/githubApi/GraphQLApi.ts @@ -1,5 +1,5 @@ import axios from 'axios'; -import GetTeacherTokenService from '../GetTeacherTokenService'; +import GetGithubTokenService from '../GetGithubTokenService'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const useGlobal: any = global; @@ -10,8 +10,8 @@ const api = axios.create({ api.interceptors.request.use(async config => { if (!useGlobal.teacherToken) { - const getTeacherToken = new GetTeacherTokenService(); - const token = await getTeacherToken.execute(); + const getGithubTokenService = new GetGithubTokenService(); + const token = await getGithubTokenService.execute(); if (token) { useGlobal.teacherToken = token; diff --git a/backend/src/services/githubApi/RestApi.ts b/backend/src/services/githubApi/RestApi.ts index d3a3be1..585a7ce 100644 --- a/backend/src/services/githubApi/RestApi.ts +++ b/backend/src/services/githubApi/RestApi.ts @@ -1,5 +1,5 @@ import axios from 'axios'; -import GetTeacherTokenService from '../v1/GetTeacherTokenService'; +import GetGithubTokenService from '../GetGithubTokenService'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const useGlobal: any = global; @@ -10,8 +10,8 @@ const api = axios.create({ api.interceptors.request.use(async config => { if (!useGlobal.teacherToken) { - const getTeacherToken = new GetTeacherTokenService(); - const token = await getTeacherToken.execute(); + const getGithubTokenService = new GetGithubTokenService(); + const token = await getGithubTokenService.execute(); if (token) { useGlobal.teacherToken = token; From 284bf034355fffdb008296d08e31c69b35a552c9 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:36:35 -0300 Subject: [PATCH 013/113] Parsing migrations to follow new names --- ...ers.ts => 1600909362948-CreateManagers.ts} | 6 ++--- ...udents.ts => 1600910013765-CreateSpots.ts} | 8 +++---- ...=> 1600911321319-CreateSpotsForeignKey.ts} | 12 +++++----- .../1600912090409-CreateRepositories.ts | 2 +- ...0912665069-CreateRepositoriesForeignKey.ts | 8 +++---- ...> 1600913787538-CreateSpotDailyReports.ts} | 8 +++---- ...72921-CreateSpotDailyReportsForeignKey.ts} | 12 +++++----- .../migrations/1600914995731-CreateCommits.ts | 2 +- .../1600915158030-CreateCommitsForeignKeys.ts | 8 +++---- ...992782822-ModifyManagersWithGithubInfo.ts} | 22 +++++++++---------- ...1217273020-AddManagerGithubLoginColumn.ts} | 6 ++--- .../migrations/1601656934842-AddGithubId.ts | 8 +++---- ... => 1602087620953-AddSpotDailyReportId.ts} | 8 +++---- ...88932-SetSpotIdOnRepositoriesToCascade.ts} | 18 +++++++-------- ...ame.ts => 1603423271597-createSpotName.ts} | 7 +++--- 15 files changed, 67 insertions(+), 68 deletions(-) rename backend/src/database/migrations/{1600909362948-CreateTeachers.ts => 1600909362948-CreateManagers.ts} (90%) rename backend/src/database/migrations/{1600910013765-CreateStudents.ts => 1600910013765-CreateSpots.ts} (86%) rename backend/src/database/migrations/{1600911321319-CreateStudentsForeignKey.ts => 1600911321319-CreateSpotsForeignKey.ts} (62%) rename backend/src/database/migrations/{1600913787538-CreateStudentDailyReports.ts => 1600913787538-CreateSpotDailyReports.ts} (90%) rename backend/src/database/migrations/{1600914672921-CreateStudentDailyReportsForeignKey.ts => 1600914672921-CreateSpotDailyReportsForeignKey.ts} (59%) rename backend/src/database/migrations/{1600992782822-ModifyTeachersWithGithubInfo.ts => 1600992782822-ModifyManagersWithGithubInfo.ts} (69%) rename backend/src/database/migrations/{1601217273020-AddTeacherGithubLoginColumn.ts => 1601217273020-AddManagerGithubLoginColumn.ts} (73%) rename backend/src/database/migrations/{1602087620953-AddStudentDailyReportId.ts => 1602087620953-AddSpotDailyReportId.ts} (77%) rename backend/src/database/migrations/{1602179988932-SetStudentIdOnRepositoriesToCascade.ts => 1602179988932-SetSpotIdOnRepositoriesToCascade.ts} (71%) rename backend/src/database/migrations/{1603423271597-createStudentName.ts => 1603423271597-createSpotName.ts} (69%) diff --git a/backend/src/database/migrations/1600909362948-CreateTeachers.ts b/backend/src/database/migrations/1600909362948-CreateManagers.ts similarity index 90% rename from backend/src/database/migrations/1600909362948-CreateTeachers.ts rename to backend/src/database/migrations/1600909362948-CreateManagers.ts index bf8c1a1..1ef236c 100644 --- a/backend/src/database/migrations/1600909362948-CreateTeachers.ts +++ b/backend/src/database/migrations/1600909362948-CreateManagers.ts @@ -1,12 +1,12 @@ import { MigrationInterface, QueryRunner, Table } from 'typeorm'; -export default class CreateTeachers1600909362948 implements MigrationInterface { +export default class CreateManagers1600909362948 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); await queryRunner.createTable( new Table({ - name: 'teachers', + name: 'managers', columns: [ { name: 'id', @@ -51,6 +51,6 @@ export default class CreateTeachers1600909362948 implements MigrationInterface { } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropTable('teachers'); + await queryRunner.dropTable('managers'); } } diff --git a/backend/src/database/migrations/1600910013765-CreateStudents.ts b/backend/src/database/migrations/1600910013765-CreateSpots.ts similarity index 86% rename from backend/src/database/migrations/1600910013765-CreateStudents.ts rename to backend/src/database/migrations/1600910013765-CreateSpots.ts index c3a0781..8dc9e5f 100644 --- a/backend/src/database/migrations/1600910013765-CreateStudents.ts +++ b/backend/src/database/migrations/1600910013765-CreateSpots.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner, Table } from 'typeorm'; -export default class CreateStudents1600910013765 implements MigrationInterface { +export default class CreateSpots1600910013765 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.createTable( new Table({ - name: 'students', + name: 'spots', columns: [ { name: 'id', @@ -14,7 +14,7 @@ export default class CreateStudents1600910013765 implements MigrationInterface { default: 'uuid_generate_v4()', }, { - name: 'teacher_id', + name: 'manager_id', type: 'uuid', isNullable: true, }, @@ -49,6 +49,6 @@ export default class CreateStudents1600910013765 implements MigrationInterface { } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropTable('students'); + await queryRunner.dropTable('spots'); } } diff --git a/backend/src/database/migrations/1600911321319-CreateStudentsForeignKey.ts b/backend/src/database/migrations/1600911321319-CreateSpotsForeignKey.ts similarity index 62% rename from backend/src/database/migrations/1600911321319-CreateStudentsForeignKey.ts rename to backend/src/database/migrations/1600911321319-CreateSpotsForeignKey.ts index a88b7e8..f9d75fc 100644 --- a/backend/src/database/migrations/1600911321319-CreateStudentsForeignKey.ts +++ b/backend/src/database/migrations/1600911321319-CreateSpotsForeignKey.ts @@ -1,15 +1,15 @@ import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; -export default class CreateStudentsForeignKey1600911321319 +export default class CreateSpotsForeignKey1600911321319 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.createForeignKey( - 'students', + 'spots', new TableForeignKey({ - name: 'studentTeacher', - columnNames: ['teacher_id'], + name: 'spotsManager', + columnNames: ['manager_id'], referencedColumnNames: ['id'], - referencedTableName: 'teachers', + referencedTableName: 'managers', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), @@ -17,6 +17,6 @@ export default class CreateStudentsForeignKey1600911321319 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('students', 'studentTeacher'); + await queryRunner.dropForeignKey('spots', 'spotsManager'); } } diff --git a/backend/src/database/migrations/1600912090409-CreateRepositories.ts b/backend/src/database/migrations/1600912090409-CreateRepositories.ts index 343408c..3528cde 100644 --- a/backend/src/database/migrations/1600912090409-CreateRepositories.ts +++ b/backend/src/database/migrations/1600912090409-CreateRepositories.ts @@ -15,7 +15,7 @@ export default class CreateRepositories1600912090409 default: 'uuid_generate_v4()', }, { - name: 'student_id', + name: 'spot_id', type: 'uuid', isNullable: true, }, diff --git a/backend/src/database/migrations/1600912665069-CreateRepositoriesForeignKey.ts b/backend/src/database/migrations/1600912665069-CreateRepositoriesForeignKey.ts index 6eeb3b5..01ffd9b 100644 --- a/backend/src/database/migrations/1600912665069-CreateRepositoriesForeignKey.ts +++ b/backend/src/database/migrations/1600912665069-CreateRepositoriesForeignKey.ts @@ -6,10 +6,10 @@ export default class CreateRepositoriesForeignKey1600912665069 await queryRunner.createForeignKey( 'repositories', new TableForeignKey({ - name: 'repositoryStudent', - columnNames: ['student_id'], + name: 'repositorySpot', + columnNames: ['spot_id'], referencedColumnNames: ['id'], - referencedTableName: 'students', + referencedTableName: 'spots', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), @@ -17,6 +17,6 @@ export default class CreateRepositoriesForeignKey1600912665069 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('repositories', 'repositoryStudent'); + await queryRunner.dropForeignKey('repositories', 'repositorySpot'); } } diff --git a/backend/src/database/migrations/1600913787538-CreateStudentDailyReports.ts b/backend/src/database/migrations/1600913787538-CreateSpotDailyReports.ts similarity index 90% rename from backend/src/database/migrations/1600913787538-CreateStudentDailyReports.ts rename to backend/src/database/migrations/1600913787538-CreateSpotDailyReports.ts index bf0df10..d9c46f8 100644 --- a/backend/src/database/migrations/1600913787538-CreateStudentDailyReports.ts +++ b/backend/src/database/migrations/1600913787538-CreateSpotDailyReports.ts @@ -1,11 +1,11 @@ import { MigrationInterface, QueryRunner, Table } from 'typeorm'; -export default class CreateStudentDailyReports1600913787538 +export default class CreateSpotDailyReports1600913787538 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.createTable( new Table({ - name: 'student_daily_reports', + name: 'spot_daily_reports', columns: [ { name: 'id', @@ -15,7 +15,7 @@ export default class CreateStudentDailyReports1600913787538 default: 'uuid_generate_v4()', }, { - name: 'student_id', + name: 'spot_id', type: 'uuid', isNullable: true, }, @@ -80,6 +80,6 @@ export default class CreateStudentDailyReports1600913787538 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropTable('student_daily_reports'); + await queryRunner.dropTable('spot_daily_reports'); } } diff --git a/backend/src/database/migrations/1600914672921-CreateStudentDailyReportsForeignKey.ts b/backend/src/database/migrations/1600914672921-CreateSpotDailyReportsForeignKey.ts similarity index 59% rename from backend/src/database/migrations/1600914672921-CreateStudentDailyReportsForeignKey.ts rename to backend/src/database/migrations/1600914672921-CreateSpotDailyReportsForeignKey.ts index e66aff2..667df8d 100644 --- a/backend/src/database/migrations/1600914672921-CreateStudentDailyReportsForeignKey.ts +++ b/backend/src/database/migrations/1600914672921-CreateSpotDailyReportsForeignKey.ts @@ -1,15 +1,15 @@ import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; -export default class CreateStudentDailyReportsForeignKey1600914672921 +export default class CreateSpotDailyReportsForeignKey1600914672921 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.createForeignKey( - 'student_daily_reports', + 'spot_daily_reports', new TableForeignKey({ - name: 'dailyStudent', - columnNames: ['student_id'], + name: 'dailySpot', + columnNames: ['spot_id'], referencedColumnNames: ['id'], - referencedTableName: 'students', + referencedTableName: 'spots', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), @@ -17,6 +17,6 @@ export default class CreateStudentDailyReportsForeignKey1600914672921 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('student_daily_reports', 'dailyStudent'); + await queryRunner.dropForeignKey('spot_daily_reports', 'dailySpot'); } } diff --git a/backend/src/database/migrations/1600914995731-CreateCommits.ts b/backend/src/database/migrations/1600914995731-CreateCommits.ts index 2e0cb86..8088378 100644 --- a/backend/src/database/migrations/1600914995731-CreateCommits.ts +++ b/backend/src/database/migrations/1600914995731-CreateCommits.ts @@ -19,7 +19,7 @@ export default class CreateCommits1600914995731 implements MigrationInterface { isNullable: true, }, { - name: 'student_id', + name: 'spot_id', type: 'uuid', isNullable: true, }, diff --git a/backend/src/database/migrations/1600915158030-CreateCommitsForeignKeys.ts b/backend/src/database/migrations/1600915158030-CreateCommitsForeignKeys.ts index 503f170..94d490b 100644 --- a/backend/src/database/migrations/1600915158030-CreateCommitsForeignKeys.ts +++ b/backend/src/database/migrations/1600915158030-CreateCommitsForeignKeys.ts @@ -18,10 +18,10 @@ export default class CreateCommitsForeignKeys1600915158030 await queryRunner.createForeignKey( 'commits', new TableForeignKey({ - name: 'commitStudent', - columnNames: ['student_id'], + name: 'commitSpot', + columnNames: ['spot_id'], referencedColumnNames: ['id'], - referencedTableName: 'students', + referencedTableName: 'spots', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), @@ -29,7 +29,7 @@ export default class CreateCommitsForeignKeys1600915158030 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('commits', 'commitStudent'); + await queryRunner.dropForeignKey('commits', 'commitSpot'); await queryRunner.dropForeignKey('commits', 'commitRepository'); } } diff --git a/backend/src/database/migrations/1600992782822-ModifyTeachersWithGithubInfo.ts b/backend/src/database/migrations/1600992782822-ModifyManagersWithGithubInfo.ts similarity index 69% rename from backend/src/database/migrations/1600992782822-ModifyTeachersWithGithubInfo.ts rename to backend/src/database/migrations/1600992782822-ModifyManagersWithGithubInfo.ts index 239e7a3..ca559a2 100644 --- a/backend/src/database/migrations/1600992782822-ModifyTeachersWithGithubInfo.ts +++ b/backend/src/database/migrations/1600992782822-ModifyManagersWithGithubInfo.ts @@ -1,13 +1,13 @@ import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; -export default class ModifyTeachersWithGithubInfo1600992782822 +export default class ModifyManagersWithGithubInfo1600992782822 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { - await queryRunner.dropColumn('teachers', 'name'); - await queryRunner.dropColumn('teachers', 'github_token'); + await queryRunner.dropColumn('managers', 'name'); + await queryRunner.dropColumn('managers', 'github_token'); await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'name', type: 'varchar', @@ -16,7 +16,7 @@ export default class ModifyTeachersWithGithubInfo1600992782822 ); await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'github_token', type: 'varchar', @@ -25,7 +25,7 @@ export default class ModifyTeachersWithGithubInfo1600992782822 ); await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'avatar_url', type: 'varchar', @@ -35,12 +35,12 @@ export default class ModifyTeachersWithGithubInfo1600992782822 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropColumn('teachers', 'avatar_url'); - await queryRunner.dropColumn('teachers', 'github_token'); - await queryRunner.dropColumn('teachers', 'name'); + await queryRunner.dropColumn('managers', 'avatar_url'); + await queryRunner.dropColumn('managers', 'github_token'); + await queryRunner.dropColumn('managers', 'name'); await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'github_token', type: 'varchar', @@ -49,7 +49,7 @@ export default class ModifyTeachersWithGithubInfo1600992782822 ); await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'name', type: 'varchar', diff --git a/backend/src/database/migrations/1601217273020-AddTeacherGithubLoginColumn.ts b/backend/src/database/migrations/1601217273020-AddManagerGithubLoginColumn.ts similarity index 73% rename from backend/src/database/migrations/1601217273020-AddTeacherGithubLoginColumn.ts rename to backend/src/database/migrations/1601217273020-AddManagerGithubLoginColumn.ts index 049b1b1..2400816 100644 --- a/backend/src/database/migrations/1601217273020-AddTeacherGithubLoginColumn.ts +++ b/backend/src/database/migrations/1601217273020-AddManagerGithubLoginColumn.ts @@ -1,10 +1,10 @@ import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; -export default class AddTeacherGithubLoginColumn1601217273020 +export default class AddManagerGithubLoginColumn1601217273020 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'github_login', type: 'varchar', @@ -14,6 +14,6 @@ export default class AddTeacherGithubLoginColumn1601217273020 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropColumn('teachers', 'github_login'); + await queryRunner.dropColumn('managers', 'github_login'); } } diff --git a/backend/src/database/migrations/1601656934842-AddGithubId.ts b/backend/src/database/migrations/1601656934842-AddGithubId.ts index 7c6310f..d97b5ba 100644 --- a/backend/src/database/migrations/1601656934842-AddGithubId.ts +++ b/backend/src/database/migrations/1601656934842-AddGithubId.ts @@ -3,7 +3,7 @@ import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; export default class AddGithubId1601656934842 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.addColumn( - 'teachers', + 'managers', new TableColumn({ name: 'github_id', type: 'varchar', @@ -11,7 +11,7 @@ export default class AddGithubId1601656934842 implements MigrationInterface { }), ); await queryRunner.addColumn( - 'students', + 'spots', new TableColumn({ name: 'github_id', type: 'varchar', @@ -39,7 +39,7 @@ export default class AddGithubId1601656934842 implements MigrationInterface { public async down(queryRunner: QueryRunner): Promise { await queryRunner.dropColumn('commits', 'sha'); await queryRunner.dropColumn('repositories', 'github_id'); - await queryRunner.dropColumn('students', 'github_id'); - await queryRunner.dropColumn('teachers', 'github_id'); + await queryRunner.dropColumn('spots', 'github_id'); + await queryRunner.dropColumn('managers', 'github_id'); } } diff --git a/backend/src/database/migrations/1602087620953-AddStudentDailyReportId.ts b/backend/src/database/migrations/1602087620953-AddSpotDailyReportId.ts similarity index 77% rename from backend/src/database/migrations/1602087620953-AddStudentDailyReportId.ts rename to backend/src/database/migrations/1602087620953-AddSpotDailyReportId.ts index b531ab5..0c7b58c 100644 --- a/backend/src/database/migrations/1602087620953-AddStudentDailyReportId.ts +++ b/backend/src/database/migrations/1602087620953-AddSpotDailyReportId.ts @@ -11,7 +11,7 @@ export default class AddStudentDailyReportId1602087620953 await queryRunner.addColumn( 'commits', new TableColumn({ - name: 'student_daily_report_id', + name: 'spot_daily_report_id', type: 'uuid', isNullable: false, }), @@ -21,9 +21,9 @@ export default class AddStudentDailyReportId1602087620953 'commits', new TableForeignKey({ name: 'commitReport', - columnNames: ['student_daily_report_id'], + columnNames: ['spot_daily_report_id'], referencedColumnNames: ['id'], - referencedTableName: 'student_daily_reports', + referencedTableName: 'spot_daily_reports', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), @@ -32,6 +32,6 @@ export default class AddStudentDailyReportId1602087620953 public async down(queryRunner: QueryRunner): Promise { await queryRunner.dropForeignKey('commits', 'commitReport'); - await queryRunner.dropColumn('commits', 'student_daily_report_id'); + await queryRunner.dropColumn('commits', 'spot_daily_reports'); } } diff --git a/backend/src/database/migrations/1602179988932-SetStudentIdOnRepositoriesToCascade.ts b/backend/src/database/migrations/1602179988932-SetSpotIdOnRepositoriesToCascade.ts similarity index 71% rename from backend/src/database/migrations/1602179988932-SetStudentIdOnRepositoriesToCascade.ts rename to backend/src/database/migrations/1602179988932-SetSpotIdOnRepositoriesToCascade.ts index 0e57954..9545615 100644 --- a/backend/src/database/migrations/1602179988932-SetStudentIdOnRepositoriesToCascade.ts +++ b/backend/src/database/migrations/1602179988932-SetSpotIdOnRepositoriesToCascade.ts @@ -1,17 +1,17 @@ import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; -export default class SetStudentIdOnRepositoriesToCascade1602179988932 +export default class SetSpotIdOnRepositoriesToCascade1602179988932 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('repositories', 'repositoryStudent'); + await queryRunner.dropForeignKey('repositories', 'repositorySpot'); await queryRunner.createForeignKey( 'repositories', new TableForeignKey({ - name: 'repositoryStudent', - columnNames: ['student_id'], + name: 'repositorySpot', + columnNames: ['spot_id'], referencedColumnNames: ['id'], - referencedTableName: 'students', + referencedTableName: 'spots', onDelete: 'CASCADE', onUpdate: 'CASCADE', }), @@ -19,15 +19,15 @@ export default class SetStudentIdOnRepositoriesToCascade1602179988932 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropForeignKey('repositories', 'repositoryStudent'); + await queryRunner.dropForeignKey('repositories', 'repositorySpot'); await queryRunner.createForeignKey( 'repositories', new TableForeignKey({ - name: 'repositoryStudent', - columnNames: ['student_id'], + name: 'repositorySpot', + columnNames: ['spot'], referencedColumnNames: ['id'], - referencedTableName: 'students', + referencedTableName: 'spots', onDelete: 'SET NULL', onUpdate: 'CASCADE', }), diff --git a/backend/src/database/migrations/1603423271597-createStudentName.ts b/backend/src/database/migrations/1603423271597-createSpotName.ts similarity index 69% rename from backend/src/database/migrations/1603423271597-createStudentName.ts rename to backend/src/database/migrations/1603423271597-createSpotName.ts index 232a1b9..ae5a291 100644 --- a/backend/src/database/migrations/1603423271597-createStudentName.ts +++ b/backend/src/database/migrations/1603423271597-createSpotName.ts @@ -1,10 +1,9 @@ import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; -export default class createStudentName1603423271597 - implements MigrationInterface { +export default class createSpotName1603423271597 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise { await queryRunner.addColumn( - 'students', + 'spots', new TableColumn({ name: 'name', type: 'varchar', @@ -14,6 +13,6 @@ export default class createStudentName1603423271597 } public async down(queryRunner: QueryRunner): Promise { - await queryRunner.dropColumn('students', 'name'); + await queryRunner.dropColumn('spots', 'name'); } } From 946a1e33fffca00fa22714668b77f6cf53392b17 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:39:10 -0300 Subject: [PATCH 014/113] Parsing migrations to follow new names --- backend/src/models/Manager.ts | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 backend/src/models/Manager.ts diff --git a/backend/src/models/Manager.ts b/backend/src/models/Manager.ts new file mode 100644 index 0000000..c7549a9 --- /dev/null +++ b/backend/src/models/Manager.ts @@ -0,0 +1,42 @@ +import { + Column, + CreateDateColumn, + UpdateDateColumn, + Entity, + PrimaryGeneratedColumn, +} from 'typeorm'; + +@Entity('managers') +class Manager { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column('varchar') + github_login: string; + + @Column('varchar') + name: string; + + @Column('varchar') + email: string; + + @Column('varchar') + password: string; + + @Column('varchar') + github_token: string; + + @Column('varchar') + avatar_url: string; + + @Column('varchar') + github_id: string; + + @CreateDateColumn() + created_at: Date; + + @UpdateDateColumn() + updated_at: Date; +} + +export default Manager; From a5392cced985a253b8a47b86c572cac90030ce03 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:39:18 -0300 Subject: [PATCH 015/113] Parsing migrations to follow new names --- backend/src/models/{Student.ts => Spot.ts} | 16 +++---- ...udentDailyReport.ts => SpotDailyReport.ts} | 16 +++---- backend/src/models/Teacher.ts | 42 ------------------- backend/src/models/v2/Manager.ts | 42 ------------------- 4 files changed, 16 insertions(+), 100 deletions(-) rename backend/src/models/{Student.ts => Spot.ts} (70%) rename backend/src/models/{StudentDailyReport.ts => SpotDailyReport.ts} (72%) delete mode 100644 backend/src/models/Teacher.ts delete mode 100644 backend/src/models/v2/Manager.ts diff --git a/backend/src/models/Student.ts b/backend/src/models/Spot.ts similarity index 70% rename from backend/src/models/Student.ts rename to backend/src/models/Spot.ts index fb2a54c..0ca1d17 100644 --- a/backend/src/models/Student.ts +++ b/backend/src/models/Spot.ts @@ -8,19 +8,19 @@ import { JoinColumn, } from 'typeorm'; -import Teacher from './Teacher'; +import Manager from './Manager'; -@Entity('students') -class Student { +@Entity('spots') +class Spot { @PrimaryGeneratedColumn('uuid') id: string; @Column('uuid') - teacher_id: string; + manager_id: string; - @ManyToOne(() => Teacher, { eager: true }) - @JoinColumn({ name: 'teacher_id' }) - teacher: Teacher; + @ManyToOne(() => Manager, { eager: true }) + @JoinColumn({ name: 'manager_id' }) + teacher: Manager; @Column('varchar') github_login: string; @@ -44,4 +44,4 @@ class Student { updated_at: Date; } -export default Student; +export default Spot; diff --git a/backend/src/models/StudentDailyReport.ts b/backend/src/models/SpotDailyReport.ts similarity index 72% rename from backend/src/models/StudentDailyReport.ts rename to backend/src/models/SpotDailyReport.ts index b6a1c63..ee01795 100644 --- a/backend/src/models/StudentDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -8,19 +8,19 @@ import { UpdateDateColumn, } from 'typeorm'; -import Student from './Student'; +import Spot from './Spot'; -@Entity('student_daily_reports') -class StudentDailyReport { +@Entity('spot_daily_reports') +class SpotDailyReports { @PrimaryGeneratedColumn('uuid') id: string; @Column('uuid') - student_id: string; + spot_id: string; - @ManyToOne(() => Student, { eager: true }) - @JoinColumn({ name: 'student_id' }) - student: Student; + @ManyToOne(() => Spot, { eager: true }) + @JoinColumn({ name: 'spot_id' }) + student: Spot; @Column('int2') new_forks: number; @@ -56,4 +56,4 @@ class StudentDailyReport { updated_at: Date; } -export default StudentDailyReport; +export default SpotDailyReports; diff --git a/backend/src/models/Teacher.ts b/backend/src/models/Teacher.ts deleted file mode 100644 index b381902..0000000 --- a/backend/src/models/Teacher.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - Column, - CreateDateColumn, - UpdateDateColumn, - Entity, - PrimaryGeneratedColumn, -} from 'typeorm'; - -@Entity('teachers') -class Teacher { - @PrimaryGeneratedColumn('uuid') - id: string; - - @Column('varchar') - github_login: string; - - @Column('varchar') - name: string; - - @Column('varchar') - email: string; - - @Column('varchar') - password: string; - - @Column('varchar') - github_token: string; - - @Column('varchar') - avatar_url: string; - - @Column('varchar') - github_id: string; - - @CreateDateColumn() - created_at: Date; - - @UpdateDateColumn() - updated_at: Date; -} - -export default Teacher; diff --git a/backend/src/models/v2/Manager.ts b/backend/src/models/v2/Manager.ts deleted file mode 100644 index e963535..0000000 --- a/backend/src/models/v2/Manager.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - Column, - CreateDateColumn, - UpdateDateColumn, - Entity, - PrimaryGeneratedColumn, -} from 'typeorm'; - -@Entity('teachers') -class Manager { - @PrimaryGeneratedColumn('uuid') - id: string; - - @Column('varchar') - github_login: string; - - @Column('varchar') - name: string; - - @Column('varchar') - email: string; - - @Column('varchar') - password: string; - - @Column('varchar') - github_token: string; - - @Column('varchar') - avatar_url: string; - - @Column('varchar') - github_id: string; - - @CreateDateColumn() - created_at: Date; - - @UpdateDateColumn() - updated_at: Date; -} - -export default Manager; From 78923da9bd4022708deef5bb7b0d26f2c02d7d4e Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:40:02 -0300 Subject: [PATCH 016/113] Parsing migrations to follow new names --- backend/src/models/Commit.ts | 4 +- backend/src/models/Repository.ts | 2 +- .../StudentDailyReportsRepository.ts | 2 +- backend/src/services/CreateManagerService.ts | 2 +- backend/src/services/GetGithubTokenService.ts | 2 +- .../services/v1/AuthenticateTeacherService.ts | 42 +++++++++++++++++++ .../ProcessStudent/ProcessStudentProcessor.ts | 2 +- .../RequestStudentsProcessProcessor.ts | 2 +- 8 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 backend/src/services/v1/AuthenticateTeacherService.ts diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index 0a3fe86..2fc4be5 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -9,8 +9,8 @@ import { } from 'typeorm'; import Repository from './Repository'; -import Student from './Student'; -import StudentDailyReport from './StudentDailyReport'; +import Student from './Spot'; +import StudentDailyReport from './SpotDailyReport'; @Entity('commits') class Commit { diff --git a/backend/src/models/Repository.ts b/backend/src/models/Repository.ts index 286a485..f3522d7 100644 --- a/backend/src/models/Repository.ts +++ b/backend/src/models/Repository.ts @@ -8,7 +8,7 @@ import { UpdateDateColumn, } from 'typeorm'; -import Student from './Student'; +import Student from './Spot'; @Entity('repositories') class Repository { diff --git a/backend/src/repositories/StudentDailyReportsRepository.ts b/backend/src/repositories/StudentDailyReportsRepository.ts index 62cb481..b19bafd 100644 --- a/backend/src/repositories/StudentDailyReportsRepository.ts +++ b/backend/src/repositories/StudentDailyReportsRepository.ts @@ -1,6 +1,6 @@ import { EntityRepository, Repository, Between } from 'typeorm'; -import StudentDailyReport from '../models/StudentDailyReport'; +import StudentDailyReport from '../models/SpotDailyReport'; @EntityRepository(StudentDailyReport) class StudentDailyReportsRepository extends Repository { diff --git a/backend/src/services/CreateManagerService.ts b/backend/src/services/CreateManagerService.ts index 1fee7b8..47a3a3c 100644 --- a/backend/src/services/CreateManagerService.ts +++ b/backend/src/services/CreateManagerService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; import api from './githubApi/RestApi'; -import Teacher from '../models/Teacher'; +import Teacher from '../models/Manager'; interface Request { github_login: string; diff --git a/backend/src/services/GetGithubTokenService.ts b/backend/src/services/GetGithubTokenService.ts index c4199e3..31ca324 100644 --- a/backend/src/services/GetGithubTokenService.ts +++ b/backend/src/services/GetGithubTokenService.ts @@ -1,5 +1,5 @@ import { getRepository } from 'typeorm'; -import Teacher from '../models/Teacher'; +import Teacher from '../models/Manager'; import { decrypt } from '../utils/crypto'; class GetGithubTokenService { diff --git a/backend/src/services/v1/AuthenticateTeacherService.ts b/backend/src/services/v1/AuthenticateTeacherService.ts new file mode 100644 index 0000000..6678ff1 --- /dev/null +++ b/backend/src/services/v1/AuthenticateTeacherService.ts @@ -0,0 +1,42 @@ +import { getRepository } from 'typeorm'; +import { compare } from 'bcryptjs'; +import jwt from 'jsonwebtoken'; +import Teacher from '../../models/Manager'; +import AppError from '../../errors/AppError'; + +interface Response { + teacher: Teacher; + token: string; +} + +class AuthenticateTeacherService { + public async execute(email: string, password: string): Promise { + const teachersRepository = getRepository(Teacher); + + const teacher = await teachersRepository.findOne({ email }); + + if (!teacher) { + throw new AppError('E-mail not found.', 404); + } + + const passwordMatched = await compare(password, teacher.password); + + if (!passwordMatched) { + throw new AppError('Incorrect password.', 401); + } + + const secret = process.env.JWT_SECRET; + if (!secret) { + throw new AppError('Internal server error.', 500); + } + + const token = jwt.sign({}, secret, { + subject: teacher.id, + expiresIn: '7d', + }); + + return { teacher, token }; + } +} + +export default AuthenticateTeacherService; diff --git a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts b/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts index e97b8e9..f8bf216 100644 --- a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts +++ b/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; import { Job } from 'bullmq'; -import Student from '../../models/Student'; +import Student from '../../models/Spot'; import Repository from '../../models/Repository'; import { StudentRequest } from '../../providers/queue/QueueProvider'; diff --git a/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts b/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts index 1d6f4fa..9e2c7c1 100644 --- a/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts +++ b/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; import { queueProvider } from '../../app'; -import Student from '../../models/Student'; +import Student from '../../models/Spot'; const requestStudentsProcessProcessor = async (): Promise => { const studentsRepository = getRepository(Student); From 511892cd0a6b686dbc617d4bd82297c19d6dc496 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:42:14 -0300 Subject: [PATCH 017/113] Parsing migrations to follow new names --- backend/src/models/Commit.ts | 14 +++++++------- backend/src/models/Repository.ts | 10 +++++----- backend/src/models/Spot.ts | 2 +- backend/src/models/SpotDailyReport.ts | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index 2fc4be5..27ffaf8 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -9,7 +9,7 @@ import { } from 'typeorm'; import Repository from './Repository'; -import Student from './Spot'; +import Spot from './Spot'; import StudentDailyReport from './SpotDailyReport'; @Entity('commits') @@ -27,16 +27,16 @@ class Commit { @Column('uuid') student_id: string; - @ManyToOne(() => Student, { eager: true }) - @JoinColumn({ name: 'student_id' }) - student: Student; + @ManyToOne(() => Spot, { eager: true }) + @JoinColumn({ name: 'spot_id' }) + spot: Spot; @Column('uuid') - student_daily_report_id: string; + spot_daily_report_id: string; @ManyToOne(() => StudentDailyReport, { eager: true }) - @JoinColumn({ name: 'student_daily_report_id' }) - studentDailyReport: StudentDailyReport; + @JoinColumn({ name: 'spot_daily_report_id' }) + spotDailyReport: StudentDailyReport; @Column('varchar') message: string; diff --git a/backend/src/models/Repository.ts b/backend/src/models/Repository.ts index f3522d7..d5e1c43 100644 --- a/backend/src/models/Repository.ts +++ b/backend/src/models/Repository.ts @@ -8,7 +8,7 @@ import { UpdateDateColumn, } from 'typeorm'; -import Student from './Spot'; +import Spot from './Spot'; @Entity('repositories') class Repository { @@ -16,11 +16,11 @@ class Repository { id: string; @Column('uuid') - student_id: string; + spot_id: string; - @ManyToOne(() => Student, { eager: true }) - @JoinColumn({ name: 'student_id' }) - student: Student; + @ManyToOne(() => Spot, { eager: true }) + @JoinColumn({ name: 'spot_id' }) + spot: Spot; @Column('varchar') name: string; diff --git a/backend/src/models/Spot.ts b/backend/src/models/Spot.ts index 0ca1d17..5b4c1fd 100644 --- a/backend/src/models/Spot.ts +++ b/backend/src/models/Spot.ts @@ -20,7 +20,7 @@ class Spot { @ManyToOne(() => Manager, { eager: true }) @JoinColumn({ name: 'manager_id' }) - teacher: Manager; + manager: Manager; @Column('varchar') github_login: string; diff --git a/backend/src/models/SpotDailyReport.ts b/backend/src/models/SpotDailyReport.ts index ee01795..032fbad 100644 --- a/backend/src/models/SpotDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -20,7 +20,7 @@ class SpotDailyReports { @ManyToOne(() => Spot, { eager: true }) @JoinColumn({ name: 'spot_id' }) - student: Spot; + spot: Spot; @Column('int2') new_forks: number; From c9e7c5b5a76e0cc3c1117b5c3f0c425e8ab42b85 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:43:56 -0300 Subject: [PATCH 018/113] Parsing migrations to follow new names --- backend/src/models/SpotDailyReport.ts | 4 +-- .../SpotDailyReportsRepository.ts | 26 +++++++++++++++++++ .../StudentDailyReportsRepository.ts | 26 ------------------- 3 files changed, 28 insertions(+), 28 deletions(-) create mode 100644 backend/src/repositories/SpotDailyReportsRepository.ts delete mode 100644 backend/src/repositories/StudentDailyReportsRepository.ts diff --git a/backend/src/models/SpotDailyReport.ts b/backend/src/models/SpotDailyReport.ts index 032fbad..add52da 100644 --- a/backend/src/models/SpotDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -11,7 +11,7 @@ import { import Spot from './Spot'; @Entity('spot_daily_reports') -class SpotDailyReports { +class SpotDailyReport { @PrimaryGeneratedColumn('uuid') id: string; @@ -56,4 +56,4 @@ class SpotDailyReports { updated_at: Date; } -export default SpotDailyReports; +export default SpotDailyReport; diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts new file mode 100644 index 0000000..1fea91e --- /dev/null +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -0,0 +1,26 @@ +import { EntityRepository, Repository, Between } from 'typeorm'; + +import SpotDailyReport from '../models/SpotDailyReport'; + +@EntityRepository(SpotDailyReport) +class SpotDailyReportsRepository extends Repository { + public async findByPeriod( + student_id: string, + since: Date, + until: Date, + ): Promise { + since.setDate(since.getDate() - 1); + until.setDate(until.getDate() + 1); + + const foundSpotDailyReports = await this.find({ + where: { + created_at: Between(since, until), + student_id, + }, + }); + + return foundSpotDailyReports || null; + } +} + +export default SpotDailyReportsRepository; diff --git a/backend/src/repositories/StudentDailyReportsRepository.ts b/backend/src/repositories/StudentDailyReportsRepository.ts deleted file mode 100644 index b19bafd..0000000 --- a/backend/src/repositories/StudentDailyReportsRepository.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { EntityRepository, Repository, Between } from 'typeorm'; - -import StudentDailyReport from '../models/SpotDailyReport'; - -@EntityRepository(StudentDailyReport) -class StudentDailyReportsRepository extends Repository { - public async findByPeriod( - student_id: string, - since: Date, - until: Date, - ): Promise { - since.setDate(since.getDate() - 1); - until.setDate(until.getDate() + 1); - - const foundStudentDailyReports = await this.find({ - where: { - created_at: Between(since, until), - student_id, - }, - }); - - return foundStudentDailyReports || null; - } -} - -export default StudentDailyReportsRepository; From fd3823d56adabbbc9ebdf862c9428049f098e1b9 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:46:42 -0300 Subject: [PATCH 019/113] Parsing names --- backend/src/controllers/SessionController.ts | 31 +++++++++++++++++++ backend/src/services/CreateManagerService.ts | 4 +-- ...rvice.ts => AuthenticateManagerService.ts} | 20 ++++++------ 3 files changed, 43 insertions(+), 12 deletions(-) create mode 100644 backend/src/controllers/SessionController.ts rename backend/src/services/v1/{AuthenticateTeacherService.ts => AuthenticateManagerService.ts} (61%) diff --git a/backend/src/controllers/SessionController.ts b/backend/src/controllers/SessionController.ts new file mode 100644 index 0000000..cb399fa --- /dev/null +++ b/backend/src/controllers/SessionController.ts @@ -0,0 +1,31 @@ +import { Request, Response } from 'express'; +import * as yup from 'yup'; + +import AuthenticateTeacherService from '../services/v1/AuthenticateManagerService'; + +class SessionController { + static async store(request: Request, response: Response): Promise { + const schema = yup.object().shape({ + email: yup.string().required('E-mail is required.'), + password: yup.string().required('Password is required.'), + }); + + await schema.validate(request.body); + + const { email, password } = request.body; + + const authenticateTeacher = new AuthenticateTeacherService(); + const { manager, token } = await authenticateTeacher.execute( + email, + password, + ); + + delete manager.password; + const hasGithubToken = !!manager.github_token; + delete manager.github_token; + + return response.json({ manager, token, hasGithubToken }); + } +} + +export default SessionController; diff --git a/backend/src/services/CreateManagerService.ts b/backend/src/services/CreateManagerService.ts index 47a3a3c..9e9e683 100644 --- a/backend/src/services/CreateManagerService.ts +++ b/backend/src/services/CreateManagerService.ts @@ -1,6 +1,6 @@ import { getRepository } from 'typeorm'; import api from './githubApi/RestApi'; -import Teacher from '../models/Manager'; +import Manager from '../models/Manager'; interface Request { github_login: string; @@ -22,7 +22,7 @@ class CreateManagerService { email, password, }: Request): Promise { - const managerRepository = getRepository(Teacher); + const managerRepository = getRepository(Manager); const githubData = await api.get(`/users/${github_login}`); diff --git a/backend/src/services/v1/AuthenticateTeacherService.ts b/backend/src/services/v1/AuthenticateManagerService.ts similarity index 61% rename from backend/src/services/v1/AuthenticateTeacherService.ts rename to backend/src/services/v1/AuthenticateManagerService.ts index 6678ff1..7660bc6 100644 --- a/backend/src/services/v1/AuthenticateTeacherService.ts +++ b/backend/src/services/v1/AuthenticateManagerService.ts @@ -1,25 +1,25 @@ import { getRepository } from 'typeorm'; import { compare } from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import Teacher from '../../models/Manager'; +import Manager from '../../models/Manager'; import AppError from '../../errors/AppError'; interface Response { - teacher: Teacher; + manager: Manager; token: string; } -class AuthenticateTeacherService { +class AuthenticateManagerService { public async execute(email: string, password: string): Promise { - const teachersRepository = getRepository(Teacher); + const managersRepository = getRepository(Manager); - const teacher = await teachersRepository.findOne({ email }); + const manager = await managersRepository.findOne({ email }); - if (!teacher) { + if (!manager) { throw new AppError('E-mail not found.', 404); } - const passwordMatched = await compare(password, teacher.password); + const passwordMatched = await compare(password, manager.password); if (!passwordMatched) { throw new AppError('Incorrect password.', 401); @@ -31,12 +31,12 @@ class AuthenticateTeacherService { } const token = jwt.sign({}, secret, { - subject: teacher.id, + subject: manager.id, expiresIn: '7d', }); - return { teacher, token }; + return { manager, token }; } } -export default AuthenticateTeacherService; +export default AuthenticateManagerService; From c062b8a4c433ef44207d7bcd1e4b93a768004efa Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:51:48 -0300 Subject: [PATCH 020/113] Parsing names --- backend/src/app.ts | 6 +- backend/src/providers/queue/QueueProvider.ts | 6 +- .../ProcessSpot/ProcessSpotProcessor.ts | 10 +++ .../ProcessStudent/ProcessStudentProcessor.ts | 78 ------------------- .../RequestSpotsProcessProcessor.ts | 26 +++++++ .../RequestStudentsProcessProcessor.ts | 26 ------- 6 files changed, 42 insertions(+), 110 deletions(-) create mode 100644 backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts delete mode 100644 backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts create mode 100644 backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts delete mode 100644 backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 5b853e6..9b536d3 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -3,15 +3,15 @@ import cors from 'cors'; import 'express-async-errors'; import 'reflect-metadata'; import dotenv from 'dotenv'; -import cron from 'node-cron'; +// import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; import v2 from './routes/v2/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; -import RequestStudentsProcessProcessor from './workers/RequestStudentsProcess/RequestStudentsProcessProcessor'; -import ProcessStudentProcessor from './workers/ProcessStudent/ProcessStudentProcessor'; +// import RequestSpotsProcessProcessor from './workers/RequestSpotsProcess/RequestSpotsProcessProcessor'; +// import ProcessSpotProcessor from './workers/ProcessSpot/ProcessSpotProcessor'; import { QueueProvider } from './providers/queue/QueueProvider'; import './database'; diff --git a/backend/src/providers/queue/QueueProvider.ts b/backend/src/providers/queue/QueueProvider.ts index 1398685..6f6e1ef 100644 --- a/backend/src/providers/queue/QueueProvider.ts +++ b/backend/src/providers/queue/QueueProvider.ts @@ -1,11 +1,11 @@ -interface StudentRequest { +interface SpotRequest { github_id: string; } interface addJobRequest { queueName: string; jobName: string; - job?: StudentRequest; + job?: SpotRequest; opts?: { removeOnComplete: boolean; }; @@ -21,4 +21,4 @@ interface QueueProvider { setUI(): void; } -export { QueueProvider, addJobRequest, registerQueueRequest, StudentRequest }; +export { QueueProvider, addJobRequest, registerQueueRequest, SpotRequest }; diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts new file mode 100644 index 0000000..5e7e367 --- /dev/null +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -0,0 +1,10 @@ +import { Job } from 'bullmq'; + +import { SpotRequest } from '../../providers/queue/QueueProvider'; + +const ProcessSpotProcessor = async (job: Job): Promise => { + console.log(job); + return null; +}; + +export default ProcessSpotProcessor; diff --git a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts b/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts deleted file mode 100644 index f8bf216..0000000 --- a/backend/src/workers/ProcessStudent/ProcessStudentProcessor.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { getRepository } from 'typeorm'; -import { Job } from 'bullmq'; -import Student from '../../models/Spot'; -import Repository from '../../models/Repository'; -import { StudentRequest } from '../../providers/queue/QueueProvider'; - -import GetUserService from '../../services/v1/GetUserService'; -import GetUserDailyReportService from '../../services/v1/GetUserDailyReportService'; -import CreateStudentDailyReportService from '../../services/v1/CreateStudentDailyReportService'; -import CreateCommitService from '../../services/v1/CreateCommitService'; - -const processStudentProcessor = async ( - job: Job, -): Promise => { - const { github_id } = job.data; - - const studentsRepository = getRepository(Student); - const repositoriesRepository = getRepository(Repository); - - const { id: student_id } = await studentsRepository.findOne({ github_id }); - - const getUser = new GetUserService(); - const { github_login } = await getUser.execute({ github_id }); - - const getUserDailyReport = new GetUserDailyReportService(); - const { payload } = await getUserDailyReport.execute(github_login); - - const { - additions, - commits, - deletions, - new_commits, - new_forks, - new_interactions, - new_issues, - new_prs, - new_repositories, - new_stars, - } = payload; - - const createStudentDailyReport = new CreateStudentDailyReportService(); - const studentDailyReport = await createStudentDailyReport.execute({ - additions, - deletions, - new_commits, - new_forks, - new_interactions, - new_issues, - new_prs, - new_repositories, - new_stars, - student_id, - }); - - const createCommit = new CreateCommitService(); - for (const commit of commits) { - const repository = await repositoriesRepository.findOne({ - github_id: commit.repository.id, - }); - - let repository_id = null; - if (repository) { - repository_id = repository.id; - } - - await createCommit.execute({ - additions: commit.additions, - deletions: commit.deletions, - message: commit.message, - sha: commit.sha, - student_daily_report_id: studentDailyReport.id, - student_id, - repository_id, - }); - } -}; - -export default processStudentProcessor; diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts new file mode 100644 index 0000000..4fb74a7 --- /dev/null +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -0,0 +1,26 @@ +import { getRepository } from 'typeorm'; +import { queueProvider } from '../../app'; +import Spot from '../../models/Spot'; + +const RequestSpotsProcessProcessor = async (): Promise => { + const spotsRepository = getRepository(Spot); + + const spots = await spotsRepository.find(); + + spots.forEach((spot: Spot) => { + console.log(`Request spot ${spot.github_login} process`); + + queueProvider.add({ + job: { + github_id: spot.github_id, + }, + jobName: `${spot.github_id} process request`, + queueName: 'spot-processor', + opts: { + removeOnComplete: false, + }, + }); + }); +}; + +export default RequestSpotsProcessProcessor; diff --git a/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts b/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts deleted file mode 100644 index 9e2c7c1..0000000 --- a/backend/src/workers/RequestStudentsProcess/RequestStudentsProcessProcessor.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { getRepository } from 'typeorm'; -import { queueProvider } from '../../app'; -import Student from '../../models/Spot'; - -const requestStudentsProcessProcessor = async (): Promise => { - const studentsRepository = getRepository(Student); - - const students = await studentsRepository.find(); - - students.forEach((student: Student) => { - console.log(`Request student ${student.github_login} process`); - - queueProvider.add({ - job: { - github_id: student.github_id, - }, - jobName: `${student.github_id} process request`, - queueName: 'student-processor', - opts: { - removeOnComplete: false, - }, - }); - }); -}; - -export default requestStudentsProcessProcessor; From c6859f61189303e7bb3f2e84b6696214882138f7 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:53:19 -0300 Subject: [PATCH 021/113] Parsing names --- backend/src/controllers/SessionController.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/controllers/SessionController.ts b/backend/src/controllers/SessionController.ts index cb399fa..d24e77f 100644 --- a/backend/src/controllers/SessionController.ts +++ b/backend/src/controllers/SessionController.ts @@ -1,7 +1,7 @@ import { Request, Response } from 'express'; import * as yup from 'yup'; -import AuthenticateTeacherService from '../services/v1/AuthenticateManagerService'; +import AuthenticateManagerService from '../services/AuthenticateManagerService'; class SessionController { static async store(request: Request, response: Response): Promise { @@ -14,8 +14,8 @@ class SessionController { const { email, password } = request.body; - const authenticateTeacher = new AuthenticateTeacherService(); - const { manager, token } = await authenticateTeacher.execute( + const authenticateManager = new AuthenticateManagerService(); + const { manager, token } = await authenticateManager.execute( email, password, ); From b94603ea61bef2d21a86ec5f16b10410550c2e53 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:53:24 -0300 Subject: [PATCH 022/113] Parsing names --- backend/src/services/{v1 => }/AuthenticateManagerService.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename backend/src/services/{v1 => }/AuthenticateManagerService.ts (91%) diff --git a/backend/src/services/v1/AuthenticateManagerService.ts b/backend/src/services/AuthenticateManagerService.ts similarity index 91% rename from backend/src/services/v1/AuthenticateManagerService.ts rename to backend/src/services/AuthenticateManagerService.ts index 7660bc6..91e5128 100644 --- a/backend/src/services/v1/AuthenticateManagerService.ts +++ b/backend/src/services/AuthenticateManagerService.ts @@ -1,8 +1,8 @@ import { getRepository } from 'typeorm'; import { compare } from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import Manager from '../../models/Manager'; -import AppError from '../../errors/AppError'; +import Manager from '../models/Manager'; +import AppError from '../errors/AppError'; interface Response { manager: Manager; From c55e244fcea12a1f61ff130d80db1719c538c6f6 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 12:54:11 -0300 Subject: [PATCH 023/113] Parsing names --- backend/src/services/GetGithubTokenService.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/backend/src/services/GetGithubTokenService.ts b/backend/src/services/GetGithubTokenService.ts index 31ca324..9184772 100644 --- a/backend/src/services/GetGithubTokenService.ts +++ b/backend/src/services/GetGithubTokenService.ts @@ -1,15 +1,15 @@ import { getRepository } from 'typeorm'; -import Teacher from '../models/Manager'; +import Manager from '../models/Manager'; import { decrypt } from '../utils/crypto'; class GetGithubTokenService { async execute(): Promise { - const teachersRepository = getRepository(Teacher); + const managersRepository = getRepository(Manager); - const teacher = await teachersRepository.findOne(); - if (!teacher || !teacher.github_token) return ''; + const manager = await managersRepository.findOne(); + if (!manager || !manager.github_token) return ''; - return decrypt(teacher.github_token); + return decrypt(manager.github_token); } } From 1b54c025fe607e1466185a598c4a33a15b0fe7cb Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 13:13:19 -0300 Subject: [PATCH 024/113] Creating manager ok --- backend/src/services/CreateManagerService.ts | 28 ++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/backend/src/services/CreateManagerService.ts b/backend/src/services/CreateManagerService.ts index 9e9e683..426293e 100644 --- a/backend/src/services/CreateManagerService.ts +++ b/backend/src/services/CreateManagerService.ts @@ -1,6 +1,8 @@ import { getRepository } from 'typeorm'; +import { hash } from 'bcryptjs'; import api from './githubApi/RestApi'; import Manager from '../models/Manager'; +import AppError from '../errors/AppError'; interface Request { github_login: string; @@ -22,13 +24,35 @@ class CreateManagerService { email, password, }: Request): Promise { - const managerRepository = getRepository(Manager); + const managersRepository = getRepository(Manager); + + const existsManager = await managersRepository.findOne({ + email, + }); + + if (existsManager) { + throw new AppError('E-mail address already used'); + } const githubData = await api.get(`/users/${github_login}`); const { login, name, avatar_url, id } = githubData.data; - return null; + const hashedPassword = await hash(password, 8); + + const manager = await managersRepository.create({ + avatar_url, + email, + name, + github_login: login, + github_id: id, + password: hashedPassword, + }); + + await managersRepository.save(manager); + delete manager.password; + + return manager; } } From 751721858a1e4ddf7d376351815496235a71c5fb Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 13:34:37 -0300 Subject: [PATCH 025/113] rename express type --- backend/src/@types/express.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/@types/express.d.ts b/backend/src/@types/express.d.ts index 33417a3..a64fa6e 100644 --- a/backend/src/@types/express.d.ts +++ b/backend/src/@types/express.d.ts @@ -1,6 +1,6 @@ declare namespace Express { export interface Request { - teacher: { + manager: { id: string; }; } From 8dfbcd0e7c4dbd70b071210a8d8410ce29998375 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 13:43:43 -0300 Subject: [PATCH 026/113] Moving manager services --- backend/src/routes/v2/manager.routes.ts | 2 +- .../services/{ => Manager}/AuthenticateManagerService.ts | 0 backend/src/services/{ => Manager}/CreateManagerService.ts | 6 +++--- 3 files changed, 4 insertions(+), 4 deletions(-) rename backend/src/services/{ => Manager}/AuthenticateManagerService.ts (100%) rename backend/src/services/{ => Manager}/CreateManagerService.ts (89%) diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/v2/manager.routes.ts index 712ca04..a7a1830 100644 --- a/backend/src/routes/v2/manager.routes.ts +++ b/backend/src/routes/v2/manager.routes.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; -import CreateManagerService from '../../services/CreateManagerService'; +import CreateManagerService from '../../services/Manager/CreateManagerService'; const manangerRouter = Router(); diff --git a/backend/src/services/AuthenticateManagerService.ts b/backend/src/services/Manager/AuthenticateManagerService.ts similarity index 100% rename from backend/src/services/AuthenticateManagerService.ts rename to backend/src/services/Manager/AuthenticateManagerService.ts diff --git a/backend/src/services/CreateManagerService.ts b/backend/src/services/Manager/CreateManagerService.ts similarity index 89% rename from backend/src/services/CreateManagerService.ts rename to backend/src/services/Manager/CreateManagerService.ts index 426293e..14a5ec4 100644 --- a/backend/src/services/CreateManagerService.ts +++ b/backend/src/services/Manager/CreateManagerService.ts @@ -1,8 +1,8 @@ import { getRepository } from 'typeorm'; import { hash } from 'bcryptjs'; -import api from './githubApi/RestApi'; -import Manager from '../models/Manager'; -import AppError from '../errors/AppError'; +import api from '../githubApi/RestApi'; +import Manager from '../../models/Manager'; +import AppError from '../../errors/AppError'; interface Request { github_login: string; From cc451a29166dc294bcaa1576761073afe12058e3 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 13:57:41 -0300 Subject: [PATCH 027/113] Create Spot Service --- backend/src/routes/v2/index.ts | 2 + backend/src/routes/v2/spots.routes.ts | 20 +++++ .../src/services/Spot/CreateSpotService.ts | 83 +++++++++++++++++++ backend/src/services/githubApi/GraphQLApi.ts | 2 +- 4 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 backend/src/routes/v2/spots.routes.ts create mode 100644 backend/src/services/Spot/CreateSpotService.ts diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index 04661fd..2e1cae1 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -1,8 +1,10 @@ import { Router } from 'express'; import manangerRouter from './manager.routes'; +import spotRouter from './spots.routes'; const routes = Router(); routes.use('/manager', manangerRouter); +routes.use('/spot', spotRouter); export default routes; diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots.routes.ts new file mode 100644 index 0000000..25e456d --- /dev/null +++ b/backend/src/routes/v2/spots.routes.ts @@ -0,0 +1,20 @@ +import { Router } from 'express'; +import CreateSpotService from '../../services/Spot/CreateSpotService'; + +const spotRouter = Router(); + +spotRouter.post('/', async (request, response) => { + const { github_login } = request.body; + const { id } = request.manager; + + const createSpotService = new CreateSpotService(); + + const spot = await createSpotService.execute({ + manager_id: id, + spot_github_login: github_login, + }); + + return response.json(spot); +}); + +export default spotRouter; diff --git a/backend/src/services/Spot/CreateSpotService.ts b/backend/src/services/Spot/CreateSpotService.ts new file mode 100644 index 0000000..20b512f --- /dev/null +++ b/backend/src/services/Spot/CreateSpotService.ts @@ -0,0 +1,83 @@ +import { getRepository } from 'typeorm'; +import Manager from '../../models/Manager'; +import Spot from '../../models/Spot'; +import { AppError } from '../../errors/AppError'; +import api from '../githubApi/GraphQLApi'; +import Repository from '../../models/Repository'; + +interface Request { + manager_id: string; + spot_github_login: string; +} + +interface Repository { + id: string; + name: string; + full_name: string; + description: string; + html_url: string; + created_at: string; + language: string; +} + +interface Response { + github_login: string; + avatar_url: string; + repositories: Repository[]; +} + +class CreateSpotService { + async execute({ manager_id, spot_github_login }: Request): Promise { + const managersRepository = getRepository(Manager); + const spotsRepository = getRepository(Spot); + const repositoriesRepository = getRepository(Repository); + + const existsManager = await managersRepository.findOne({ + id: manager_id, + }); + + if (!existsManager) { + throw new AppError('Manager does not exists'); + } + + const existsSpot = await spotsRepository.findOne({ + github_login: spot_github_login, + }); + + if (!existsSpot) { + throw new AppError('Spot already registered'); + } + + const spotGithubData = await api.post('', { + query: this.getQuery(spot_github_login), + }); + + console.log(spotGithubData.data); + + return null; + } + + private getQuery(github_id: string): string { + const query = `query { + user(login: "${github_id}") { + bio + login + name + avatarUrl + id + repositories(first: 100 privacy: PUBLIC affiliations: OWNER) { + nodes { + nameWithOwner + description + url + id + } + } + } + }`; + + return query; + } +} + +export default CreateSpotService; diff --git a/backend/src/services/githubApi/GraphQLApi.ts b/backend/src/services/githubApi/GraphQLApi.ts index f84fa01..21aa032 100644 --- a/backend/src/services/githubApi/GraphQLApi.ts +++ b/backend/src/services/githubApi/GraphQLApi.ts @@ -18,7 +18,7 @@ api.interceptors.request.use(async config => { } } if (useGlobal.teacherToken) { - config.headers.authorization = `token ${useGlobal.teacherToken}`; + config.headers.authorization = `bearer ${useGlobal.teacherToken}`; } return config; From d51d226821b1760d2da10abcdd3b2ebc1bae861b Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 14:02:35 -0300 Subject: [PATCH 028/113] Session route --- backend/src/routes/v2/index.ts | 2 ++ backend/src/routes/v2/sessions.routes.ts | 21 +++++++++++++++++++ .../Manager/AuthenticateManagerService.ts | 11 +++++++--- 3 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 backend/src/routes/v2/sessions.routes.ts diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index 2e1cae1..fef2ff8 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -1,10 +1,12 @@ import { Router } from 'express'; import manangerRouter from './manager.routes'; import spotRouter from './spots.routes'; +import sessionsRouter from './sessions.routes'; const routes = Router(); routes.use('/manager', manangerRouter); routes.use('/spot', spotRouter); +routes.use('/session', sessionsRouter); export default routes; diff --git a/backend/src/routes/v2/sessions.routes.ts b/backend/src/routes/v2/sessions.routes.ts new file mode 100644 index 0000000..c7d518b --- /dev/null +++ b/backend/src/routes/v2/sessions.routes.ts @@ -0,0 +1,21 @@ +import { Router } from 'express'; +import AuthenticateManagerService from '../../services/Manager/AuthenticateManagerService'; + +const sessionsRouter = Router(); + +sessionsRouter.post('/', async (request, response) => { + const { email, password } = request.body; + + const authenticateUser = new AuthenticateManagerService(); + + const { manager, token } = await authenticateUser.execute({ + email, + password, + }); + + delete manager.password; + + return response.json({ manager, token }); +}); + +export default sessionsRouter; diff --git a/backend/src/services/Manager/AuthenticateManagerService.ts b/backend/src/services/Manager/AuthenticateManagerService.ts index 91e5128..3de4f7a 100644 --- a/backend/src/services/Manager/AuthenticateManagerService.ts +++ b/backend/src/services/Manager/AuthenticateManagerService.ts @@ -1,16 +1,21 @@ import { getRepository } from 'typeorm'; import { compare } from 'bcryptjs'; import jwt from 'jsonwebtoken'; -import Manager from '../models/Manager'; -import AppError from '../errors/AppError'; +import Manager from '../../models/Manager'; +import AppError from '../../errors/AppError'; interface Response { manager: Manager; token: string; } +interface Request { + email: string; + password: string; +} + class AuthenticateManagerService { - public async execute(email: string, password: string): Promise { + public async execute({ email, password }: Request): Promise { const managersRepository = getRepository(Manager); const manager = await managersRepository.findOne({ email }); From d07f17fd71072887869960b985a1d610ec672f3c Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 14:23:13 -0300 Subject: [PATCH 029/113] Setting github token --- backend/src/routes/v2/manager.routes.ts | 11 +++ .../services/Manager/SetGithubTokenService.ts | 69 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 backend/src/services/Manager/SetGithubTokenService.ts diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/v2/manager.routes.ts index a7a1830..a6f4e7f 100644 --- a/backend/src/routes/v2/manager.routes.ts +++ b/backend/src/routes/v2/manager.routes.ts @@ -1,5 +1,6 @@ import { Router } from 'express'; import CreateManagerService from '../../services/Manager/CreateManagerService'; +import SetGithubTokenService from '../../services/Manager/SetGithubTokenService'; const manangerRouter = Router(); @@ -17,4 +18,14 @@ manangerRouter.post('/', async (request, response) => { return response.json(manager); }); +manangerRouter.get('/callback', async (request, response) => { + const { code } = request.query; + + const setGithubTokenService = new SetGithubTokenService(); + + await setGithubTokenService.execute({ code: code as string }); + + return response.json({ message: 'Github Token registered.' }); +}); + export default manangerRouter; diff --git a/backend/src/services/Manager/SetGithubTokenService.ts b/backend/src/services/Manager/SetGithubTokenService.ts new file mode 100644 index 0000000..42418c1 --- /dev/null +++ b/backend/src/services/Manager/SetGithubTokenService.ts @@ -0,0 +1,69 @@ +import axios from 'axios'; +import { getRepository } from 'typeorm'; +import AppError from '../../errors/AppError'; +import { encrypt } from '../../utils/crypto'; +import Manager from '../../models/Manager'; + +interface Request { + code: string; +} + +class SetGithubTokenService { + async execute({ code }: Request): Promise { + const clientId = process.env.GITHUB_APP_CLIENT_ID; + const clientSecret = process.env.GITHUB_APP_CLIENT_SECRET; + const managersRepository = getRepository(Manager); + + if (!clientId || !clientSecret) { + throw new AppError('Internal server error.', 500); + } + + let tokenRequest; + try { + tokenRequest = await axios.post( + 'https://github.com/login/oauth/access_token', + { + client_id: clientId, + client_secret: clientSecret, + code, + }, + { + headers: { + Accept: 'application/json', + }, + }, + ); + } catch (error) { + throw new AppError('Not able to get github access token.', 401); + } + + const accessToken = tokenRequest.data.access_token; + if (!accessToken) { + throw new AppError('Not able to get github access token.', 401); + } + + let response; + try { + response = await axios.get('https://api.github.com/user', { + headers: { + Authorization: `token ${accessToken}`, + }, + }); + } catch (error) { + throw new AppError('Unable to get user information on GitHub api.', 500); + } + const { login } = response.data; + + const encryptedToken = encrypt(accessToken); + + const manager = await managersRepository.findOne({ + github_login: login, + }); + + manager.github_token = encryptedToken; + + await managersRepository.save(manager); + } +} + +export default SetGithubTokenService; From d0cb887f70328badfc5a2acfaff35dec4eff9c29 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 14:25:09 -0300 Subject: [PATCH 030/113] auth completed --- backend/src/middlewares/authMiddleware.ts | 2 +- backend/src/routes/v2/spots.routes.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.ts index e79b55f..6077b89 100644 --- a/backend/src/middlewares/authMiddleware.ts +++ b/backend/src/middlewares/authMiddleware.ts @@ -31,7 +31,7 @@ function authMiddleware( const { sub } = decoded; - request.teacher = { + request.manager = { id: sub, }; diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots.routes.ts index 25e456d..914a4a9 100644 --- a/backend/src/routes/v2/spots.routes.ts +++ b/backend/src/routes/v2/spots.routes.ts @@ -1,9 +1,10 @@ import { Router } from 'express'; import CreateSpotService from '../../services/Spot/CreateSpotService'; +import authMiddleware from '../../middlewares/authMiddleware'; const spotRouter = Router(); -spotRouter.post('/', async (request, response) => { +spotRouter.post('/', authMiddleware, async (request, response) => { const { github_login } = request.body; const { id } = request.manager; From fe8b41f75bf7cf64aa28b58cbb8c7e5ba05be91c Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 15:14:15 -0300 Subject: [PATCH 031/113] CreateSpotService --- backend/src/models/Spot.ts | 1 + .../src/services/Spot/CreateSpotService.ts | 96 +++++++++++++++++-- 2 files changed, 88 insertions(+), 9 deletions(-) diff --git a/backend/src/models/Spot.ts b/backend/src/models/Spot.ts index 5b4c1fd..6349ee3 100644 --- a/backend/src/models/Spot.ts +++ b/backend/src/models/Spot.ts @@ -9,6 +9,7 @@ import { } from 'typeorm'; import Manager from './Manager'; +import Repository from './Repository'; @Entity('spots') class Spot { diff --git a/backend/src/services/Spot/CreateSpotService.ts b/backend/src/services/Spot/CreateSpotService.ts index 20b512f..9feccec 100644 --- a/backend/src/services/Spot/CreateSpotService.ts +++ b/backend/src/services/Spot/CreateSpotService.ts @@ -10,20 +10,26 @@ interface Request { spot_github_login: string; } -interface Repository { +interface RepositoryInfo { id: string; name: string; full_name: string; description: string; html_url: string; - created_at: string; - language: string; +} + +interface RepositoryNode { + nameWithOwner: string; + name: string; + description: string; + url: string; + id: string; } interface Response { github_login: string; avatar_url: string; - repositories: Repository[]; + repositories: RepositoryInfo[]; } class CreateSpotService { @@ -44,7 +50,7 @@ class CreateSpotService { github_login: spot_github_login, }); - if (!existsSpot) { + if (existsSpot) { throw new AppError('Spot already registered'); } @@ -52,22 +58,94 @@ class CreateSpotService { query: this.getQuery(spot_github_login), }); - console.log(spotGithubData.data); + const { + login, + name, + avatarUrl, + id, + repositories, + } = spotGithubData.data.data.user; + + console.log(name); + + const spot = spotsRepository.create({ + avatar_url: avatarUrl, + github_id: id, + manager_id, + name, + github_login: login, + top_language: 'none', + }); + + const savedSpot = await spotsRepository.save(spot); + const { id: spot_id } = savedSpot; + + // save Repositories + const repositoriesNode: RepositoryNode[] = repositories.nodes; + + for (const data of repositoriesNode) { + const { + description, + id: repository_id, + name: repositoy_name, + nameWithOwner: full_name, + url, + } = data; + + const repository = repositoriesRepository.create({ + description, + github_id: repository_id, + name: repositoy_name, + full_name, + spot_id, + html_url: url, + }); + + await repositoriesRepository.save(repository); + } + + const { github_login, avatar_url } = await spotsRepository.findOne({ + id: spot_id, + }); + + const spotRepositories = await repositoriesRepository.find({ + spot_id, + }); + + const repositoriesReponse = spotRepositories.map( + ({ + id: repository_id, + name: repository_name, + full_name, + description, + html_url, + }) => { + const parsedRepository = { + id: repository_id, + name: repository_name, + full_name, + description, + html_url, + }; + + return parsedRepository; + }, + ); - return null; + return { github_login, avatar_url, repositories: repositoriesReponse }; } private getQuery(github_id: string): string { const query = `query { user(login: "${github_id}") { - bio login - name avatarUrl + name id repositories(first: 100 privacy: PUBLIC affiliations: OWNER) { nodes { nameWithOwner + name description url id From de68b533362fe654f7e1db872a4a70dc420f1426 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 17:27:51 -0300 Subject: [PATCH 032/113] GetDailyReportService --- .../DailyReport/GetDailyReportService.ts | 241 ++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 backend/src/services/DailyReport/GetDailyReportService.ts diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts new file mode 100644 index 0000000..0dd7727 --- /dev/null +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -0,0 +1,241 @@ +import api from '../githubApi/GraphQLApi'; + +interface Request { + github_login: string; +} + +interface Commit { + repository: { + id: string; + name: string; + url: string; + }; + sha: string; + message: string; + additions: number; + deletions: number; +} + +interface Response { + user: { + github_login: string; + avatar_url: string; + }; + payload: { + new_interactions: number; + new_repositories: number; + new_prs: number; + new_issues: number; + new_commits: number; + additions: number; + deletions: number; + commits: Commit[]; + }; +} + +interface RepositoryNode { + nameWithOwner: string; + id: string; + url: string; + defaultBranchRef: Branch; +} + +interface Branch { + target: Target; +} + +interface Target { + history: CommitHistory; +} + +interface CommitHistory { + nodes: CommitNode[]; +} + +interface CommitNode { + commitUrl: string; + author: { + user: { + login: string; + name: string; + }; + }; + message: string; + additions: number; + deletions: number; + id: string; +} + +class GetDailyReportService { + async execute({ github_login }: Request): Promise { + const data = await api.post('', { + query: this.getQuery(github_login), + }); + + const { + repositories, + contributionsCollection, + avatarUrl, + } = data.data.data.user; + + const { + totalIssueContributions, + totalCommitContributions, + totalRepositoryContributions, + totalPullRequestContributions, + totalPullRequestReviewContributions, + } = contributionsCollection; + + const repositoriesNodes: RepositoryNode[] = repositories.nodes; + + const filteredRepositories = repositoriesNodes.filter(rep => { + return rep.defaultBranchRef.target.history.nodes.length > 0; + }); + + const commits: Commit[] = this.getCommits( + github_login, + filteredRepositories, + ); + + const { additions, deletions } = this.getLines(commits); + + const payload = { + new_interactions: + totalIssueContributions + + totalCommitContributions + + totalRepositoryContributions + + totalPullRequestContributions + + totalPullRequestReviewContributions, + new_repositories: totalRepositoryContributions, + new_prs: totalPullRequestContributions, + new_issues: totalIssueContributions, + new_commits: totalCommitContributions, + additions, + deletions, + commits, + }; + + return { + user: { + avatar_url: avatarUrl, + github_login, + }, + payload, + }; + } + + private getLines( + commits: Commit[], + ): { additions: number; deletions: number } { + let additions = 0; + let deletions = 0; + + for (const commit of commits) { + const { + additions: commit_additions, + deletions: commit_deletions, + } = commit; + + additions += commit_additions; + deletions += commit_deletions; + } + + return { additions, deletions }; + } + + private getCommits( + github_login: string, + repositories: RepositoryNode[], + ): Commit[] { + const commits: Commit[] = []; + + for (const repository of repositories) { + const { + nameWithOwner, + id: repository_id, + defaultBranchRef, + url, + } = repository; + + const repositoryCommits = defaultBranchRef.target.history.nodes; + + const spotCommits = repositoryCommits.filter(({ author }) => { + const { login } = author.user; + + return login === github_login; + }); + + for (const commit of spotCommits) { + const { additions, deletions, id: commit_id, message } = commit; + + const serializedCommit: Commit = { + additions, + deletions, + message, + sha: commit_id, + repository: { + id: repository_id, + name: nameWithOwner, + url, + }, + }; + + commits.push(serializedCommit); + } + } + + return commits; + } + + private getQuery(github_login: string): string { + const since = new Date(); + since.setHours(since.getHours() - 3); + + const query = `{ + user(login:"${github_login}") { + avatarUrl + repositories(first: 100, privacy: PUBLIC, affiliations: COLLABORATOR) { + nodes { + nameWithOwner + id + url + defaultBranchRef { + target { + ... on Commit { + history(first: 100, since: "${since.toISOString()}") { + nodes { + ... on Commit { + commitUrl + author { + user { + login + name + } + } + message + additions + deletions + id + } + } + } + } + } + } + } + } + contributionsCollection(from: "${since.toISOString()}") { + totalIssueContributions + totalCommitContributions + totalRepositoryContributions + totalPullRequestContributions + totalPullRequestReviewContributions + } + } + }`; + + return query; + } +} + +export default GetDailyReportService; From 1eac25129cede3449ecd03a0d6a7718284dc31dd Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 17:42:20 -0300 Subject: [PATCH 033/113] ProcessSportProcessor --- backend/src/models/Commit.ts | 2 +- .../ProcessSpot/ProcessSpotProcessor.ts | 77 ++++++++++++++++++- 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index 27ffaf8..bd478c7 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -25,7 +25,7 @@ class Commit { repository: Repository; @Column('uuid') - student_id: string; + spot_id: string; @ManyToOne(() => Spot, { eager: true }) @JoinColumn({ name: 'spot_id' }) diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 5e7e367..52313e1 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -1,10 +1,83 @@ import { Job } from 'bullmq'; +import { getRepository } from 'typeorm'; import { SpotRequest } from '../../providers/queue/QueueProvider'; +import Spot from '../../models/Spot'; +import GetDailyReportService from '../../services/DailyReport/GetDailyReportService'; +import Commit from '../../models/Commit'; +import SpotDailyReport from '../../models/SpotDailyReport'; +import Repository from '../../models/Repository'; const ProcessSpotProcessor = async (job: Job): Promise => { - console.log(job); - return null; + const { github_id } = job.data; + + const spotRepository = getRepository(Spot); + const commitRepository = getRepository(Commit); + const dailyReportRepository = getRepository(SpotDailyReport); + const repositoriesRepository = getRepository(Repository); + + const { github_login, id: spot_id } = await spotRepository.findOne({ + github_id, + }); + + const getDailyReportService = new GetDailyReportService(); + + const { payload } = await getDailyReportService.execute({ + github_login, + }); + + const { + additions, + deletions, + commits, + new_commits, + new_interactions, + new_issues, + new_prs, + new_repositories, + } = payload; + + const dailyReport = dailyReportRepository.create({ + additions, + deletions, + new_commits, + new_forks: 0, + new_interactions, + new_issues, + new_prs, + new_repositories, + new_stars: 0, + spot_id, + }); + + const { id: spot_daily_report_id } = await dailyReportRepository.save( + dailyReport, + ); + + for await (const commit of commits) { + const { + additions: commit_additions, + deletions: commit_deletions, + message, + sha, + } = commit; + + const { id: repository_id } = await repositoriesRepository.findOne({ + github_id: commit.repository.id, + }); + + const spotCommit = commitRepository.create({ + additions: commit_additions, + deletions: commit_deletions, + message, + spot_daily_report_id, + spot_id, + repository_id, + sha, + }); + + await dailyReportRepository.save(spotCommit); + } }; export default ProcessSpotProcessor; From 659c49d77b8f70ac0c4aeb9fa1b36d97af9ddfce Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 17:43:19 -0300 Subject: [PATCH 034/113] minor changes --- backend/src/app.ts | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index 9b536d3..6867ec8 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -3,15 +3,15 @@ import cors from 'cors'; import 'express-async-errors'; import 'reflect-metadata'; import dotenv from 'dotenv'; -// import cron from 'node-cron'; +import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; import v2 from './routes/v2/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; -// import RequestSpotsProcessProcessor from './workers/RequestSpotsProcess/RequestSpotsProcessProcessor'; -// import ProcessSpotProcessor from './workers/ProcessSpot/ProcessSpotProcessor'; +import RequestSpotsProcessProcessor from './workers/RequestSpotsProcess/RequestSpotsProcessProcessor'; +import ProcessSpotProcessor from './workers/ProcessSpot/ProcessSpotProcessor'; import { QueueProvider } from './providers/queue/QueueProvider'; import './database'; @@ -50,32 +50,32 @@ class App { } private defineCron(): void { - // cron.schedule('00 23 * * *', async () => - // this.queueProvider.add({ - // jobName: 'request students process', - // queueName: 'students-process-requester', - // opts: { - // removeOnComplete: false, - // }, - // }), - // ); + cron.schedule('00 23 * * *', async () => + this.queueProvider.add({ + jobName: 'request students process', + queueName: 'students-process-requester', + opts: { + removeOnComplete: false, + }, + }), + ); } private queues(): void { - // this.queueProvider.register({ queueName: 'students-process-requester' }); - // this.queueProvider.register({ queueName: 'student-processor' }); - // this.queueProvider.setUI(); + this.queueProvider.register({ queueName: 'students-process-requester' }); + this.queueProvider.register({ queueName: 'student-processor' }); + this.queueProvider.setUI(); } private workers(): void { - // this.studentsProcessRequester = new Worker( - // 'students-process-requester', - // RequestStudentsProcessProcessor, - // ); - // this.studentProcessor = new Worker( - // 'student-processor', - // ProcessStudentProcessor, - // ); + this.studentsProcessRequester = new Worker( + 'students-process-requester', + RequestSpotsProcessProcessor, + ); + this.studentProcessor = new Worker( + 'student-processor', + ProcessSpotProcessor, + ); } private routes(): void { From e5b6d9a05584472f8e4dd97f04f659fb119776ec Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 18:37:06 -0300 Subject: [PATCH 035/113] fixing processors --- backend/src/app.ts | 17 +++++------ ...6821-RemoveForksAndStarsFromDailyReport.ts | 29 +++++++++++++++++++ backend/src/models/SpotDailyReport.ts | 6 ---- backend/src/providers/queue/QueueProvider.ts | 2 ++ .../DailyReport/GetDailyReportService.ts | 14 ++++----- .../src/services/Spot/CreateSpotService.ts | 4 +-- .../ProcessSpot/ProcessSpotProcessor.ts | 18 ++---------- .../RequestSpotsProcessProcessor.ts | 4 +++ 8 files changed, 51 insertions(+), 43 deletions(-) create mode 100644 backend/src/database/migrations/1605734706821-RemoveForksAndStarsFromDailyReport.ts diff --git a/backend/src/app.ts b/backend/src/app.ts index 6867ec8..de515e0 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -50,10 +50,10 @@ class App { } private defineCron(): void { - cron.schedule('00 23 * * *', async () => + cron.schedule('* * * * *', async () => this.queueProvider.add({ - jobName: 'request students process', - queueName: 'students-process-requester', + jobName: 'request spot process', + queueName: 'spot-process-requester', opts: { removeOnComplete: false, }, @@ -62,20 +62,17 @@ class App { } private queues(): void { - this.queueProvider.register({ queueName: 'students-process-requester' }); - this.queueProvider.register({ queueName: 'student-processor' }); + this.queueProvider.register({ queueName: 'spot-process-requester' }); + this.queueProvider.register({ queueName: 'spot-processor' }); this.queueProvider.setUI(); } private workers(): void { this.studentsProcessRequester = new Worker( - 'students-process-requester', + 'spot-process-requester', RequestSpotsProcessProcessor, ); - this.studentProcessor = new Worker( - 'student-processor', - ProcessSpotProcessor, - ); + this.studentProcessor = new Worker('spot-processor', ProcessSpotProcessor); } private routes(): void { diff --git a/backend/src/database/migrations/1605734706821-RemoveForksAndStarsFromDailyReport.ts b/backend/src/database/migrations/1605734706821-RemoveForksAndStarsFromDailyReport.ts new file mode 100644 index 0000000..75c727a --- /dev/null +++ b/backend/src/database/migrations/1605734706821-RemoveForksAndStarsFromDailyReport.ts @@ -0,0 +1,29 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class RemoveForksAndStarsFromDailyReport1605734706821 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('spot_daily_reports', 'new_stars'); + await queryRunner.dropColumn('spot_daily_reports', 'new_forks'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'spot_daily_reports', + new TableColumn({ + name: 'new_forks', + type: 'int2', + isNullable: true, + }), + ); + + await queryRunner.addColumn( + 'spot_daily_reports', + new TableColumn({ + name: 'new_stars', + type: 'int2', + isNullable: true, + }), + ); + } +} diff --git a/backend/src/models/SpotDailyReport.ts b/backend/src/models/SpotDailyReport.ts index add52da..75364ed 100644 --- a/backend/src/models/SpotDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -22,18 +22,12 @@ class SpotDailyReport { @JoinColumn({ name: 'spot_id' }) spot: Spot; - @Column('int2') - new_forks: number; - @Column('int2') new_issues: number; @Column('int2') new_prs: number; - @Column('int2') - new_stars: number; - @Column('int2') new_repositories: number; diff --git a/backend/src/providers/queue/QueueProvider.ts b/backend/src/providers/queue/QueueProvider.ts index 6f6e1ef..848426a 100644 --- a/backend/src/providers/queue/QueueProvider.ts +++ b/backend/src/providers/queue/QueueProvider.ts @@ -1,5 +1,7 @@ interface SpotRequest { github_id: string; + date: string; + github_name: string; } interface addJobRequest { diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index 0dd7727..e444689 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -2,6 +2,7 @@ import api from '../githubApi/GraphQLApi'; interface Request { github_login: string; + date: string; } interface Commit { @@ -67,9 +68,9 @@ interface CommitNode { } class GetDailyReportService { - async execute({ github_login }: Request): Promise { + async execute({ github_login, date }: Request): Promise { const data = await api.post('', { - query: this.getQuery(github_login), + query: this.getQuery(github_login, date), }); const { @@ -187,10 +188,7 @@ class GetDailyReportService { return commits; } - private getQuery(github_login: string): string { - const since = new Date(); - since.setHours(since.getHours() - 3); - + private getQuery(github_login: string, date: string): string { const query = `{ user(login:"${github_login}") { avatarUrl @@ -202,7 +200,7 @@ class GetDailyReportService { defaultBranchRef { target { ... on Commit { - history(first: 100, since: "${since.toISOString()}") { + history(first: 100, since: "${date}") { nodes { ... on Commit { commitUrl @@ -224,7 +222,7 @@ class GetDailyReportService { } } } - contributionsCollection(from: "${since.toISOString()}") { + contributionsCollection(from: "${date}") { totalIssueContributions totalCommitContributions totalRepositoryContributions diff --git a/backend/src/services/Spot/CreateSpotService.ts b/backend/src/services/Spot/CreateSpotService.ts index 9feccec..2550728 100644 --- a/backend/src/services/Spot/CreateSpotService.ts +++ b/backend/src/services/Spot/CreateSpotService.ts @@ -66,8 +66,6 @@ class CreateSpotService { repositories, } = spotGithubData.data.data.user; - console.log(name); - const spot = spotsRepository.create({ avatar_url: avatarUrl, github_id: id, @@ -142,7 +140,7 @@ class CreateSpotService { avatarUrl name id - repositories(first: 100 privacy: PUBLIC affiliations: OWNER) { + repositories(first: 100 privacy: PUBLIC affiliations: OWNER ownerAffiliations:OWNER) { nodes { nameWithOwner name diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 52313e1..c975070 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -2,28 +2,21 @@ import { Job } from 'bullmq'; import { getRepository } from 'typeorm'; import { SpotRequest } from '../../providers/queue/QueueProvider'; -import Spot from '../../models/Spot'; import GetDailyReportService from '../../services/DailyReport/GetDailyReportService'; import Commit from '../../models/Commit'; import SpotDailyReport from '../../models/SpotDailyReport'; -import Repository from '../../models/Repository'; const ProcessSpotProcessor = async (job: Job): Promise => { - const { github_id } = job.data; + const { github_id: spot_id, date, github_name: github_login } = job.data; - const spotRepository = getRepository(Spot); const commitRepository = getRepository(Commit); const dailyReportRepository = getRepository(SpotDailyReport); - const repositoriesRepository = getRepository(Repository); - - const { github_login, id: spot_id } = await spotRepository.findOne({ - github_id, - }); const getDailyReportService = new GetDailyReportService(); const { payload } = await getDailyReportService.execute({ github_login, + date, }); const { @@ -41,12 +34,10 @@ const ProcessSpotProcessor = async (job: Job): Promise => { additions, deletions, new_commits, - new_forks: 0, new_interactions, new_issues, new_prs, new_repositories, - new_stars: 0, spot_id, }); @@ -62,17 +53,12 @@ const ProcessSpotProcessor = async (job: Job): Promise => { sha, } = commit; - const { id: repository_id } = await repositoriesRepository.findOne({ - github_id: commit.repository.id, - }); - const spotCommit = commitRepository.create({ additions: commit_additions, deletions: commit_deletions, message, spot_daily_report_id, spot_id, - repository_id, sha, }); diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 4fb74a7..9faaf13 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -4,6 +4,8 @@ import Spot from '../../models/Spot'; const RequestSpotsProcessProcessor = async (): Promise => { const spotsRepository = getRepository(Spot); + const since = new Date(); + since.setHours(since.getHours() - 3); const spots = await spotsRepository.find(); @@ -13,6 +15,8 @@ const RequestSpotsProcessProcessor = async (): Promise => { queueProvider.add({ job: { github_id: spot.github_id, + date: since.toISOString(), + github_name: spot.github_login, }, jobName: `${spot.github_id} process request`, queueName: 'spot-processor', From b33dc097e4af399360ceb6237ff8b1727fcefbfc Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 18:43:28 -0300 Subject: [PATCH 036/113] Minor changes --- backend/src/providers/queue/QueueProvider.ts | 2 +- backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts | 2 +- .../RequestSpotsProcess/RequestSpotsProcessProcessor.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/src/providers/queue/QueueProvider.ts b/backend/src/providers/queue/QueueProvider.ts index 848426a..d9567b1 100644 --- a/backend/src/providers/queue/QueueProvider.ts +++ b/backend/src/providers/queue/QueueProvider.ts @@ -1,5 +1,5 @@ interface SpotRequest { - github_id: string; + spot_id: string; date: string; github_name: string; } diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index c975070..f058e4d 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -7,7 +7,7 @@ import Commit from '../../models/Commit'; import SpotDailyReport from '../../models/SpotDailyReport'; const ProcessSpotProcessor = async (job: Job): Promise => { - const { github_id: spot_id, date, github_name: github_login } = job.data; + const { spot_id, date, github_name: github_login } = job.data; const commitRepository = getRepository(Commit); const dailyReportRepository = getRepository(SpotDailyReport); diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 9faaf13..b9e612b 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -14,11 +14,11 @@ const RequestSpotsProcessProcessor = async (): Promise => { queueProvider.add({ job: { - github_id: spot.github_id, + spot_id: spot.id, date: since.toISOString(), github_name: spot.github_login, }, - jobName: `${spot.github_id} process request`, + jobName: `${spot.github_login} process request`, queueName: 'spot-processor', opts: { removeOnComplete: false, From 857fdb0a77a196abd437970a00397889da50acd4 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 18:51:24 -0300 Subject: [PATCH 037/113] Minor fixes --- backend/src/repositories/SpotDailyReportsRepository.ts | 4 ++-- .../src/workers/ProcessSpot/ProcessSpotProcessor.ts | 10 ++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 1fea91e..0371e45 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -5,7 +5,7 @@ import SpotDailyReport from '../models/SpotDailyReport'; @EntityRepository(SpotDailyReport) class SpotDailyReportsRepository extends Repository { public async findByPeriod( - student_id: string, + spot_id: string, since: Date, until: Date, ): Promise { @@ -15,7 +15,7 @@ class SpotDailyReportsRepository extends Repository { const foundSpotDailyReports = await this.find({ where: { created_at: Between(since, until), - student_id, + spot_id, }, }); diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index f058e4d..8dbfd8c 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -25,25 +25,23 @@ const ProcessSpotProcessor = async (job: Job): Promise => { commits, new_commits, new_interactions, - new_issues, + new_issues: issues, new_prs, new_repositories, } = payload; const dailyReport = dailyReportRepository.create({ + new_issues: issues, additions, deletions, new_commits, new_interactions, - new_issues, new_prs, new_repositories, spot_id, }); - const { id: spot_daily_report_id } = await dailyReportRepository.save( - dailyReport, - ); + const { id: daily_id } = await dailyReportRepository.save(dailyReport); for await (const commit of commits) { const { @@ -57,7 +55,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { additions: commit_additions, deletions: commit_deletions, message, - spot_daily_report_id, + spot_daily_report_id: daily_id, spot_id, sha, }); From 1f108d6a7fde1f62db1dc9b8acd4b6f9d6ecf8d8 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 20:03:17 -0300 Subject: [PATCH 038/113] fixing daily processor hour --- .../src/workers/ProcessSpot/ProcessSpotProcessor.ts | 4 ++-- .../RequestSpotsProcessProcessor.ts | 11 ++++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 8dbfd8c..33c86cc 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -43,7 +43,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { const { id: daily_id } = await dailyReportRepository.save(dailyReport); - for await (const commit of commits) { + for (const commit of commits) { const { additions: commit_additions, deletions: commit_deletions, @@ -60,7 +60,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { sha, }); - await dailyReportRepository.save(spotCommit); + await commitRepository.save(spotCommit); } }; diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index b9e612b..4a2c3c4 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -5,12 +5,17 @@ import Spot from '../../models/Spot'; const RequestSpotsProcessProcessor = async (): Promise => { const spotsRepository = getRepository(Spot); const since = new Date(); - since.setHours(since.getHours() - 3); + since.setHours(0); + since.setMinutes(0); + since.setSeconds(0); + since.setMilliseconds(0); const spots = await spotsRepository.find(); spots.forEach((spot: Spot) => { - console.log(`Request spot ${spot.github_login} process`); + console.log( + `Request spot ${spot.github_login} process at ${since.toISOString()}`, + ); queueProvider.add({ job: { @@ -18,7 +23,7 @@ const RequestSpotsProcessProcessor = async (): Promise => { date: since.toISOString(), github_name: spot.github_login, }, - jobName: `${spot.github_login} process request`, + jobName: `${spot.github_login} process request at ${since.toISOString()}`, queueName: 'spot-processor', opts: { removeOnComplete: false, From 8fd8659d0f6f89c609138056edca17194309d3ff Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 20:33:44 -0300 Subject: [PATCH 039/113] cron schedule' --- backend/src/app.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index de515e0..b981608 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -50,7 +50,7 @@ class App { } private defineCron(): void { - cron.schedule('* * * * *', async () => + cron.schedule('00 23 * * *', async () => this.queueProvider.add({ jobName: 'request spot process', queueName: 'spot-process-requester', From 120d770f6649de73d81dd246a342d307bff38652 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 20:33:54 -0300 Subject: [PATCH 040/113] List spots --- backend/src/routes/v2/spots.routes.ts | 9 +++++++++ backend/src/services/Spot/GetSpotsService.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 backend/src/services/Spot/GetSpotsService.ts diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots.routes.ts index 914a4a9..36c79d0 100644 --- a/backend/src/routes/v2/spots.routes.ts +++ b/backend/src/routes/v2/spots.routes.ts @@ -1,6 +1,7 @@ import { Router } from 'express'; import CreateSpotService from '../../services/Spot/CreateSpotService'; import authMiddleware from '../../middlewares/authMiddleware'; +import GetSpotsService from '../../services/Spot/GetSpotsService'; const spotRouter = Router(); @@ -18,4 +19,12 @@ spotRouter.post('/', authMiddleware, async (request, response) => { return response.json(spot); }); +spotRouter.get('/', authMiddleware, async (request, response) => { + const getSpotsService = new GetSpotsService(); + + const spots = await getSpotsService.execute(); + + return response.json(spots); +}); + export default spotRouter; diff --git a/backend/src/services/Spot/GetSpotsService.ts b/backend/src/services/Spot/GetSpotsService.ts new file mode 100644 index 0000000..fcac5d8 --- /dev/null +++ b/backend/src/services/Spot/GetSpotsService.ts @@ -0,0 +1,16 @@ +import { getRepository } from 'typeorm'; +import Spot from '../../models/Spot'; + +class GetSpotsService { + async execute(): Promise { + const spotsRepository = getRepository(Spot); + + const spots = await spotsRepository.find({ + loadEagerRelations: false, + }); + + return spots; + } +} + +export default GetSpotsService; From 35202e185fc5a4a655b7ad950a21996cc5158555 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Wed, 18 Nov 2020 22:59:13 -0300 Subject: [PATCH 041/113] Daily report by period --- .../SpotDailyReportsRepository.ts | 23 ++++++++++++------- backend/src/routes/v2/index.ts | 19 +++++++++++++++ .../src/services/Spot/GetSpotsBelowAverage.ts | 14 +++++++++++ 3 files changed, 48 insertions(+), 8 deletions(-) create mode 100644 backend/src/services/Spot/GetSpotsBelowAverage.ts diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 0371e45..8119866 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -1,4 +1,5 @@ -import { EntityRepository, Repository, Between } from 'typeorm'; +import { EntityRepository, Repository } from 'typeorm'; +import Spot from '../models/Spot'; import SpotDailyReport from '../models/SpotDailyReport'; @@ -12,14 +13,20 @@ class SpotDailyReportsRepository extends Repository { since.setDate(since.getDate() - 1); until.setDate(until.getDate() + 1); - const foundSpotDailyReports = await this.find({ - where: { - created_at: Between(since, until), - spot_id, - }, - }); + const report = await this.createQueryBuilder('report') + .where('report.spot_id = :id', { id: spot_id }) + .andWhere(`created_at >= :since`, { since: since.toISOString() }) + .andWhere('created_at < :until', { until: until.toISOString() }) + .select('SUM(report.new_interactions)', 'new_interactions') + .addSelect('SUM(report.new_commits)', 'new_commits') + .addSelect('SUM(report.new_prs)', 'new_prs') + .addSelect('SUM(report.new_issues)', 'new_issues') + .addSelect('SUM(report.new_repositories)', 'new_repositories') + .addSelect('SUM(report.additions)', 'additions') + .addSelect('SUM(report.deletions)', 'deletions') + .getRawOne(); - return foundSpotDailyReports || null; + return report; } } diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index fef2ff8..af8cfde 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -1,12 +1,31 @@ import { Router } from 'express'; +import { getCustomRepository } from 'typeorm'; import manangerRouter from './manager.routes'; import spotRouter from './spots.routes'; import sessionsRouter from './sessions.routes'; +import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; const routes = Router(); routes.use('/manager', manangerRouter); routes.use('/spot', spotRouter); routes.use('/session', sessionsRouter); +routes.get('/test', async (request, response) => { + const spotDailyReportsRepository = getCustomRepository( + SpotDailyReportsRepository, + ); + + const since = new Date(); + + since.setMonth(since.getMonth() - 1); + + const data = await spotDailyReportsRepository.findByPeriod( + 'af733d6f-c198-41ac-9299-f6524a7108d9', + since, + new Date(), + ); + + return response.json(data); +}); export default routes; diff --git a/backend/src/services/Spot/GetSpotsBelowAverage.ts b/backend/src/services/Spot/GetSpotsBelowAverage.ts new file mode 100644 index 0000000..b28b63f --- /dev/null +++ b/backend/src/services/Spot/GetSpotsBelowAverage.ts @@ -0,0 +1,14 @@ +import { getCustomRepository } from 'typeorm'; +import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; +import GetSpotsService from './GetSpotsService'; + +class GetSpotsBelowAverage { + async execute(): Promise { + const spotDailyRepository = getCustomRepository(SpotDailyReportsRepository); + const getSpotsService = new GetSpotsService(); + + const spots = await getSpotsService.execute(); + } +} + +export default GetSpotsBelowAverage; From a026d2cae8e9d832b5282b62c2b11cf9eae10c0f Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 08:31:07 -0300 Subject: [PATCH 042/113] Trying to get spot that's associated with report --- backend/src/models/Spot.ts | 1 - backend/src/repositories/SpotDailyReportsRepository.ts | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/backend/src/models/Spot.ts b/backend/src/models/Spot.ts index 6349ee3..5b4c1fd 100644 --- a/backend/src/models/Spot.ts +++ b/backend/src/models/Spot.ts @@ -9,7 +9,6 @@ import { } from 'typeorm'; import Manager from './Manager'; -import Repository from './Repository'; @Entity('spots') class Spot { diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 8119866..1d9e8d3 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -1,5 +1,4 @@ import { EntityRepository, Repository } from 'typeorm'; -import Spot from '../models/Spot'; import SpotDailyReport from '../models/SpotDailyReport'; @@ -15,8 +14,9 @@ class SpotDailyReportsRepository extends Repository { const report = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) - .andWhere(`created_at >= :since`, { since: since.toISOString() }) - .andWhere('created_at < :until', { until: until.toISOString() }) + .leftJoinAndSelect('report.spot', 'spot') + .andWhere(`report.created_at >= :since`, { since: since.toISOString() }) + .andWhere('report.created_at < :until', { until: until.toISOString() }) .select('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') .addSelect('SUM(report.new_prs)', 'new_prs') From 9cf11e6957fae7b89488d9a07e888ead1e4d5b26 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 08:42:22 -0300 Subject: [PATCH 043/113] Removing controllers --- backend/src/controllers/SessionController.ts | 31 -------------------- 1 file changed, 31 deletions(-) delete mode 100644 backend/src/controllers/SessionController.ts diff --git a/backend/src/controllers/SessionController.ts b/backend/src/controllers/SessionController.ts deleted file mode 100644 index d24e77f..0000000 --- a/backend/src/controllers/SessionController.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Request, Response } from 'express'; -import * as yup from 'yup'; - -import AuthenticateManagerService from '../services/AuthenticateManagerService'; - -class SessionController { - static async store(request: Request, response: Response): Promise { - const schema = yup.object().shape({ - email: yup.string().required('E-mail is required.'), - password: yup.string().required('Password is required.'), - }); - - await schema.validate(request.body); - - const { email, password } = request.body; - - const authenticateManager = new AuthenticateManagerService(); - const { manager, token } = await authenticateManager.execute( - email, - password, - ); - - delete manager.password; - const hasGithubToken = !!manager.github_token; - delete manager.github_token; - - return response.json({ manager, token, hasGithubToken }); - } -} - -export default SessionController; From 5432c121f52a9486c2b9bbc021e7552f4918cada Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:05:44 -0300 Subject: [PATCH 044/113] SpotDailyReport --- .../SpotDailyReportsRepository.ts | 79 ++++++++++++++++++- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 1d9e8d3..0d50516 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -2,30 +2,103 @@ import { EntityRepository, Repository } from 'typeorm'; import SpotDailyReport from '../models/SpotDailyReport'; +interface RawReport { + spot_id: string; + spot_manager_id: string; + spot_github_login: string; + spot_avatar_url: string; + spot_top_language: string; + spot_github_id: string; + spot_name: string; + spot_created_at: string; + spot_updated_at: string; + new_interactions: number; + new_commits: number; + new_prs: number; + new_issues: number; + new_repositories: number; + additions: number; + deletions: number; +} + +interface Report { + spot: { + id: string; + github_login: string; + name: string; + }; + metrics: { + new_interactions: number; + new_commits: number; + new_prs: number; + new_issues: number; + new_repositories: number; + additions: number; + deletions: number; + }; +} + @EntityRepository(SpotDailyReport) class SpotDailyReportsRepository extends Repository { public async findByPeriod( spot_id: string, since: Date, until: Date, - ): Promise { + ): Promise { since.setDate(since.getDate() - 1); until.setDate(until.getDate() + 1); - const report = await this.createQueryBuilder('report') + const rawReport: RawReport = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) .leftJoinAndSelect('report.spot', 'spot') .andWhere(`report.created_at >= :since`, { since: since.toISOString() }) .andWhere('report.created_at < :until', { until: until.toISOString() }) - .select('SUM(report.new_interactions)', 'new_interactions') + .select('spot') + .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') .addSelect('SUM(report.new_prs)', 'new_prs') .addSelect('SUM(report.new_issues)', 'new_issues') .addSelect('SUM(report.new_repositories)', 'new_repositories') .addSelect('SUM(report.additions)', 'additions') .addSelect('SUM(report.deletions)', 'deletions') + .groupBy('spot.id') .getRawOne(); + const report = this.parsetRawReport(rawReport); + + return report; + } + + private parsetRawReport(rawReport: RawReport): Report { + const { + additions, + deletions, + new_commits, + new_interactions, + new_issues, + new_prs, + new_repositories, + spot_github_login, + spot_id, + spot_name, + } = rawReport; + + const report: Report = { + spot: { + id: spot_id, + github_login: spot_github_login, + name: spot_name, + }, + metrics: { + additions, + deletions, + new_commits, + new_interactions, + new_issues, + new_prs, + new_repositories, + }, + }; return report; } } From 5055118e5e1cc53dda0130e83f3ef6eb5a9499c6 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:06:06 -0300 Subject: [PATCH 045/113] Removing test route --- backend/src/routes/v2/index.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index af8cfde..9e3acf8 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -10,22 +10,5 @@ const routes = Router(); routes.use('/manager', manangerRouter); routes.use('/spot', spotRouter); routes.use('/session', sessionsRouter); -routes.get('/test', async (request, response) => { - const spotDailyReportsRepository = getCustomRepository( - SpotDailyReportsRepository, - ); - - const since = new Date(); - - since.setMonth(since.getMonth() - 1); - - const data = await spotDailyReportsRepository.findByPeriod( - 'af733d6f-c198-41ac-9299-f6524a7108d9', - since, - new Date(), - ); - - return response.json(data); -}); export default routes; From b649f4e7240c75df3e625d10fd50eab3268dd430 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:06:22 -0300 Subject: [PATCH 046/113] Removing unused imports --- backend/src/routes/v2/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index 9e3acf8..fef2ff8 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -1,9 +1,7 @@ import { Router } from 'express'; -import { getCustomRepository } from 'typeorm'; import manangerRouter from './manager.routes'; import spotRouter from './spots.routes'; import sessionsRouter from './sessions.routes'; -import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; const routes = Router(); From b2f38278da827fc1f8de2b5e27c6fa2a2a31e3be Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:10:19 -0300 Subject: [PATCH 047/113] Parsing metrics to number --- .../src/repositories/SpotDailyReportsRepository.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 0d50516..0578270 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -90,13 +90,13 @@ class SpotDailyReportsRepository extends Repository { name: spot_name, }, metrics: { - additions, - deletions, - new_commits, - new_interactions, - new_issues, - new_prs, - new_repositories, + additions: Number(additions), + deletions: Number(deletions), + new_commits: Number(new_commits), + new_interactions: Number(new_interactions), + new_issues: Number(new_issues), + new_prs: Number(new_prs), + new_repositories: Number(new_repositories), }, }; return report; From 9aba663ce85bf50f0c72f3998fe368b01cdd686d Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:14:12 -0300 Subject: [PATCH 048/113] Creating findByPeriod on SpotDailyReportrepository --- .../SpotDailyReportsRepository.ts | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 0578270..b6a0a33 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -40,7 +40,7 @@ interface Report { @EntityRepository(SpotDailyReport) class SpotDailyReportsRepository extends Repository { - public async findByPeriod( + public async findByPeriodAndId( spot_id: string, since: Date, until: Date, @@ -69,6 +69,33 @@ class SpotDailyReportsRepository extends Repository { return report; } + public async findByPeriod( + since: Date, + until: Date, + ): Promise { + since.setDate(since.getDate() - 1); + until.setDate(until.getDate() + 1); + + const rawReport: RawReport[] = await this.createQueryBuilder('report') + .leftJoinAndSelect('report.spot', 'spot') + .andWhere(`report.created_at >= :since`, { since: since.toISOString() }) + .andWhere('report.created_at < :until', { until: until.toISOString() }) + .select('spot') + .addSelect('SUM(report.new_interactions)', 'new_interactions') + .addSelect('SUM(report.new_commits)', 'new_commits') + .addSelect('SUM(report.new_prs)', 'new_prs') + .addSelect('SUM(report.new_issues)', 'new_issues') + .addSelect('SUM(report.new_repositories)', 'new_repositories') + .addSelect('SUM(report.additions)', 'additions') + .addSelect('SUM(report.deletions)', 'deletions') + .groupBy('spot.id') + .getRawMany(); + + const report = rawReport.map(raw => this.parsetRawReport(raw)); + + return report; + } + private parsetRawReport(rawReport: RawReport): Report { const { additions, From 9fb956ca73b74e35478942f1ce826194fbe03515 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:30:12 -0300 Subject: [PATCH 049/113] adding fields into report spot --- .../repositories/SpotDailyReportsRepository.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index b6a0a33..f1e3abc 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -25,7 +25,13 @@ interface Report { spot: { id: string; github_login: string; + manager_id: string; + avatar_url: string; + top_language: string; + github_id: string; name: string; + created_at: string; + updated_at: string; }; metrics: { new_interactions: number; @@ -108,6 +114,12 @@ class SpotDailyReportsRepository extends Repository { spot_github_login, spot_id, spot_name, + spot_avatar_url, + spot_top_language, + spot_created_at, + spot_github_id, + spot_manager_id, + spot_updated_at, } = rawReport; const report: Report = { @@ -115,6 +127,12 @@ class SpotDailyReportsRepository extends Repository { id: spot_id, github_login: spot_github_login, name: spot_name, + avatar_url: spot_avatar_url, + top_language: spot_top_language, + github_id: spot_github_id, + manager_id: spot_manager_id, + created_at: spot_created_at, + updated_at: spot_updated_at, }, metrics: { additions: Number(additions), From 2857300cba6da84cfd90844d693381f3ff5a9d4f Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:30:28 -0300 Subject: [PATCH 050/113] GetBelowAverageOnProjectService --- .../GetBelowAverageOnProjectService.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 backend/src/services/Project/GetBelowAverageOnProjectService.ts diff --git a/backend/src/services/Project/GetBelowAverageOnProjectService.ts b/backend/src/services/Project/GetBelowAverageOnProjectService.ts new file mode 100644 index 0000000..32a2229 --- /dev/null +++ b/backend/src/services/Project/GetBelowAverageOnProjectService.ts @@ -0,0 +1,44 @@ +import { getCustomRepository } from 'typeorm'; +import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; + +interface Request { + since: Date; + until: Date; +} + +interface Spot { + id: string; + github_login: string; + manager_id: string; + avatar_url: string; + top_language: string; + github_id: string; + name: string; + created_at: string; + updated_at: string; +} + +class GetBelowAverageOnProjectService { + public async execute({ since, until }: Request): Promise { + const dailyReportRepository = getCustomRepository( + SpotDailyReportsRepository, + ); + + const reports = await dailyReportRepository.findByPeriod(since, until); + + const total = Object.values(reports).reduce( + (interactions, { metrics }) => interactions + metrics.new_interactions, + 0, + ); + + const average = total / reports.length; + + const spotsBelowAverage = reports + .filter(({ metrics }) => metrics.new_interactions < average) + .map(({ spot }) => spot); + + return spotsBelowAverage; + } +} + +export default GetBelowAverageOnProjectService; From 0fc3de044e73e988bad7938333c8656b4f74c9c6 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:41:37 -0300 Subject: [PATCH 051/113] minor changes --- .../SpotDailyReportsRepository.ts | 22 +++++++------------ .../GetBelowAverageOnProjectService.ts | 4 ++-- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index f1e3abc..6ae01ed 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -48,17 +48,14 @@ interface Report { class SpotDailyReportsRepository extends Repository { public async findByPeriodAndId( spot_id: string, - since: Date, - until: Date, + since: string, + until: string, ): Promise { - since.setDate(since.getDate() - 1); - until.setDate(until.getDate() + 1); - const rawReport: RawReport = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.created_at >= :since`, { since: since.toISOString() }) - .andWhere('report.created_at < :until', { until: until.toISOString() }) + .andWhere(`report.created_at >= :since`, { since }) + .andWhere('report.created_at < :until', { until }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') @@ -76,16 +73,13 @@ class SpotDailyReportsRepository extends Repository { } public async findByPeriod( - since: Date, - until: Date, + since: string, + until: string, ): Promise { - since.setDate(since.getDate() - 1); - until.setDate(until.getDate() + 1); - const rawReport: RawReport[] = await this.createQueryBuilder('report') .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.created_at >= :since`, { since: since.toISOString() }) - .andWhere('report.created_at < :until', { until: until.toISOString() }) + .andWhere(`report.created_at >= :since`, { since }) + .andWhere('report.created_at < :until', { until }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') diff --git a/backend/src/services/Project/GetBelowAverageOnProjectService.ts b/backend/src/services/Project/GetBelowAverageOnProjectService.ts index 32a2229..cca8cbd 100644 --- a/backend/src/services/Project/GetBelowAverageOnProjectService.ts +++ b/backend/src/services/Project/GetBelowAverageOnProjectService.ts @@ -2,8 +2,8 @@ import { getCustomRepository } from 'typeorm'; import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; interface Request { - since: Date; - until: Date; + since: string; + until: string; } interface Spot { From 7408ac3ab8a5623c8b0bb43cd4d7eca11d672a22 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Thu, 19 Nov 2020 10:43:48 -0300 Subject: [PATCH 052/113] backend setup configuration added on README --- backend/README.md | 97 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 88 insertions(+), 9 deletions(-) diff --git a/backend/README.md b/backend/README.md index e128f16..435f8d8 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,6 +1,7 @@ ## 🏁 Iniciando Você pode clonar o respositório com o git, com o seguinte comando: + ``` git clone https://github.com/Guardians-DSC/GitRadar.git ``` @@ -8,25 +9,73 @@ git clone https://github.com/Guardians-DSC/GitRadar.git ### Pré-requisitos Você precisará de NodeJS e Yarn (para facilitar o processo) no seu computador.
+ - [NodeJS](https://nodejs.org/en/download/)
- [Yarn](https://yarnpkg.com/getting-started/install) ### Instalando No terminal, abra a pasta do projeto e abra a pasta do Backend. + ``` cd GitRadar/backend ``` + Então, digite: + ``` yarn ``` -Pronto! Tudo está configurado para você começar a usar o projeto. +
+Antes de executar a aplicação, você precisa configurar alguns serviços, o primeiro deles é ter um Banco de Dados Postgres para a utilização da aplicação. + +- [Link para a imagem Docker aqui.](https://hub.docker.com/_/postgres) + +
+Com isso feito, você precisa criar um aplicativo OAuth com a sua conta do GitHub, a aplicação irá utilizá-la para permitir o uso das credenciais dos usuários e aumentar o limite de requisições. + +- [Siga esse tutorial do GitHub para isso.](https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/) + +A sua página da aplicação deve ficar assim: + +Guarde os valores do ClientID e ClientSecret, você usará no ".env", além disso atente-se para as urls da aplicação, como a aplicação está sendo executada localmente, as urls direcionam para o frontend no endereço localhost, segue os campos em texto: + +- Homepage URL: http://localhost:3000 +- Authorization callback URL: http://localhost:3000/dashboard + +Essa configuração serve para que a autenticação com o Github de um professor seja possível. A maneira mais fácil e eficiente é executar o frontend e o backend simultaneamente para que você realize o vínculo através da interface gráfica do site. +

+Agora, precisamos configurar as variáveis de ambiente. Para isso, você deve copiar o arquivo ".env.sample" e +o renomear para ".env" na pasta raiz do Backend. Você precisa preencher os valores de todas as variáveis de acordo com o seu significado. +
+Segue o arquivo ".env" comentado: + +```bash +# Informações do Banco de Dados Postgresql +DB_HOST=localhost # Endereço de acesso +DB_PORT=5432 # Porta de acesso +DB_USERNAME=example_username # Usuário do BD +DB_PASSWORD=example_password # Senha do BD +DB_NAME=database_name # Nome do Bando de Dados + +# Informações do Aplicativo OAuth do GitHub +GITHUB_APP_CLIENT_ID=your_client_id # ClientID +GITHUB_APP_CLIENT_SECRET=your_client_secret # ClientSecret + +# Informações de segurança para o GitRadar +JWT_SECRET=your_jwt_secret # Gere um código qualquer para servir como secret da autenticação JWT da aplicação. Recomendo usar geradores de hash online. + +CRYPTO_SECRET=your_crypto_secret # Gere um código qualquer para servir como secret para encriptações na aplicação. +CRYPTO_IV=90b7fd08a94e987e6aeb910a79e26672 # Buffer em hexadecimal do Crypto IV usado nas encriptações da aplicação, recomendo deixar esse valor padrão. +``` + +Pronto! Tudo está configurado para você começar a usar o projeto. ## 🚀 Modo de uso Você pode iniciar o servidor local de desenvolvimento, com o seguinte comando: + ``` yarn dev:server ``` @@ -34,10 +83,13 @@ yarn dev:server # 🔎 Endpoints da API ## Obter perfil: + ``` GET /user/:username ``` + Use essa rota para obter informações sobre o perfil de determinado usuário, basta substituir o parâmetro ":username" da rota pelo usuário do github correspondente, você deve receber uma resposta no seguinte modelo: + ```json { "github_login": "davigsousa", @@ -58,24 +110,21 @@ Use essa rota para obter informações sobre o perfil de determinado usuário, b "html_url": "https://github.com/davigsousa/doeteca", "created_at": "2020-02-17T22:01:18Z", "language": "JavaScript" - }, + } ], "top_language": "JavaScript", - "top_5_languages": [ - "JavaScript", - "Python", - "C++", - "CSS", - "TypeScript" - ] + "top_5_languages": ["JavaScript", "Python", "C++", "CSS", "TypeScript"] } ``` ## Obter relatório do dia atual: + ``` GET /user/daily/:username ``` + Use essa rota para obter informações de interações de determinado usuário no dia atual, basta substituir o parâmetro ":username" da rota pelo usuário do github correspondente, você deve receber uma resposta no seguinte modelo: + ```json { "new_forks": 0, @@ -107,10 +156,13 @@ Use essa rota para obter informações de interações de determinado usuário n ``` ## Iniciar sessão com a conta de um professor: + ``` POST /session ``` + Realiza a sessão de um professor na aplicação, para realizar a requisição, deve-se enviar uma chave "email" com o e-mail do professor uma chave "password" com a senha, dessa forma, se recebe como retorno o token JWT para o uso em rotas autenticadas, exemplo de retorno: + ```json { "teacher": { @@ -131,10 +183,13 @@ Realiza a sessão de um professor na aplicação, para realizar a requisição, ## ⭐ A partir daqui, todas as rotas são autenticadas. ## Listar alunos de uma turma: + ``` GET /class/ ``` + Listar todos os alunos da turma da aplicação, exemplo de retorno: + ```json [ { @@ -163,10 +218,13 @@ Listar todos os alunos da turma da aplicação, exemplo de retorno: ``` ## Listar alunos da turma abaixo da média: + ``` GET /class/below_average?since=2020-10-02 ``` + Informando o parâmetro "since" na query, você informa o início do período de avaliação da média, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para listar todos os alunos da turma abaixo da média de interações, exemplo de retorno: + ```json [ { @@ -195,10 +253,13 @@ Informando o parâmetro "since" na query, você informa o início do período de ``` ## Obter Relatório da Turma: + ``` GET /class/report?since=2020-10-02 ``` + Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de uma turma em um período, exemplo de retorno: + ```json { "all_new_interactions": 36, @@ -209,10 +270,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ``` ## Adicionar aluno na Turma: + ``` POST /student ``` + Adiciona-se um aluno na turma, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do aluno no Github, dessa forma, se recebe como retorno o aluno criado, exemplo de retorno: + ```json { "teacher_id": "84e5a509-16af-4f3d-805c-c400751e6d4c", @@ -228,10 +292,13 @@ Adiciona-se um aluno na turma, para realizar a requisição, deve-se enviar uma ``` ## Obtém as informações de um aluno: + ``` GET /student/:username ``` + Obtém as informações de um aluno, deve-se enviar o username do Github do aluno como params :username, é retornado as informações do estudante e seus repositórios: + ```json { "student": { @@ -273,10 +340,13 @@ Obtém as informações de um aluno, deve-se enviar o username do Github do alun ``` ## Obtém a quantidade de interações por dia em um período de um estudante: + ``` GET /student/:username/interactions/volume?since=2020-11-02 ``` + Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade de interações por dia de um aluno, deve-se enviar o username do Github do aluno como params :username, as quantidades são retornadas no seguinte modelo: + ```json [ { @@ -295,10 +365,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ``` ## Obtém a adição e remoção de linhas por dia em um período de um estudante: + ``` GET /student/:username/lines/volume?since=2020-11-02 ``` + Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade adições e remoções de linhas de código por dia de um aluno, deve-se enviar o username do Github do aluno como params :username, as quantidades são retornadas no seguinte modelo: + ```json [ { @@ -320,10 +393,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ``` ## Obter Relatório de um estudante: + ``` GET /student/:username/report?since=2020-10-02 ``` + Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de um estudante em um período, exemplo de retorno: + ```json { "additions": 3950, @@ -354,10 +430,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ``` ## Adicionar professor na aplicação: + ``` POST /teacher ``` + Adiciona-se um professor na aplicação, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do professor no Github, uma chave "email" com o e-mail do professor e uma chave "password" no body da requisição, dessa forma, se recebe como retorno o professor criado, exemplo de retorno: + ```json { "github_login": "davigsousa", From cd82588d1cf96049c986c020831ef8e1726b980a Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Thu, 19 Nov 2020 10:45:39 -0300 Subject: [PATCH 053/113] Get spots below average --- backend/src/routes/v2/index.ts | 2 ++ backend/src/routes/v2/project.routes.ts | 26 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 backend/src/routes/v2/project.routes.ts diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index fef2ff8..da2f94d 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -2,11 +2,13 @@ import { Router } from 'express'; import manangerRouter from './manager.routes'; import spotRouter from './spots.routes'; import sessionsRouter from './sessions.routes'; +import projectRouter from './project.routes'; const routes = Router(); routes.use('/manager', manangerRouter); routes.use('/spot', spotRouter); routes.use('/session', sessionsRouter); +routes.use('/project', projectRouter); export default routes; diff --git a/backend/src/routes/v2/project.routes.ts b/backend/src/routes/v2/project.routes.ts new file mode 100644 index 0000000..9f8c92d --- /dev/null +++ b/backend/src/routes/v2/project.routes.ts @@ -0,0 +1,26 @@ +import { Router } from 'express'; +import authMiddleware from '../../middlewares/authMiddleware'; +import GetBelowAverageOnProjectService from '../../services/Project/GetBelowAverageOnProjectService'; + +const projectRouter = Router(); + +projectRouter.get( + '/below_average', + authMiddleware, + async (request, response) => { + const getBelowAverageOnProjectService = new GetBelowAverageOnProjectService(); + + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; + + const spots = await getBelowAverageOnProjectService.execute({ + since: since as string, + until: until as string, + }); + + return response.json(spots); + }, +); + +export default projectRouter; From 01b4609ccd37d03fce649bc29f307c4dda29ef52 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Thu, 19 Nov 2020 10:48:21 -0300 Subject: [PATCH 054/113] frontend setup configuration added on README --- frontend/README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/frontend/README.md b/frontend/README.md index 3f5861c..1648fb2 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -1,6 +1,7 @@ ## 🏁 Iniciando Você pode clonar o respositório com o git, com o seguinte comando: + ``` git clone https://github.com/Guardians-DSC/GitRadar.git ``` @@ -8,26 +9,42 @@ git clone https://github.com/Guardians-DSC/GitRadar.git ### Pré-requisitos Você precisará de NodeJS e Yarn (para facilitar o processo) no seu computador.
+ - [NodeJS](https://nodejs.org/en/download/)
- [Yarn](https://yarnpkg.com/getting-started/install) ### Instalando No terminal, abra a pasta do projeto e do Frontend. + ``` cd GitRadar/frontend ``` + Então, digite: + ``` yarn ``` -Pronto! Tudo está configurado para você começar a usar o projeto. +Agora, precisamos configurar as variáveis de ambiente. Para isso, você deve copiar o arquivo ".env.sample" e +o renomear para ".env" na pasta raiz do Backend. Você precisa preencher os valores de todas as variáveis de acordo com o seu significado. +
+Segue o arquivo ".env" comentado: + +```bash +# Informações do Aplicativo OAuth do GitHub +REACT_APP_CLIENT_ID=your_client_id # Mesmo valor do ClientID obtido na configuração do Backend, consulte o README do Backend. +``` + +Pronto! Tudo está configurado para você começar a usar o projeto. ## 🚀 Modo de uso Você pode iniciar o servidor local de desenvolvimento, com o seguinte comando: + ``` yarn start ``` + Pronto, o servidor estará sendo executado em http://localhost:3000! From 5582b55fe2aa9d75c07bdcf8884416fe8db41618 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Thu, 19 Nov 2020 10:49:45 -0300 Subject: [PATCH 055/113] oauth example image updated --- backend/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/README.md b/backend/README.md index 435f8d8..535916d 100644 --- a/backend/README.md +++ b/backend/README.md @@ -38,7 +38,8 @@ Com isso feito, você precisa criar um aplicativo OAuth com a sua conta do GitHu - [Siga esse tutorial do GitHub para isso.](https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/) A sua página da aplicação deve ficar assim: - + +
Guarde os valores do ClientID e ClientSecret, você usará no ".env", além disso atente-se para as urls da aplicação, como a aplicação está sendo executada localmente, as urls direcionam para o frontend no endereço localhost, segue os campos em texto: - Homepage URL: http://localhost:3000 From 633c7471825f60a75956db1df24056b38454b1af Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Thu, 19 Nov 2020 10:52:24 -0300 Subject: [PATCH 056/113] migration instructions added on Backend README --- backend/README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/README.md b/backend/README.md index 535916d..6565729 100644 --- a/backend/README.md +++ b/backend/README.md @@ -75,7 +75,13 @@ Pronto! Tudo está configurado para você começar a usar o projeto. ## 🚀 Modo de uso -Você pode iniciar o servidor local de desenvolvimento, com o seguinte comando: +Com o Banco de Dados devidamente configurado, você deve executar as migrations da aplicação para que sejam criadas as tabelas necessárias. Execute o seguinte comando: + +``` +yarn typeorm migration:run +``` + +Agora, você pode iniciar o servidor local de desenvolvimento, com o seguinte comando: ``` yarn dev:server From 8aa7de4a11d2639ecc8e1916c03af83b56fb2721 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 08:02:49 -0300 Subject: [PATCH 057/113] Putting primary language on repository --- backend/src/services/Spot/CreateSpotService.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/src/services/Spot/CreateSpotService.ts b/backend/src/services/Spot/CreateSpotService.ts index 2550728..4dd1bb8 100644 --- a/backend/src/services/Spot/CreateSpotService.ts +++ b/backend/src/services/Spot/CreateSpotService.ts @@ -24,6 +24,9 @@ interface RepositoryNode { description: string; url: string; id: string; + primaryLanguage: { + name: string; + }; } interface Response { @@ -110,7 +113,7 @@ class CreateSpotService { spot_id, }); - const repositoriesReponse = spotRepositories.map( + const repositoriesReponse: RepositoryInfo[] = spotRepositories.map( ({ id: repository_id, name: repository_name, @@ -147,6 +150,9 @@ class CreateSpotService { description url id + primaryLanguage { + name + } } } } From 824b308f857659d2fd51d26dc3d9fdb384121114 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 15:12:16 -0300 Subject: [PATCH 058/113] Get Project Report --- backend/src/routes/v2/project.routes.ts | 16 ++++ .../src/services/Project/GetProjectReport.ts | 73 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 backend/src/services/Project/GetProjectReport.ts diff --git a/backend/src/routes/v2/project.routes.ts b/backend/src/routes/v2/project.routes.ts index 9f8c92d..9d34102 100644 --- a/backend/src/routes/v2/project.routes.ts +++ b/backend/src/routes/v2/project.routes.ts @@ -1,6 +1,7 @@ import { Router } from 'express'; import authMiddleware from '../../middlewares/authMiddleware'; import GetBelowAverageOnProjectService from '../../services/Project/GetBelowAverageOnProjectService'; +import GetProjectReportService from '../../services/Project/GetProjectReport'; const projectRouter = Router(); @@ -23,4 +24,19 @@ projectRouter.get( }, ); +projectRouter.get('/report', authMiddleware, async (request, response) => { + const getProjectReportService = new GetProjectReportService(); + + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; + + const spots = await getProjectReportService.execute({ + since: since as string, + until: until as string, + }); + + return response.json(spots); +}); + export default projectRouter; diff --git a/backend/src/services/Project/GetProjectReport.ts b/backend/src/services/Project/GetProjectReport.ts new file mode 100644 index 0000000..63258f6 --- /dev/null +++ b/backend/src/services/Project/GetProjectReport.ts @@ -0,0 +1,73 @@ +import { getCustomRepository } from 'typeorm'; +import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; + +interface Response { + all_new_interactions: number; + all_new_commits: number; + new_interactions_average: number; + new_commits_average: number; +} + +interface Request { + since: string; + until: string; +} + +interface Report { + spot: { + id: string; + github_login: string; + manager_id: string; + avatar_url: string; + top_language: string; + github_id: string; + name: string; + created_at: string; + updated_at: string; + }; + metrics: { + new_interactions: number; + new_commits: number; + new_prs: number; + new_issues: number; + new_repositories: number; + additions: number; + deletions: number; + }; +} + +class GetProjectReportService { + async execute({ since, until }: Request): Promise { + const reportsRepository = getCustomRepository(SpotDailyReportsRepository); + + const reports = await reportsRepository.findByPeriod(since, until); + + const projectReports = this.parseProjectReport(reports); + + return projectReports; + } + + private parseProjectReport(reports: Report[]): Response { + const projectReports = { + all_new_interactions: 0, + all_new_commits: 0, + new_interactions_average: 0, + new_commits_average: 0, + }; + + reports.forEach(({ metrics }) => { + projectReports.all_new_commits += metrics.new_commits; + projectReports.all_new_interactions += metrics.new_interactions; + }); + + const spots = reports.length; + + projectReports.new_commits_average = projectReports.all_new_commits / spots; + projectReports.new_interactions_average = + projectReports.all_new_interactions / spots; + + return projectReports; + } +} + +export default GetProjectReportService; From d1d8027d94ddf426e8a3d5a75591f011f9425522 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 15:17:53 -0300 Subject: [PATCH 059/113] GetSpotsOnProject --- backend/src/routes/v2/project.routes.ts | 9 +++++++++ backend/src/routes/v2/spots.routes.ts | 9 --------- backend/src/services/Spot/GetSpotsBelowAverage.ts | 14 -------------- ...SpotsService.ts => GetSpotsOnProjectService.ts} | 4 ++-- 4 files changed, 11 insertions(+), 25 deletions(-) delete mode 100644 backend/src/services/Spot/GetSpotsBelowAverage.ts rename backend/src/services/Spot/{GetSpotsService.ts => GetSpotsOnProjectService.ts} (79%) diff --git a/backend/src/routes/v2/project.routes.ts b/backend/src/routes/v2/project.routes.ts index 9d34102..3f78427 100644 --- a/backend/src/routes/v2/project.routes.ts +++ b/backend/src/routes/v2/project.routes.ts @@ -2,9 +2,18 @@ import { Router } from 'express'; import authMiddleware from '../../middlewares/authMiddleware'; import GetBelowAverageOnProjectService from '../../services/Project/GetBelowAverageOnProjectService'; import GetProjectReportService from '../../services/Project/GetProjectReport'; +import GetSpotsOnProjectService from '../../services/Spot/GetSpotsOnProjectService'; const projectRouter = Router(); +projectRouter.get('/:project', authMiddleware, async (request, response) => { + const getSpotsService = new GetSpotsOnProjectService(); + + const spots = await getSpotsService.execute(); + + return response.json(spots); +}); + projectRouter.get( '/below_average', authMiddleware, diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots.routes.ts index 36c79d0..914a4a9 100644 --- a/backend/src/routes/v2/spots.routes.ts +++ b/backend/src/routes/v2/spots.routes.ts @@ -1,7 +1,6 @@ import { Router } from 'express'; import CreateSpotService from '../../services/Spot/CreateSpotService'; import authMiddleware from '../../middlewares/authMiddleware'; -import GetSpotsService from '../../services/Spot/GetSpotsService'; const spotRouter = Router(); @@ -19,12 +18,4 @@ spotRouter.post('/', authMiddleware, async (request, response) => { return response.json(spot); }); -spotRouter.get('/', authMiddleware, async (request, response) => { - const getSpotsService = new GetSpotsService(); - - const spots = await getSpotsService.execute(); - - return response.json(spots); -}); - export default spotRouter; diff --git a/backend/src/services/Spot/GetSpotsBelowAverage.ts b/backend/src/services/Spot/GetSpotsBelowAverage.ts deleted file mode 100644 index b28b63f..0000000 --- a/backend/src/services/Spot/GetSpotsBelowAverage.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { getCustomRepository } from 'typeorm'; -import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; -import GetSpotsService from './GetSpotsService'; - -class GetSpotsBelowAverage { - async execute(): Promise { - const spotDailyRepository = getCustomRepository(SpotDailyReportsRepository); - const getSpotsService = new GetSpotsService(); - - const spots = await getSpotsService.execute(); - } -} - -export default GetSpotsBelowAverage; diff --git a/backend/src/services/Spot/GetSpotsService.ts b/backend/src/services/Spot/GetSpotsOnProjectService.ts similarity index 79% rename from backend/src/services/Spot/GetSpotsService.ts rename to backend/src/services/Spot/GetSpotsOnProjectService.ts index fcac5d8..e00bce3 100644 --- a/backend/src/services/Spot/GetSpotsService.ts +++ b/backend/src/services/Spot/GetSpotsOnProjectService.ts @@ -1,7 +1,7 @@ import { getRepository } from 'typeorm'; import Spot from '../../models/Spot'; -class GetSpotsService { +class GetSpotsOnProjectService { async execute(): Promise { const spotsRepository = getRepository(Spot); @@ -13,4 +13,4 @@ class GetSpotsService { } } -export default GetSpotsService; +export default GetSpotsOnProjectService; From 3197d067072e9c32ca5f9426ea32aa0ce438c22d Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 15:18:43 -0300 Subject: [PATCH 060/113] Minor fixes --- backend/src/routes/v2/project.routes.ts | 28 ++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/backend/src/routes/v2/project.routes.ts b/backend/src/routes/v2/project.routes.ts index 3f78427..271d2df 100644 --- a/backend/src/routes/v2/project.routes.ts +++ b/backend/src/routes/v2/project.routes.ts @@ -15,7 +15,7 @@ projectRouter.get('/:project', authMiddleware, async (request, response) => { }); projectRouter.get( - '/below_average', + '/below_average/:project', authMiddleware, async (request, response) => { const getBelowAverageOnProjectService = new GetBelowAverageOnProjectService(); @@ -33,19 +33,23 @@ projectRouter.get( }, ); -projectRouter.get('/report', authMiddleware, async (request, response) => { - const getProjectReportService = new GetProjectReportService(); +projectRouter.get( + '/report/:project', + authMiddleware, + async (request, response) => { + const getProjectReportService = new GetProjectReportService(); - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; - const spots = await getProjectReportService.execute({ - since: since as string, - until: until as string, - }); + const spots = await getProjectReportService.execute({ + since: since as string, + until: until as string, + }); - return response.json(spots); -}); + return response.json(spots); + }, +); export default projectRouter; From 04a7fe17bf4cd96508d88e534a3bd9a64f566209 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 15:50:34 -0300 Subject: [PATCH 061/113] GetSportReportService --- backend/src/routes/v2/spots.routes.ts | 23 +++++++ .../src/services/Spot/GetSpotReportService.ts | 61 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 backend/src/services/Spot/GetSpotReportService.ts diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots.routes.ts index 914a4a9..125b99f 100644 --- a/backend/src/routes/v2/spots.routes.ts +++ b/backend/src/routes/v2/spots.routes.ts @@ -1,6 +1,7 @@ import { Router } from 'express'; import CreateSpotService from '../../services/Spot/CreateSpotService'; import authMiddleware from '../../middlewares/authMiddleware'; +import GetSpotReportService from '../../services/Spot/GetSpotReportService'; const spotRouter = Router(); @@ -18,4 +19,26 @@ spotRouter.post('/', authMiddleware, async (request, response) => { return response.json(spot); }); +spotRouter.get( + '/:spot_id/report', + authMiddleware, + async (request, response) => { + const { spot_id } = request.params; + + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; + + const getSpotReportService = new GetSpotReportService(); + + const spotReport = await getSpotReportService.execute({ + since: since as string, + spot_id, + until: until as string, + }); + + return response.json(spotReport); + }, +); + export default spotRouter; diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts new file mode 100644 index 0000000..2bc3f37 --- /dev/null +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -0,0 +1,61 @@ +import { Between, getCustomRepository, getRepository } from 'typeorm'; +import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; +import Commit from '../../models/Commit'; + +interface Request { + spot_id: string; + since: string; + until: string; +} + +interface Response { + spot: { + id: string; + github_login: string; + manager_id: string; + avatar_url: string; + top_language: string; + github_id: string; + name: string; + created_at: string; + updated_at: string; + }; + metrics: { + new_interactions: number; + new_commits: number; + new_prs: number; + new_issues: number; + new_repositories: number; + additions: number; + deletions: number; + }; + commits: Commit[]; +} + +class GetSpotReportService { + async execute({ spot_id, since, until }: Request): Promise { + const reportsRepository = getCustomRepository(SpotDailyReportsRepository); + const commitRepository = getRepository(Commit); + + const spotReport = await reportsRepository.findByPeriodAndId( + spot_id, + since, + until, + ); + + const commits = await commitRepository.find({ + where: { + spot_id, + created_at: Between(since, until), + }, + }); + + console.log(spot_id); + + console.log(spotReport); + + return { ...spotReport, commits }; + } +} + +export default GetSpotReportService; From e89ad9fcaede64e52a8dcdaec0c6487c88c6402e Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:05:08 -0300 Subject: [PATCH 062/113] Removing some unused relations --- ...8322310-RemoveSpotDailyReportForeignKey.ts | 22 +++++++++++++++++++ ...605898474371-RemoveCommitSpotForeignKey.ts | 22 +++++++++++++++++++ ...597912-RemoveCommitRepositoryForeignKey.ts | 22 +++++++++++++++++++ ...5898667830-RemoveRepositoryIdFromCommit.ts | 19 ++++++++++++++++ ...34652-RemoveSpotDailyReportIdFromCommit.ts | 19 ++++++++++++++++ 5 files changed, 104 insertions(+) create mode 100644 backend/src/database/migrations/1605898322310-RemoveSpotDailyReportForeignKey.ts create mode 100644 backend/src/database/migrations/1605898474371-RemoveCommitSpotForeignKey.ts create mode 100644 backend/src/database/migrations/1605898597912-RemoveCommitRepositoryForeignKey.ts create mode 100644 backend/src/database/migrations/1605898667830-RemoveRepositoryIdFromCommit.ts create mode 100644 backend/src/database/migrations/1605898834652-RemoveSpotDailyReportIdFromCommit.ts diff --git a/backend/src/database/migrations/1605898322310-RemoveSpotDailyReportForeignKey.ts b/backend/src/database/migrations/1605898322310-RemoveSpotDailyReportForeignKey.ts new file mode 100644 index 0000000..858ad1f --- /dev/null +++ b/backend/src/database/migrations/1605898322310-RemoveSpotDailyReportForeignKey.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; + +export default class RemoveSpotDailyReportForeignKey1605898322310 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropForeignKey('spot_daily_reports', 'dailySpot'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.createForeignKey( + 'spot_daily_reports', + new TableForeignKey({ + name: 'dailySpot', + columnNames: ['spot_id'], + referencedColumnNames: ['id'], + referencedTableName: 'spots', + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }), + ); + } +} diff --git a/backend/src/database/migrations/1605898474371-RemoveCommitSpotForeignKey.ts b/backend/src/database/migrations/1605898474371-RemoveCommitSpotForeignKey.ts new file mode 100644 index 0000000..4dae636 --- /dev/null +++ b/backend/src/database/migrations/1605898474371-RemoveCommitSpotForeignKey.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; + +export default class RemoveCommitSpotForeignKey1605898474371 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropForeignKey('commits', 'commitSpot'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.createForeignKey( + 'commits', + new TableForeignKey({ + name: 'commitSpot', + columnNames: ['spot_id'], + referencedColumnNames: ['id'], + referencedTableName: 'spots', + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }), + ); + } +} diff --git a/backend/src/database/migrations/1605898597912-RemoveCommitRepositoryForeignKey.ts b/backend/src/database/migrations/1605898597912-RemoveCommitRepositoryForeignKey.ts new file mode 100644 index 0000000..6d61244 --- /dev/null +++ b/backend/src/database/migrations/1605898597912-RemoveCommitRepositoryForeignKey.ts @@ -0,0 +1,22 @@ +import { MigrationInterface, QueryRunner, TableForeignKey } from 'typeorm'; + +export default class RemoveCommitRepositoryForeignKey1605898597912 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropForeignKey('commits', 'commitRepository'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.createForeignKey( + 'commits', + new TableForeignKey({ + name: 'commitRepository', + columnNames: ['repository_id'], + referencedColumnNames: ['id'], + referencedTableName: 'repositories', + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }), + ); + } +} diff --git a/backend/src/database/migrations/1605898667830-RemoveRepositoryIdFromCommit.ts b/backend/src/database/migrations/1605898667830-RemoveRepositoryIdFromCommit.ts new file mode 100644 index 0000000..bbbec42 --- /dev/null +++ b/backend/src/database/migrations/1605898667830-RemoveRepositoryIdFromCommit.ts @@ -0,0 +1,19 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class RemoveRepositoryIdFromCommit1605898667830 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('commits', 'repository_id'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'commits', + new TableColumn({ + name: 'spot_daily_report_id', + type: 'uuid', + isNullable: false, + }), + ); + } +} diff --git a/backend/src/database/migrations/1605898834652-RemoveSpotDailyReportIdFromCommit.ts b/backend/src/database/migrations/1605898834652-RemoveSpotDailyReportIdFromCommit.ts new file mode 100644 index 0000000..b6cff04 --- /dev/null +++ b/backend/src/database/migrations/1605898834652-RemoveSpotDailyReportIdFromCommit.ts @@ -0,0 +1,19 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class RemoveSpotDailyReportIdFromCommit1605898834652 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('commits', 'spot_daily_report_id'); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'commits', + new TableColumn({ + name: 'repository_id', + type: 'uuid', + isNullable: true, + }), + ); + } +} From 8348df6274183bf54489b3c82f10ba3072aac563 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:07:00 -0300 Subject: [PATCH 063/113] Removing unused fields --- backend/src/models/Commit.ts | 24 ------------------- .../ProcessSpot/ProcessSpotProcessor.ts | 3 +-- 2 files changed, 1 insertion(+), 26 deletions(-) diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index bd478c7..a047d2f 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -2,42 +2,18 @@ import { Entity, PrimaryGeneratedColumn, Column, - ManyToOne, - JoinColumn, CreateDateColumn, UpdateDateColumn, } from 'typeorm'; -import Repository from './Repository'; -import Spot from './Spot'; -import StudentDailyReport from './SpotDailyReport'; - @Entity('commits') class Commit { @PrimaryGeneratedColumn('uuid') id: string; - @Column('uuid') - repository_id: string; - - @ManyToOne(() => Repository, { eager: true }) - @JoinColumn({ name: 'repository_id' }) - repository: Repository; - @Column('uuid') spot_id: string; - @ManyToOne(() => Spot, { eager: true }) - @JoinColumn({ name: 'spot_id' }) - spot: Spot; - - @Column('uuid') - spot_daily_report_id: string; - - @ManyToOne(() => StudentDailyReport, { eager: true }) - @JoinColumn({ name: 'spot_daily_report_id' }) - spotDailyReport: StudentDailyReport; - @Column('varchar') message: string; diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 33c86cc..f22dfd3 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -41,7 +41,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { spot_id, }); - const { id: daily_id } = await dailyReportRepository.save(dailyReport); + await dailyReportRepository.save(dailyReport); for (const commit of commits) { const { @@ -55,7 +55,6 @@ const ProcessSpotProcessor = async (job: Job): Promise => { additions: commit_additions, deletions: commit_deletions, message, - spot_daily_report_id: daily_id, spot_id, sha, }); From e10ca04832f24f8d777f2620f39de788baa3c5a8 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:13:13 -0300 Subject: [PATCH 064/113] Minor changes --- backend/src/app.ts | 2 +- .../RequestSpotsProcess/RequestSpotsProcessProcessor.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index b981608..de515e0 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -50,7 +50,7 @@ class App { } private defineCron(): void { - cron.schedule('00 23 * * *', async () => + cron.schedule('* * * * *', async () => this.queueProvider.add({ jobName: 'request spot process', queueName: 'spot-process-requester', diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 4a2c3c4..1a94a55 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -5,11 +5,13 @@ import Spot from '../../models/Spot'; const RequestSpotsProcessProcessor = async (): Promise => { const spotsRepository = getRepository(Spot); const since = new Date(); - since.setHours(0); + since.setHours(-3); since.setMinutes(0); since.setSeconds(0); since.setMilliseconds(0); + console.log(`Starting spot crawl request at ${since.toISOString()}`); + const spots = await spotsRepository.find(); spots.forEach((spot: Spot) => { From 6111914ab4c76312f63b4aec0af786af53cedfb8 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:15:07 -0300 Subject: [PATCH 065/113] Cron fixes --- backend/src/app.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index de515e0..b981608 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -50,7 +50,7 @@ class App { } private defineCron(): void { - cron.schedule('* * * * *', async () => + cron.schedule('00 23 * * *', async () => this.queueProvider.add({ jobName: 'request spot process', queueName: 'spot-process-requester', From 2307d4cf4316c636fdb50ba55a1627e45be73498 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:22:18 -0300 Subject: [PATCH 066/113] Removing unused logs --- backend/src/services/Spot/GetSpotReportService.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts index 2bc3f37..68e5e03 100644 --- a/backend/src/services/Spot/GetSpotReportService.ts +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -50,10 +50,6 @@ class GetSpotReportService { }, }); - console.log(spot_id); - - console.log(spotReport); - return { ...spotReport, commits }; } } From f417a7a1979f15e425bdcbc637b10f99b1becfe6 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:36:02 -0300 Subject: [PATCH 067/113] adding commitUrl and repository name on commit --- ...7-AddCommitUrlAndRepositoryNameOnCommit.ts | 29 +++++++++++++++++++ backend/src/models/Commit.ts | 6 ++++ .../DailyReport/GetDailyReportService.ts | 10 ++++++- .../ProcessSpot/ProcessSpotProcessor.ts | 4 +++ 4 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 backend/src/database/migrations/1605900478747-AddCommitUrlAndRepositoryNameOnCommit.ts diff --git a/backend/src/database/migrations/1605900478747-AddCommitUrlAndRepositoryNameOnCommit.ts b/backend/src/database/migrations/1605900478747-AddCommitUrlAndRepositoryNameOnCommit.ts new file mode 100644 index 0000000..537ae58 --- /dev/null +++ b/backend/src/database/migrations/1605900478747-AddCommitUrlAndRepositoryNameOnCommit.ts @@ -0,0 +1,29 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class AddCommitUrlAndRepositoryNameOnCommit1605900478747 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'commits', + new TableColumn({ + name: 'commit_url', + type: 'varchar', + isNullable: false, + }), + ); + + await queryRunner.addColumn( + 'commits', + new TableColumn({ + name: 'repository_name', + type: 'varchar', + isNullable: false, + }), + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('commits', 'repository_name'); + await queryRunner.dropColumn('commits', 'commit_url'); + } +} diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index a047d2f..bab8735 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -20,6 +20,12 @@ class Commit { @Column('int2') additions: number; + @Column('varchar') + commit_url: string; + + @Column('varchar') + repository_name: string; + @Column('int2') deletions: number; diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index e444689..0518990 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -11,6 +11,7 @@ interface Commit { name: string; url: string; }; + commit_url: string; sha: string; message: string; additions: number; @@ -167,13 +168,20 @@ class GetDailyReportService { }); for (const commit of spotCommits) { - const { additions, deletions, id: commit_id, message } = commit; + const { + additions, + deletions, + id: commit_id, + message, + commitUrl, + } = commit; const serializedCommit: Commit = { additions, deletions, message, sha: commit_id, + commit_url: commitUrl, repository: { id: repository_id, name: nameWithOwner, diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index f22dfd3..b78c098 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -49,6 +49,8 @@ const ProcessSpotProcessor = async (job: Job): Promise => { deletions: commit_deletions, message, sha, + commit_url, + repository, } = commit; const spotCommit = commitRepository.create({ @@ -57,6 +59,8 @@ const ProcessSpotProcessor = async (job: Job): Promise => { message, spot_id, sha, + commit_url, + repository_name: repository.name, }); await commitRepository.save(spotCommit); From c9d4406f1adfcc93d69aba8315d05ec04476c044 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 16:44:09 -0300 Subject: [PATCH 068/113] adding commitUrl and repository name on commit --- .../1605901117924-AddRepositoryUrlOnCommit.ts | 19 +++++++++++++++++++ backend/src/models/Commit.ts | 3 +++ .../ProcessSpot/ProcessSpotProcessor.ts | 1 + 3 files changed, 23 insertions(+) create mode 100644 backend/src/database/migrations/1605901117924-AddRepositoryUrlOnCommit.ts diff --git a/backend/src/database/migrations/1605901117924-AddRepositoryUrlOnCommit.ts b/backend/src/database/migrations/1605901117924-AddRepositoryUrlOnCommit.ts new file mode 100644 index 0000000..2ee45e9 --- /dev/null +++ b/backend/src/database/migrations/1605901117924-AddRepositoryUrlOnCommit.ts @@ -0,0 +1,19 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class AddRepositoryUrlOnCommit1605901117924 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'commits', + new TableColumn({ + name: 'repository_url', + type: 'varchar', + isNullable: false, + }), + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('commits', 'repository_url'); + } +} diff --git a/backend/src/models/Commit.ts b/backend/src/models/Commit.ts index bab8735..52774fb 100644 --- a/backend/src/models/Commit.ts +++ b/backend/src/models/Commit.ts @@ -26,6 +26,9 @@ class Commit { @Column('varchar') repository_name: string; + @Column('varchar') + repository_url: string; + @Column('int2') deletions: number; diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index b78c098..2ddbb1c 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -61,6 +61,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { sha, commit_url, repository_name: repository.name, + repository_url: repository.url, }); await commitRepository.save(spotCommit); From 705c807cc7495d4a1813c81a5a6886493da0b34b Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 17:07:04 -0300 Subject: [PATCH 069/113] Interactions volume --- backend/src/routes/v2/index.ts | 2 +- .../src/routes/v2/{ => spots}/spots.routes.ts | 9 ++-- .../v2/spots/volume/spots.volume.routes.ts | 29 +++++++++++ .../Spot/GetInteractionsVolumeService.ts | 48 +++++++++++++++++++ 4 files changed, 84 insertions(+), 4 deletions(-) rename backend/src/routes/v2/{ => spots}/spots.routes.ts (74%) create mode 100644 backend/src/routes/v2/spots/volume/spots.volume.routes.ts create mode 100644 backend/src/services/Spot/GetInteractionsVolumeService.ts diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/v2/index.ts index da2f94d..621b52b 100644 --- a/backend/src/routes/v2/index.ts +++ b/backend/src/routes/v2/index.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; import manangerRouter from './manager.routes'; -import spotRouter from './spots.routes'; +import spotRouter from './spots/spots.routes'; import sessionsRouter from './sessions.routes'; import projectRouter from './project.routes'; diff --git a/backend/src/routes/v2/spots.routes.ts b/backend/src/routes/v2/spots/spots.routes.ts similarity index 74% rename from backend/src/routes/v2/spots.routes.ts rename to backend/src/routes/v2/spots/spots.routes.ts index 125b99f..82ce6a4 100644 --- a/backend/src/routes/v2/spots.routes.ts +++ b/backend/src/routes/v2/spots/spots.routes.ts @@ -1,10 +1,13 @@ import { Router } from 'express'; -import CreateSpotService from '../../services/Spot/CreateSpotService'; -import authMiddleware from '../../middlewares/authMiddleware'; -import GetSpotReportService from '../../services/Spot/GetSpotReportService'; +import CreateSpotService from '../../../services/Spot/CreateSpotService'; +import authMiddleware from '../../../middlewares/authMiddleware'; +import GetSpotReportService from '../../../services/Spot/GetSpotReportService'; +import spotVolumeRouter from './volume/spots.volume.routes'; const spotRouter = Router(); +spotRouter.use('/volume', spotVolumeRouter); + spotRouter.post('/', authMiddleware, async (request, response) => { const { github_login } = request.body; const { id } = request.manager; diff --git a/backend/src/routes/v2/spots/volume/spots.volume.routes.ts b/backend/src/routes/v2/spots/volume/spots.volume.routes.ts new file mode 100644 index 0000000..8ba5692 --- /dev/null +++ b/backend/src/routes/v2/spots/volume/spots.volume.routes.ts @@ -0,0 +1,29 @@ +import { Router } from 'express'; +import authMiddleware from '../../../../middlewares/authMiddleware'; +import GetInteractionsVolumeService from '../../../../services/Spot/GetInteractionsVolumeService'; + +const spotVolumeRouter = Router(); + +spotVolumeRouter.get( + '/:spot_id/interactions', + authMiddleware, + async (request, response) => { + const { spot_id } = request.params; + + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; + + const getInteractionsVolume = new GetInteractionsVolumeService(); + + const volume = await getInteractionsVolume.execute({ + spot_id, + since: since as string, + until: until as string, + }); + + return response.json(volume); + }, +); + +export default spotVolumeRouter; diff --git a/backend/src/services/Spot/GetInteractionsVolumeService.ts b/backend/src/services/Spot/GetInteractionsVolumeService.ts new file mode 100644 index 0000000..a190bbc --- /dev/null +++ b/backend/src/services/Spot/GetInteractionsVolumeService.ts @@ -0,0 +1,48 @@ +import { Between, getRepository } from 'typeorm'; +import SpotDailyReport from '../../models/SpotDailyReport'; + +interface Request { + since: string; + until: string; + spot_id: string; +} + +interface Data { + date: Date; + value: number; +} + +interface DataBaseRequest { + created_at: Date; + new_interactions: number; +} + +class GetInteractionsVolumeService { + async execute({ since, until, spot_id }: Request): Promise { + const dailyReportRepository = getRepository(SpotDailyReport); + + const dailyReports = await dailyReportRepository.find({ + where: { + created_at: Between(since, until), + spot_id, + }, + select: ['created_at', 'new_interactions'], + order: { + created_at: 'ASC', + }, + }); + + const parsedData = dailyReports.map( + ({ created_at, new_interactions }: DataBaseRequest) => { + return { + value: new_interactions, + date: created_at, + }; + }, + ); + + return parsedData; + } +} + +export default GetInteractionsVolumeService; From e4e1a39bbdb5853d254355e35df971b47cdabf7f Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 17:12:00 -0300 Subject: [PATCH 070/113] Get Lines Volume --- .../v2/spots/volume/spots.volume.routes.ts | 23 +++++++++ .../services/Spot/GetLinesVolumeService.ts | 51 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 backend/src/services/Spot/GetLinesVolumeService.ts diff --git a/backend/src/routes/v2/spots/volume/spots.volume.routes.ts b/backend/src/routes/v2/spots/volume/spots.volume.routes.ts index 8ba5692..f1ed257 100644 --- a/backend/src/routes/v2/spots/volume/spots.volume.routes.ts +++ b/backend/src/routes/v2/spots/volume/spots.volume.routes.ts @@ -1,6 +1,7 @@ import { Router } from 'express'; import authMiddleware from '../../../../middlewares/authMiddleware'; import GetInteractionsVolumeService from '../../../../services/Spot/GetInteractionsVolumeService'; +import GetLinesVolumeService from '../../../../services/Spot/GetLinesVolumeService'; const spotVolumeRouter = Router(); @@ -26,4 +27,26 @@ spotVolumeRouter.get( }, ); +spotVolumeRouter.get( + '/:spot_id/lines', + authMiddleware, + async (request, response) => { + const { spot_id } = request.params; + + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; + + const getLinesVolume = new GetLinesVolumeService(); + + const volume = await getLinesVolume.execute({ + spot_id, + since: since as string, + until: until as string, + }); + + return response.json(volume); + }, +); + export default spotVolumeRouter; diff --git a/backend/src/services/Spot/GetLinesVolumeService.ts b/backend/src/services/Spot/GetLinesVolumeService.ts new file mode 100644 index 0000000..a839ef3 --- /dev/null +++ b/backend/src/services/Spot/GetLinesVolumeService.ts @@ -0,0 +1,51 @@ +import { Between, getRepository } from 'typeorm'; +import SpotDailyReport from '../../models/SpotDailyReport'; + +interface Request { + since: string; + until: string; + spot_id: string; +} + +interface Data { + date: Date; + gains: number; + loss: number; +} + +interface DataBaseRequest { + created_at: Date; + additions: number; + deletions: number; +} + +class GetLinesVolumeService { + async execute({ since, until, spot_id }: Request): Promise { + const dailyReportRepository = getRepository(SpotDailyReport); + + const dailyReports = await dailyReportRepository.find({ + where: { + created_at: Between(since, until), + spot_id, + }, + select: ['created_at', 'additions', 'deletions'], + order: { + created_at: 'ASC', + }, + }); + + const parsedData = dailyReports.map( + ({ created_at, additions, deletions }: DataBaseRequest) => { + return { + gains: additions, + loss: deletions, + date: created_at, + }; + }, + ); + + return parsedData; + } +} + +export default GetLinesVolumeService; From 79de3498d804b80ebf24c6919e376b6ca50f6087 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 17:15:27 -0300 Subject: [PATCH 071/113] Moving routes --- backend/src/app.ts | 4 ++-- backend/src/routes/{v2 => }/index.ts | 0 backend/src/routes/{v2 => }/manager.routes.ts | 4 ++-- backend/src/routes/{v2 => }/project.routes.ts | 8 ++++---- backend/src/routes/{v2 => }/sessions.routes.ts | 2 +- backend/src/routes/{v2 => }/spots/spots.routes.ts | 6 +++--- .../routes/{v2 => }/spots/volume/spots.volume.routes.ts | 6 +++--- 7 files changed, 15 insertions(+), 15 deletions(-) rename backend/src/routes/{v2 => }/index.ts (100%) rename backend/src/routes/{v2 => }/manager.routes.ts (81%) rename backend/src/routes/{v2 => }/project.routes.ts (79%) rename backend/src/routes/{v2 => }/sessions.routes.ts (82%) rename backend/src/routes/{v2 => }/spots/spots.routes.ts (82%) rename backend/src/routes/{v2 => }/spots/volume/spots.volume.routes.ts (81%) diff --git a/backend/src/app.ts b/backend/src/app.ts index b981608..d8bb3f4 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -7,7 +7,7 @@ import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; -import v2 from './routes/v2/index'; +import v2 from './routes/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; import RequestSpotsProcessProcessor from './workers/RequestSpotsProcess/RequestSpotsProcessProcessor'; @@ -76,7 +76,7 @@ class App { } private routes(): void { - this.express.use('/v2', v2); + this.express.use(v2); } } diff --git a/backend/src/routes/v2/index.ts b/backend/src/routes/index.ts similarity index 100% rename from backend/src/routes/v2/index.ts rename to backend/src/routes/index.ts diff --git a/backend/src/routes/v2/manager.routes.ts b/backend/src/routes/manager.routes.ts similarity index 81% rename from backend/src/routes/v2/manager.routes.ts rename to backend/src/routes/manager.routes.ts index a6f4e7f..e05de31 100644 --- a/backend/src/routes/v2/manager.routes.ts +++ b/backend/src/routes/manager.routes.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; -import CreateManagerService from '../../services/Manager/CreateManagerService'; -import SetGithubTokenService from '../../services/Manager/SetGithubTokenService'; +import CreateManagerService from '../services/Manager/CreateManagerService'; +import SetGithubTokenService from '../services/Manager/SetGithubTokenService'; const manangerRouter = Router(); diff --git a/backend/src/routes/v2/project.routes.ts b/backend/src/routes/project.routes.ts similarity index 79% rename from backend/src/routes/v2/project.routes.ts rename to backend/src/routes/project.routes.ts index 271d2df..c1e38bc 100644 --- a/backend/src/routes/v2/project.routes.ts +++ b/backend/src/routes/project.routes.ts @@ -1,8 +1,8 @@ import { Router } from 'express'; -import authMiddleware from '../../middlewares/authMiddleware'; -import GetBelowAverageOnProjectService from '../../services/Project/GetBelowAverageOnProjectService'; -import GetProjectReportService from '../../services/Project/GetProjectReport'; -import GetSpotsOnProjectService from '../../services/Spot/GetSpotsOnProjectService'; +import authMiddleware from '../middlewares/authMiddleware'; +import GetBelowAverageOnProjectService from '../services/Project/GetBelowAverageOnProjectService'; +import GetProjectReportService from '../services/Project/GetProjectReport'; +import GetSpotsOnProjectService from '../services/Spot/GetSpotsOnProjectService'; const projectRouter = Router(); diff --git a/backend/src/routes/v2/sessions.routes.ts b/backend/src/routes/sessions.routes.ts similarity index 82% rename from backend/src/routes/v2/sessions.routes.ts rename to backend/src/routes/sessions.routes.ts index c7d518b..b70579d 100644 --- a/backend/src/routes/v2/sessions.routes.ts +++ b/backend/src/routes/sessions.routes.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; -import AuthenticateManagerService from '../../services/Manager/AuthenticateManagerService'; +import AuthenticateManagerService from '../services/Manager/AuthenticateManagerService'; const sessionsRouter = Router(); diff --git a/backend/src/routes/v2/spots/spots.routes.ts b/backend/src/routes/spots/spots.routes.ts similarity index 82% rename from backend/src/routes/v2/spots/spots.routes.ts rename to backend/src/routes/spots/spots.routes.ts index 82ce6a4..079237c 100644 --- a/backend/src/routes/v2/spots/spots.routes.ts +++ b/backend/src/routes/spots/spots.routes.ts @@ -1,7 +1,7 @@ import { Router } from 'express'; -import CreateSpotService from '../../../services/Spot/CreateSpotService'; -import authMiddleware from '../../../middlewares/authMiddleware'; -import GetSpotReportService from '../../../services/Spot/GetSpotReportService'; +import CreateSpotService from '../../services/Spot/CreateSpotService'; +import authMiddleware from '../../middlewares/authMiddleware'; +import GetSpotReportService from '../../services/Spot/GetSpotReportService'; import spotVolumeRouter from './volume/spots.volume.routes'; const spotRouter = Router(); diff --git a/backend/src/routes/v2/spots/volume/spots.volume.routes.ts b/backend/src/routes/spots/volume/spots.volume.routes.ts similarity index 81% rename from backend/src/routes/v2/spots/volume/spots.volume.routes.ts rename to backend/src/routes/spots/volume/spots.volume.routes.ts index f1ed257..b4fa467 100644 --- a/backend/src/routes/v2/spots/volume/spots.volume.routes.ts +++ b/backend/src/routes/spots/volume/spots.volume.routes.ts @@ -1,7 +1,7 @@ import { Router } from 'express'; -import authMiddleware from '../../../../middlewares/authMiddleware'; -import GetInteractionsVolumeService from '../../../../services/Spot/GetInteractionsVolumeService'; -import GetLinesVolumeService from '../../../../services/Spot/GetLinesVolumeService'; +import authMiddleware from '../../../middlewares/authMiddleware'; +import GetInteractionsVolumeService from '../../../services/Spot/GetInteractionsVolumeService'; +import GetLinesVolumeService from '../../../services/Spot/GetLinesVolumeService'; const spotVolumeRouter = Router(); From 94244079348d74dfc6e22f6293994c2f225e3b5f Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Fri, 20 Nov 2020 18:02:45 -0300 Subject: [PATCH 072/113] v2 variable changed to routes in app.ts --- backend/src/app.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index d8bb3f4..dec50cc 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -7,7 +7,7 @@ import cron from 'node-cron'; import { router } from 'bull-board'; import { Worker } from 'bullmq'; -import v2 from './routes/index'; +import routes from './routes/index'; import errorHandlerMiddleware from './middlewares/errorHandlerMiddleware'; import BullQueueProvider from './providers/queue/implementations/BullQueueProvider'; import RequestSpotsProcessProcessor from './workers/RequestSpotsProcess/RequestSpotsProcessProcessor'; @@ -76,7 +76,7 @@ class App { } private routes(): void { - this.express.use(v2); + this.express.use(routes); } } From 43ec91ffe1e845e404ed3ff9b0999ce3d341eb65 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Fri, 20 Nov 2020 18:25:18 -0300 Subject: [PATCH 073/113] parset changed to parse --- backend/src/repositories/SpotDailyReportsRepository.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 6ae01ed..c16167d 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -67,7 +67,7 @@ class SpotDailyReportsRepository extends Repository { .groupBy('spot.id') .getRawOne(); - const report = this.parsetRawReport(rawReport); + const report = this.parseRawReport(rawReport); return report; } @@ -91,12 +91,12 @@ class SpotDailyReportsRepository extends Repository { .groupBy('spot.id') .getRawMany(); - const report = rawReport.map(raw => this.parsetRawReport(raw)); + const report = rawReport.map(raw => this.parseRawReport(raw)); return report; } - private parsetRawReport(rawReport: RawReport): Report { + private parseRawReport(rawReport: RawReport): Report { const { additions, deletions, From 7f68f4540b3032d8beff961ff1fbfa20f738172c Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 19:44:05 -0300 Subject: [PATCH 074/113] Fixes --- .../SpotDailyReportsRepository.ts | 89 +++++++------------ .../src/services/Project/GetProjectReport.ts | 16 +--- .../src/services/Spot/GetSpotReportService.ts | 17 +++- 3 files changed, 47 insertions(+), 75 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index c16167d..d455161 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -3,15 +3,6 @@ import { EntityRepository, Repository } from 'typeorm'; import SpotDailyReport from '../models/SpotDailyReport'; interface RawReport { - spot_id: string; - spot_manager_id: string; - spot_github_login: string; - spot_avatar_url: string; - spot_top_language: string; - spot_github_id: string; - spot_name: string; - spot_created_at: string; - spot_updated_at: string; new_interactions: number; new_commits: number; new_prs: number; @@ -22,17 +13,6 @@ interface RawReport { } interface Report { - spot: { - id: string; - github_login: string; - manager_id: string; - avatar_url: string; - top_language: string; - github_id: string; - name: string; - created_at: string; - updated_at: string; - }; metrics: { new_interactions: number; new_commits: number; @@ -97,48 +77,41 @@ class SpotDailyReportsRepository extends Repository { } private parseRawReport(rawReport: RawReport): Report { - const { - additions, - deletions, - new_commits, - new_interactions, - new_issues, - new_prs, - new_repositories, - spot_github_login, - spot_id, - spot_name, - spot_avatar_url, - spot_top_language, - spot_created_at, - spot_github_id, - spot_manager_id, - spot_updated_at, - } = rawReport; + if (rawReport) { + const { + additions, + deletions, + new_commits, + new_interactions, + new_issues, + new_prs, + new_repositories, + } = rawReport; - const report: Report = { - spot: { - id: spot_id, - github_login: spot_github_login, - name: spot_name, - avatar_url: spot_avatar_url, - top_language: spot_top_language, - github_id: spot_github_id, - manager_id: spot_manager_id, - created_at: spot_created_at, - updated_at: spot_updated_at, - }, + const report: Report = { + metrics: { + additions: Number(additions), + deletions: Number(deletions), + new_commits: Number(new_commits), + new_interactions: Number(new_interactions), + new_issues: Number(new_issues), + new_prs: Number(new_prs), + new_repositories: Number(new_repositories), + }, + }; + return report; + } + return { metrics: { - additions: Number(additions), - deletions: Number(deletions), - new_commits: Number(new_commits), - new_interactions: Number(new_interactions), - new_issues: Number(new_issues), - new_prs: Number(new_prs), - new_repositories: Number(new_repositories), + additions: 0, + deletions: 0, + new_commits: 0, + new_interactions: 0, + new_issues: 0, + new_prs: 0, + new_repositories: 0, }, }; - return report; } } diff --git a/backend/src/services/Project/GetProjectReport.ts b/backend/src/services/Project/GetProjectReport.ts index 63258f6..325ddd0 100644 --- a/backend/src/services/Project/GetProjectReport.ts +++ b/backend/src/services/Project/GetProjectReport.ts @@ -14,17 +14,6 @@ interface Request { } interface Report { - spot: { - id: string; - github_login: string; - manager_id: string; - avatar_url: string; - top_language: string; - github_id: string; - name: string; - created_at: string; - updated_at: string; - }; metrics: { new_interactions: number; new_commits: number; @@ -62,9 +51,10 @@ class GetProjectReportService { const spots = reports.length; - projectReports.new_commits_average = projectReports.all_new_commits / spots; + projectReports.new_commits_average = + projectReports.all_new_commits / spots || 0; projectReports.new_interactions_average = - projectReports.all_new_interactions / spots; + projectReports.all_new_interactions / spots || 0; return projectReports; } diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts index 68e5e03..5e3ef2e 100644 --- a/backend/src/services/Spot/GetSpotReportService.ts +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -1,6 +1,7 @@ import { Between, getCustomRepository, getRepository } from 'typeorm'; import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; import Commit from '../../models/Commit'; +import Spot from '../../models/Spot'; interface Request { spot_id: string; @@ -17,8 +18,8 @@ interface Response { top_language: string; github_id: string; name: string; - created_at: string; - updated_at: string; + created_at: Date; + updated_at: Date; }; metrics: { new_interactions: number; @@ -36,13 +37,21 @@ class GetSpotReportService { async execute({ spot_id, since, until }: Request): Promise { const reportsRepository = getCustomRepository(SpotDailyReportsRepository); const commitRepository = getRepository(Commit); + const spotRepository = getRepository(Spot); - const spotReport = await reportsRepository.findByPeriodAndId( + const { metrics } = await reportsRepository.findByPeriodAndId( spot_id, since, until, ); + const spot = await spotRepository.findOne({ + where: { + id: spot_id, + }, + loadEagerRelations: false, + }); + const commits = await commitRepository.find({ where: { spot_id, @@ -50,7 +59,7 @@ class GetSpotReportService { }, }); - return { ...spotReport, commits }; + return { spot: { ...spot }, metrics: { ...metrics }, commits }; } } From 91b0c0c70ede6999ccd59b8b5f91e573d5500435 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 20:03:20 -0300 Subject: [PATCH 075/113] Using period to crawl --- backend/src/providers/queue/QueueProvider.ts | 3 ++- .../DailyReport/GetDailyReportService.ts | 13 ++++++------ .../ProcessSpot/ProcessSpotProcessor.ts | 5 +++-- .../RequestSpotsProcessProcessor.ts | 20 ++++++++++++++++--- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/backend/src/providers/queue/QueueProvider.ts b/backend/src/providers/queue/QueueProvider.ts index d9567b1..37a7ea9 100644 --- a/backend/src/providers/queue/QueueProvider.ts +++ b/backend/src/providers/queue/QueueProvider.ts @@ -1,6 +1,7 @@ interface SpotRequest { spot_id: string; - date: string; + since: string; + until: string; github_name: string; } diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index 0518990..a8ad34f 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -2,7 +2,8 @@ import api from '../githubApi/GraphQLApi'; interface Request { github_login: string; - date: string; + since: string; + until: string; } interface Commit { @@ -69,9 +70,9 @@ interface CommitNode { } class GetDailyReportService { - async execute({ github_login, date }: Request): Promise { + async execute({ github_login, since, until }: Request): Promise { const data = await api.post('', { - query: this.getQuery(github_login, date), + query: this.getQuery(github_login, since, until), }); const { @@ -196,7 +197,7 @@ class GetDailyReportService { return commits; } - private getQuery(github_login: string, date: string): string { + private getQuery(github_login: string, since: string, until: string): string { const query = `{ user(login:"${github_login}") { avatarUrl @@ -208,7 +209,7 @@ class GetDailyReportService { defaultBranchRef { target { ... on Commit { - history(first: 100, since: "${date}") { + history(first: 100, since: "${since}" until: "${until}") { nodes { ... on Commit { commitUrl @@ -230,7 +231,7 @@ class GetDailyReportService { } } } - contributionsCollection(from: "${date}") { + contributionsCollection(from: "${since}" to:"${until}") { totalIssueContributions totalCommitContributions totalRepositoryContributions diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 2ddbb1c..5ae2178 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -7,7 +7,7 @@ import Commit from '../../models/Commit'; import SpotDailyReport from '../../models/SpotDailyReport'; const ProcessSpotProcessor = async (job: Job): Promise => { - const { spot_id, date, github_name: github_login } = job.data; + const { spot_id, since, until, github_name: github_login } = job.data; const commitRepository = getRepository(Commit); const dailyReportRepository = getRepository(SpotDailyReport); @@ -16,7 +16,8 @@ const ProcessSpotProcessor = async (job: Job): Promise => { const { payload } = await getDailyReportService.execute({ github_login, - date, + since, + until, }); const { diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 1a94a55..19bebb9 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -5,12 +5,23 @@ import Spot from '../../models/Spot'; const RequestSpotsProcessProcessor = async (): Promise => { const spotsRepository = getRepository(Spot); const since = new Date(); + const until = new Date(); + + // since since.setHours(-3); since.setMinutes(0); since.setSeconds(0); since.setMilliseconds(0); - console.log(`Starting spot crawl request at ${since.toISOString()}`); + // until + until.setHours(20); + until.setMinutes(59); + until.setSeconds(59); + until.setMilliseconds(59); + + console.log( + `Starting spot crawl request at ${since.toISOString()} - ${until.toISOString()}`, + ); const spots = await spotsRepository.find(); @@ -22,10 +33,13 @@ const RequestSpotsProcessProcessor = async (): Promise => { queueProvider.add({ job: { spot_id: spot.id, - date: since.toISOString(), + since: since.toISOString(), + until: until.toISOString(), github_name: spot.github_login, }, - jobName: `${spot.github_login} process request at ${since.toISOString()}`, + jobName: `${ + spot.github_login + } process request at ${since.toISOString()} - ${until.toISOString()}`, queueName: 'spot-processor', opts: { removeOnComplete: false, From 14e9d65d16997372a16f9e5f19d5e05cd33acf24 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 20:12:52 -0300 Subject: [PATCH 076/113] Period using taken_at --- .../1605913545598-AddTakenAtOnReport.ts | 19 +++++++++++++++++++ backend/src/models/SpotDailyReport.ts | 3 +++ .../SpotDailyReportsRepository.ts | 8 ++++---- .../ProcessSpot/ProcessSpotProcessor.ts | 1 + 4 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 backend/src/database/migrations/1605913545598-AddTakenAtOnReport.ts diff --git a/backend/src/database/migrations/1605913545598-AddTakenAtOnReport.ts b/backend/src/database/migrations/1605913545598-AddTakenAtOnReport.ts new file mode 100644 index 0000000..a960745 --- /dev/null +++ b/backend/src/database/migrations/1605913545598-AddTakenAtOnReport.ts @@ -0,0 +1,19 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class AddTakenAtOnReport1605913545598 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'spot_daily_reports', + new TableColumn({ + name: 'taken_at', + type: 'timestamp', + isNullable: false, + }), + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('spot_daily_reports', 'taken_at'); + } +} diff --git a/backend/src/models/SpotDailyReport.ts b/backend/src/models/SpotDailyReport.ts index 75364ed..6a731e4 100644 --- a/backend/src/models/SpotDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -48,6 +48,9 @@ class SpotDailyReport { @UpdateDateColumn() updated_at: Date; + + @Column('timestamp') + taken_at: Date; } export default SpotDailyReport; diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index d455161..2c34f1e 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -34,8 +34,8 @@ class SpotDailyReportsRepository extends Repository { const rawReport: RawReport = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.created_at >= :since`, { since }) - .andWhere('report.created_at < :until', { until }) + .andWhere(`report.taken_at >= :since`, { since }) + .andWhere('report.taken_at <= :until', { until }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') @@ -58,8 +58,8 @@ class SpotDailyReportsRepository extends Repository { ): Promise { const rawReport: RawReport[] = await this.createQueryBuilder('report') .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.created_at >= :since`, { since }) - .andWhere('report.created_at < :until', { until }) + .andWhere(`report.taken_at >= :since`, { since }) + .andWhere('report.taken_at <= :until', { until }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 5ae2178..5ff31d2 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -40,6 +40,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { new_prs, new_repositories, spot_id, + taken_at: until, }); await dailyReportRepository.save(dailyReport); From 7a6b9e0abcd7dce2e598f5c214e60776b12aed59 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 20:20:55 -0300 Subject: [PATCH 077/113] Fixes --- .../SpotDailyReportsRepository.ts | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 2c34f1e..0f2e7bd 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -3,6 +3,15 @@ import { EntityRepository, Repository } from 'typeorm'; import SpotDailyReport from '../models/SpotDailyReport'; interface RawReport { + spot_id: string; + spot_manager_id: string; + spot_github_login: string; + spot_avatar_url: string; + spot_top_language: string; + spot_github_id: string; + spot_name: string; + spot_created_at: string; + spot_updated_at: string; new_interactions: number; new_commits: number; new_prs: number; @@ -13,6 +22,17 @@ interface RawReport { } interface Report { + spot?: { + id: string; + github_login: string; + manager_id: string; + avatar_url: string; + top_language: string; + github_id: string; + name: string; + created_at: string; + updated_at: string; + }; metrics: { new_interactions: number; new_commits: number; @@ -86,9 +106,29 @@ class SpotDailyReportsRepository extends Repository { new_issues, new_prs, new_repositories, + spot_avatar_url, + spot_created_at, + spot_github_id, + spot_github_login, + spot_id, + spot_manager_id, + spot_name, + spot_top_language, + spot_updated_at, } = rawReport; const report: Report = { + spot: { + id: spot_id, + github_login: spot_github_login, + manager_id: spot_manager_id, + avatar_url: spot_avatar_url, + top_language: spot_top_language, + github_id: spot_github_id, + name: spot_name, + created_at: spot_created_at, + updated_at: spot_updated_at, + }, metrics: { additions: Number(additions), deletions: Number(deletions), From 97e1d006829fd30bba85869131e082ee74732524 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Fri, 20 Nov 2020 22:17:50 -0300 Subject: [PATCH 078/113] timezone control improved --- backend/.env.sample | 2 + .../RequestSpotsProcessProcessor.ts | 37 ++++++++++++------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/backend/.env.sample b/backend/.env.sample index 23cda7f..720ac7a 100644 --- a/backend/.env.sample +++ b/backend/.env.sample @@ -11,3 +11,5 @@ JWT_SECRET=your_jwt_secret CRYPTO_SECRET=your_crypto_secret CRYPTO_IV=90b7fd08a94e987e6aeb910a79e26672 + +TZ=America/Bahia diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 19bebb9..80acd5d 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -4,24 +4,35 @@ import Spot from '../../models/Spot'; const RequestSpotsProcessProcessor = async (): Promise => { const spotsRepository = getRepository(Spot); - const since = new Date(); - const until = new Date(); - // since - since.setHours(-3); - since.setMinutes(0); - since.setSeconds(0); - since.setMilliseconds(0); - - // until - until.setHours(20); - until.setMinutes(59); - until.setSeconds(59); - until.setMilliseconds(59); + const today = new Date(); + const since = new Date( + Date.UTC( + today.getFullYear(), + today.getMonth(), + today.getDate(), + 0, + 0, + 0, + 0, + ), + ); + const until = new Date( + Date.UTC( + today.getFullYear(), + today.getMonth(), + today.getDate(), + 23, + 59, + 59, + 999, + ), + ); console.log( `Starting spot crawl request at ${since.toISOString()} - ${until.toISOString()}`, ); + console.log('aaaaa', since.getTimezoneOffset()); const spots = await spotsRepository.find(); From 1da4e884db2a5d1ec11c7531abd8687e323e6f3d Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:26:55 -0300 Subject: [PATCH 079/113] Changing nomenclature --- frontend/src/pages/Dashboard/index.tsx | 6 +++--- frontend/src/pages/Profile/index.tsx | 6 ------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index e3f2af0..0e991a0 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -176,7 +176,7 @@ const Dashboard: React.FC = () => { ({ label: item.github_login, @@ -189,7 +189,7 @@ const Dashboard: React.FC = () => { - Informações da Turma + Informações do Radar @@ -219,7 +219,7 @@ const Dashboard: React.FC = () => { ({ label: item.github_login, diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index e72cb2f..1273303 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -72,11 +72,9 @@ const Profile: React.FC = () => { const [newInteractions, setNewInteractions] = useState(0); const [additions, setAdditions] = useState(0); const [deletions, setDeletions] = useState(0); - const [newForks, setNewForks] = useState(0); const [newIssues, setNewIssues] = useState(0); const [newPrs, setNewPrs] = useState(0); const [newRepos, setNewRepos] = useState(0); - const [newStars, setNewStars] = useState(0); const [commits, setCommits] = useState([]); const [repositories, setRepositories] = useState([]); @@ -104,11 +102,9 @@ const Profile: React.FC = () => { setNewInteractions(report.new_interactions); setAdditions(report.additions); setDeletions(report.deletions); - setNewForks(report.new_forks); setNewIssues(report.new_issues); setNewPrs(report.new_prs); setNewRepos(report.new_repositories); - setNewStars(report.new_stars); setCommits(report.commits); } catch (error) { setLoadingCommits(false); @@ -243,11 +239,9 @@ const Profile: React.FC = () => { number={deletions} label="Linhas Removidas" /> - - From 56f56196739b2d68cdcfbd3215a4faae14abc906 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:30:28 -0300 Subject: [PATCH 080/113] Changing Manager sign up --- frontend/src/pages/SignUp/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/pages/SignUp/index.tsx b/frontend/src/pages/SignUp/index.tsx index 1e1e97b..f28407b 100644 --- a/frontend/src/pages/SignUp/index.tsx +++ b/frontend/src/pages/SignUp/index.tsx @@ -55,7 +55,7 @@ const SignUp: React.FC = () => { password, }); - await api.post('/teacher', { + await api.post('/manager', { github_login: github, email, password, From d7f5f75840c115900bb5b22c33da8522ebbe61b2 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:39:28 -0300 Subject: [PATCH 081/113] Changing requests --- frontend/src/pages/Dashboard/index.tsx | 10 +++++----- frontend/src/pages/Login/index.tsx | 4 ++-- frontend/src/services/auth.ts | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 0e991a0..8d80bc3 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -49,7 +49,7 @@ const Dashboard: React.FC = () => { if (code) { try { - await api.get(`/teacher/callback?code=${code}`); + await api.get(`/manager/callback?code=${code}`); toast('Sua conta do GitHub foi vinculada com sucesso!', { type: 'success', }); @@ -69,7 +69,7 @@ const Dashboard: React.FC = () => { try { const response = await api.get( - `/class/report?since=${since.toISOString()}`, + `/project/report?since=${since.toISOString()}`, ); const { @@ -92,7 +92,7 @@ const Dashboard: React.FC = () => { setLoadingStudents(true); try { - const response = await api.get('/class'); + const response = await api.get('/project'); setAllStudents(response.data); setLoadingStudents(false); @@ -109,7 +109,7 @@ const Dashboard: React.FC = () => { try { const response = await api.get( - `/class/below_average?since=${since.toISOString()}`, + `/project/below_average?since=${since.toISOString()}`, ); setBelowAverage(response.data); @@ -126,7 +126,7 @@ const Dashboard: React.FC = () => { try { setLoadingSubmit(true); - await api.post('/student', { + await api.post('/spot', { github_login: monitored, }); setLoadingSubmit(false); diff --git a/frontend/src/pages/Login/index.tsx b/frontend/src/pages/Login/index.tsx index ca765df..d3b66a6 100644 --- a/frontend/src/pages/Login/index.tsx +++ b/frontend/src/pages/Login/index.tsx @@ -51,8 +51,8 @@ const Login: React.FC = () => { password, }); - const { teacher, token, hasGithubToken } = response.data; - login(token, teacher, hasGithubToken); + const { manager, token, hasGithubToken } = response.data; + login(token, manager, hasGithubToken); setLoading(false); toast('Login realizado com sucesso!', { type: 'success' }); diff --git a/frontend/src/services/auth.ts b/frontend/src/services/auth.ts index 36fe3a5..9ac95e9 100644 --- a/frontend/src/services/auth.ts +++ b/frontend/src/services/auth.ts @@ -1,7 +1,7 @@ import { Teacher } from '../entities'; export const TOKEN_KEY = '@GitRadar-Token'; -export const TEACHER_KEY = '@Logged-Teacher'; +export const MANAGER_KEY = '@Logged-Teacher'; export const HAS_GITHUB_KEY = '@Github-Token'; export const isAuthenticated = (): boolean => @@ -10,7 +10,7 @@ export const isAuthenticated = (): boolean => export const getToken = (): string | null => localStorage.getItem(TOKEN_KEY); export const getTeacher = (): Teacher | null => { - const teacherJSON = localStorage.getItem(TEACHER_KEY); + const teacherJSON = localStorage.getItem(MANAGER_KEY); if (teacherJSON) { return JSON.parse(teacherJSON); @@ -35,7 +35,7 @@ export const login = ( hasGithubToken: boolean, ): void => { localStorage.setItem(TOKEN_KEY, token); - localStorage.setItem(TEACHER_KEY, JSON.stringify(teacher)); + localStorage.setItem(MANAGER_KEY, JSON.stringify(teacher)); localStorage.setItem(HAS_GITHUB_KEY, String(hasGithubToken)); }; From 09ef242fdadb62553549ccd7cc2114a97f0ff018 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:49:22 -0300 Subject: [PATCH 082/113] Changing nomenclature --- frontend/src/pages/Dashboard/index.tsx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 8d80bc3..42ed501 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -30,7 +30,7 @@ const Dashboard: React.FC = () => { const location = useLocation(); const history = useHistory(); - const [allStudents, setAllStudents] = useState([]); + const [allSpots, setallSpots] = useState([]); const [belowAverage, setBelowAverage] = useState([]); const [allNewInteractions, setAllNewInteractions] = useState(0); const [allNewCommits, setAllNewCommits] = useState(0); @@ -63,13 +63,13 @@ const Dashboard: React.FC = () => { } }, [location.search, history]); - const getClassInformation = useCallback(async () => { + const getProjectInformation = useCallback(async () => { const since = new Date(); since.setMonth(since.getMonth() - 1); try { const response = await api.get( - `/project/report?since=${since.toISOString()}`, + `/report/coming?since=${since.toISOString()}`, ); const { @@ -88,13 +88,13 @@ const Dashboard: React.FC = () => { } }, []); - const getAllStudents = useCallback(async () => { + const getallSpots = useCallback(async () => { setLoadingStudents(true); try { - const response = await api.get('/project'); + const response = await api.get('/project/coming'); - setAllStudents(response.data); + setallSpots(response.data); setLoadingStudents(false); } catch (error) { setLoadingStudents(false); @@ -132,28 +132,28 @@ const Dashboard: React.FC = () => { setLoadingSubmit(false); setMonitored(''); - setAllStudents([]); + setallSpots([]); setBelowAverage([]); - getAllStudents(); + getallSpots(); getBelowAverage(); } catch (error) { setLoadingSubmit(false); validationError(error); } }, - [monitored, getAllStudents, getBelowAverage], + [monitored, getallSpots, getBelowAverage], ); useEffect(() => { syncGithub(); - getClassInformation(); + getProjectInformation(); - getAllStudents(); + getallSpots(); getBelowAverage(); - }, [syncGithub, getClassInformation, getAllStudents, getBelowAverage]); + }, [syncGithub, getProjectInformation, getallSpots, getBelowAverage]); return ( @@ -177,7 +177,7 @@ const Dashboard: React.FC = () => { isLoading={loadingStudents} listHeight={285} title="Spots Monitorados" - items={allStudents} + items={allSpots} mapItem={item => ({ label: item.github_login, subLabel: item.name, From eb00332c30979a71e6c7ee87b1e0787881455837 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:55:14 -0300 Subject: [PATCH 083/113] Changing nomenclature --- frontend/src/components/Header/index.tsx | 10 +++++----- frontend/src/entities/index.ts | 4 ++-- frontend/src/pages/Dashboard/index.tsx | 16 ++++++++-------- frontend/src/services/auth.ts | 16 ++++++++-------- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/frontend/src/components/Header/index.tsx b/frontend/src/components/Header/index.tsx index 0fab517..e042f10 100644 --- a/frontend/src/components/Header/index.tsx +++ b/frontend/src/components/Header/index.tsx @@ -1,7 +1,7 @@ import React, { useState } from 'react'; import { useHistory } from 'react-router-dom'; -import { Teacher } from '../../entities'; -import { getTeacher, logout, verifyHasGithubToken } from '../../services/auth'; +import { Manager } from '../../entities'; +import { getManager, logout, verifyHasGithubToken } from '../../services/auth'; import { Container, ButtonsArea, @@ -21,7 +21,7 @@ import logo from '../../assets/logo.png'; const Header: React.FC = () => { const history = useHistory(); - const [teacher] = useState(getTeacher()); + const [manager] = useState(getManager()); const handleLogout = () => { logout(); @@ -46,7 +46,7 @@ const Header: React.FC = () => { - Bem-vindo, {teacher?.name} + Bem-vindo, {manager?.name} {!verifyHasGithubToken() && ( @@ -61,7 +61,7 @@ const Header: React.FC = () => { - + Log out diff --git a/frontend/src/entities/index.ts b/frontend/src/entities/index.ts index 4d14d4f..67ccb7f 100644 --- a/frontend/src/entities/index.ts +++ b/frontend/src/entities/index.ts @@ -1,4 +1,4 @@ -export interface Teacher { +export interface Manager { github_login: string; name: string; email: string; @@ -6,7 +6,7 @@ export interface Teacher { github_id: string; } -export interface Student { +export interface Spot { id: string; teacher_id: string; github_login: string; diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 42ed501..911e992 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -6,7 +6,7 @@ import api from '../../services/api'; import { confirmHasGithubToken } from '../../services/auth'; import validationError from '../../utils/validationError'; import { normalizeInformation } from '../../utils/normalizeStrings'; -import { Student } from '../../entities'; +import { Spot } from '../../entities'; import ListContainer from '../../components/ListContainer'; import { PageContainer, @@ -30,8 +30,8 @@ const Dashboard: React.FC = () => { const location = useLocation(); const history = useHistory(); - const [allSpots, setallSpots] = useState([]); - const [belowAverage, setBelowAverage] = useState([]); + const [allSpots, setallSpots] = useState([]); + const [belowAverage, setBelowAverage] = useState([]); const [allNewInteractions, setAllNewInteractions] = useState(0); const [allNewCommits, setAllNewCommits] = useState(0); const [newInteractionsAverage, setNewInteractionsAverage] = useState(0); @@ -39,7 +39,7 @@ const Dashboard: React.FC = () => { const [monitored, setMonitored] = useState(''); const [loadingSubmit, setLoadingSubmit] = useState(false); - const [loadingStudents, setLoadingStudents] = useState(false); + const [loadingSpots, setLoadingSpots] = useState(false); const [loadingBelow, setLoadingBelow] = useState(false); const syncGithub = useCallback(async () => { @@ -89,15 +89,15 @@ const Dashboard: React.FC = () => { }, []); const getallSpots = useCallback(async () => { - setLoadingStudents(true); + setLoadingSpots(true); try { const response = await api.get('/project/coming'); setallSpots(response.data); - setLoadingStudents(false); + setLoadingSpots(false); } catch (error) { - setLoadingStudents(false); + setLoadingSpots(false); validationError(error); } }, []); @@ -174,7 +174,7 @@ const Dashboard: React.FC = () => { @@ -9,11 +9,11 @@ export const isAuthenticated = (): boolean => export const getToken = (): string | null => localStorage.getItem(TOKEN_KEY); -export const getTeacher = (): Teacher | null => { - const teacherJSON = localStorage.getItem(MANAGER_KEY); +export const getManager = (): Manager | null => { + const managerJSON = localStorage.getItem(MANAGER_KEY); - if (teacherJSON) { - return JSON.parse(teacherJSON); + if (managerJSON) { + return JSON.parse(managerJSON); } return null; @@ -31,11 +31,11 @@ export const verifyHasGithubToken = (): boolean => { export const login = ( token: string, - teacher: Teacher, + manager: Manager, hasGithubToken: boolean, ): void => { localStorage.setItem(TOKEN_KEY, token); - localStorage.setItem(MANAGER_KEY, JSON.stringify(teacher)); + localStorage.setItem(MANAGER_KEY, JSON.stringify(manager)); localStorage.setItem(HAS_GITHUB_KEY, String(hasGithubToken)); }; From 9f277fd844bedf171abfd87ec9aef8c78616b138 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:55:34 -0300 Subject: [PATCH 084/113] Changing nomenclature --- frontend/src/entities/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/entities/index.ts b/frontend/src/entities/index.ts index 67ccb7f..38706a8 100644 --- a/frontend/src/entities/index.ts +++ b/frontend/src/entities/index.ts @@ -8,7 +8,7 @@ export interface Manager { export interface Spot { id: string; - teacher_id: string; + manager_id: string; github_login: string; name: string; avatar_url: string; From 863543cd0aff70a9f0d19160bf3b2e7647aa0b42 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Fri, 20 Nov 2020 22:59:15 -0300 Subject: [PATCH 085/113] Minor changes --- frontend/src/pages/Dashboard/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 911e992..8357f42 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -182,7 +182,7 @@ const Dashboard: React.FC = () => { label: item.github_login, subLabel: item.name, photo: item.avatar_url, - link: `/dashboard/${item.github_login}`, + link: `/dashboard/${item.id}`, })} /> @@ -225,7 +225,7 @@ const Dashboard: React.FC = () => { label: item.github_login, subLabel: item.name, photo: item.avatar_url, - link: `/dashboard/${item.github_login}`, + link: `/dashboard/${item.id}`, })} /> From d706b874f725f5f86b584d39c4066dd959fdaf5e Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Fri, 20 Nov 2020 23:59:16 -0300 Subject: [PATCH 086/113] Student changed to Spot on Profile Page --- frontend/src/pages/Profile/index.tsx | 68 +++++++++++----------------- frontend/src/routes/index.tsx | 2 +- 2 files changed, 27 insertions(+), 43 deletions(-) diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index 1273303..9fc02c5 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -29,7 +29,7 @@ import SimpleLineChart from '../../components/SimpleLineChart/index'; import SimpleBarChart from '../../components/SimpleBarChart/index'; interface ProfileParams { - username: string; + spotId: string; } interface ShowInformationProps { @@ -61,12 +61,13 @@ const ShowInformation: React.FC = ({ ); const Profile: React.FC = () => { - const { username } = useParams(); + const { spotId } = useParams(); const [loadingRepos, setLoadingRepos] = useState(false); const [loadingCommits, setLoadingCommits] = useState(false); const [photo, setPhoto] = useState(''); + const [username, setUsername] = useState(''); const [name, setName] = useState(''); const [newCommits, setNewCommits] = useState(0); const [newInteractions, setNewInteractions] = useState(0); @@ -86,47 +87,37 @@ const Profile: React.FC = () => { LinesGrowthChartInfo[] >([]); - const getStudentReport = useCallback(async () => { + const getSpotReport = useCallback(async () => { const since = new Date(); since.setMonth(since.getMonth() - 1); setLoadingCommits(true); try { const response = await api.get( - `/student/${username}/report?since=${since.toISOString()}`, + `/spot/${spotId}/report?since=${since.toISOString()}`, ); - const report = response.data; + const { spot, metrics, commits: responseCommits } = response.data; setLoadingCommits(false); - setNewCommits(report.new_commits); - setNewInteractions(report.new_interactions); - setAdditions(report.additions); - setDeletions(report.deletions); - setNewIssues(report.new_issues); - setNewPrs(report.new_prs); - setNewRepos(report.new_repositories); - setCommits(report.commits); - } catch (error) { - setLoadingCommits(false); - validationError(error); - } - }, [username]); + setName(spot.name); + setPhoto(spot.avatar_url); + setUsername(spot.github_login); + setRepositories([]); - const getStudentInfo = useCallback(async () => { - setLoadingRepos(true); - try { - const response = await api.get(`/student/${username}`); - const { student, repositories: repositoriesResponse } = response.data; - setLoadingRepos(false); + setNewCommits(metrics.new_commits); + setNewInteractions(metrics.new_interactions); + setAdditions(metrics.additions); + setDeletions(metrics.deletions); + setNewIssues(metrics.new_issues); + setNewPrs(metrics.new_prs); + setNewRepos(metrics.new_repositories); - setName(student.name); - setPhoto(student.avatar_url); - setRepositories(repositoriesResponse); + setCommits(responseCommits); } catch (error) { - setLoadingRepos(false); + setLoadingCommits(false); validationError(error); } - }, [username]); + }, [spotId]); const getInteractionsVolume = useCallback(async () => { const since = new Date(); @@ -134,7 +125,7 @@ const Profile: React.FC = () => { try { const response = await api.get( - `/student/${username}/interactions/volume?since=${since.toISOString()}`, + `/spot/volume/${spotId}/interactions?since=${since.toISOString()}`, ); setInteractionsChartInfo( @@ -153,7 +144,7 @@ const Profile: React.FC = () => { } catch (error) { validationError(error); } - }, [username]); + }, [spotId]); const getLinesGrowhtVolume = useCallback(async () => { const since = new Date(); @@ -161,7 +152,7 @@ const Profile: React.FC = () => { try { const response = await api.get( - `/student/${username}/lines/volume?since=${since.toISOString()}`, + `/spot/volume/${spotId}/lines?since=${since.toISOString()}`, ); setLinesGrowthChartInfo( @@ -185,22 +176,15 @@ const Profile: React.FC = () => { } catch (error) { validationError(error); } - }, [username]); + }, [spotId]); useEffect(() => { - getStudentReport(); - - getStudentInfo(); + getSpotReport(); getInteractionsVolume(); getLinesGrowhtVolume(); - }, [ - getStudentReport, - getStudentInfo, - getInteractionsVolume, - getLinesGrowhtVolume, - ]); + }, [getSpotReport, getInteractionsVolume, getLinesGrowhtVolume]); return ( diff --git a/frontend/src/routes/index.tsx b/frontend/src/routes/index.tsx index e587f8a..4d79632 100644 --- a/frontend/src/routes/index.tsx +++ b/frontend/src/routes/index.tsx @@ -11,7 +11,7 @@ const Routes: React.FC = () => ( - + } /> ); From ea1a4eef2c967236bda711cc6b1b362c1fba77b2 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 00:04:11 -0300 Subject: [PATCH 087/113] GetSpotRepositories service added --- .../src/services/Spot/GetSpotRepositories.ts | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 backend/src/services/Spot/GetSpotRepositories.ts diff --git a/backend/src/services/Spot/GetSpotRepositories.ts b/backend/src/services/Spot/GetSpotRepositories.ts new file mode 100644 index 0000000..67d8c63 --- /dev/null +++ b/backend/src/services/Spot/GetSpotRepositories.ts @@ -0,0 +1,22 @@ +import { getRepository } from 'typeorm'; +import Repository from '../../models/Repository'; + +interface Request { + spotId: string; +} + +class GetSpotRepositories { + async execute({ spotId }: Request): Promise { + const repositoriesRepository = getRepository(Repository); + + const repositories = repositoriesRepository.find({ + where: { + spot_id: spotId, + }, + }); + + return repositories; + } +} + +export default GetSpotRepositories; From 9cce5c16e060206556aac2e9f268fd8aaa1618b5 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 00:16:57 -0300 Subject: [PATCH 088/113] get repositories route added --- backend/src/routes/spots/spots.routes.ts | 15 +++++++++++++++ backend/src/services/Spot/GetSpotRepositories.ts | 6 +++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/backend/src/routes/spots/spots.routes.ts b/backend/src/routes/spots/spots.routes.ts index 079237c..81f12e6 100644 --- a/backend/src/routes/spots/spots.routes.ts +++ b/backend/src/routes/spots/spots.routes.ts @@ -2,6 +2,7 @@ import { Router } from 'express'; import CreateSpotService from '../../services/Spot/CreateSpotService'; import authMiddleware from '../../middlewares/authMiddleware'; import GetSpotReportService from '../../services/Spot/GetSpotReportService'; +import GetSpotRepositories from '../../services/Spot/GetSpotRepositories'; import spotVolumeRouter from './volume/spots.volume.routes'; const spotRouter = Router(); @@ -44,4 +45,18 @@ spotRouter.get( }, ); +spotRouter.get( + '/:spot_id/repositories', + authMiddleware, + async (request, response) => { + const { spot_id } = request.params; + + const getSpotRepositories = new GetSpotRepositories(); + + const repositories = await getSpotRepositories.execute({ spot_id }); + + return response.json(repositories); + }, +); + export default spotRouter; diff --git a/backend/src/services/Spot/GetSpotRepositories.ts b/backend/src/services/Spot/GetSpotRepositories.ts index 67d8c63..93feeb7 100644 --- a/backend/src/services/Spot/GetSpotRepositories.ts +++ b/backend/src/services/Spot/GetSpotRepositories.ts @@ -2,16 +2,16 @@ import { getRepository } from 'typeorm'; import Repository from '../../models/Repository'; interface Request { - spotId: string; + spot_id: string; } class GetSpotRepositories { - async execute({ spotId }: Request): Promise { + async execute({ spot_id }: Request): Promise { const repositoriesRepository = getRepository(Repository); const repositories = repositoriesRepository.find({ where: { - spot_id: spotId, + spot_id, }, }); From d6083c56d4330586189a4c95a0077eae215da743 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 00:26:09 -0300 Subject: [PATCH 089/113] getSpotRepositories added on Profile page --- frontend/src/pages/Profile/index.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index 9fc02c5..81cfdfa 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -119,6 +119,18 @@ const Profile: React.FC = () => { } }, [spotId]); + const getSpotRepositories = useCallback(async () => { + try { + setLoadingRepos(true); + const response = await api.get('/spot/${spotId}/repositories'); + setLoadingRepos(false); + setRepositories(response.data); + } catch (error) { + setLoadingCommits(false); + validationError(error); + } + }, [spotId]); + const getInteractionsVolume = useCallback(async () => { const since = new Date(); since.setMonth(since.getMonth() - 1); @@ -181,6 +193,8 @@ const Profile: React.FC = () => { useEffect(() => { getSpotReport(); + getSpotRepositories(); + getInteractionsVolume(); getLinesGrowhtVolume(); From d9c9eb8c8bd3e912a8f605d48b2cc419f00a740d Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 00:34:42 -0300 Subject: [PATCH 090/113] get repositories route fixed --- backend/src/services/Spot/GetSpotRepositories.ts | 2 +- frontend/src/pages/Profile/index.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/services/Spot/GetSpotRepositories.ts b/backend/src/services/Spot/GetSpotRepositories.ts index 93feeb7..e392fda 100644 --- a/backend/src/services/Spot/GetSpotRepositories.ts +++ b/backend/src/services/Spot/GetSpotRepositories.ts @@ -9,7 +9,7 @@ class GetSpotRepositories { async execute({ spot_id }: Request): Promise { const repositoriesRepository = getRepository(Repository); - const repositories = repositoriesRepository.find({ + const repositories = await repositoriesRepository.find({ where: { spot_id, }, diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index 81cfdfa..f5c7dfa 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -102,7 +102,6 @@ const Profile: React.FC = () => { setName(spot.name); setPhoto(spot.avatar_url); setUsername(spot.github_login); - setRepositories([]); setNewCommits(metrics.new_commits); setNewInteractions(metrics.new_interactions); @@ -122,8 +121,9 @@ const Profile: React.FC = () => { const getSpotRepositories = useCallback(async () => { try { setLoadingRepos(true); - const response = await api.get('/spot/${spotId}/repositories'); + const response = await api.get(`/spot/${spotId}/repositories`); setLoadingRepos(false); + setRepositories(response.data); } catch (error) { setLoadingCommits(false); From f73bd454f2ef1857f6023e30769c7020e74b827f Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 00:42:58 -0300 Subject: [PATCH 091/113] get repositories effect error fixed --- frontend/src/pages/Profile/index.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index f5c7dfa..14dd561 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -198,7 +198,12 @@ const Profile: React.FC = () => { getInteractionsVolume(); getLinesGrowhtVolume(); - }, [getSpotReport, getInteractionsVolume, getLinesGrowhtVolume]); + }, [ + getSpotReport, + getSpotRepositories, + getInteractionsVolume, + getLinesGrowhtVolume, + ]); return ( From 836ffae4f7b4938c4e2c5e78073ea15408638c86 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 08:56:48 -0300 Subject: [PATCH 092/113] Chaging project report request --- frontend/src/pages/Dashboard/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 8357f42..bf2d719 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -69,7 +69,7 @@ const Dashboard: React.FC = () => { try { const response = await api.get( - `/report/coming?since=${since.toISOString()}`, + `/project/report/coming?since=${since.toISOString()}`, ); const { From b1e8313b980fde9f0316c16b71c260bbb6af61d8 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:00:13 -0300 Subject: [PATCH 093/113] Using github_login to get spot data on routes --- backend/src/routes/spots/spots.routes.ts | 12 ++++----- .../spots/volume/spots.volume.routes.ts | 12 ++++----- .../Spot/GetInteractionsVolumeService.ts | 19 +++++++++++--- .../services/Spot/GetLinesVolumeService.ts | 19 +++++++++++--- .../src/services/Spot/GetSpotReportService.ts | 26 ++++++++++++------- 5 files changed, 60 insertions(+), 28 deletions(-) diff --git a/backend/src/routes/spots/spots.routes.ts b/backend/src/routes/spots/spots.routes.ts index 81f12e6..cb604e0 100644 --- a/backend/src/routes/spots/spots.routes.ts +++ b/backend/src/routes/spots/spots.routes.ts @@ -24,10 +24,10 @@ spotRouter.post('/', authMiddleware, async (request, response) => { }); spotRouter.get( - '/:spot_id/report', + '/:github_login/report', authMiddleware, async (request, response) => { - const { spot_id } = request.params; + const { github_login } = request.params; let { until } = request.query; until = until || new Date().toISOString(); @@ -37,7 +37,7 @@ spotRouter.get( const spotReport = await getSpotReportService.execute({ since: since as string, - spot_id, + github_login, until: until as string, }); @@ -46,14 +46,14 @@ spotRouter.get( ); spotRouter.get( - '/:spot_id/repositories', + '/:github_login/repositories', authMiddleware, async (request, response) => { - const { spot_id } = request.params; + const { github_login } = request.params; const getSpotRepositories = new GetSpotRepositories(); - const repositories = await getSpotRepositories.execute({ spot_id }); + const repositories = await getSpotRepositories.execute({ github_login }); return response.json(repositories); }, diff --git a/backend/src/routes/spots/volume/spots.volume.routes.ts b/backend/src/routes/spots/volume/spots.volume.routes.ts index b4fa467..997cb3d 100644 --- a/backend/src/routes/spots/volume/spots.volume.routes.ts +++ b/backend/src/routes/spots/volume/spots.volume.routes.ts @@ -6,10 +6,10 @@ import GetLinesVolumeService from '../../../services/Spot/GetLinesVolumeService' const spotVolumeRouter = Router(); spotVolumeRouter.get( - '/:spot_id/interactions', + '/:github_login/interactions', authMiddleware, async (request, response) => { - const { spot_id } = request.params; + const { github_login } = request.params; let { until } = request.query; until = until || new Date().toISOString(); @@ -18,7 +18,7 @@ spotVolumeRouter.get( const getInteractionsVolume = new GetInteractionsVolumeService(); const volume = await getInteractionsVolume.execute({ - spot_id, + github_login, since: since as string, until: until as string, }); @@ -28,10 +28,10 @@ spotVolumeRouter.get( ); spotVolumeRouter.get( - '/:spot_id/lines', + '/:github_login/lines', authMiddleware, async (request, response) => { - const { spot_id } = request.params; + const { github_login } = request.params; let { until } = request.query; until = until || new Date().toISOString(); @@ -40,7 +40,7 @@ spotVolumeRouter.get( const getLinesVolume = new GetLinesVolumeService(); const volume = await getLinesVolume.execute({ - spot_id, + github_login, since: since as string, until: until as string, }); diff --git a/backend/src/services/Spot/GetInteractionsVolumeService.ts b/backend/src/services/Spot/GetInteractionsVolumeService.ts index a190bbc..b992642 100644 --- a/backend/src/services/Spot/GetInteractionsVolumeService.ts +++ b/backend/src/services/Spot/GetInteractionsVolumeService.ts @@ -1,10 +1,12 @@ import { Between, getRepository } from 'typeorm'; +import Spot from '../../models/Spot'; import SpotDailyReport from '../../models/SpotDailyReport'; +import { AppError } from '../../errors/AppError'; interface Request { since: string; until: string; - spot_id: string; + github_login: string; } interface Data { @@ -18,13 +20,24 @@ interface DataBaseRequest { } class GetInteractionsVolumeService { - async execute({ since, until, spot_id }: Request): Promise { + async execute({ since, until, github_login }: Request): Promise { const dailyReportRepository = getRepository(SpotDailyReport); + const spotRepository = getRepository(Spot); + + const spot = await spotRepository.findOne({ + where: { + github_login, + }, + }); + + if (!spot) { + throw new AppError('Spot not registered', 400); + } const dailyReports = await dailyReportRepository.find({ where: { created_at: Between(since, until), - spot_id, + spot_id: spot.id, }, select: ['created_at', 'new_interactions'], order: { diff --git a/backend/src/services/Spot/GetLinesVolumeService.ts b/backend/src/services/Spot/GetLinesVolumeService.ts index a839ef3..33d75c5 100644 --- a/backend/src/services/Spot/GetLinesVolumeService.ts +++ b/backend/src/services/Spot/GetLinesVolumeService.ts @@ -1,10 +1,12 @@ import { Between, getRepository } from 'typeorm'; +import AppError from '../../errors/AppError'; +import Spot from '../../models/Spot'; import SpotDailyReport from '../../models/SpotDailyReport'; interface Request { since: string; until: string; - spot_id: string; + github_login: string; } interface Data { @@ -20,13 +22,24 @@ interface DataBaseRequest { } class GetLinesVolumeService { - async execute({ since, until, spot_id }: Request): Promise { + async execute({ since, until, github_login }: Request): Promise { const dailyReportRepository = getRepository(SpotDailyReport); + const spotRepository = getRepository(Spot); + + const spot = await spotRepository.findOne({ + where: { + github_login, + }, + }); + + if (!spot) { + throw new AppError('Spot not registered', 400); + } const dailyReports = await dailyReportRepository.find({ where: { created_at: Between(since, until), - spot_id, + spot_id: spot.id, }, select: ['created_at', 'additions', 'deletions'], order: { diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts index 5e3ef2e..ad16931 100644 --- a/backend/src/services/Spot/GetSpotReportService.ts +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -2,9 +2,10 @@ import { Between, getCustomRepository, getRepository } from 'typeorm'; import SpotDailyReportsRepository from '../../repositories/SpotDailyReportsRepository'; import Commit from '../../models/Commit'; import Spot from '../../models/Spot'; +import AppError from '../../errors/AppError'; interface Request { - spot_id: string; + github_login: string; since: string; until: string; } @@ -34,27 +35,32 @@ interface Response { } class GetSpotReportService { - async execute({ spot_id, since, until }: Request): Promise { + async execute({ github_login, since, until }: Request): Promise { const reportsRepository = getCustomRepository(SpotDailyReportsRepository); const commitRepository = getRepository(Commit); const spotRepository = getRepository(Spot); - const { metrics } = await reportsRepository.findByPeriodAndId( - spot_id, - since, - until, - ); - const spot = await spotRepository.findOne({ where: { - id: spot_id, + github_login, }, loadEagerRelations: false, }); + if (!spot) { + throw new AppError('Spot not registered', 400); + } + + const { id } = spot; + + const { metrics } = await reportsRepository.findByPeriodAndId( + id, + since, + until, + ); const commits = await commitRepository.find({ where: { - spot_id, + id, created_at: Between(since, until), }, }); From b0420555eaa2b4006d429f850aec252afe99d4cf Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:02:12 -0300 Subject: [PATCH 094/113] Using github_login to get spot data on routes --- .../src/services/Spot/GetSpotRepositories.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/backend/src/services/Spot/GetSpotRepositories.ts b/backend/src/services/Spot/GetSpotRepositories.ts index e392fda..fb10e8f 100644 --- a/backend/src/services/Spot/GetSpotRepositories.ts +++ b/backend/src/services/Spot/GetSpotRepositories.ts @@ -1,17 +1,30 @@ import { getRepository } from 'typeorm'; import Repository from '../../models/Repository'; +import Spot from '../../models/Spot'; +import { AppError } from '../../errors/AppError'; interface Request { - spot_id: string; + github_login: string; } class GetSpotRepositories { - async execute({ spot_id }: Request): Promise { + async execute({ github_login }: Request): Promise { const repositoriesRepository = getRepository(Repository); + const spotRepository = getRepository(Spot); + + const spot = await spotRepository.findOne({ + where: { + github_login, + }, + }); + + if (!spot) { + throw new AppError('Spot not registered', 400); + } const repositories = await repositoriesRepository.find({ where: { - spot_id, + spot_id: spot.id, }, }); From abb13619f1c1677ed78d71384c7416d51a034caa Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:03:24 -0300 Subject: [PATCH 095/113] Removing auth from github spot auth --- backend/src/routes/spots/spots.routes.ts | 46 ++++++++----------- .../spots/volume/spots.volume.routes.ts | 32 ++++++------- 2 files changed, 32 insertions(+), 46 deletions(-) diff --git a/backend/src/routes/spots/spots.routes.ts b/backend/src/routes/spots/spots.routes.ts index cb604e0..f4754df 100644 --- a/backend/src/routes/spots/spots.routes.ts +++ b/backend/src/routes/spots/spots.routes.ts @@ -23,40 +23,32 @@ spotRouter.post('/', authMiddleware, async (request, response) => { return response.json(spot); }); -spotRouter.get( - '/:github_login/report', - authMiddleware, - async (request, response) => { - const { github_login } = request.params; +spotRouter.get('/:github_login/report', async (request, response) => { + const { github_login } = request.params; - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; - const getSpotReportService = new GetSpotReportService(); + const getSpotReportService = new GetSpotReportService(); - const spotReport = await getSpotReportService.execute({ - since: since as string, - github_login, - until: until as string, - }); + const spotReport = await getSpotReportService.execute({ + since: since as string, + github_login, + until: until as string, + }); - return response.json(spotReport); - }, -); + return response.json(spotReport); +}); -spotRouter.get( - '/:github_login/repositories', - authMiddleware, - async (request, response) => { - const { github_login } = request.params; +spotRouter.get('/:github_login/repositories', async (request, response) => { + const { github_login } = request.params; - const getSpotRepositories = new GetSpotRepositories(); + const getSpotRepositories = new GetSpotRepositories(); - const repositories = await getSpotRepositories.execute({ github_login }); + const repositories = await getSpotRepositories.execute({ github_login }); - return response.json(repositories); - }, -); + return response.json(repositories); +}); export default spotRouter; diff --git a/backend/src/routes/spots/volume/spots.volume.routes.ts b/backend/src/routes/spots/volume/spots.volume.routes.ts index 997cb3d..5328613 100644 --- a/backend/src/routes/spots/volume/spots.volume.routes.ts +++ b/backend/src/routes/spots/volume/spots.volume.routes.ts @@ -1,5 +1,4 @@ import { Router } from 'express'; -import authMiddleware from '../../../middlewares/authMiddleware'; import GetInteractionsVolumeService from '../../../services/Spot/GetInteractionsVolumeService'; import GetLinesVolumeService from '../../../services/Spot/GetLinesVolumeService'; @@ -7,7 +6,6 @@ const spotVolumeRouter = Router(); spotVolumeRouter.get( '/:github_login/interactions', - authMiddleware, async (request, response) => { const { github_login } = request.params; @@ -27,26 +25,22 @@ spotVolumeRouter.get( }, ); -spotVolumeRouter.get( - '/:github_login/lines', - authMiddleware, - async (request, response) => { - const { github_login } = request.params; +spotVolumeRouter.get('/:github_login/lines', async (request, response) => { + const { github_login } = request.params; - let { until } = request.query; - until = until || new Date().toISOString(); - const { since } = request.query; + let { until } = request.query; + until = until || new Date().toISOString(); + const { since } = request.query; - const getLinesVolume = new GetLinesVolumeService(); + const getLinesVolume = new GetLinesVolumeService(); - const volume = await getLinesVolume.execute({ - github_login, - since: since as string, - until: until as string, - }); + const volume = await getLinesVolume.execute({ + github_login, + since: since as string, + until: until as string, + }); - return response.json(volume); - }, -); + return response.json(volume); +}); export default spotVolumeRouter; From 97afdfd2cfbd4f509be3f55cf737d49d5bbc9379 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:06:27 -0300 Subject: [PATCH 096/113] Using github_login to get spot data --- frontend/src/pages/Dashboard/index.tsx | 4 ++-- frontend/src/pages/Profile/index.tsx | 20 ++++++++++---------- frontend/src/routes/index.tsx | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index bf2d719..3d8d6ad 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -182,7 +182,7 @@ const Dashboard: React.FC = () => { label: item.github_login, subLabel: item.name, photo: item.avatar_url, - link: `/dashboard/${item.id}`, + link: `/dashboard/${item.github_login}`, })} /> @@ -225,7 +225,7 @@ const Dashboard: React.FC = () => { label: item.github_login, subLabel: item.name, photo: item.avatar_url, - link: `/dashboard/${item.id}`, + link: `/dashboard/${item.github_login}`, })} /> diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index 14dd561..db726ed 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -29,7 +29,7 @@ import SimpleLineChart from '../../components/SimpleLineChart/index'; import SimpleBarChart from '../../components/SimpleBarChart/index'; interface ProfileParams { - spotId: string; + githubLogin: string; } interface ShowInformationProps { @@ -61,7 +61,7 @@ const ShowInformation: React.FC = ({ ); const Profile: React.FC = () => { - const { spotId } = useParams(); + const { githubLogin } = useParams(); const [loadingRepos, setLoadingRepos] = useState(false); const [loadingCommits, setLoadingCommits] = useState(false); @@ -94,7 +94,7 @@ const Profile: React.FC = () => { try { const response = await api.get( - `/spot/${spotId}/report?since=${since.toISOString()}`, + `/spot/${githubLogin}/report?since=${since.toISOString()}`, ); const { spot, metrics, commits: responseCommits } = response.data; setLoadingCommits(false); @@ -116,12 +116,12 @@ const Profile: React.FC = () => { setLoadingCommits(false); validationError(error); } - }, [spotId]); + }, [githubLogin]); const getSpotRepositories = useCallback(async () => { try { setLoadingRepos(true); - const response = await api.get(`/spot/${spotId}/repositories`); + const response = await api.get(`/spot/${githubLogin}/repositories`); setLoadingRepos(false); setRepositories(response.data); @@ -129,7 +129,7 @@ const Profile: React.FC = () => { setLoadingCommits(false); validationError(error); } - }, [spotId]); + }, [githubLogin]); const getInteractionsVolume = useCallback(async () => { const since = new Date(); @@ -137,7 +137,7 @@ const Profile: React.FC = () => { try { const response = await api.get( - `/spot/volume/${spotId}/interactions?since=${since.toISOString()}`, + `/spot/volume/${githubLogin}/interactions?since=${since.toISOString()}`, ); setInteractionsChartInfo( @@ -156,7 +156,7 @@ const Profile: React.FC = () => { } catch (error) { validationError(error); } - }, [spotId]); + }, [githubLogin]); const getLinesGrowhtVolume = useCallback(async () => { const since = new Date(); @@ -164,7 +164,7 @@ const Profile: React.FC = () => { try { const response = await api.get( - `/spot/volume/${spotId}/lines?since=${since.toISOString()}`, + `/spot/volume/${githubLogin}/lines?since=${since.toISOString()}`, ); setLinesGrowthChartInfo( @@ -188,7 +188,7 @@ const Profile: React.FC = () => { } catch (error) { validationError(error); } - }, [spotId]); + }, [githubLogin]); useEffect(() => { getSpotReport(); diff --git a/frontend/src/routes/index.tsx b/frontend/src/routes/index.tsx index 4d79632..2bff347 100644 --- a/frontend/src/routes/index.tsx +++ b/frontend/src/routes/index.tsx @@ -11,7 +11,7 @@ const Routes: React.FC = () => ( - + } /> ); From e9946507a2de3e15174f664a0f7bbd2bc7e24345 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:15:27 -0300 Subject: [PATCH 097/113] hasGithubToken on session --- backend/src/routes/sessions.routes.ts | 4 ++-- backend/src/services/Manager/AuthenticateManagerService.ts | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/backend/src/routes/sessions.routes.ts b/backend/src/routes/sessions.routes.ts index b70579d..44f9934 100644 --- a/backend/src/routes/sessions.routes.ts +++ b/backend/src/routes/sessions.routes.ts @@ -8,14 +8,14 @@ sessionsRouter.post('/', async (request, response) => { const authenticateUser = new AuthenticateManagerService(); - const { manager, token } = await authenticateUser.execute({ + const { manager, token, hasGithubToken } = await authenticateUser.execute({ email, password, }); delete manager.password; - return response.json({ manager, token }); + return response.json({ manager, token, hasGithubToken }); }); export default sessionsRouter; diff --git a/backend/src/services/Manager/AuthenticateManagerService.ts b/backend/src/services/Manager/AuthenticateManagerService.ts index 3de4f7a..3a547cd 100644 --- a/backend/src/services/Manager/AuthenticateManagerService.ts +++ b/backend/src/services/Manager/AuthenticateManagerService.ts @@ -7,6 +7,7 @@ import AppError from '../../errors/AppError'; interface Response { manager: Manager; token: string; + hasGithubToken: boolean; } interface Request { @@ -40,7 +41,9 @@ class AuthenticateManagerService { expiresIn: '7d', }); - return { manager, token }; + const hasGithubToken = !!manager.github_token; + + return { manager, token, hasGithubToken }; } } From e586e23131821cb86d28c68e3fa842c53bee41a1 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:31:24 -0300 Subject: [PATCH 098/113] Fixing period --- .../SpotDailyReportsRepository.ts | 66 +++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 0f2e7bd..423ab55 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -51,11 +51,23 @@ class SpotDailyReportsRepository extends Repository { since: string, until: string, ): Promise { + const { since: parsedSince, until: parsedUntil } = this.parseDates( + since, + until, + ); + + console.log(parsedSince); + console.log(parsedUntil); + const rawReport: RawReport = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.taken_at >= :since`, { since }) - .andWhere('report.taken_at <= :until', { until }) + .andWhere(`report.taken_at >= :since`, { + since: parsedSince.toISOString(), + }) + .andWhere('report.taken_at < :until', { + until: parsedUntil.toISOString(), + }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') @@ -76,10 +88,19 @@ class SpotDailyReportsRepository extends Repository { since: string, until: string, ): Promise { + const { since: parsedSince, until: parsedUntil } = this.parseDates( + since, + until, + ); + const rawReport: RawReport[] = await this.createQueryBuilder('report') .leftJoinAndSelect('report.spot', 'spot') - .andWhere(`report.taken_at >= :since`, { since }) - .andWhere('report.taken_at <= :until', { until }) + .andWhere(`report.taken_at >= :since`, { + since: parsedSince.toISOString(), + }) + .andWhere('report.taken_at < :until', { + until: parsedUntil.toISOString(), + }) .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') @@ -96,6 +117,43 @@ class SpotDailyReportsRepository extends Repository { return report; } + private parseDates( + since: string, + until: string, + ): { since: Date; until: Date } { + const sinceDate = new Date(since); + const untilDate = new Date(until); + + const parsedSince = new Date( + Date.UTC( + sinceDate.getFullYear(), + sinceDate.getMonth(), + sinceDate.getDate(), + 0, + 0, + 0, + 0, + ), + ); + + const parsedUntil = new Date( + Date.UTC( + untilDate.getFullYear(), + untilDate.getMonth(), + untilDate.getDate(), + 23, + 59, + 59, + 59, + ), + ); + + return { + since: parsedSince, + until: parsedUntil, + }; + } + private parseRawReport(rawReport: RawReport): Report { if (rawReport) { const { From bd16e4b63b16b26af85f2c4949fa78f3131a0a28 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:49:00 -0300 Subject: [PATCH 099/113] Project route bug resolved --- backend/src/routes/project.routes.ts | 4 ++-- frontend/src/pages/Dashboard/index.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/src/routes/project.routes.ts b/backend/src/routes/project.routes.ts index c1e38bc..2d14081 100644 --- a/backend/src/routes/project.routes.ts +++ b/backend/src/routes/project.routes.ts @@ -15,7 +15,7 @@ projectRouter.get('/:project', authMiddleware, async (request, response) => { }); projectRouter.get( - '/below_average/:project', + '/:project/below_average', authMiddleware, async (request, response) => { const getBelowAverageOnProjectService = new GetBelowAverageOnProjectService(); @@ -34,7 +34,7 @@ projectRouter.get( ); projectRouter.get( - '/report/:project', + '/:project/report', authMiddleware, async (request, response) => { const getProjectReportService = new GetProjectReportService(); diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsx index 3d8d6ad..cb5d7ec 100644 --- a/frontend/src/pages/Dashboard/index.tsx +++ b/frontend/src/pages/Dashboard/index.tsx @@ -69,7 +69,7 @@ const Dashboard: React.FC = () => { try { const response = await api.get( - `/project/report/coming?since=${since.toISOString()}`, + `/project/coming/report?since=${since.toISOString()}`, ); const { @@ -109,7 +109,7 @@ const Dashboard: React.FC = () => { try { const response = await api.get( - `/project/below_average?since=${since.toISOString()}`, + `/project/coming/below_average?since=${since.toISOString()}`, ); setBelowAverage(response.data); From e37c1a15c4032c534e624db1c355c907df5ae8b9 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 10:50:17 -0300 Subject: [PATCH 100/113] removing unused logs --- backend/src/repositories/SpotDailyReportsRepository.ts | 3 --- .../RequestSpotsProcess/RequestSpotsProcessProcessor.ts | 1 - 2 files changed, 4 deletions(-) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 423ab55..9b2ed06 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -56,9 +56,6 @@ class SpotDailyReportsRepository extends Repository { until, ); - console.log(parsedSince); - console.log(parsedUntil); - const rawReport: RawReport = await this.createQueryBuilder('report') .where('report.spot_id = :id', { id: spot_id }) .leftJoinAndSelect('report.spot', 'spot') diff --git a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts index 80acd5d..81b67a8 100644 --- a/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts +++ b/backend/src/workers/RequestSpotsProcess/RequestSpotsProcessProcessor.ts @@ -32,7 +32,6 @@ const RequestSpotsProcessProcessor = async (): Promise => { console.log( `Starting spot crawl request at ${since.toISOString()} - ${until.toISOString()}`, ); - console.log('aaaaa', since.getTimezoneOffset()); const spots = await spotsRepository.find(); From f162a1cd239e5d0ee91ef1eeb82b558a5c5fc934 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 12:58:00 -0300 Subject: [PATCH 101/113] oauth token fix --- backend/src/services/githubApi/GraphQLApi.ts | 6 +++--- backend/src/services/githubApi/RestApi.ts | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/backend/src/services/githubApi/GraphQLApi.ts b/backend/src/services/githubApi/GraphQLApi.ts index 21aa032..0a3f218 100644 --- a/backend/src/services/githubApi/GraphQLApi.ts +++ b/backend/src/services/githubApi/GraphQLApi.ts @@ -14,11 +14,11 @@ api.interceptors.request.use(async config => { const token = await getGithubTokenService.execute(); if (token) { - useGlobal.teacherToken = token; + useGlobal.managerToken = token; } } - if (useGlobal.teacherToken) { - config.headers.authorization = `bearer ${useGlobal.teacherToken}`; + if (useGlobal.managerToken) { + config.headers.authorization = `bearer ${useGlobal.managerToken}`; } return config; diff --git a/backend/src/services/githubApi/RestApi.ts b/backend/src/services/githubApi/RestApi.ts index 585a7ce..11aa529 100644 --- a/backend/src/services/githubApi/RestApi.ts +++ b/backend/src/services/githubApi/RestApi.ts @@ -9,16 +9,17 @@ const api = axios.create({ }); api.interceptors.request.use(async config => { - if (!useGlobal.teacherToken) { + if (!useGlobal.managerToken) { const getGithubTokenService = new GetGithubTokenService(); const token = await getGithubTokenService.execute(); + console.log(token); if (token) { - useGlobal.teacherToken = token; + useGlobal.managerToken = token; } } - if (useGlobal.teacherToken) { - config.headers.authorization = `token ${useGlobal.teacherToken}`; + if (useGlobal.managerToken) { + config.headers.authorization = `token ${useGlobal.managerToken}`; } return config; From a58d2d7f8cfff1fbf9430ccaece138a3a2060750 Mon Sep 17 00:00:00 2001 From: Davi Sousa Date: Sat, 21 Nov 2020 13:08:51 -0300 Subject: [PATCH 102/113] hotfix: loadEager relation disabled on get repositories --- backend/src/services/Spot/GetSpotRepositories.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/src/services/Spot/GetSpotRepositories.ts b/backend/src/services/Spot/GetSpotRepositories.ts index fb10e8f..382c06d 100644 --- a/backend/src/services/Spot/GetSpotRepositories.ts +++ b/backend/src/services/Spot/GetSpotRepositories.ts @@ -26,6 +26,7 @@ class GetSpotRepositories { where: { spot_id: spot.id, }, + loadEagerRelations: false, }); return repositories; From fe6b618d9a98fa1dd5ff341cd06e207c54f01de4 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 13:24:54 -0300 Subject: [PATCH 103/113] Migration to add new_prs_review on reports --- ...975756087-AddPullRequestsReviewOnReport.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts diff --git a/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts b/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts new file mode 100644 index 0000000..c828144 --- /dev/null +++ b/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts @@ -0,0 +1,19 @@ +import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm'; + +export default class AddPullRequestsReviewOnReport1605975756087 + implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.addColumn( + 'spot_daily_reports', + new TableColumn({ + name: 'new_prs_review', + type: 'timestamp', + isNullable: false, + }), + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.dropColumn('spot_daily_reports', 'new_prs_review'); + } +} From 7b5acb806be383f020de343fb45f62725053c585 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 13:25:17 -0300 Subject: [PATCH 104/113] Migration to add new_prs_review on reports --- .../migrations/1605975756087-AddPullRequestsReviewOnReport.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts b/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts index c828144..2f3d0ec 100644 --- a/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts +++ b/backend/src/database/migrations/1605975756087-AddPullRequestsReviewOnReport.ts @@ -7,7 +7,7 @@ export default class AddPullRequestsReviewOnReport1605975756087 'spot_daily_reports', new TableColumn({ name: 'new_prs_review', - type: 'timestamp', + type: 'int2', isNullable: false, }), ); From 340a5e145e87ef46a0be2d3278c4b3661f9610d9 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 13:27:50 -0300 Subject: [PATCH 105/113] saving pull requests review on crawler --- backend/src/services/DailyReport/GetDailyReportService.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index a8ad34f..e893f4e 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -27,6 +27,7 @@ interface Response { payload: { new_interactions: number; new_repositories: number; + new_prs_review: number; new_prs: number; new_issues: number; new_commits: number; @@ -113,6 +114,7 @@ class GetDailyReportService { new_prs: totalPullRequestContributions, new_issues: totalIssueContributions, new_commits: totalCommitContributions, + new_prs_review: totalPullRequestReviewContributions, additions, deletions, commits, From 0961f1047ea1d2b9bf1a147e919ba61e0fef151a Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 13:30:23 -0300 Subject: [PATCH 106/113] new_prs_review on spotDailyReportsRepository --- backend/src/repositories/SpotDailyReportsRepository.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/backend/src/repositories/SpotDailyReportsRepository.ts b/backend/src/repositories/SpotDailyReportsRepository.ts index 9b2ed06..6860c5a 100644 --- a/backend/src/repositories/SpotDailyReportsRepository.ts +++ b/backend/src/repositories/SpotDailyReportsRepository.ts @@ -13,6 +13,7 @@ interface RawReport { spot_created_at: string; spot_updated_at: string; new_interactions: number; + new_prs_review: number; new_commits: number; new_prs: number; new_issues: number; @@ -34,6 +35,7 @@ interface Report { updated_at: string; }; metrics: { + new_prs_review: number; new_interactions: number; new_commits: number; new_prs: number; @@ -68,6 +70,7 @@ class SpotDailyReportsRepository extends Repository { .select('spot') .addSelect('SUM(report.new_interactions)', 'new_interactions') .addSelect('SUM(report.new_commits)', 'new_commits') + .addSelect('SUM(report.new_prs_review)', 'new_prs_review') .addSelect('SUM(report.new_prs)', 'new_prs') .addSelect('SUM(report.new_issues)', 'new_issues') .addSelect('SUM(report.new_repositories)', 'new_repositories') @@ -161,6 +164,7 @@ class SpotDailyReportsRepository extends Repository { new_issues, new_prs, new_repositories, + new_prs_review, spot_avatar_url, spot_created_at, spot_github_id, @@ -192,6 +196,7 @@ class SpotDailyReportsRepository extends Repository { new_issues: Number(new_issues), new_prs: Number(new_prs), new_repositories: Number(new_repositories), + new_prs_review: Number(new_prs_review), }, }; return report; @@ -205,6 +210,7 @@ class SpotDailyReportsRepository extends Repository { new_issues: 0, new_prs: 0, new_repositories: 0, + new_prs_review: 0, }, }; } From 9b7152793ea3a23384b6edc77b7f933fd9563d25 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sat, 21 Nov 2020 13:35:25 -0300 Subject: [PATCH 107/113] New prs review added --- backend/src/models/SpotDailyReport.ts | 3 +++ backend/src/services/Spot/GetSpotReportService.ts | 1 + backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts | 2 ++ 3 files changed, 6 insertions(+) diff --git a/backend/src/models/SpotDailyReport.ts b/backend/src/models/SpotDailyReport.ts index 6a731e4..516f8a9 100644 --- a/backend/src/models/SpotDailyReport.ts +++ b/backend/src/models/SpotDailyReport.ts @@ -51,6 +51,9 @@ class SpotDailyReport { @Column('timestamp') taken_at: Date; + + @Column('int2') + new_prs_review: Date; } export default SpotDailyReport; diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts index ad16931..88e81bc 100644 --- a/backend/src/services/Spot/GetSpotReportService.ts +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -27,6 +27,7 @@ interface Response { new_commits: number; new_prs: number; new_issues: number; + new_prs_review: number; new_repositories: number; additions: number; deletions: number; diff --git a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts index 5ff31d2..5aff185 100644 --- a/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts +++ b/backend/src/workers/ProcessSpot/ProcessSpotProcessor.ts @@ -29,6 +29,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { new_issues: issues, new_prs, new_repositories, + new_prs_review, } = payload; const dailyReport = dailyReportRepository.create({ @@ -41,6 +42,7 @@ const ProcessSpotProcessor = async (job: Job): Promise => { new_repositories, spot_id, taken_at: until, + new_prs_review, }); await dailyReportRepository.save(dailyReport); From 5615efa7280d588fcf1f07c22a9a3d4948857801 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 10:50:54 -0300 Subject: [PATCH 108/113] Removing unsed routes. and changing /session response doc --- backend/README.md | 96 ++++++----------------------------------------- 1 file changed, 12 insertions(+), 84 deletions(-) diff --git a/backend/README.md b/backend/README.md index 6565729..0c89a7a 100644 --- a/backend/README.md +++ b/backend/README.md @@ -89,79 +89,6 @@ yarn dev:server # 🔎 Endpoints da API -## Obter perfil: - -``` -GET /user/:username -``` - -Use essa rota para obter informações sobre o perfil de determinado usuário, basta substituir o parâmetro ":username" da rota pelo usuário do github correspondente, você deve receber uma resposta no seguinte modelo: - -```json -{ - "github_login": "davigsousa", - "avatar_url": "https://avatars0.githubusercontent.com/u/40612788?v=4", - "repositories": [ - { - "name": "algorithms", - "full_name": "davigsousa/algorithms", - "description": "Some useful algorithms (Still learning and updating more).", - "html_url": "https://github.com/davigsousa/algorithms", - "created_at": "2020-05-27T14:50:25Z", - "language": "C++" - }, - { - "name": "doeteca", - "full_name": "davigsousa/doeteca", - "description": "A Frontend for a Conceptual Project named Doeteca. Online on: https://doeteca.netlify.app/", - "html_url": "https://github.com/davigsousa/doeteca", - "created_at": "2020-02-17T22:01:18Z", - "language": "JavaScript" - } - ], - "top_language": "JavaScript", - "top_5_languages": ["JavaScript", "Python", "C++", "CSS", "TypeScript"] -} -``` - -## Obter relatório do dia atual: - -``` -GET /user/daily/:username -``` - -Use essa rota para obter informações de interações de determinado usuário no dia atual, basta substituir o parâmetro ":username" da rota pelo usuário do github correspondente, você deve receber uma resposta no seguinte modelo: - -```json -{ - "new_forks": 0, - "new_issues": 0, - "new_prs": 4, - "new_stars": 0, - "new_repositories": 0, - "new_interactions": 4, - "new_commits": 32, - "commits": [ - { - "repository": { - "id": 289791710, - "name": "Guardians-DSC/GitRadar", - "url": "https://api.github.com/repos/Guardians-DSC/GitRadar" - }, - "message": "initial Service structure created" - }, - { - "repository": { - "id": 293942092, - "name": "davigsousa/GitRadar", - "url": "https://api.github.com/repos/davigsousa/GitRadar" - }, - "message": "Merge pull request #1 from davigsousa/develop\n\nCriação da Api e Criação do Profile Service" - } - ] -} -``` - ## Iniciar sessão com a conta de um professor: ``` @@ -172,18 +99,19 @@ Realiza a sessão de um professor na aplicação, para realizar a requisição, ```json { - "teacher": { - "id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "davigsousa", - "name": "Davi Sousa", - "email": "davi@email.com", - "avatar_url": "https://avatars0.githubusercontent.com/u/40612788?v=4", - "github_id": "40612788", - "created_at": "2020-10-28T04:41:07.360Z", - "updated_at": "2020-10-28T04:45:26.492Z" + "manager": { + "id": "058bd335-1a2a-4856-8969-861d6707586a", + "github_login": "AntonioNtV", + "name": "Antonio Bertino de Vasconcelos Cabral Neto ", + "email": "antoniontv1920@gmail.com", + "github_token": null, + "avatar_url": "https://avatars3.githubusercontent.com/u/38543529?v=4", + "github_id": "38543529", + "created_at": "2020-11-22T16:50:12.236Z", + "updated_at": "2020-11-22T16:50:12.236Z" }, - "token": "tokenJWT", - "hasGithubToken": true + "token": "TOKEN", + "hasGithubToken": false } ``` From 78784657cc4410fba6a6d8c9d524bb2c90fbfb1b Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 11:02:04 -0300 Subject: [PATCH 109/113] Changing nomenclature of teachers, spots, and projetcs in project docs --- backend/README.md | 245 ++++++++++++++++++++++------------------------ 1 file changed, 119 insertions(+), 126 deletions(-) diff --git a/backend/README.md b/backend/README.md index 0c89a7a..ce2185d 100644 --- a/backend/README.md +++ b/backend/README.md @@ -45,7 +45,7 @@ Guarde os valores do ClientID e ClientSecret, você usará no ".env", além diss - Homepage URL: http://localhost:3000 - Authorization callback URL: http://localhost:3000/dashboard -Essa configuração serve para que a autenticação com o Github de um professor seja possível. A maneira mais fácil e eficiente é executar o frontend e o backend simultaneamente para que você realize o vínculo através da interface gráfica do site. +Essa configuração serve para que a autenticação com o Github de um Manager seja possível. A maneira mais fácil e eficiente é executar o frontend e o backend simultaneamente para que você realize o vínculo através da interface gráfica do site.

Agora, precisamos configurar as variáveis de ambiente. Para isso, você deve copiar o arquivo ".env.sample" e o renomear para ".env" na pasta raiz do Backend. Você precisa preencher os valores de todas as variáveis de acordo com o seu significado. @@ -89,13 +89,13 @@ yarn dev:server # 🔎 Endpoints da API -## Iniciar sessão com a conta de um professor: +## Iniciar sessão com a conta de um Manager: ``` POST /session ``` -Realiza a sessão de um professor na aplicação, para realizar a requisição, deve-se enviar uma chave "email" com o e-mail do professor uma chave "password" com a senha, dessa forma, se recebe como retorno o token JWT para o uso em rotas autenticadas, exemplo de retorno: +Realiza a sessão de um Manager na aplicação, para realizar a requisição, deve-se enviar uma chave "email" com o e-mail do manager uma chave "password" com a senha, dessa forma, se recebe como retorno o token JWT para o uso em rotas autenticadas, exemplo de retorno: ```json { @@ -117,170 +117,163 @@ Realiza a sessão de um professor na aplicação, para realizar a requisição, ## ⭐ A partir daqui, todas as rotas são autenticadas. -## Listar alunos de uma turma: +## Listar Spots de um Projeto: ``` -GET /class/ +GET /project/:project_id ``` -Listar todos os alunos da turma da aplicação, exemplo de retorno: +Listar todos os Spots de um projeto salvo na aplicação, exemplo de retorno: ```json [ { - "id": "69615485-8f7c-473e-9099-cce2ce31200d", - "teacher_id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "natalia-sa", - "avatar_url": "https://avatars2.githubusercontent.com/u/55745942?v=4", - "top_language": "Java", - "github_id": "55745942", - "name": "Natália Salvino André", - "created_at": "2020-10-28T04:45:42.499Z", - "updated_at": "2020-10-28T04:45:42.499Z" + "id": "efdbc8b0-8a59-4247-9a65-d80bfc70967d", + "manager_id": null, + "github_login": "davigsousa", + "avatar_url": "https://avatars3.githubusercontent.com/u/40612788?u=abb3a9982b62292b78f741ce47e8eb3a8803bd84&v=4", + "top_language": "none", + "github_id": "MDQ6VXNlcjQwNjEyNzg4", + "name": "Davi Sousa", + "created_at": "2020-11-21T16:17:12.464Z", + "updated_at": "2020-11-21T16:17:12.464Z" + }, + { + "id": "464945d6-f905-481f-8f27-18d09d029240", + "manager_id": null, + "github_login": "arturbs", + "avatar_url": "https://avatars3.githubusercontent.com/u/41977691?v=4", + "top_language": "none", + "github_id": "MDQ6VXNlcjQxOTc3Njkx", + "name": "arturbs", + "created_at": "2020-11-21T18:57:18.116Z", + "updated_at": "2020-11-21T18:57:18.116Z" }, { - "id": "15f7c236-075f-454b-be9e-9b8e4a8aa335", - "teacher_id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "kleberfsobrinho", - "avatar_url": "https://avatars2.githubusercontent.com/u/56925275?v=4", - "top_language": "Java", - "github_id": "56925275", - "name": null, - "created_at": "2020-10-28T04:51:31.278Z", - "updated_at": "2020-10-28T04:51:31.278Z" + "id": "1a523c45-5b45-41cb-aec3-325618f60f1f", + "manager_id": null, + "github_login": "NathanLCR", + "avatar_url": "https://avatars1.githubusercontent.com/u/48298897?u=6736c6de331e65dc08b6d79e6fbfac29919c2b3c&v=4", + "top_language": "none", + "github_id": "MDQ6VXNlcjQ4Mjk4ODk3", + "name": "Nathan Lucio", + "created_at": "2020-11-21T18:57:23.884Z", + "updated_at": "2020-11-21T18:57:23.884Z" } ] ``` -## Listar alunos da turma abaixo da média: +## Listar Spots do projeto com interações abaixo da média: ``` -GET /class/below_average?since=2020-10-02 +GET /project/:project_id/below_average?since=2020-10-02 ``` -Informando o parâmetro "since" na query, você informa o início do período de avaliação da média, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para listar todos os alunos da turma abaixo da média de interações, exemplo de retorno: +Informando o parâmetro "since" na query, você informa o início do período de avaliação da média, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para listar todos os spots de um projeto abaixo da média de interações, exemplo de retorno: ```json [ { - "id": "69615485-8f7c-473e-9099-cce2ce31200d", - "teacher_id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "natalia-sa", - "avatar_url": "https://avatars2.githubusercontent.com/u/55745942?v=4", - "top_language": "Java", - "github_id": "55745942", - "name": "Natália Salvino André", - "created_at": "2020-10-28T04:45:42.499Z", - "updated_at": "2020-10-28T04:45:42.499Z" + "id": "1a523c45-5b45-41cb-aec3-325618f60f1f", + "github_login": "NathanLCR", + "manager_id": null, + "avatar_url": "https://avatars1.githubusercontent.com/u/48298897?u=6736c6de331e65dc08b6d79e6fbfac29919c2b3c&v=4", + "top_language": "none", + "github_id": "MDQ6VXNlcjQ4Mjk4ODk3", + "name": "Nathan Lucio", + "created_at": "2020-11-21T18:57:23.884Z", + "updated_at": "2020-11-21T18:57:23.884Z" }, { - "id": "15f7c236-075f-454b-be9e-9b8e4a8aa335", - "teacher_id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "kleberfsobrinho", - "avatar_url": "https://avatars2.githubusercontent.com/u/56925275?v=4", - "top_language": "Java", - "github_id": "56925275", - "name": null, - "created_at": "2020-10-28T04:51:31.278Z", - "updated_at": "2020-10-28T04:51:31.278Z" + "id": "2d624fbc-152e-46be-92f9-60e631ea8db0", + "github_login": "HigorSnt", + "manager_id": null, + "avatar_url": "https://avatars1.githubusercontent.com/u/40602956?u=079b6f0f87e03d57e31081bba7c7809c7c9c14b8&v=4", + "top_language": "none", + "github_id": "MDQ6VXNlcjQwNjAyOTU2", + "name": "Higor Santos", + "created_at": "2020-11-21T18:56:12.970Z", + "updated_at": "2020-11-21T18:56:12.970Z" } ] ``` -## Obter Relatório da Turma: +## Obter Relatório do Projeto: ``` -GET /class/report?since=2020-10-02 +GET /project/:project_id/report?since=2020-10-02 ``` -Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de uma turma em um período, exemplo de retorno: +Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de um projeto em um período, exemplo de retorno: ```json { - "all_new_interactions": 36, - "all_new_commits": 29, - "new_interactions_average": 3, - "new_commits_average": 2.4166666666666665 + "all_new_interactions": 2, + "all_new_commits": 0, + "new_interactions_average": 0.25, + "new_commits_average": 0 } ``` -## Adicionar aluno na Turma: +## Adicionar Spot no Projeto: ``` -POST /student +POST /spot ``` -Adiciona-se um aluno na turma, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do aluno no Github, dessa forma, se recebe como retorno o aluno criado, exemplo de retorno: +Adiciona-se um spot no projeto, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do spot no Github, dessa forma, se recebe como retorno o spot criado, exemplo de retorno: ```json { - "teacher_id": "84e5a509-16af-4f3d-805c-c400751e6d4c", - "github_login": "antoniontv", - "avatar_url": "https://avatars3.githubusercontent.com/u/38543529?v=4", - "top_language": "Java", - "github_id": "38543529", - "name": "Antonio Bertino de Vasconcelos Cabral Neto ", - "id": "62085bb4-4a0a-47ca-a470-c43c3cdcc080", - "created_at": "2020-10-23T08:04:42.903Z", - "updated_at": "2020-10-23T08:04:42.903Z" -} -``` - -## Obtém as informações de um aluno: - -``` -GET /student/:username -``` - -Obtém as informações de um aluno, deve-se enviar o username do Github do aluno como params :username, é retornado as informações do estudante e seus repositórios: - -```json -{ - "student": { - "id": "f5de7532-0a61-4db1-833c-2513aa5f0dab", - "teacher_id": "7ea79496-c141-487c-a810-522aa949839f", - "github_login": "davigsousa", - "avatar_url": "https://avatars0.githubusercontent.com/u/40612788?v=4", - "top_language": "JavaScript", - "github_id": "40612788", - "name": "Davi Sousa", - "created_at": "2020-10-28T04:47:35.601Z", - "updated_at": "2020-10-28T04:47:35.601Z" - }, + "github_login": "DaniloDMF", + "avatar_url": "https://avatars1.githubusercontent.com/u/55511256?v=4", "repositories": [ { - "id": "35d0645f-1ace-439d-8349-379a40f5c8a8", - "student_id": "f5de7532-0a61-4db1-833c-2513aa5f0dab", - "name": "a-granja-api", - "full_name": "davigsousa/a-granja-api", - "description": "API RESTful para servir os dados das votações no Programa \"A Granja\".", - "html_url": "https://github.com/davigsousa/a-granja-api", - "github_id": "277945496", - "created_at": "2020-10-28T04:47:35.864Z", - "updated_at": "2020-10-28T04:47:35.864Z" + "id": "a0826bd8-798f-4c98-bf21-85996aca234b", + "name": "hello-world", + "full_name": "DaniloDMF/hello-world", + "description": null, + "html_url": "https://github.com/DaniloDMF/hello-world" + }, + { + "id": "05348432-3086-4bfc-9806-06e144a438a3", + "name": "README.md", + "full_name": "DaniloDMF/README.md", + "description": "README.md", + "html_url": "https://github.com/DaniloDMF/README.md" }, { - "id": "fdf99a27-c1c7-4f0b-b55c-eb79eb444f4d", - "student_id": "f5de7532-0a61-4db1-833c-2513aa5f0dab", - "name": "viva-web", - "full_name": "davigsousa/viva-web", - "description": "Website desenvolvido no Hackathon MegaHack. (Descontinuado)", - "html_url": "https://github.com/davigsousa/viva-web", - "github_id": "260795504", - "created_at": "2020-10-28T04:47:41.821Z", - "updated_at": "2020-10-28T04:47:41.821Z" + "id": "c1e816bb-7f17-4cc0-a966-89fcb9cc3802", + "name": "OlaMundo", + "full_name": "DaniloDMF/OlaMundo", + "description": null, + "html_url": "https://github.com/DaniloDMF/OlaMundo" + }, + { + "id": "2a87f715-4ee3-4ff0-935d-03aa8ca44410", + "name": "PWEB", + "full_name": "DaniloDMF/PWEB", + "description": null, + "html_url": "https://github.com/DaniloDMF/PWEB" + }, + { + "id": "b8e58c79-9e93-4915-bc10-cdfb4f43191b", + "name": "montanha-do-dragao-negro", + "full_name": "DaniloDMF/montanha-do-dragao-negro", + "description": null, + "html_url": "https://github.com/DaniloDMF/montanha-do-dragao-negro" } ] } ``` -## Obtém a quantidade de interações por dia em um período de um estudante: +## Obtém a quantidade de interações por dia em um período de um Spot: ``` -GET /student/:username/interactions/volume?since=2020-11-02 +GET /spot/volume/:username/interactions?since=2020-11-02 ``` -Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade de interações por dia de um aluno, deve-se enviar o username do Github do aluno como params :username, as quantidades são retornadas no seguinte modelo: +Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade de interações por dia de um spot, deve-se enviar o username do Github do spot como params :username, as quantidades são retornadas no seguinte modelo: ```json [ @@ -299,13 +292,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ] ``` -## Obtém a adição e remoção de linhas por dia em um período de um estudante: +## Obtém a adição e remoção de linhas por dia em um período de um Spot: ``` -GET /student/:username/lines/volume?since=2020-11-02 +GET /spot/volume/:username/lines?since=2020-11-02 ``` -Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade adições e remoções de linhas de código por dia de um aluno, deve-se enviar o username do Github do aluno como params :username, as quantidades são retornadas no seguinte modelo: +Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Obtém a quantidade adições e remoções de linhas de código por dia de um spot, deve-se enviar o username do Github do spot como params :username, as quantidades são retornadas no seguinte modelo: ```json [ @@ -327,13 +320,13 @@ Informando o parâmetro "since" na query, você informa o início do período, o ] ``` -## Obter Relatório de um estudante: +## Obter Relatório de um Spot: ``` -GET /student/:username/report?since=2020-10-02 +GET /spot/:username/report?since=2020-10-02 ``` -Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de um estudante em um período, exemplo de retorno: +Informando o parâmetro "since" na query, você informa o início do período, outro parâmetro opcional na rota é "until" que delimita o final do período. Use essa rota para obter o relatório de um spot em um período, exemplo de retorno: ```json { @@ -364,23 +357,23 @@ Informando o parâmetro "since" na query, você informa o início do período, o } ``` -## Adicionar professor na aplicação: +## Adicionar Manager na aplicação: ``` -POST /teacher +POST /manager ``` -Adiciona-se um professor na aplicação, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do professor no Github, uma chave "email" com o e-mail do professor e uma chave "password" no body da requisição, dessa forma, se recebe como retorno o professor criado, exemplo de retorno: +Adiciona-se um Manger na aplicação, para realizar a requisição, deve-se enviar uma chave "github_login" com o username do Manager no Github, uma chave "email" com o e-mail do Manager e uma chave "password" no body da requisição, dessa forma, se recebe como retorno o Manager criado, exemplo de retorno: ```json { - "github_login": "davigsousa", - "name": "Davi Sousa", - "email": "davi.gomes.sousa@ccc.ufcg.edu.br", - "avatar_url": "https://avatars0.githubusercontent.com/u/40612788?v=4", - "github_id": "40612788", - "id": "84e5a509-16af-4f3d-805c-c400751e6d4c", - "created_at": "2020-10-15T21:52:19.772Z", - "updated_at": "2020-10-15T21:52:19.772Z" + "github_login": "AntonioNtV", + "name": "Antonio Bertino de Vasconcelos Cabral Neto ", + "email": "antoniontv1920@gmail.com", + "avatar_url": "https://avatars3.githubusercontent.com/u/38543529?v=4", + "github_id": 38543529, + "id": "058bd335-1a2a-4856-8969-861d6707586a", + "created_at": "2020-11-22T16:50:12.236Z", + "updated_at": "2020-11-22T16:50:12.236Z" } ``` From cb0611c9fd934fee93c5444b99ee7731c7db46cb Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 11:30:28 -0300 Subject: [PATCH 110/113] Fixing empty repositories bug --- backend/src/services/DailyReport/GetDailyReportService.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index e893f4e..bed1380 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -162,7 +162,13 @@ class GetDailyReportService { url, } = repository; - const repositoryCommits = defaultBranchRef.target.history.nodes; + // Empty Repositories + let repositoryCommits: CommitNode[] = []; + if (defaultBranchRef) { + repositoryCommits = defaultBranchRef.target.history.nodes; + } else { + repositoryCommits = []; + } const spotCommits = repositoryCommits.filter(({ author }) => { const { login } = author.user; From 8e8aac0e4e3d0d5bd19b19a719d896d523158ddd Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 11:42:56 -0300 Subject: [PATCH 111/113] removing unsed logs! --- backend/src/services/DailyReport/GetDailyReportService.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/backend/src/services/DailyReport/GetDailyReportService.ts b/backend/src/services/DailyReport/GetDailyReportService.ts index bed1380..21257df 100644 --- a/backend/src/services/DailyReport/GetDailyReportService.ts +++ b/backend/src/services/DailyReport/GetDailyReportService.ts @@ -93,7 +93,10 @@ class GetDailyReportService { const repositoriesNodes: RepositoryNode[] = repositories.nodes; const filteredRepositories = repositoriesNodes.filter(rep => { - return rep.defaultBranchRef.target.history.nodes.length > 0; + if (rep.defaultBranchRef) { + return rep.defaultBranchRef.target.history.nodes.length > 0; + } + return false; }); const commits: Commit[] = this.getCommits( From ac3eab4f35ac66333420f774670f0be716bcaebf Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 11:44:37 -0300 Subject: [PATCH 112/113] Fixing commits on spot report --- backend/src/services/Spot/GetSpotReportService.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/services/Spot/GetSpotReportService.ts b/backend/src/services/Spot/GetSpotReportService.ts index 88e81bc..365a851 100644 --- a/backend/src/services/Spot/GetSpotReportService.ts +++ b/backend/src/services/Spot/GetSpotReportService.ts @@ -61,7 +61,7 @@ class GetSpotReportService { ); const commits = await commitRepository.find({ where: { - id, + spot_id: id, created_at: Between(since, until), }, }); From bf4b85b969ee45dba8da1bf31d707c0b7e7c7f83 Mon Sep 17 00:00:00 2001 From: AntonioNtV Date: Sun, 22 Nov 2020 11:48:31 -0300 Subject: [PATCH 113/113] Redirecting to commit url when click on commit --- frontend/src/pages/Profile/index.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/frontend/src/pages/Profile/index.tsx b/frontend/src/pages/Profile/index.tsx index db726ed..95876db 100644 --- a/frontend/src/pages/Profile/index.tsx +++ b/frontend/src/pages/Profile/index.tsx @@ -311,14 +311,12 @@ const Profile: React.FC = () => { const repositoryName = item.repository ? item.repository.name : 'Repositório indisponível'; - const repositoryLink = item.repository - ? `https://github.com/${username}/${repositoryName}` - : ''; + return { label: repositoryName, subLabel: item.message, - link: repositoryLink, + link: item.commit_url, }; }} title="Commits"