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

[58] Export Submissions #360

Open
wants to merge 14 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
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
16 changes: 16 additions & 0 deletions app/assets/stylesheets/application.sass.scss
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,19 @@ dialog::backdrop {
.usa-combo-box .border-secondary + input {
border: 1px solid red;
}

.usa-prose .usa-checkbox {
.usa-checkbox__label::before {
border-radius: 0 !important;
left: 1rem !important;
}

.usa-checkbox__input:checked + .usa-checkbox__label::before {
border-radius: 0 !important;
}

.usa-checkbox__label {
padding-left: 3rem !important;
text-align: left !important;
}
}
12 changes: 12 additions & 0 deletions app/controllers/phases_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ def submissions
render_response
end

def export_submissions
authorize_user('challenge_manager')
service = ExportSubmissionsService.new(@phase, params[:options])
csv_data = service.export

respond_to do |format|
format.csv do
send_data(csv_data, type: 'text/csv')
end
end
end

private

def set_phase
Expand Down
101 changes: 101 additions & 0 deletions app/javascript/controllers/export_submissions_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
static targets = ["modal"]
static values = {
phaseId: String,
challengeTitle: String,
phaseNumber: String
}

connect() {
this.modalTarget.addEventListener('click', this.handleOutsideClick.bind(this));
}

disconnect() {
this.modalTarget.removeEventListener('click', this.handleOutsideClick.bind(this));
}

open(event) {
event.preventDefault();
this.phaseIdValue = event.currentTarget.dataset.phaseId;
this.challengeTitleValue = event.currentTarget.dataset.challengeTitle;
this.phaseNumberValue = event.currentTarget.dataset.phaseNumber;
this.modalTarget.showModal();
}

close() {
this.modalTarget.close();
}

handleOutsideClick = (event) => {
if (event.target === this.modalTarget) {
this.close();
}
}

getSelectedOptions() {
return Array.from(
document.querySelectorAll('input[name="export-options"]:checked')
).map(checkbox => checkbox.value);
}

createFilename(option, sanitizedTitle) {
return `${sanitizedTitle}_${option}_${new Date().toISOString().split('T')[0]}.csv`;
}

sanitizeTitle() {
const title = `${this.challengeTitleValue} - Phase ${this.phaseNumberValue}`;
return title.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
}

async downloadCSV(blob, filename) {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}

async fetchExportData(option) {
const params = new URLSearchParams({ options: option, format: 'csv' });
const response = await fetch(`/phases/${this.phaseIdValue}/export_submissions?${params}`, {
method: 'GET',
headers: {
'Accept': 'text/csv',
'X-Requested-With': 'XMLHttpRequest'
}
});

if (!response.ok) throw new Error('Export failed');
return response.blob();
}

async exportSubmissions(event) {
event.preventDefault();
const selectedOptions = this.getSelectedOptions();

if (selectedOptions.length === 0) {
alert('Please select at least one export option');
return;
}

try {
const sanitizedTitle = this.sanitizeTitle();

for (const option of selectedOptions) {
const blob = await this.fetchExportData(option);
const filename = this.createFilename(option, sanitizedTitle);
await this.downloadCSV(blob, filename);
}

this.close();
} catch (error) {
console.error('Export failed:', error);
alert('Export failed. Please try again.');
}
}
}
3 changes: 3 additions & 0 deletions app/javascript/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ application.register("evaluation-criteria", EvaluationCriteriaController);
import EvaluationFormController from "./evaluation_form_controller";
application.register("evaluation-form", EvaluationFormController);

import ExportSubmissionsController from "./export_submissions_controller";
application.register("export-submissions", ExportSubmissionsController);

import FormValidationController from "./form_validation_controller";
application.register("form-validation", FormValidationController);

Expand Down
92 changes: 92 additions & 0 deletions app/services/export_submissions_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# frozen_string_literal: true

require 'csv'

# This service handles exporting submissions and evaluations into a csv.
class ExportSubmissionsService
def initialize(phase, options)
@phase = phase
@options = options&.split(',') || []
end

def export
if @options.include?('submissions') && @options.include?('evaluations')
{
submissions: create_submissions_csv,
evaluations: create_evaluations_csv
}
elsif @options.include?('submissions')
create_submissions_csv
elsif @options.include?('evaluations')
create_evaluations_csv
end
end

private

def sanitize_text(text)
ActionView::Base.full_sanitizer.sanitize(text.to_s)
end

# submission csv
def submissions_headers
[
'Submission ID', 'Title', 'Brief Description', 'Description',
'External URL', 'Status', 'Created At', 'Updated At',
'Eligible for Evaluation', 'Selected to Advance'
]
end

def submission_data(submission)
[
submission.id,
submission.title || '',
sanitize_text(submission.brief_description) || '',
sanitize_text(submission.description) || '',
submission.external_url || '',
submission.status,
submission.inserted_at,
submission.updated_at,
submission.eligible_for_evaluation? ? 'Eligible' : 'Not Eligible',
submission.selected_to_advance? ? 'Selected' : 'Not Selected'
]
end

def create_submissions_csv
CSV.generate(headers: true) do |csv|
csv << submissions_headers
@phase.submissions.find_each do |submission|
csv << submission_data(submission)
end
end
end

# evaluations csv
def evaluations_headers
[
'Submission ID', 'Evaluator Name', 'Evaluator Email',
'Evaluation Status', 'Score'
]
end

