Add API to select SO information

This commit is contained in:
zandercymatics 2024-08-08 09:17:28 -06:00
parent b092fc61b3
commit a2f87c7084
No known key found for this signature in database
GPG key ID: FF4636ABEC9682B7
5 changed files with 103 additions and 23 deletions

View file

@ -511,11 +511,21 @@ function initializeWidgetOnList(list, parentId) {
var actionNeededReasonDropdown = document.querySelector("#id_action_needed_reason"); var actionNeededReasonDropdown = document.querySelector("#id_action_needed_reason");
var actionNeededEmail = document.querySelector("#id_action_needed_reason_email"); var actionNeededEmail = document.querySelector("#id_action_needed_reason_email");
var readonlyView = document.querySelector("#action-needed-reason-email-readonly"); var readonlyView = document.querySelector("#action-needed-reason-email-readonly");
if(!actionNeededEmail || !actionNeededReasonDropdown) {
return;
}
let emailWasSent = document.getElementById("action-needed-email-sent"); let emailWasSent = document.getElementById("action-needed-email-sent");
let actionNeededEmailData = document.getElementById('action-needed-emails-data').textContent; if (!emailWasSent) {
let actionNeededEmailsJson = JSON.parse(actionNeededEmailData); return;
}
let actionNeededEmailData = document.getElementById('action-needed-emails-data').textContent;
if(!actionNeededEmailData) {
return;
}
let actionNeededEmailsJson = JSON.parse(actionNeededEmailData);
const domainRequestId = actionNeededReasonDropdown ? document.querySelector("#domain_request_id").value : null const domainRequestId = actionNeededReasonDropdown ? document.querySelector("#domain_request_id").value : null
const emailSentSessionVariableName = `actionNeededEmailSent-${domainRequestId}`; const emailSentSessionVariableName = `actionNeededEmailSent-${domainRequestId}`;
const oldDropdownValue = actionNeededReasonDropdown ? actionNeededReasonDropdown.value : null; const oldDropdownValue = actionNeededReasonDropdown ? actionNeededReasonDropdown.value : null;
@ -791,35 +801,58 @@ function initializeWidgetOnList(list, parentId) {
}); });
function handleFederalAgencyChange(federalAgency, organizationType) { function handleFederalAgencyChange(federalAgency, organizationType) {
// Set the org type to federal if an agency is selected // Set the org type to federal if an agency is selected
let selectedText = federalAgency.find("option:selected").text(); let selectedText = federalAgency.find("option:selected").text();
if (selectedText !== "Non-Federal Agency" && selectedText) { if (selectedText !== "Non-Federal Agency" && selectedText) {
organizationType.value = "federal"; if (organizationType.value !== "federal") {
}else { organizationType.value = "federal";
if (organizationType.value === "federal") {
organizationType.value = "";
} }
// Set the SO field
}else if (selectedText === "Non-Federal Agency" && organizationType.value === "federal") {
organizationType.value = "";
// Set the SO field
}
// There isn't a senior official associated with null records and non federal agencies
if (!selectedText || selectedText === "Non-Federal Agency") {
return;
} }
// Automatically set the SO field. // Get the associated senior official with this federal agency
// How do we do this without an API?????????? let $seniorOfficial = django.jQuery("#id_senior_official");
// let seniorOfficialId = assignSelfButton.getAttribute("data-user-id"); if (!$seniorOfficial) {
// let seniorOfficialName = assignSelfButton.getAttribute("data-user-name"); console.log("Could not find the senior official field");
// if (!currentUserId || !currentUserName){ return;
// console.error("Could not assign current user: no values found.") }
// return;
// }
// if (selector.find(`option[value='${currentUserId}']`).length) { let seniorOfficialApi = document.querySelector("#senior_official_from_agency_json_url").value;
// // Select the value that is associated with the current user. fetch(`${seniorOfficialApi}?agency_name=${selectedText}`)
// selector.val(currentUserId).trigger("change"); .then(response => response.json())
// } else { .then(data => {
// // Create a DOM Option that matches the desired user. Then append it and select it. if (data.error) {
// let userOption = new Option(currentUserName, currentUserId, true, true); console.error('Error in AJAX call: ' + data.error);
// selector.append(userOption).trigger("change"); return;
// } }
let seniorOfficialId = data.id;
let seniorOfficialName = [data.first_name, data.last_name].join(" ");
if (!seniorOfficialId || !seniorOfficialName || !seniorOfficialName.trim()){
console.error("Could not assign current Senior Official: no values found.")
return;
}
// Add the senior official to the dropdown.
// This format supports select2 - if we decide to convert this field in the future.
if ($seniorOfficial.find(`option[value='${seniorOfficialId}']`).length) {
// Select the value that is associated with the current Senior Official.
$seniorOfficial.val(seniorOfficialId).trigger("change");
} else {
// Create a DOM Option that matches the desired Senior Official. Then append it and select it.
let userOption = new Option(seniorOfficialName, seniorOfficialId, true, true);
$seniorOfficial.append(userOption).trigger("change");
}
})
.catch(error => console.error('Error fetching senior official:', error));
} }
function handleStateTerritoryChange(stateTerritory, urbanizationField) { function handleStateTerritoryChange(stateTerritory, urbanizationField) {

View file

@ -24,6 +24,7 @@ from registrar.views.report_views import (
from registrar.views.domain_request import Step from registrar.views.domain_request import Step
from registrar.views.domain_requests_json import get_domain_requests_json from registrar.views.domain_requests_json import get_domain_requests_json
from registrar.views.utility.api_views import get_senior_official_from_federal_agency_json
from registrar.views.domains_json import get_domains_json from registrar.views.domains_json import get_domains_json
from registrar.views.utility import always_404 from registrar.views.utility import always_404
from api.views import available, get_current_federal, get_current_full from api.views import available, get_current_federal, get_current_full
@ -155,6 +156,12 @@ urlpatterns = [
path("api/v1/available/", available, name="available"), path("api/v1/available/", available, name="available"),
path("api/v1/get-report/current-federal", get_current_federal, name="get-current-federal"), path("api/v1/get-report/current-federal", get_current_federal, name="get-current-federal"),
path("api/v1/get-report/current-full", get_current_full, name="get-current-full"), path("api/v1/get-report/current-full", get_current_full, name="get-current-full"),
# TODO convert to admin view
path(
"api/v1/get-senior-official-from-federal-agency-json/",
get_senior_official_from_federal_agency_json,
name="get-senior-official-from-federal-agency-json"
),
path( path(
"todo", "todo",
lambda r: always_404(r, "We forgot to include this link, sorry."), lambda r: always_404(r, "We forgot to include this link, sorry."),

View file

@ -1,6 +1,13 @@
{% extends 'django/admin/email_clipboard_change_form.html' %} {% extends 'django/admin/email_clipboard_change_form.html' %}
{% load i18n static %} {% load i18n static %}
{% block content %}
{% comment %} Stores the json endpoint in a url for easlier access {% endcomment %}
{% url 'get-senior-official-from-federal-agency-json' as url %}
<input id="senior_official_from_agency_json_url" class="display-none" value="{{url}}" />
{{ block.super }}
{% endblock content %}
{% block after_related_objects %} {% block after_related_objects %}
<div class="module aligned padding-3"> <div class="module aligned padding-3">
<h2>Associated groups and suborganizations</h2> <h2>Associated groups and suborganizations</h2>

View file

@ -8,3 +8,4 @@ from .permission_views import (
DomainInvitationPermissionDeleteView, DomainInvitationPermissionDeleteView,
DomainRequestWizardPermissionView, DomainRequestWizardPermissionView,
) )
from .api_views import get_senior_official_from_federal_agency_json

View file

@ -0,0 +1,32 @@
import logging
from django.http import JsonResponse
from django.forms.models import model_to_dict
from registrar.models import FederalAgency, SeniorOfficial
from django.utils.dateformat import format
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db.models import Q
logger = logging.getLogger(__name__)
@login_required
def get_senior_official_from_federal_agency_json(request):
"""Returns federal_agency information as a JSON"""
# This API is only accessible to admins
superuser_perm = request.user.has_perm("registrar.full_access_permission")
analyst_perm = request.user.has_perm("registrar.analyst_access_permission")
if not request.user.is_authenticated or not analyst_perm or not superuser_perm:
# We intentionally don't return anything here
return {}
agency_name = request.GET.get("agency_name")
agency = FederalAgency.objects.filter(agency=agency_name).first()
senior_official = SeniorOfficial.objects.filter(federal_agency=agency).first()
if agency and senior_official:
# Convert the agency object to a dictionary
so_dict = model_to_dict(senior_official)
return JsonResponse(so_dict)
else:
return JsonResponse({"error": "Senior Official not found"})