Skip to content

Instantly share code, notes, and snippets.

@chrisekelley
Created February 4, 2021 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisekelley/d6b3a45e2edffa3856c5a07387836ed4 to your computer and use it in GitHub Desktop.
Save chrisekelley/d6b3a45e2edffa3856c5a07387836ed4 to your computer and use it in GitHub Desktop.
setLocation and generateCase
async setLocation() {
// Get a Device to set the location
const device = await this.deviceService.getDevice()
if (device) {
let syncLocation = device.syncLocations[0]
let locationSetting = syncLocation.value.slice(-1).pop()
let location = {
[`${locationSetting.level}`]: locationSetting.value
}
return location
}
}
async generateCases(numberOfCases, registrationFormName) {
let customGenerators, customSubstitutions
// try {
// const genny = require(`${groupPath}/custom-generators.js`)
// console.log("customGenerators: " + JSON.stringify(genny))
// customGenerators = genny.customGenerators
// customSubstitutions = genny.customSubstitutions
// } catch(e) {
// customGenerators = {}
// customSubstitutions = null
// console.error(e.message);
// console.error("custom-generators.js not found. No custom work for you!");
// }
if (!registrationFormName) {
registrationFormName = 'registration-role-1'
console.log("expecting a registration form called " + registrationFormName + ". If the case uses a different name, append it to this command.")
}
let numberOfCasesCompleted = 0
let firstnames = ['Mary', 'Jennifer', 'Lisa', 'Sandra ','Michelle',
'Patricia', 'Maria','Nancy','Donna','Laura', 'Linda','Susan','Karen',
'Carol','Sarah','Barbara','Margaret','Betty','Ruth','Kimberly','Elizabeth',
'Dorothy','Helen','Sharon','Deborah']
let surnames = ['Smith','Johnson','Williams','Jones','Brown','Davis','Miller',
'Wilson','Moore','Taylor','Anderson','Thomas','Jackson','White','Harris',
'Martin','Thompson','Garcia','Martinez','Robinson','Clark','Rodriguez','Lewis','Lee','Walker']
while (numberOfCasesCompleted < numberOfCases) {
const templateDocs = await this.export()
const caseDoc = templateDocs.find(doc => doc['type'] === 'case')
// Change the case's ID.
const caseId = UUID()
caseDoc._id = caseId
// note that participant_id and participantUuid are different!
const participant_id = Math.round(Math.random() * 1000000)
const participantUuid = UUID()
let barcode_data = {
"participant_id": participant_id,
"treatment_assignment": "Experiment",
"bin-mother": "A",
"bin-infant": "B",
"sub-studies": {"S1": true, "S2": false, "S3": false, "S4": true}
}
let tangerineModifiedOn = new Date();
// tangerineModifiedOn is set to numberOfCasesCompleted days before today, and its time is set based upon numberOfCasesCompleted.
tangerineModifiedOn.setDate(tangerineModifiedOn.getDate() - numberOfCasesCompleted);
tangerineModifiedOn.setTime(tangerineModifiedOn.getTime() - (numberOfCases - numberOfCasesCompleted))
const location = await this.setLocation();
console.log("location: " + JSON.stringify(location));
if (!location) {
throw new Error('No location! You need to create at least one Device Registration so that the generated docs will sync.')
}
const day = String(tangerineModifiedOn.getDate()).padStart(2, '0');
const month = String(tangerineModifiedOn.getMonth() + 1).padStart(2, '0');
const year = tangerineModifiedOn.getFullYear();
const date = year + '-' + month + '-' + day;
let subs = {
"runOnce": {}
}
subs['firstname'] = () => firstnames[this.getRandomInt(0, firstnames.length + 1)]
subs['surname'] = () => surnames[this.getRandomInt(0, surnames.length + 1)]
subs['tangerineModifiedOn'] = tangerineModifiedOn
subs['day'] = day
subs['month'] = month
subs['year'] = year
subs['date'] = date
subs['participant_id'] = participant_id
subs['participantUuid'] = participantUuid
let allSubs = {...subs, ...customGenerators}
if (customSubstitutions) {
// assign any customSubstitutions where runOnce is set.
for (const docTypeDefinition in customSubstitutions) {
// console.log(`docTypeDefinition: ${docTypeDefinition}: ${JSON.stringify(customSubstitutions[docTypeDefinition])}`);
if (customSubstitutions[docTypeDefinition]['substitutions']) {
const substitutions = customSubstitutions[docTypeDefinition]['substitutions']
for (const functionDefinition in substitutions) {
// console.log(`functionDefinition: ${functionDefinition}: ${JSON.stringify(substitutions[functionDefinition])}`);
if (substitutions[functionDefinition].runOnce) {
subs.runOnce[substitutions[functionDefinition].functionName] = allSubs[substitutions[functionDefinition].functionName]()
}
}
}
}
}
let caseMother = {
_id: caseId,
tangerineModifiedOn: subs['tangerineModifiedOn'],
"participants": [{
"id": participantUuid,
"caseRoleId": "role-1",
"data": {
"firstname": subs.runOnce['firstname'] ? subs.runOnce['firstname'] : subs['firstname'](),
"surname": subs.runOnce['surname'] ? subs.runOnce['surname'] : subs['surname'](),
"participant_id": subs.runOnce['participant_id'] ? subs.runOnce['participant_id'] : subs['participant_id']
}
}],
}
// console.log("motherId: " + caseId + " participantId: " + participant_id + " surname: " + subs.surname);
console.log("caseMother: " + JSON.stringify(caseMother));
Object.assign(caseDoc, caseMother);
if (customSubstitutions) {
const caseDocSubs = customSubstitutions.find(doc => doc.type === 'caseDoc')
if (caseDocSubs && caseDocSubs['substitutions']) {
for (const substitution of caseDocSubs['substitutions']) {
console.log(substitution);
// TODO: finish this...
}
}
} else {
caseDoc.items[0].inputs[0].value = subs['participant_id'];
// caseDoc.items[0].inputs[2].value = enrollment_date;
if (caseDoc.items[0].inputs.length > 3) {
caseDoc.items[0].inputs[1].value = subs['participant_id'];
caseDoc.items[0].inputs[2].value = subs['firstname']();
caseDoc.items[0].inputs[3].value = subs['surname']();
}
caseDoc.location = location
}
for (let caseEvent of caseDoc['events']) {
const caseEventId = UUID()
caseEvent.id = caseEventId
caseEvent.caseId = caseId
for (let eventForm of caseEvent.eventForms) {
eventForm.id = UUID()
eventForm.caseId = caseId
eventForm.caseEventId = caseEventId
if (eventForm.eventFormDefinitionId !== "enrollment-screening-form") {
eventForm.participantId = participantUuid
}
// Some eventForms might not have a corresponding form response.
if (eventForm.formResponseId) {
const originalId = `${eventForm.formResponseId}`
const newId = UUID()
// Replace originalId with newId in both the reference to the FormResponse doc and the FormResponse doc itself.
eventForm.formResponseId = newId
const formResponse = templateDocs.find(doc => doc._id === originalId)
if (!formResponse) {
debugger
}
formResponse._id = newId
formResponse.location = location
formResponse['caseEventId'] = caseEventId
formResponse['caseId'] = caseId
formResponse['eventFormId'] = eventForm.id
if (eventForm.eventFormDefinitionId !== "enrollment-screening-form") {
formResponse['participantId'] = participantUuid
}
}
}
}
caseDoc.location = await this.setLocation.call(this);
if (customSubstitutions) {
const demoDocSubs = customSubstitutions.find(doc => doc.type === 'demoDoc')
const demoDoc = templateDocs.find(doc => doc.form.id === demoDocSubs.formId)
let inputs = []
demoDoc.items.forEach(item => inputs = [...inputs, ...item.inputs])
if (demoDocSubs['substitutions']) {
for (const [inputName, functionDefinition] of Object.entries(demoDocSubs['substitutions'])) {
let foundInput = inputs.find(input => {
if (input.name === inputName) {
return input
}
})
if (foundInput) {
let functionName = functionDefinition['functionName']
if (functionDefinition['runOnce']) {
let val = allSubs.runOnce[functionDefinition['functionName']]
// console.log("allSubs.runOnce: " + JSON.stringify(allSubs.runOnce))
// console.log("Assigned function name using runOnce value: " + functionDefinition.functionName + " to value: " + val)
foundInput['value'] = val
} else {
let val = allSubs[functionName]()
// console.log("Assigned function name use live generated value: " + functionName + " to value: " + val)
foundInput['value'] = val
}
}
}
}
} else {
// modify the demographics form - s01a-participant-information-f254b9
const demoDoc = templateDocs.find(doc => doc.form.id === registrationFormName)
if (typeof demoDoc !== 'undefined') {
demoDoc.items[1].inputs[1].value = subs['participant_id'];
demoDoc.items[1].inputs[2].value = subs['date'];
// "id": "randomization",
// demoDoc.items[10].inputs[1].value = barcode_data;
// demoDoc.items[10].inputs[2].value = subs.participant_id;
// demoDoc.items[10].inputs[7].value = enrollment_date;
// "id": "participant_information",
if (demoDoc.items[0]) {
console.log("Filling out firstname and surname: " + subs['firstname']() + ' ' + subs['surname']())
demoDoc.items[0].inputs[0].value = subs['firstname']();
demoDoc.items[0].inputs[1].value = subs['surname']();
} else {
console.log("Unable to substitute the firstname and surname; they are expected to be ar demoDoc.items[0].inputs[0]")
}
}
}
for (let doc of templateDocs) {
// @ts-ignore
// sometimes doc is false...
if (doc !== false) {
try {
delete doc._rev
await this.tangyFormService.saveResponse(doc)
} catch (e) {
console.log('Error: ' + e)
}
}
}
numberOfCasesCompleted++
console.log("motherId: " + caseId + " participantId: " + participant_id + " Completed " + numberOfCasesCompleted + " of " + numberOfCases);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment