-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat/bring back coefficients dirty #100
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
cbc8636
fix: bug reading null in codigo and subject creation
mateusbrg 387a51d
wip: histórico de fato
mateusbrg f344281
docs: some thoughts
mateusbrg 0cb96eb
feat: handle quadrimestre suplementar
mateusbrg d248d70
refactor: maintaining component category if exists
mateusbrg 09cc8c7
wip: optimize endpoint
Joabesv 8432a1b
Merge branch 'main' into feat/bring-back-coefficients-dirty
Joabesv 752aca9
wip: history categories
Joabesv 382f05c
wip do wip
Joabesv b784b7e
feat: dynamic course id and grade - crimes here pay attention sry
mateusbrg 8a97a3d
Merge branch 'main' into feat/bring-back-coefficients-dirty
mateusbrg 261ab24
Merge branch 'main' into feat/bring-back-coefficients-dirty
mateusbrg 40fcbf1
feat: get credits if free subject exists
mateusbrg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,28 @@ | ||
import { LRUCache } from 'lru-cache'; | ||
import { z } from 'zod'; | ||
import { HistoryModel } from '@/models/History.js'; | ||
import { SubjectModel } from '@/models/Subject.js'; | ||
import { | ||
type Categories, | ||
type History, | ||
HistoryModel, | ||
} from '@/models/History.js'; | ||
import { logger } from '@next/common'; | ||
import { transformCourseName } from '../utils/transformCourseName.js'; | ||
import type { FastifyReply, FastifyRequest } from 'fastify'; | ||
import { | ||
ufProcessor, | ||
type GraduationComponents, | ||
} from '@/services/ufprocessor.js'; | ||
|
||
import { type Subject, SubjectModel } from '@/models/Subject.js'; | ||
|
||
const CACHE_TTL = 1000 * 60 * 60; | ||
const cache = new LRUCache<string, any>({ | ||
max: 3, | ||
ttl: CACHE_TTL, | ||
}); | ||
const historyCache = new LRUCache<string, History>({ max: 3, ttl: CACHE_TTL }); | ||
|
||
const validateSigaaComponents = z.object({ | ||
ano: z.coerce.number(), | ||
periodo: z.string(), | ||
periodo: z | ||
.enum(['1', '2', '3', 'QS']) | ||
.transform((p) => (p === 'QS' ? '3' : p)), | ||
codigo: z.string(), | ||
situacao: z | ||
.enum(['APROVADO', 'REPROVADO', 'REPROVADO POR FALTAS', '--', '']) | ||
|
@@ -24,14 +32,23 @@ const validateSigaaComponents = z.object({ | |
}); | ||
|
||
const validateSigaaHistory = z.object({ | ||
//updateTime: z.date().optional(), | ||
course: z.string().transform((c) => c.toLocaleLowerCase()), | ||
ra: z.number(), | ||
courseKind: z.string().toLowerCase(), | ||
components: validateSigaaComponents.array(), | ||
}); | ||
|
||
type StudentComponent = z.infer<typeof validateSigaaComponents>; | ||
type HydratedComponent = { | ||
disciplina: string; | ||
conceito: StudentComponent['resultado'] | null; | ||
periodo: StudentComponent['periodo']; | ||
codigo: StudentComponent['codigo']; | ||
ano: number; | ||
situacao: string | null; | ||
categoria: Categories; | ||
creditos: number; | ||
}; | ||
|
||
export async function createHistory( | ||
request: FastifyRequest, | ||
|
@@ -44,103 +61,155 @@ export async function createHistory( | |
} | ||
|
||
const cacheKey = `history:${studentHistory.ra}`; | ||
const cached = cache.get(cacheKey); | ||
const cached = historyCache.get(cacheKey); | ||
|
||
if (cached) { | ||
return { | ||
msg: 'Retrieved from cache', | ||
history: cached, | ||
msg: 'Cached history!', | ||
cached, | ||
}; | ||
} | ||
|
||
const hydratedComponentsPromises = studentHistory.components.map( | ||
(component) => hydrateComponents(component, studentHistory.ra), | ||
); | ||
const hydratedComponents = await Promise.all(hydratedComponentsPromises); | ||
let history = await HistoryModel.findOne({ | ||
ra: studentHistory.ra, | ||
}).lean<History>(); | ||
|
||
const course = transformCourseName( | ||
studentHistory.course, | ||
studentHistory.courseKind, | ||
) as string; | ||
const allUFCourses = await ufProcessor.getCourses(); | ||
const studentCourse = allUFCourses.find( | ||
(UFCourse) => UFCourse.name === course.toLocaleLowerCase(), | ||
); | ||
|
||
let history = await HistoryModel.findOne({ | ||
ra: studentHistory.ra, | ||
}); | ||
if (!studentCourse) { | ||
return reply.notFound('not found user course'); | ||
} | ||
|
||
let studentGrade = ''; | ||
|
||
if (history?.grade) { | ||
studentGrade = history.grade; | ||
} else { | ||
const studentCourseGrades = await ufProcessor.getCourseGrades( | ||
studentCourse.UFcourseId, | ||
); | ||
|
||
if (!studentCourseGrades) { | ||
return reply.notFound( | ||
'Curso não encontrado (entre em contato conosco por favor)', | ||
); | ||
} | ||
studentGrade = studentCourseGrades.at(0)?.year ?? ''; | ||
} | ||
|
||
const UFgraduation = await ufProcessor.getGraduationComponents( | ||
studentCourse.UFcourseId, | ||
studentGrade, | ||
); | ||
|
||
const allSubjects = await SubjectModel.find({}); | ||
|
||
const hydratedComponents = await hydrateComponents( | ||
studentHistory.components, | ||
UFgraduation.components, | ||
allSubjects, | ||
); | ||
|
||
if (!history && hydratedComponents.length > 0) { | ||
history = await HistoryModel.create({ | ||
ra: studentHistory.ra, | ||
curso: course, | ||
disciplinas: hydratedComponents, | ||
coefficients: null, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Corrigir coeficientes no futuro |
||
grade: null, | ||
grade: studentGrade, | ||
}); | ||
cache.set(cacheKey, history); | ||
return { | ||
msg: `Created history for ${studentHistory.ra}`, | ||
history, | ||
}; | ||
} else if (history) { | ||
history = await HistoryModel.findOneAndUpdate( | ||
{ ra: studentHistory.ra, curso: course }, | ||
{ $set: { disciplinas: hydratedComponents } }, | ||
{ new: true }, | ||
); | ||
} | ||
|
||
history = await HistoryModel.findOneAndUpdate( | ||
{ | ||
ra: studentHistory.ra, | ||
curso: course, | ||
}, | ||
{ | ||
$set: { | ||
disciplinas: hydratedComponents, | ||
}, | ||
}, | ||
{ | ||
new: true, | ||
}, | ||
); | ||
|
||
cache.set(cacheKey, history); | ||
historyCache.set(cacheKey, history); | ||
|
||
return { | ||
msg: `Updated history for ${studentHistory.ra}`, | ||
msg: history | ||
? `Updated history for ${studentHistory.ra}` | ||
: `Created history for ${studentHistory.ra}`, | ||
history, | ||
}; | ||
} | ||
|
||
async function hydrateComponents(component: StudentComponent, ra: number) { | ||
const subjects = await SubjectModel.find({ | ||
creditos: { | ||
$exists: true, | ||
}, | ||
}); | ||
const normalizedSubjects = subjects.map((subject) => ({ | ||
name: subject.name.trim().toLocaleLowerCase(), | ||
credits: subject.creditos, | ||
})); | ||
const componentSubject = component.disciplina.trim().toLocaleLowerCase(); | ||
const validComponent = normalizedSubjects.find( | ||
(subject) => subject.name === componentSubject, | ||
); | ||
async function hydrateComponents( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nao sobrescrever as categorias |
||
components: StudentComponent[], | ||
graduationComponents: GraduationComponents[], | ||
allSubjects: Subject[], | ||
): Promise<HydratedComponent[]> { | ||
const hydratedComponents = []; | ||
|
||
if (!validComponent) { | ||
logger.warn({ name: componentSubject, ra }, 'No valid component found'); | ||
return; | ||
} | ||
|
||
const existingHistory = await HistoryModel.findOne({ ra }); | ||
let category = null; | ||
if (existingHistory) { | ||
const existingComponents = existingHistory.disciplinas.find( | ||
(disciplina) => disciplina.codigo === component?.codigo || false, | ||
for (const component of components) { | ||
const gradComponent = graduationComponents.find( | ||
(gc) => gc.UFComponentCode === component.codigo, | ||
); | ||
category = existingComponents?.categoria ?? null; | ||
|
||
let componentCredits = 0; | ||
if (!gradComponent) { | ||
// this will always be a free component | ||
logger.warn( | ||
{ name: component.disciplina, codigo: component.codigo }, | ||
'No matching graduation component found', | ||
); | ||
|
||
const subject = allSubjects.find( | ||
(subject) => subject.name.toLocaleLowerCase() === component.disciplina, | ||
); | ||
|
||
if (!subject) { | ||
const createdSubject = await SubjectModel.create({ | ||
name: component.disciplina, | ||
creditos: 0, | ||
}); | ||
componentCredits = createdSubject.creditos; | ||
} else { | ||
componentCredits = subject.creditos; | ||
} | ||
} else { | ||
componentCredits = gradComponent.credits; | ||
} | ||
|
||
hydratedComponents.push({ | ||
disciplina: component.disciplina, | ||
creditos: componentCredits, | ||
conceito: | ||
component.resultado === '--' || component.resultado === '' | ||
? null | ||
: component.resultado, | ||
periodo: component.periodo, | ||
situacao: | ||
component.situacao === '--' || component.situacao === '' | ||
? null | ||
: component.situacao, | ||
ano: component.ano, | ||
codigo: component.codigo, | ||
categoria: resolveCategory(gradComponent?.category), | ||
}); | ||
} | ||
|
||
return { | ||
conceito: component.resultado === '--' || '' ? null : component.resultado, | ||
periodo: component.periodo, | ||
situacao: component.situacao === '--' || '' ? null : component.situacao, | ||
ano: component.ano, | ||
codigo: component.codigo, | ||
creditos: validComponent.credits, | ||
disciplina: validComponent.name, | ||
categoria: category, | ||
}; | ||
return hydratedComponents; | ||
} | ||
|
||
const resolveCategory = ( | ||
category?: GraduationComponents['category'], | ||
): Categories => { | ||
switch (category) { | ||
case 'limited': | ||
return 'Opção Limitada'; | ||
case 'mandatory': | ||
return 'Obrigatória'; | ||
default: | ||
return 'Livre Escolha'; | ||
} | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.