def evaluation_data(submission, assignment)
[
submission.id,
"#{assignment.evaluator.first_name || ''} #{assignment.evaluator.last_name || ''}",
assignment.evaluator.email,
assignment.evaluation_status.to_s.titleize,
assignment.evaluation&.total_score || ''
]
end

def create_evaluations_csv
CSV.generate(headers: true) do |csv|
csv << evaluations_headers
@phase.submissions.includes(evaluator_submission_assignments: [:evaluator, :evaluation]).find_each do |submission|
submission.evaluator_submission_assignments.each do |assignment|
csv << evaluation_data(submission, assignment)
end
end
end
end
end
3 changes: 1 addition & 2 deletions app/views/evaluator_submission_assignments/index.html.erb
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<div data-controller="unassign-evaluator-submission-modal"
data-unassign-evaluator-submission-modal-challenge-id-value="<%= @challenge.id %>"
data-unassign-evaluator-submission-modal-phase-id-value="<%= @phase.id %>"
data-page="evaluator-submissions">
data-unassign-evaluator-submission-modal-phase-id-value="<%= @phase.id %>" >

<%= render 'shared/back_link', path: phase_evaluators_path(@phase) %>

Expand Down
115 changes: 115 additions & 0 deletions app/views/phases/_export_submissions.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<div data-controller="export-submissions">
<div class="grid-container padding-x-0">
<div class="grid-row flex-justify-end">
<div class="grid-col-6 display-flex flex-justify-end padding-top-105">
<nav aria-label="export submissions" class="tablet:usa-nav display-flex">
<ul class="usa-nav__primary usa-accordion">
<li class="radius-md">
<button
type="button"
class="usa-accordion__button"
aria-expanded="false"
style="background-color: white; border: none; padding: 0;"
data-action="click->export-submissions#open"
data-phase-id="<%= @phase.id %>"
data-challenge-title="<%= @challenge.title %>"
data-phase-number="<%= phase_number(@challenge, @phase) %>"
>
<span class="text-primary text-bold font-sans-md text-underline" style="text-decoration-thickness: 2px;">Export</span>
<%= image_tag "images/usa-icons/file_download.svg",
class: "usa-icon icon-down",
alt: "",
aria: { hidden: true } %>
</button>
</li>
</ul>
</nav>
</div>
</div>
</div>

<dialog
id="export-submissions-modal"
data-export-submissions-target="modal"
aria-labelledby="export-modal-heading"
aria-describedby="export-modal-description"
class="radius-lg"
>
<div class="usa-modal__content maxw-mobile-lg">
<div class="usa-modal__main display-flex flex-column flex-align-center text-center">
<h2 class="usa-modal__heading maxw-card-lg margin-x-auto" id="export-modal-heading">
Please select what data you would like to export.
</h2>
<p id="export-modal-description" class="usa-sr-only">
Select from export submissions options submissions CSV, submission attachments zip, and evaluations CSV.
</p>
<div class="usa-prose margin-y-2">
<fieldset class="usa-fieldset">
<legend class="usa-sr-only">Export submissions options</legend>

<div class="usa-checkbox">
<input
class="usa-checkbox__input"
id="submissions-csv"
type="checkbox"
name="export-options"
value="submissions"
/>
<label class="usa-checkbox__label padding-2 radius-md border-2px border-base-light width-full" for="submissions-csv">
Submissions (CSV)
</label>
</div>

<div class="usa-checkbox margin-top-2">
<input
class="usa-checkbox__input"
id="attachments-zip"
type="checkbox"
name="export-options"
value="attachments"
disabled
/>
<label class="usa-checkbox__label padding-2 radius-md border-2px border-base-light width-full" for="attachments-zip">
Submission attachments (zip)
</label>
</div>

<div class="usa-checkbox margin-top-2">
<input
class="usa-checkbox__input"
id="evaluations-csv"
type="checkbox"
name="export-options"
value="evaluations"
/>
<label class="usa-checkbox__label padding-2 radius-md border-2px border-base-light width-full" for="evaluations-csv">
Evaluations (CSV)
</label>
</div>
</fieldset>
</div>
<div class="usa-modal__footer">
<ul class="usa-button-group display-flex flex-column">
<li class="usa-button-group__item margin-bottom-2">
<button
type="button"
class="usa-button"
data-action="click->export-submissions#exportSubmissions"
>
Export
</button>
</li>
<li class="usa-button-group__item">
<a
href="#"
class="usa-link"
data-action="click->export-submissions#close">
Back
</a>
</li>
</ul>
</div>
</div>
</div>
</dialog>
</div>
4 changes: 2 additions & 2 deletions app/views/phases/_sort_and_filter.html.erb
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<div class="grid-container padding-x-0">
<div class="grid-row">
<div class="grid-col-12 display-flex flex-column flex-align-start padding-top-105">
<div class="grid-col-6 display-flex flex-column flex-align-start padding-top-105">
<nav aria-label="Sort and filter options" class="tablet:usa-nav display-flex" data-controller="sort-filter-menu">
<ul class="usa-nav__primary usa-accordion" style="position: relative;">
<li class="radius-md">
<li class="radius-md text-no-wrap">
<button
type="button"
class="usa-accordion__button"
Expand Down
Loading
Loading