Clean up debugging code and commented out experiments

This commit is contained in:
Rachid Mrad 2023-12-20 11:18:51 -05:00
parent 35fda9d124
commit aac5cd698c
No known key found for this signature in database
GPG key ID: EF38E4CEC4A8F3CF
4 changed files with 38 additions and 92 deletions

View file

@ -276,53 +276,27 @@ function enableRelatedWidgetButtons(changeLink, deleteLink, viewLink, elementPk,
viewLink.setAttribute('title', viewLink.getAttribute('title-template').replace('selected item', elementText));
}
// function performDataLookup(e) {
// e.preventDefault(); // Prevent the default form submission
/** An IIFE for admin in DjangoAdmin to listen to clicks on the growth report export button,
* attach the seleted start and end dates to a url that'll trigger the view, and finally
* redirect to that url.
*/
(function (){
// console.log('Form submitted!');
let exportGrowthReportButton = document.getElementById('exportLink');
if (exportGrowthReportButton) {
exportGrowthReportButton.addEventListener('click', function() {
// Get the selected start and end dates
let startDate = document.getElementById('start').value;
let endDate = document.getElementById('end').value;
let exportUrl = document.getElementById('exportLink').dataset.exportUrl;
// var form = document.getElementById("exportDataForm");
// var formData = new FormData(form);
// // Perform an AJAX request to fetch data
// fetch('/admin/', {
// method: 'POST',
// body: formData,
// })
// .then(response => {
// if (!response.ok) {
// console.log(response);
// console.log(`HTTP error! Status: ${response.status}`);
// throw new Error(`HTTP error! Status: ${response.status}`);
// }
// return response.json();
// })
// .then(data => {
// // Handle the data (update the result div, for example)
// document.getElementById("dataResult").innerText = JSON.stringify(data);
// })
// .catch(error => console.error('Error:', error));
// }
(function (){
document.getElementById('exportLink').addEventListener('click', function(event) {
event.preventDefault(); // Prevent the default link behavior
// Build the URL with parameters
exportUrl += "?start_date=" + startDate + "&end_date=" + endDate;
// Get the selected start and end dates
var startDate = document.getElementById('start').value;
var endDate = document.getElementById('end').value;
var exportUrl = document.getElementById('exportLink').dataset.exportUrl;
// Redirect to the export URL
window.location.href = exportUrl;
});
}
// Build the URL with parameters
exportUrl += "?start_date=" + startDate + "&end_date=" + endDate;
// Redirect to the export URL
window.location.href = exportUrl;
});
// document.getElementById('exportDataForm').addEventListener('submit', performDataLookup);
})();

View file

@ -10,6 +10,8 @@
Inputs of type date suck for accessibility.
We'll need to replace those guys with a django form once we figure out how to hook one onto this page.
The challenge is in the path definition in urls. Itdoes NOT like admin/export_data/
See the commit "Review for ticket #999"
{% endcomment %}
<label for="start">Start date:</label>
@ -17,8 +19,7 @@
<label for="end">End date:</label>
<input type="date" id="end" name="trip-end" value="2023-12-19" min="2023-12-01" />
{% comment %} TODO: add a aria label or something {% endcomment %}
<a id="exportLink" data-export-url="{% url 'admin_export_data' %}" href="#" class="button">Export</a>
<button id="exportLink" data-export-url="{% url 'admin_export_data' %}" type="button" class="button">Export</button>
</div>
</div>

View file

@ -1,4 +1,5 @@
import csv
import logging
from datetime import datetime
from registrar.models.domain import Domain
from registrar.models.domain_information import DomainInformation
@ -7,20 +8,20 @@ from django.db.models import Value
from django.db.models.functions import Coalesce
from itertools import chain
logger = logging.getLogger(__name__)
def export_domains_to_writer(writer, columns, sort_fields, filter_condition):
# write columns headers to writer
writer.writerow(columns)
print(f"filter_condition {filter_condition}")
# Get the domainInfos
domainInfos = DomainInformation.objects.filter(**filter_condition).order_by(*sort_fields)
# domain__created_at__gt is in filter_conditions. This means that we're querrying for the growth report and
# need to fetch the domainInfos for the deleted domains. This is an OR situation so we can' combine the filters
# in one query which would be an AND operation.
if 'domain__created_at__gt' in filter_condition:
deleted_domainInfos = DomainInformation.objects.filter(domain__state=Domain.State.DELETED).order_by("domain__deleted_at")
print(f"filtering by deleted {domainInfos}")
deleted_domainInfos = DomainInformation.objects.filter(domain__state=Domain.State.DELETED).order_by("domain__deleted_at")
# Combine the two querysets into a single iterable
all_domainInfos = list(chain(domainInfos, deleted_domainInfos))
else:
@ -150,27 +151,20 @@ def export_data_federal_to_csv(csv_file):
def export_data_growth_to_csv(csv_file, start_date, end_date):
print(f'start_date {start_date}')
print(f'end_date {end_date}')
# Check if start_date is not empty before using strptime
if start_date:
start_date_formatted = datetime.strptime(start_date, "%Y-%m-%d")
print(f'start_date_formatted {start_date_formatted}')
else:
# Handle the case where start_date is missing or empty
print('ON NO')
# TODO: use Nov 1 2023
start_date_formatted = None # Replace with appropriate handling
# Default to a date that's prior to our first deployment
logger.error(f"Error fetching the start date, will default to 12023/1/1")
start_date_formatted = datetime(2023, 11, 1) # Replace with appropriate handling
if end_date:
end_date_formatted = datetime.strptime(end_date, "%Y-%m-%d")
print(f'end_date_formatted {end_date_formatted}')
else:
# Handle the case where start_date is missing or empty
print('ON NO')
# TODO: use now
end_date_formatted = None # Replace with appropriate handling
# Handle the case where end_date is missing or empty
logger.error(f"Error fetching the end date, will default to now()")
end_date_formatted = datetime.now() # Replace with appropriate handling
writer = csv.writer(csv_file)
# define columns to include in export

View file

@ -1,54 +1,31 @@
"""Admin-related views."""
from django.http import HttpResponse, JsonResponse
from django.http import HttpResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from registrar.utility import csv_export
from django.views.generic import TemplateView
from registrar.models import (
Domain,
DomainApplication,
DomainInvitation,
DomainInformation,
UserDomainRole,
)
import logging
logger = logging.getLogger(__name__)
class ExportData(View):
def get_context_data(self, **kwargs):
print('VIE VIE VIE')
context = super().get_context_data(**kwargs)
context['form'] = self.form_class()
context['test'] = 'testing the context'
return context
def get(self, request, *args, **kwargs):
# Get start_date and end_date from the request's GET parameters
# #999: not needed if we switch to django forms
start_date = request.GET.get('start_date', '')
end_date = request.GET.get('end_date', '')
print(start_date)
print(end_date)
# Do something with start_date and end_date, e.g., include in the CSV export logic
# # Federal only
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = f'attachment; filename="growth-from-{start_date}-to-{end_date}.csv"'
# For #999: set export_data_growth_to_csv to return the resulting queryset, which we can then use
# in context to display this data in the template.
csv_export.export_data_growth_to_csv(response, start_date, end_date)
# response = HttpResponse(content_type="text/csv")
# response["Content-Disposition"] = 'attachment; filename="current-federal.csv"'
# csv_export.export_data_growth_to_csv(response)
return response