Skip to content

Commit

Permalink
Undo revert (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
paularintaharri authored Mar 31, 2023
1 parent 6c003cb commit 42c44b8
Show file tree
Hide file tree
Showing 9 changed files with 594 additions and 0 deletions.
45 changes: 45 additions & 0 deletions migrations/1671010308952_create-agegroup-completed-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable camelcase */

exports.shorthands = undefined

exports.up = (pgm) => {
pgm.createType('agegroup_state', ['COMPLETED'])
pgm.createTable('completed_agegroup_entries', {
id: 'id',
user_guid: {
type: 'text',
notNull: true,
},
created_at: {
type: 'timestamp',
default: pgm.func('NOW()'),
},
created_by: {
type: 'text',
notNull: true,
},
agegroup_guid: {
type: 'text',
notNull: true,
},
completion_status: {
type: 'agegroup_state',
notNull: true,
},
})
}

exports.down = async (pgm) => {
// Make sure we don't have any data we can lose in the table when doing a migrate down
const hasRows =
(await pgm.db.query('SELECT id FROM completed_agegroup_entries')).rows
.length > 0
if (hasRows) {
throw new Error(`
Migrate down aborted - possible lose of data if completed_agegroup_entries table is dropped: \n
Make sure you've emptied the table before dropping.
`)
}
pgm.dropTable('completed_agegroup_entries')
pgm.dropType('agegroup_state')
}
49 changes: 49 additions & 0 deletions src/database/ageGroups.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { db } from './index'
import { createNotification } from './notifications'

export async function postAgegroupEntry(ageGroupEntry) {
const { user_guid, created_by, agegroup_guid, completed, group_leader_name } =
ageGroupEntry

try {
// Create an entry for the agegroup entry state change
const data = await db.one(
'INSERT INTO completed_agegroup_entries(user_guid, created_by, agegroup_guid, completion_status) VALUES ($1, $2, $3, $4) RETURNING id',
[user_guid, created_by, agegroup_guid, completed]
)

const entry = await db.one(
'SELECT agegroup_guid, completion_status FROM completed_agegroup_entries WHERE id = $1',
data.id
)

// Create a notification about the state change
const notification = await createNotification({
itemGuid: agegroup_guid,
itemType: 'AGE_GROUP',
notificationType: completed,
userGuid: user_guid,
createdBy: created_by,
groupLeaderName: group_leader_name,
})
if (!notification) {
throw new Error('Failed to create a notification.')
}

return entry
} catch (error) {
console.error('post agegroup entry - error: ', error)
}
}

export async function getAgeGroupEntries(user_guid) {
try {
const data = await db.any(
'SELECT agegroup_guid, completion_status FROM completed_agegroup_entries WHERE user_guid = $1 ORDER BY created_at ASC',
user_guid.toString()
)
return data
} catch (error) {
console.log('error', error)
}
}
12 changes: 12 additions & 0 deletions src/groups.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getGroupMembers,
} from './kuksa'
import { getTaskEntries, getTaskGroupEntries } from './database'
import { getAgeGroupEntries } from './database/ageGroups'

async function getMemberData(groupMembers) {
return Promise.all(
Expand All @@ -13,6 +14,9 @@ async function getMemberData(groupMembers) {
const allMemberTaskGroupEntries = await getTaskGroupEntries(
groupMember.id.id
)
const allMemberAgeGroupEntries = await getAgeGroupEntries(
groupMember.id.id
)
const taskEntries = allMemberTaskEntries.reduce((acc, task) => {
acc[task.task_guid] = task.completion_status
return acc
Expand All @@ -24,6 +28,13 @@ async function getMemberData(groupMembers) {
},
{}
)
const ageGroupEntries = allMemberAgeGroupEntries.reduce(
(acc, agegroup) => {
acc[agegroup.agegroup_guid] = agegroup.completion_status
return acc
},
{}
)
return Object.assign(
{},
{
Expand All @@ -33,6 +44,7 @@ async function getMemberData(groupMembers) {
groupMember.name.firstname + ' ' + groupMember.name.lastname,
memberTasks: taskEntries,
memberTaskGroups: taskgroupEntries,
memberAgeGroups: ageGroupEntries,
}
)
})
Expand Down
40 changes: 40 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import taskGroups from './taskGroups'
import { deleteOldNotifications } from './database/notifications'
import https from 'https'
import fs from 'fs'
import { postAgegroupEntry, getAgeGroupEntries } from './database/ageGroups'

require('dotenv').config()

Expand Down Expand Up @@ -159,6 +160,45 @@ const main = async () => {
})
})

