Skip to content
This repository was archived by the owner on Jan 23, 2025. It is now read-only.

Commit 3445b59

Browse files
authored
Merge pull request #28 from topcoder-platform/terms-script
Create script to sync terms with legacy
2 parents 60de4dd + efcc6eb commit 3445b59

File tree

3 files changed

+138
-2
lines changed

3 files changed

+138
-2
lines changed

config/default.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -72,5 +72,9 @@ module.exports = {
7272
LEGACY_TERMS_NDA_ID: process.env.LEGACY_TERMS_NDA_ID || 21343,
7373
LEGACY_SUBMITTER_ROLE_ID: process.env.LEGACY_SUBMITTER_ROLE_ID || 1,
7474

75-
COPILOT_PAYMENT_TYPE: process.env.COPILOT_PAYMENT_TYPE || 'copilot'
75+
COPILOT_PAYMENT_TYPE: process.env.COPILOT_PAYMENT_TYPE || 'copilot',
76+
77+
// V5 Term UUID
78+
SYNC_V5_TERM_UUID: process.env.SYNC_V5_TERM_UUID || '317cd8f9-d66c-4f2a-8774-63c612d99cd4',
79+
SYNC_V5_WRITE_ENABLED: process.env.SYNC_V5_WRITE_ENABLED === 'true' || false
7680
}

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
"lint:fix": "standard --fix",
1010
"mock-api": "NODE_ENV=test node test/mock/mock",
1111
"test": "nyc --reporter=html --reporter=text mocha test/unit/test.js --timeout 20000 --exit",
12-
"e2e": "nyc --reporter=html --reporter=text mocha test/e2e/test.js --timeout 20000 --exit"
12+
"e2e": "nyc --reporter=html --reporter=text mocha test/e2e/test.js --timeout 20000 --exit",
13+
"sync-terms": "node src/scripts/sync-terms.js"
1314
},
1415
"repository": "https://github.com/topcoder-platform/legacy-challenge-processor",
1516
"author": "TCSCODER",

src/scripts/sync-terms.js

