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: sort responses for csv download according to creation date #2028

Merged
merged 3 commits into from
Jun 8, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/public/modules/forms/helpers/CsvMergedHeadersGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class CsvMergedHeadersGenerator extends CsvGenerator {
super(expectedNumberOfRecords, numOfMetaDataRows)

this.hasBeenProcessed = false
this.hasBeenSorted = false
this.fieldIdToQuestion = new Map()
this.fieldIdToNumCols = {}
this.unprocessed = []
Expand Down Expand Up @@ -121,10 +122,18 @@ class CsvMergedHeadersGenerator extends CsvGenerator {
}
this.addLine(row)
})

this.hasBeenProcessed = true
}

/**
* Sorts unprocessed records from oldest to newest
*/
sort() {
if (this.hasBeenSorted) return
this.unprocessed.sort((a, b) => this._dateComparator(a.created, b.created))
this.hasBeenSorted = true
}

/**
* Add meta-data as first three rows of the CSV. If there is already meta-data
* added, it will be replaced by the latest counts.
Expand All @@ -145,9 +154,29 @@ class CsvMergedHeadersGenerator extends CsvGenerator {
* @param {string} filename
*/
downloadCsv(filename) {
this.sort()
this.process()
this.triggerFileDownload(filename)
}

/**
* Comparator for dates
* @param string firstDate
* @param string secondDate
*/
_dateComparator(firstDate, secondDate) {
// cast to Asia/Singapore to ensure both dates are of the same timezone
const first = moment(firstDate).tz('Asia/Singapore')
const second = moment(secondDate).tz('Asia/Singapore')
if (first.isBefore(second)) {
return -1
} else if (first.isAfter(second)) {
return 1
} else {
// dates are the same
return 0
}
}
}

module.exports = CsvMergedHeadersGenerator