app.post(
'/groups/mark-agegroup-done/:agegroup_guid',
isLoggedIn,
isGroupLeader,
async (req, res) => {
try {
const userData = req.body
const promises = Object.values(userData.groups).map((userIds) => {
const promises = userIds.map((user_guid) =>
Promise.resolve(
postAgegroupEntry({
user_guid: Number(user_guid),
created_by: Number(req.user.membernumber),
agegroup_guid: req.params.agegroup_guid,
completed: 'COMPLETED',
group_leader_name: userData.group_leader_name,
})
)
)
return promises
})
const iterablePromises = [].concat.apply([], promises)
const entries = await Promise.all(iterablePromises)
res.json(entries).status(200)
} catch (e) {
res.status(e.statusCode).send(e.message)
}
}
)

app.get('/agegroup-entries', isLoggedIn, async (req, res) => {
try {
const entries = await getAgeGroupEntries(req.user.membernumber)
res.json(entries).status(200)
} catch (e) {
res.status(e.statusCode).send(e.message)
}
})

app.post('/task-entry', isLoggedIn, async (req, res) => {
try {
const data = req.body
Expand Down
35 changes: 35 additions & 0 deletions src/scripts/delete-activities-by-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const fs = require('fs')
const path = require('path')
require('dotenv').config()
const pgp = require('pg-promise')()

const db = pgp(process.env.DATABASE_URL)
const unusedActivities = require('./get-unused-activities')

async function deleteTaskEntriesById(task_guid) {
try {
const data = await db.any(
'DELETE FROM task_entries WHERE task_guid = $1 RETURNING task_guid',
[task_guid.toString()]
)

console.log('entries successfully deleted', data)
return data
} catch (error) {
console.log('delete taskentries - error', error)
}
}

async function main() {
const oldIds = unusedActivities.main()
const resolvedIds = await oldIds
resolvedIds.forEach((task_guid) => {
try {
return deleteTaskEntriesById(task_guid)
} catch (error) {
console.log('error while migrating', error)
}
})
}

main()
106 changes: 106 additions & 0 deletions src/scripts/get-unused-activities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
require('dotenv').config()
const fs = require('fs')
var path = require('path')
var request = require('request-promise')

const DBURL = process.env.POF_BACKEND_STAGING
async function fetchActivitiesFromStrapi() {
try {
const countRes = await request(`${DBURL}/activities/count?_locale=fi`)
const activities = await request(`${DBURL}/activities?_limit=${countRes}`)

return activities
} catch (e) {
console.log(`Error getting activities: ${e}`)
return null
}
}

const sortArraysAscending = (array) => {
return array.sort(function (a, b) {
return a - b
})
}

const uniqueValues = (value, index, self) => {
return self.indexOf(value) === index
}

function writeUnusedActivitiesToTxtFile(ids) {
const writeStream = fs.createWriteStream('unusedActivityIds.txt')
const pathName = writeStream.path

// write each value of the array on the file breaking line
ids.forEach((value) => writeStream.write(`${value}\n`))

writeStream.on('finish', () => {
console.log(`wrote all the array data to file ${pathName}`)
})
writeStream.on('error', (err) => {
console.error(`There is an error writing the file ${pathName} => ${err}`)
})
writeStream.end()
}

async function main() {
// Change filename below to match the csv-file with migration activities
const filePath = path.join(__dirname, './aktiviteetti_aa.csv')
// Read CSV
let file = fs.readFileSync(filePath, { encoding: 'utf-8' }, function (err) {
console.log(err)
})

// Split on row
file = file.split('\n')

// Get first row for column headers
headers = file.shift().split(',')

let json = []
file.forEach(function (row) {
// Loop through each row
tmp = {}
row = row.split(',')
for (let i = 0; i < headers.length; i++) {
tmp[headers[i]] = row[i]
}
// Add object to list
json.push(tmp)
})

const activityIdsFromKuksa = json.map((row) => {
return row.activities_Partioaktiviteetti_Yhdistä1_aktiviteetti_View_id
})

const uniqueIdValuesInOrder = sortArraysAscending(
activityIdsFromKuksa.filter(uniqueValues)
)

const activityidsFromStrapiPromise = fetchActivitiesFromStrapi().then(
function (activities) {
const activitiesJson = JSON.parse(activities)
const ids = activitiesJson.map((activity) => {
return activity.id.toString()
})
return sortArraysAscending(ids)
}
)

const activityIdsFromStrapi = await Promise.resolve(
activityidsFromStrapiPromise
)

const oldIdsFromKuksa = uniqueIdValuesInOrder.filter(
(x) => !activityIdsFromStrapi.includes(x)
)

if (oldIdsFromKuksa.length) {
writeUnusedActivitiesToTxtFile(oldIdsFromKuksa)
return oldIdsFromKuksa
} else {
console.log('No old ids')
}
}

main()
module.exports = { main }
Loading

0 comments on commit 42c44b8

Please sign in to comment.