+131
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
require('../bootstrap')
2+
const util = require('util')
3+
const config = require('config')
4+
const request = require('superagent')
5+
const _ = require('lodash')
6+
const logger = require('../common/logger')
7+
const helper = require('../common/helper')
8+
9+
const QUERY_GET_ENTRIES = 'SELECT user_id FROM user_terms_of_use_xref WHERE terms_of_use_id = %d'
10+
const QUERY_INSERT_ENTRY = 'INSERT INTO user_terms_of_use_xref (user_id, terms_of_use_id, create_date, modify_date) VALUES (?, ?, ?, ?)'
11+
12+
/**
13+
* Prepare Informix statement
14+
* @param {Object} connection the Informix connection
15+
* @param {String} sql the sql
16+
* @return {Object} Informix statement
17+
*/
18+
async function prepare (connection, sql) {
19+
// logger.debug(`Preparing SQL ${sql}`)
20+
const stmt = await connection.prepareAsync(sql)
21+
return Promise.promisifyAll(stmt)
22+
}
23+
24+
/**
25+
* Gets the entries from ifx
26+
* @param {Number} termsOfUseId the legacy terms of use ID
27+
*/
28+
async function getTermsFromIfx (termsOfUseId) {
29+
const connection = await helper.getInformixConnection()
30+
let result = null
31+
try {
32+
result = await connection.queryAsync(util.format(QUERY_GET_ENTRIES, termsOfUseId))
33+
} catch (e) {
34+
logger.error(`Error in 'getTermsFromIfx' ${e}`)
35+
throw e
36+
} finally {
37+
await connection.closeAsync()
38+
}
39+
return _.map(result, r => _.toInteger(r.user_id))
40+
}
41+
42+
/**
43+
* Creates a new entry in IFX
44+
* @param {Number} termsOfUseId the legacy terms of use ID
45+
* @param {Number} memberId the member ID
46+
*/
47+
async function createEntry (termsOfUseId, memberId) {
48+
const connection = await helper.getInformixConnection()
49+
let result = null
50+
try {
51+
// await connection.beginTransactionAsync()
52+
const currentDateIso = new Date().toISOString().replace('T', ' ').replace('Z', '').split('.')[0]
53+
const query = await prepare(connection, QUERY_INSERT_ENTRY)
54+
result = await query.executeAsync([termsOfUseId, memberId, currentDateIso, currentDateIso])
55+
// await connection.commitTransactionAsync()
56+
} catch (e) {
57+
logger.error(`Error in 'createEntry' ${e}, rolling back transaction`)
58+
await connection.rollbackTransactionAsync()
59+
throw e
60+
} finally {
61+
logger.info(`Entry for term ${termsOfUseId} and member ${memberId} has been created`)
62+
await connection.closeAsync()
63+
}
64+
return result
65+
}
66+
67+
/**
68+
* Gets all paginated results from `/terms/:id/users`
69+
* @param {String} m2mToken the m2m token
70+
*/
71+
async function getAllTermUsers (m2mToken) {
72+
let allData = []
73+
// get search is paginated, we need to get all pages' data
74+
let page = 1
75+
while (true) {
76+
const result = await request
77+
.get(`${config.V5_TERMS_API_URL}/${config.SYNC_V5_TERM_UUID}/users`)
78+
.query({ page, perPage: 100 })
79+
.set('Authorization', `Bearer ${m2mToken}`)
80+
.set('Content-Type', 'application/json')
81+
.set('Accept', 'application/json')
82+
83+
const users = _.get(result, 'body.result', [])
84+
if (users.length === 0) {
85+
break
86+
}
87+
allData = allData.concat(users)
88+
page += 1
89+
if (result.headers['x-total-pages'] && page > Number(result.headers['x-total-pages'])) {
90+
break
91+
}
92+
}
93+
return allData
94+
}
95+
96+
/**
97+
* Application entry point
98+
*/
99+
async function main () {
100+
try {
101+
const m2mToken = await helper.getM2MToken()
102+
logger.info(`Fetching details for term ${config.SYNC_V5_TERM_UUID}`)
103+
const res = await helper.getRequest(`${config.V5_TERMS_API_URL}/${config.SYNC_V5_TERM_UUID}`, m2mToken)
104+
const legacyTermId = _.get(res, 'body.legacyId')
105+
if (!legacyTermId) {
106+
throw new Error(`Term ${config.SYNC_V5_TERM_UUID} does not have a legacyId`)
107+
}
108+
logger.info(`Fetching users that have agreed to ${config.SYNC_V5_TERM_UUID}`)
109+
const v5Entries = await getAllTermUsers(m2mToken)
110+
logger.debug(`Found ${v5Entries.length} users`)
111+
112+
logger.info(`Fetching users from legacy for ID: ${legacyTermId}`)
113+
const legacyIntries = await getTermsFromIfx(legacyTermId)
114+
logger.debug(`Found ${legacyIntries.length} users`)
115+
for (const memberId of v5Entries) {
116+
if (legacyIntries.indexOf(memberId) === -1) {
117+
if (config.SYNC_V5_WRITE_ENABLED) {
118+
await createEntry(legacyTermId, memberId)
119+
} else {
120+
const currentDateIso = new Date().toISOString().replace('T', ' ').replace('Z', '').split('.')[0]
121+
logger.debug(`INSERT INTO user_terms_of_use_xref (user_id, terms_of_use_id, create_date, modify_date) VALUES (${legacyTermId}, ${memberId}, ${currentDateIso}, ${currentDateIso})`)
122+
}
123+
}
124+
}
125+
logger.info('Completed!')
126+
} catch (e) {
127+
logger.logFullError(e)
128+
}
129+
}
130+
131+
main()

0 commit comments

Comments
 (0)