Skip to content

Commit

Permalink
Merge pull request #5 from ONSdigital/master
Browse files Browse the repository at this point in the history
ONSdigital
  • Loading branch information
pricem14pc authored Dec 16, 2021
2 parents f2eabde + c61a541 commit 2126295
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 100 deletions.
2 changes: 1 addition & 1 deletion launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func serveTemplate(templateName string, data interface{}, w http.ResponseWriter,
}

type page struct {
Schemas surveys.LauncherSchemas
Schemas map[string][]surveys.LauncherSchema
AccountServiceURL string
AccountServiceLogOutURL string
}
Expand Down
87 changes: 33 additions & 54 deletions surveys/surveys.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,9 @@ import (

// LauncherSchema is a representation of a schema in the Launcher
type LauncherSchema struct {
Name string
URL string
}

// LauncherSchemas is a separation of Test and Live schemas
type LauncherSchemas struct {
Business []LauncherSchema
Social []LauncherSchema
Test []LauncherSchema
Other []LauncherSchema
Name string
SurveyType string
URL string
}

// RegisterResponse is the response from the eq-survey-register request
Expand All @@ -46,35 +39,29 @@ type Schema struct {
var eqIDFormTypeRegex = regexp.MustCompile(`^(?P<eq_id>[a-z0-9]+)_(?P<form_type>\w+)`)

// LauncherSchemaFromFilename creates a LauncherSchema record from a schema filename
func LauncherSchemaFromFilename(filename string) LauncherSchema {
func LauncherSchemaFromFilename(filename string, surveyType string) LauncherSchema {
return LauncherSchema{
Name: filename,
Name: filename,
SurveyType: surveyType,
}
}

// GetAvailableSchemas Gets the list of static schemas an joins them with any schemas from the eq-survey-register if defined
func GetAvailableSchemas() LauncherSchemas {
schemaList := LauncherSchemas{}

func GetAvailableSchemas() map[string][]LauncherSchema {
runnerSchemas := getAvailableSchemasFromRunner()
registerSchemas := getAvailableSchemasFromRegister()

for _, launcherSchema := range runnerSchemas {
if strings.HasPrefix(launcherSchema.Name, "test_") {
schemaList.Test = append(schemaList.Test, launcherSchema)
} else if strings.HasPrefix(launcherSchema.Name, "lms_") {
schemaList.Social = append(schemaList.Social, launcherSchema)
} else {
schemaList.Business = append(schemaList.Business, launcherSchema)
}
}
allSchemas := []LauncherSchema{}
allSchemas = append(runnerSchemas, registerSchemas...)

schemaList.Other = getAvailableSchemasFromRegister()
sort.Sort(ByFilename(allSchemas))

sort.Sort(ByFilename(schemaList.Business))
sort.Sort(ByFilename(schemaList.Social))
sort.Sort(ByFilename(schemaList.Test))
schemasBySurveyType := map[string][]LauncherSchema{}
for _, schema := range allSchemas {
schemasBySurveyType[strings.Title(schema.SurveyType)] = append(schemasBySurveyType[strings.Title(schema.SurveyType)], schema)
}

return schemaList
return schemasBySurveyType
}

// ByFilename implements sort.Interface based on the Name field.
Expand Down Expand Up @@ -118,8 +105,9 @@ func getAvailableSchemasFromRegister() []LauncherSchema {
for _, schema := range schemas {
url := schema.Links["self"]
schemaList = append(schemaList, LauncherSchema{
Name: schema.Name,
URL: url.Href,
Name: schema.Name,
URL: url.Href,
SurveyType: "Other",
})
}
}
Expand All @@ -138,6 +126,7 @@ func getAvailableSchemasFromRunner() []LauncherSchema {
url := fmt.Sprintf("%s/schemas", hostURL)

resp, err := clients.GetHTTPClient().Get(url)

if err != nil {
return []LauncherSchema{}
}
Expand All @@ -152,15 +141,17 @@ func getAvailableSchemasFromRunner() []LauncherSchema {
return []LauncherSchema{}
}

var schemaListResponse []string
var schemaMapResponse = map[string][]string{}

if err := json.Unmarshal(responseBody, &schemaListResponse); err != nil {
if err := json.Unmarshal(responseBody, &schemaMapResponse); err != nil {
log.Print(err)
return []LauncherSchema{}
}

for _, schema := range schemaListResponse {
schemaList = append(schemaList, LauncherSchemaFromFilename(schema))
for surveyType, schemas := range schemaMapResponse {
for _, schemaName := range schemas {
schemaList = append(schemaList, LauncherSchemaFromFilename(schemaName, surveyType))
}
}

return schemaList
Expand All @@ -170,25 +161,13 @@ func getAvailableSchemasFromRunner() []LauncherSchema {
func FindSurveyByName(name string) LauncherSchema {
availableSchemas := GetAvailableSchemas()

for _, survey := range availableSchemas.Business {
if survey.Name == name {
return survey
}
}
for _, survey := range availableSchemas.Social {
if survey.Name == name {
return survey
}
}
for _, survey := range availableSchemas.Test {
if survey.Name == name {
return survey
}
}
for _, survey := range availableSchemas.Other {
if survey.Name == name {
return survey
for _, schemasBySurveyType := range availableSchemas {
for _, schema := range schemasBySurveyType {
if schema.Name == name {
return schema
}
}
}
panic("Survey not found")

panic("Schema not found")
}
79 changes: 34 additions & 45 deletions templates/launch.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,18 @@ <h1>Launch a survey</h1>
<label for="schema_name">Schemas</label>
<select id="schema_name" name="schema_name" class="qa-select-schema" onchange="loadMetadata()">
<option selected disabled>Select Schema</option>
<optgroup label="Business Surveys">
{{range .Schemas.Business}}
<option name="{{.Name}}" value="{{.Name}}">{{.Name}}</option>
{{end}}
</optgroup>
<optgroup label="Social Surveys">
{{range .Schemas.Social}}
<option name="{{.Name}}" value="{{.Name}}">{{.Name}}</option>
{{end}}
</optgroup>
<optgroup label="Test Surveys">
{{range .Schemas.Test}}
<option name="{{.Name}}" value="{{.Name}}">{{.Name}}</option>
{{end}}
</optgroup>
<optgroup label="Other Surveys">
{{range .Schemas.Other}}
<option name="{{.Name}}" value="{{.Name}}">{{.Name}}</option>
{{end}}
</optgroup>

{{ range $surveyType, $schemasList := .Schemas }}
<optgroup label="{{ $surveyType }} Surveys">
{{ range $schema := $schemasList }}
<option name="{{ $schema.Name }}" value="{{ $schema.Name }}" data-survey-type="{{ $surveyType }}">{{ $schema.Name }}</option>
{{ end }}
</optgroup>
{{ end }}
</select>
</div>

<div id="business_claims">
<div id="survey_metadata_fields">
</div>

<h3>Survey Metadata</h3>
Expand Down Expand Up @@ -131,16 +119,16 @@ <h3>Runner Data</h3>
// uuidv4: from https://github.com/kelektiv/node-uuid
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.uuidv4=e()}}(function(){return function e(n,r,o){function t(f,u){if(!r[f]){if(!n[f]){var a="function"==typeof require&&require;if(!u&&a)return a(f,!0);if(i)return i(f,!0);var d=new Error("Cannot find module '"+f+"'");throw d.code="MODULE_NOT_FOUND",d}var p=r[f]={exports:{}};n[f][0].call(p.exports,function(e){var r=n[f][1][e];return t(r?r:e)},p,p.exports,e,n,r,o)}return r[f].exports}for(var i="function"==typeof require&&require,f=0;f<o.length;f++)t(o[f]);return t}({1:[function(e,n,r){function o(e,n){var r=n||0,o=t;return[o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],"-",o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]],o[e[r++]]].join("")}for(var t=[],i=0;i<256;++i)t[i]=(i+256).toString(16).substr(1);n.exports=o},{}],2:[function(e,n,r){var o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(o){var t=new Uint8Array(16);n.exports=function(){return o(t),t}}else{var i=new Array(16);n.exports=function(){for(var e,n=0;n<16;n++)0===(3&n)&&(e=4294967296*Math.random()),i[n]=e>>>((3&n)<<3)&255;return i}}},{}],3:[function(e,n,r){function o(e,n,r){var o=n&&r||0;"string"==typeof e&&(n="binary"===e?new Array(16):null,e=null),e=e||{};var f=e.random||(e.rng||t)();if(f[6]=15&f[6]|64,f[8]=63&f[8]|128,n)for(var u=0;u<16;++u)n[o+u]=f[u];return n||i(f)}var t=e("./lib/rng"),i=e("./lib/bytesToUuid");n.exports=o},{"./lib/bytesToUuid":1,"./lib/rng":2}]},{},[3])(3)});

function clearBusinessClaims() {
document.getElementById('business_claims').innerHTML = ""
function clearSurveyMetadataFields() {
document.querySelector('#survey_metadata_fields').innerHTML = ""
}

function includeBusinessClaims(schema_name) {
function includeSurveyMetadataFields(schema_name, survey_type) {
let eqIdValue = schema_name.split('_')[0]
let formTypeValue = schema_name.split('_')[1]

document.getElementById('business_claims').innerHTML = `
<h3>Business Survey Metadata</h3>
document.querySelector('#survey_metadata_fields').innerHTML = `
<h3>${survey_type} Survey Metadata</h3>
<div class="field-container">
<label for="eq_id">eq_id</label>
<input id="eq_id" name="eq_id" type="text" value="${eqIdValue}" class="qa-eq_id">
Expand All @@ -153,23 +141,24 @@ <h3>Business Survey Metadata</h3>
}

function loadMetadata() {
document.getElementById("submit-btn").disabled = true;
document.getElementById("flush-btn").disabled = true;
document.querySelector("#submit-btn").disabled = true;
document.querySelector("#flush-btn").disabled = true;

const schema_name = document.getElementById("schema_name").value
const schema_name = document.querySelector("#schema_name").value
const survey_type = document.querySelector(`#schema_name option[value=${schema_name}]`).dataset.surveyType

if (schema_name.startsWith('test_')) {
clearBusinessClaims()
if (survey_type.toLowerCase() === "test") {
clearSurveyMetadataFields()
} else {
includeBusinessClaims(schema_name)
includeSurveyMetadataFields(schema_name, survey_type)
}

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {

document.getElementById("survey_metadata").innerHTML = ""
document.querySelector("#survey_metadata").innerHTML = ""

var response = JSON.parse(this.responseText);

Expand Down Expand Up @@ -212,26 +201,26 @@ <h3>Business Survey Metadata</h3>
"</div>"
}

document.getElementById("survey_metadata").innerHTML = document.getElementById("survey_metadata").innerHTML + metadataFieldHtml;
document.querySelector("#survey_metadata").innerHTML = document.querySelector("#survey_metadata").innerHTML + metadataFieldHtml;
}
} else {
document.getElementById("survey_metadata").innerHTML = "No metadata required for this survey";
document.querySelector("#survey_metadata").innerHTML = "No metadata required for this survey";
}

document.getElementById("submit-btn").disabled = false;
document.getElementById("flush-btn").disabled = false;
document.querySelector("#submit-btn").disabled = false;
document.querySelector("#flush-btn").disabled = false;

} else {
document.getElementById("survey_metadata").innerHTML = "Failed to load Schema Metadata";
document.querySelector("#survey_metadata").innerHTML = "Failed to load Schema Metadata";
}
}
};
xhttp.open("GET", "/metadata?schema=" + document.getElementById('schema_name').value, true);
xhttp.open("GET", "/metadata?schema=" + document.querySelector("#schema_name").value, true);
xhttp.send();
}

function uuid(el_id) {
document.getElementById(el_id).value = uuidv4();
document.querySelector(`#${el_id}`).value = uuidv4();
}

function numericId(el_id) {
Expand All @@ -240,7 +229,7 @@ <h3>Business Survey Metadata</h3>
for (var i = 16; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
document.getElementById(el_id).value = result;
document.querySelector(`#${el_id}`).value = result;
}

function ruref(el_id) {
Expand All @@ -249,23 +238,23 @@ <h3>Business Survey Metadata</h3>
for (var i = 11; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
result += chars[Math.round(Math.random() * (chars.length - 1))];
document.getElementById(el_id).value = result;
document.querySelector(`#${el_id}`).value = result;
}

function setResponseExpiry(days_offset=7) {
var dt = new Date();
dt.setDate(dt.getDate()+days_offset)
document.getElementById('response_expires_at').value=dt.toISOString().replace(/(\.\d*)/, '').replace(/Z/, '+00:00');
document.querySelector('#response_expires_at').value=dt.toISOString().replace(/(\.\d*)/, '').replace(/Z/, '+00:00');
}

function validateForm() {
validateResponseExpiresAt();
}

function validateResponseExpiresAt() {
response_expires_at = Date.parse(document.getElementById('response_expires_at').value)
response_expires_at = Date.parse(document.querySelector('#response_expires_at').value)
if (isNaN(response_expires_at)) {
document.getElementById('response_expires_at').remove()
document.querySelector('#response_expires_at').remove()
}
}

Expand Down

0 comments on commit 2126295

Please sign in to comment.