Skip to content
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/add application codes to all memos #168

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
48 changes: 48 additions & 0 deletions server/controllers/memoDataCtrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,38 @@ async function getDraftByEndPoint(req, res) {
}
}

async function putApplicationCodesInMemo(req, res) {
// STEP 2 EDITING: USE IT IN A SECOND STEP
try {
const { applicationCodes, ladokRoundIds } = req.body
const { memoEndPoint, status, courseCode, semester } = req.params

const dbResponse = []

const draftExist = await dbOneDocument.fetchMemo({ memoEndPoint, status, courseCode, ladokRoundIds, semester })

if (draftExist) {
log.info(
'memo draft already exists,' + memoEndPoint + ' so it will be updated (object id ' + draftExist._id + ')'
)
dbResponse.push(
await dbOneDocument.updateMemo(
{ memoEndPoint, status, courseCode, ladokRoundIds, semester },
{ applicationCodes }
)
)
} else {
log.debug('no memo draft was found to update with memoEndPoint: ', memoEndPoint)
}

log.info('dbResponse length', dbResponse.length, { memoEndPoint })
res.status(201).json(dbResponse)
} catch (error) {
log.error('Error in while trying to putMemoById', { error })
return error
}
}

async function putDraftByEndPoint(req, res) {
// STEP 2 EDITING: USE IT IN A SECOND STEP
try {
Expand Down Expand Up @@ -172,6 +204,20 @@ async function createDraftByMemoEndPoint(req, res) {
}
}

// No need to merge
async function getAllMemos(req, res) {
log.info('getAllMemos: Received request for memo')
try {
const dbResponse = await dbArrayOfDocument.getAllMemos()

res.json(dbResponse || [])
log.info('getAllMemos: Responded to request for memo')
} catch (err) {
log.error('getAllMemos: Failed request for memo, error:', { err })
return err
}
}

async function getAllMemosByCourseCodeAndType(req, res) {
// TODO: ADD FETCHING USED COURSE ROUNDS (DRAFTS + PUBLISHED)
const { courseCode, type } = req.params
Expand Down Expand Up @@ -259,10 +305,12 @@ module.exports = {
createDraftByMemoEndPoint,
getDraftByEndPoint,
getPublishedMemoByEndPoint,
getAllMemos,
getAllMemosByCourseCodeAndType,
getMemosStartingFromPrevSemester,
getCourseSemesterUsedRounds,
deleteDraftByMemoEndPoint,
postNewVersionOfPublishedMemo,
putDraftByEndPoint,
putApplicationCodesInMemo,
}
14 changes: 13 additions & 1 deletion server/controllers/mixedWebAndPdfMemosCtrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,22 @@ async function _formPrioritizedMemosByCourseRounds(courseCode, pdfMemos, webBase
const miniMemos = {}
// firstly fetch web-based
await webBasedMemos.forEach(
({ ladokRoundIds, memoEndPoint, memoCommonLangAbbr, memoName, semester, version, lastChangeDate }) => {
({
ladokRoundIds,
memoEndPoint,
memoCommonLangAbbr,
memoName,
semester,
version,
lastChangeDate,
applicationCodes,
}) => {
if (!semester) return
if (!miniMemos[semester]) miniMemos[semester] = {}
ladokRoundIds.forEach(roundId => {
miniMemos[semester][roundId] = {
courseCode,
applicationCodes,
ladokRoundIds,
semester,
memoEndPoint,
Expand All @@ -186,13 +196,15 @@ async function _formPrioritizedMemosByCourseRounds(courseCode, pdfMemos, webBase
lastChangeDate = pdfMemoUploadDate,
previousFileList,
semester,
applicationCode,
}) => {
if (!semester) return
if (!koppsRoundId) return
if (!miniMemos[semester]) miniMemos[semester] = {}
if (!miniMemos[semester][koppsRoundId]) {
miniMemos[semester][koppsRoundId] = {
courseCode,
applicationCodes: [applicationCode],
courseMemoFileName,
ladokRoundIds: [koppsRoundId],
lastChangeDate,
Expand Down
39 changes: 39 additions & 0 deletions server/controllers/storedMemoPdfsCtrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

const log = require('@kth/log')
const { StoredMemoPdfsModel } = require('../models/storedMemoPdfsModel')
const dbOneDocument = require('../lib/dbDataById')

async function getStoredMemoPdfListByCourseCode(req, res) {
if (!req.params.courseCode) throw new Error('courseCode must be set')
Expand Down Expand Up @@ -55,6 +56,18 @@ async function fetchAll() {
return migrated
}

async function fetchAllMemoFiles(req, res) {
try {
log.debug('Fetching all migrated courseMemos ')
const migrated = await StoredMemoPdfsModel.find({})
log.info('Length of data in db', migrated.length)
res.json(migrated || [])
} catch (error) {
log.error('Error in while trying to get all migrating memos files ', { error })
return error
}
}

// /count
async function checkLength(req, res) {
try {
Expand All @@ -68,7 +81,33 @@ async function checkLength(req, res) {
}
}

async function updateStoredPdfMemoWithApplicationCodes(req, res) {
try {
const applicationCodes = req.body
const { _id } = req.params

const dbResponse = []

const draftExist = await dbOneDocument.fetchMemoFileById(_id)

if (draftExist) {
log.info('memo file already exists,' + _id + ' so it will be updated (object id ' + draftExist._id + ')')
dbResponse.push(await dbOneDocument.updateMemoFile(_id, applicationCodes))
} else {
log.debug('no memo file was found to update with Id: ', _id)
}

log.info('dbResponse length', dbResponse.length, { _id })
res.status(201).json(dbResponse)
} catch (error) {
log.error('Error in while trying to update memo file with application codes', { error })
return error
}
}

module.exports = {
collectionLength: checkLength,
getStoredMemoPdfListByCourseCode,
fetchAllMemoFiles,
updateStoredPdfMemoWithApplicationCodes,
}
74 changes: 73 additions & 1 deletion server/lib/dbDataById.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/* eslint-disable no-underscore-dangle */
const log = require('@kth/log')
const { CourseMemo } = require('../models/mainMemoModel')
const { StoredMemoPdfsModel } = require('../models/storedMemoPdfsModel')

/* ****** */
/* ANY BY STATUS AND MemoEndPoint */
Expand All @@ -12,6 +13,21 @@ async function fetchMemoByEndPointAndStatus(memoEndPoint, status) {
const memo = await CourseMemo.findOne({ memoEndPoint, status }) // courseCode
return memo
}
// No need to merge this method to master. This is only for updating old memos
async function fetchMemo(memo) {
if (!memo) throw new Error('Memo must be set')
log.debug('Fetching memo based on ', memo)
const doc = await CourseMemo.findOne(memo)
return doc
}

// No need to merge this method to master. This is only for updating old memos
async function fetchMemoFileById(Id) {
if (!Id) throw new Error('Id must be set')
log.debug('Fetching memo based on ', Id)
const doc = await StoredMemoPdfsModel.findById(Id)
return doc
}

async function getMemoVersion(courseCode, memoEndPoint, version) {
if (!courseCode) throw new Error('courseCode must be set')
Expand All @@ -34,7 +50,7 @@ async function storeNewCourseMemoData(data) {
// ***** USED TO POST NEW COURSE MEMO FIRST DRAFT
if (!data) throw new Error('Trying to post empty/innacurate data in storeNewCourseMemoData')
else {
if (!data.courseCode || !data.semester || !data.ladokRoundIds)
if (!data.courseCode || !data.semester || !data.applicationCodes)
throw new Error('Trying to post data without courseCode or semester or ladokRoundsIds in storeNewCourseMemoData')
data.lastChangeDate = new Date()
const doc = new CourseMemo(data)
Expand All @@ -43,6 +59,58 @@ async function storeNewCourseMemoData(data) {
return result
}
}
// No need to merge this method to master. This is only for updating old memos
async function updateMemo(memo, data) {
// UPPDATERA DRAFT GENOM memoEndPoint
if (memo) {
log.debug('Update of existing memo: ', { memo })

const resultAfterUpdate = await CourseMemo.findOneAndUpdate(
memo,
{ $set: data },
{ maxTimeMS: 100, new: true, useFindAndModify: false }
)
if (resultAfterUpdate && resultAfterUpdate.version) {
log.debug('Updated draft: ', {
version: resultAfterUpdate.version,
memoEndPoint: resultAfterUpdate.memoEndPoint,
memoName: resultAfterUpdate.memoName,
id: resultAfterUpdate.id,
applicationCodes: resultAfterUpdate.applicationCodes,
semester: resultAfterUpdate.semester,
courseCode: resultAfterUpdate.courseCode,
ladokRoundIds: resultAfterUpdate.ladokRoundIds,
})
}
return resultAfterUpdate
}
log.debug('No roundCourseMemoData found for updating it with new data', { memo })
}

// No need to merge this method to master. This is only for updating old memos
async function updateMemoFile(_id, data) {
// UPPDATERA DRAFT GENOM memoEndPoint
if (_id) {
log.debug('Update of existing memo: ', { _id })

const resultAfterUpdate = await StoredMemoPdfsModel.findByIdAndUpdate(
_id,
{ $set: data },
{ maxTimeMS: 100, new: true, useFindAndModify: false }
)
if (resultAfterUpdate && resultAfterUpdate.id) {
log.debug('Updated draft: ', {
id: resultAfterUpdate.id,
koppsRoundId: resultAfterUpdate.koppsRoundId,
semester: resultAfterUpdate.semester,
courseCode: resultAfterUpdate.courseCode,
applicationCode: resultAfterUpdate.applicationCode,
})
}
return resultAfterUpdate
}
log.debug('No roundCourseMemoFileData found for updating it with new data', { _id })
}

async function updateMemoByEndPointAndStatus(memoEndPoint, data, status) {
// UPPDATERA DRAFT GENOM memoEndPoint
Expand Down Expand Up @@ -73,6 +141,10 @@ module.exports = {
getMemoVersion,
fetchMemoByEndPointAndStatus,
storeNewCourseMemoData,
updateMemo,
updateMemoByEndPointAndStatus,
removeCourseMemoDataById,
fetchMemo,
fetchMemoFileById,
updateMemoFile,
}
14 changes: 12 additions & 2 deletions server/lib/dbSeveralDocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ function logInCaseOfPossibleLimit(doc = [], matchingParameters = {}) {
return
}

// No need to merge this method to master. This is only for updating old memos
async function getAllMemos() {
log.debug('Fetching all courseMemos')
const allDocuments = await CourseMemo.find()
if (allDocuments) log.debug('Done fetching memos total: ', allDocuments.length)
logInCaseOfPossibleLimit(allDocuments)
return allDocuments
}

async function getAllMemosByStatus(courseCode, status) {
if (!courseCode) throw new Error('courseCode must be set')
const matchingParameters = { courseCode, status }
Expand Down Expand Up @@ -62,8 +71,8 @@ async function getCourseSemesterUsedRounds(courseCode, semester) {
const finalObj = {
usedRoundsThisSemester: [],
}
await webBasedMemos.map(({ ladokRoundIds }) => finalObj.usedRoundsThisSemester.push(...ladokRoundIds))
await dbMigratedPdfs.map(({ koppsRoundId }) => finalObj.usedRoundsThisSemester.push(...koppsRoundId))
await webBasedMemos.map(({ applicationCodes }) => finalObj.usedRoundsThisSemester.push(...applicationCodes))
await dbMigratedPdfs.map(({ applicationCodes }) => finalObj.usedRoundsThisSemester.push(...applicationCodes))
Copy link
Contributor

Choose a reason for hiding this comment

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

here it looks like it should destruct dbMigratedPdfs applicationCode (singular) if to compare with prev code


log.debug('Successfully got used round ids for', {
courseCode,
Expand Down Expand Up @@ -170,6 +179,7 @@ async function getMemosFromPrevSemester(courseCode, fromSemester) {
}

module.exports = {
getAllMemos,
getAllMemosByStatus,
getCourseSemesterUsedRounds,
getFirstMemosBySemesterAndStatus,
Expand Down
8 changes: 7 additions & 1 deletion server/models/mainMemoModel.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'

const combinedMemoData = require('./combinedMemoData')
const mongoose = require('mongoose')
const combinedMemoData = require('./combinedMemoData')

const schema = mongoose.Schema({
// _id: mongoose.Schema.Types.ObjectId,
Expand All @@ -28,6 +28,12 @@ const schema = mongoose.Schema({
trim: true,
required: [true, 'Enter course rounds'],
},
applicationCodes: {
type: Array,
items: String,
trim: true,
required: [true, 'Enter course application codes'],
},
lastChangeDate: {
type: String,
default: new Date(),
Expand Down
5 changes: 5 additions & 0 deletions server/models/storedMemoPdfsModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ const schema = mongoose.Schema({
type: Array,
default: [],
},
applicationCode: {
type: String,
trim: true,
default: '',
},
})

const StoredMemoPdfsModel = mongoose.model('MemoFile', schema)
Expand Down
11 changes: 9 additions & 2 deletions server/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'

const server = require('@kth/server')
const path = require('path')
const server = require('@kth/server')

// Load .env file in development mode
const nodeEnv = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase()
Expand Down Expand Up @@ -143,8 +143,8 @@ addPaths(
const authByApiKey = passport.authenticate('apikey', { session: false })

// Application specific API enpoints
const { CourseMemo, MixedWebAndPdfMemosList } = require('./controllers')
const { ApiRouter } = require('kth-node-express-routing')
const { CourseMemo, MixedWebAndPdfMemosList } = require('./controllers')

const apiRoute = ApiRouter(authByApiKey)
const paths = getPaths()
Expand All @@ -158,12 +158,14 @@ apiRoute.register(paths.api.getMemoVersion, CourseMemo.getMemoVersion) // step 2
// Get one draft | update it
apiRoute.register(paths.api.getDraftByEndPoint, CourseMemo.getDraftByEndPoint) // step 2: editor, fetch data
apiRoute.register(paths.api.updateCreatedDraft, CourseMemo.putDraftByEndPoint) // step 2: editor, fast update
apiRoute.register(paths.api.updatedMemoWithApplicationCodes, CourseMemo.putApplicationCodesInMemo)

// step 1: choose action, new draft, or copied draft from published memo (same memoEndPoint)
apiRoute.register(paths.api.createDraftByMemoEndPoint, CourseMemo.createDraftByMemoEndPoint)
apiRoute.register(paths.api.copyFromAPublishedMemo, CourseMemo.createDraftByMemoEndPoint)

// // GET ARRAY OF MEMOS BY TYPE AND COURSE CODE
apiRoute.register(paths.api.getAllMemos, CourseMemo.getAllMemos)
apiRoute.register(paths.api.getAllMemosByCourseCodeAndType, CourseMemo.getAllMemosByCourseCodeAndType)
apiRoute.register(paths.api.getCourseSemesterUsedRounds, CourseMemo.getCourseSemesterUsedRounds) // step 1: to show up which rounds already taken
apiRoute.register(paths.api.getMemosStartingFromPrevYearSemester, CourseMemo.getMemosStartingFromPrevSemester) // step 1: to show up which rounds already taken
Expand All @@ -177,7 +179,12 @@ server.use('/', apiRoute.getRouter())
apiRoute.register(paths.api.deleteDraftByMemoEndPoint, CourseMemo.deleteDraftByMemoEndPoint)

// Get list of stored pdf files for kursinfo-web (migrated from kurs-pm-api)
apiRoute.register(paths.api.getStoredMemoPdfList, StoredMemoPdf.fetchAllMemoFiles)
apiRoute.register(paths.api.getStoredMemoPdfListByCourseCode, StoredMemoPdf.getStoredMemoPdfListByCourseCode)
apiRoute.register(
paths.api.updateStoredPdfMemoWithApplicationCodes,
StoredMemoPdf.updateStoredPdfMemoWithApplicationCodes
)
// Get list of stored pdf files together with web-based memos all published for kurs-pm-web (migrated from kurs-pm-api)
apiRoute.register(
paths.api.getPdfAndWebMemosListByCourseCode,
Expand Down
Loading