diff --git a/.github/actions/django-security-check/README.md b/.github/actions/django-security-check/README.md index 4eddcf74c..94f02a97c 100644 --- a/.github/actions/django-security-check/README.md +++ b/.github/actions/django-security-check/README.md @@ -38,7 +38,7 @@ jobs: id: check uses: victoriadrake/django-security-check@master - name: Upload output - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: security-check-output path: output.txt diff --git a/.github/workflows/deploy-manual.yaml b/.github/workflows/deploy-manual.yaml index e0bbee436..ba85342b0 100644 --- a/.github/workflows/deploy-manual.yaml +++ b/.github/workflows/deploy-manual.yaml @@ -30,6 +30,7 @@ on: - litterbox - ms - ad + - ag # GitHub Actions has no "good" way yet to dynamically input branches branch: description: 'Branch to deploy' diff --git a/.github/workflows/security-check.yaml b/.github/workflows/security-check.yaml index dd75d5c98..aea700613 100644 --- a/.github/workflows/security-check.yaml +++ b/.github/workflows/security-check.yaml @@ -44,7 +44,7 @@ jobs: id: check uses: ./.github/actions/django-security-check - name: Upload output - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: security-check-output path: ./src/output.txt diff --git a/docs/architecture/diagrams/model_timeline.md b/docs/architecture/diagrams/model_timeline.md index f05b9e056..eed2610eb 100644 --- a/docs/architecture/diagrams/model_timeline.md +++ b/docs/architecture/diagrams/model_timeline.md @@ -42,7 +42,6 @@ class DomainRequest { creator (User) investigator (User) senior_official (Contact) - submitter (Contact) other_contacts (Contacts) approved_domain (Domain) requested_domain (DraftDomain) @@ -80,7 +79,7 @@ class Contact { -- } -DomainRequest *-r-* Contact : senior_official, submitter, other_contacts +DomainRequest *-r-* Contact : senior_official, other_contacts class DraftDomain { Requested domain diff --git a/docs/architecture/diagrams/models_diagram.md b/docs/architecture/diagrams/models_diagram.md index 455f8fb09..1856407aa 100644 --- a/docs/architecture/diagrams/models_diagram.md +++ b/docs/architecture/diagrams/models_diagram.md @@ -38,7 +38,6 @@ class "registrar.Contact " as registrar.Contact #d6f4e9 { + id (BigAutoField) + created_at (DateTimeField) + updated_at (DateTimeField) - ~ user (OneToOneField) + first_name (CharField) + middle_name (CharField) + last_name (CharField) @@ -47,7 +46,6 @@ class "registrar.Contact " as registrar.Contact #d6f4e9 { + phone (PhoneNumberField) -- } -registrar.Contact -- registrar.User class "registrar.Host " as registrar.Host #d6f4e9 { @@ -143,6 +141,8 @@ class "registrar.FederalAgency " as registrar.FederalAgency #d6f4e9 { + updated_at (DateTimeField) + agency (CharField) + federal_type (CharField) + + initials (CharField) + + is_fceb (BooleanField) -- } @@ -159,6 +159,7 @@ class "registrar.DomainRequest " as registrar.DomainRequest #d6f4e9 { + action_needed_reason_email (TextField) ~ federal_agency (ForeignKey) ~ portfolio (ForeignKey) + ~ sub_organization (ForeignKey) ~ creator (ForeignKey) ~ investigator (ForeignKey) + generic_org_type (CharField) @@ -179,7 +180,6 @@ class "registrar.DomainRequest " as registrar.DomainRequest #d6f4e9 { ~ senior_official (ForeignKey) ~ approved_domain (OneToOneField) ~ requested_domain (OneToOneField) - ~ submitter (ForeignKey) + purpose (TextField) + no_other_contacts_rationale (TextField) + anything_else (TextField) @@ -198,12 +198,12 @@ class "registrar.DomainRequest " as registrar.DomainRequest #d6f4e9 { } registrar.DomainRequest -- registrar.FederalAgency registrar.DomainRequest -- registrar.Portfolio +registrar.DomainRequest -- registrar.Suborganization registrar.DomainRequest -- registrar.User registrar.DomainRequest -- registrar.User registrar.DomainRequest -- registrar.Contact registrar.DomainRequest -- registrar.Domain registrar.DomainRequest -- registrar.DraftDomain -registrar.DomainRequest -- registrar.Contact registrar.DomainRequest *--* registrar.Website registrar.DomainRequest *--* registrar.Website registrar.DomainRequest *--* registrar.Contact @@ -218,6 +218,7 @@ class "registrar.DomainInformation " as registrar.DomainInformation # ~ federal_agency (ForeignKey) ~ creator (ForeignKey) ~ portfolio (ForeignKey) + ~ sub_organization (ForeignKey) ~ domain_request (OneToOneField) + generic_org_type (CharField) + organization_type (CharField) @@ -236,7 +237,6 @@ class "registrar.DomainInformation " as registrar.DomainInformation # + about_your_organization (TextField) ~ senior_official (ForeignKey) ~ domain (OneToOneField) - ~ submitter (ForeignKey) + purpose (TextField) + no_other_contacts_rationale (TextField) + anything_else (TextField) @@ -253,10 +253,10 @@ class "registrar.DomainInformation " as registrar.DomainInformation # registrar.DomainInformation -- registrar.FederalAgency registrar.DomainInformation -- registrar.User registrar.DomainInformation -- registrar.Portfolio +registrar.DomainInformation -- registrar.Suborganization registrar.DomainInformation -- registrar.DomainRequest registrar.DomainInformation -- registrar.Contact registrar.DomainInformation -- registrar.Domain -registrar.DomainInformation -- registrar.Contact registrar.DomainInformation *--* registrar.Contact @@ -285,6 +285,38 @@ class "registrar.DomainInvitation " as registrar.DomainInvitation #d6 registrar.DomainInvitation -- registrar.Domain +class "registrar.UserPortfolioPermission " as registrar.UserPortfolioPermission #d6f4e9 { + user portfolio permission + -- + + id (BigAutoField) + + created_at (DateTimeField) + + updated_at (DateTimeField) + ~ user (ForeignKey) + ~ portfolio (ForeignKey) + + roles (ArrayField) + + additional_permissions (ArrayField) + -- +} +registrar.UserPortfolioPermission -- registrar.User +registrar.UserPortfolioPermission -- registrar.Portfolio + + +class "registrar.PortfolioInvitation " as registrar.PortfolioInvitation #d6f4e9 { + portfolio invitation + -- + + id (BigAutoField) + + created_at (DateTimeField) + + updated_at (DateTimeField) + + email (EmailField) + ~ portfolio (ForeignKey) + + portfolio_roles (ArrayField) + + portfolio_additional_permissions (ArrayField) + + status (FSMField) + -- +} +registrar.PortfolioInvitation -- registrar.Portfolio + + class "registrar.TransitionDomain " as registrar.TransitionDomain #d6f4e9 { transition domain -- @@ -409,10 +441,11 @@ class "registrar.Portfolio " as registrar.Portfolio #d6f4e9 { + created_at (DateTimeField) + updated_at (DateTimeField) ~ creator (ForeignKey) + + organization_name (CharField) + + organization_type (CharField) + notes (TextField) ~ federal_agency (ForeignKey) - + organization_type (CharField) - + organization_name (CharField) + ~ senior_official (ForeignKey) + address_line1 (CharField) + address_line2 (CharField) + city (CharField) @@ -424,6 +457,7 @@ class "registrar.Portfolio " as registrar.Portfolio #d6f4e9 { } registrar.Portfolio -- registrar.User registrar.Portfolio -- registrar.FederalAgency +registrar.Portfolio -- registrar.SeniorOfficial class "registrar.DomainGroup " as registrar.DomainGroup #d6f4e9 { @@ -454,7 +488,21 @@ class "registrar.Suborganization " as registrar.Suborganization #d6f4 registrar.Suborganization -- registrar.Portfolio -@enduml -``` +class "registrar.SeniorOfficial " as registrar.SeniorOfficial #d6f4e9 { + senior official + -- + + id (BigAutoField) + + created_at (DateTimeField) + + updated_at (DateTimeField) + + first_name (CharField) + + last_name (CharField) + + title (CharField) + + phone (PhoneNumberField) + + email (EmailField) + ~ federal_agency (ForeignKey) + -- +} +registrar.SeniorOfficial -- registrar.FederalAgency - + +@enduml diff --git a/docs/architecture/diagrams/models_diagram.svg b/docs/architecture/diagrams/models_diagram.svg index f8cf3a46d..85c0e7620 100644 --- a/docs/architecture/diagrams/models_diagram.svg +++ b/docs/architecture/diagrams/models_diagram.svg @@ -1 +1 @@ -registrarregistrar.ContactRegistrarcontactid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)user (OneToOneField)first_name (CharField)middle_name (CharField)last_name (CharField)title (CharField)email (EmailField)phone (PhoneNumberField)registrar.UserRegistraruserid (BigAutoField)password (CharField)last_login (DateTimeField)is_superuser (BooleanField)username (CharField)first_name (CharField)last_name (CharField)email (EmailField)is_staff (BooleanField)is_active (BooleanField)date_joined (DateTimeField)status (CharField)phone (PhoneNumberField)middle_name (CharField)title (CharField)verification_type (CharField)groups (ManyToManyField)user_permissions (ManyToManyField)domains (ManyToManyField)registrar.HostRegistrarhostid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)domain (ForeignKey)registrar.DomainRegistrardomainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (DomainField)state (FSMField)expiration_date (DateField)security_contact_registry_id (TextField)deleted (DateField)first_ready (DateField)dsdata_last_change (TextField)registrar.HostIPRegistrarhost ipid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)address (CharField)host (ForeignKey)registrar.PublicContactRegistrarpublic contactid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)contact_type (CharField)registry_id (CharField)domain (ForeignKey)name (CharField)org (CharField)street1 (CharField)street2 (CharField)street3 (CharField)city (CharField)sp (CharField)pc (CharField)cc (CharField)email (EmailField)voice (CharField)fax (CharField)pw (CharField)registrar.UserDomainRoleRegistraruser domain roleid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)user (ForeignKey)domain (ForeignKey)role (TextField)registrar.FederalAgencyRegistrarFederal agencyid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)agency (CharField)federal_type (CharField)registrar.DomainRequestRegistrardomain requestid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)status (FSMField)rejection_reason (TextField)action_needed_reason (TextField)action_needed_reason_email (TextField)federal_agency (ForeignKey)portfolio (ForeignKey)creator (ForeignKey)investigator (ForeignKey)generic_org_type (CharField)is_election_board (BooleanField)organization_type (CharField)federally_recognized_tribe (BooleanField)state_recognized_tribe (BooleanField)tribe_name (CharField)federal_type (CharField)organization_name (CharField)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)about_your_organization (TextField)senior_official (ForeignKey)approved_domain (OneToOneField)requested_domain (OneToOneField)submitter (ForeignKey)purpose (TextField)no_other_contacts_rationale (TextField)anything_else (TextField)has_anything_else_text (BooleanField)cisa_representative_email (EmailField)cisa_representative_first_name (CharField)cisa_representative_last_name (CharField)has_cisa_representative (BooleanField)is_policy_acknowledged (BooleanField)submission_date (DateField)notes (TextField)current_websites (ManyToManyField)alternative_domains (ManyToManyField)other_contacts (ManyToManyField)registrar.PortfolioRegistrarportfolioid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)creator (ForeignKey)notes (TextField)federal_agency (ForeignKey)organization_type (CharField)organization_name (CharField)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)security_contact_email (EmailField)registrar.DraftDomainRegistrardraft domainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)registrar.WebsiteRegistrarwebsiteid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)website (CharField)registrar.DomainInformationRegistrardomain informationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)federal_agency (ForeignKey)creator (ForeignKey)portfolio (ForeignKey)domain_request (OneToOneField)generic_org_type (CharField)organization_type (CharField)federally_recognized_tribe (BooleanField)state_recognized_tribe (BooleanField)tribe_name (CharField)federal_type (CharField)is_election_board (BooleanField)organization_name (CharField)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)about_your_organization (TextField)senior_official (ForeignKey)domain (OneToOneField)submitter (ForeignKey)purpose (TextField)no_other_contacts_rationale (TextField)anything_else (TextField)has_anything_else_text (BooleanField)cisa_representative_email (EmailField)cisa_representative_first_name (CharField)cisa_representative_last_name (CharField)has_cisa_representative (BooleanField)is_policy_acknowledged (BooleanField)notes (TextField)other_contacts (ManyToManyField)registrar.DomainInvitationRegistrardomain invitationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)email (EmailField)domain (ForeignKey)status (FSMField)registrar.TransitionDomainRegistrartransition domainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)username (CharField)domain_name (CharField)status (CharField)email_sent (BooleanField)processed (BooleanField)generic_org_type (CharField)organization_name (CharField)federal_type (CharField)federal_agency (CharField)epp_creation_date (DateField)epp_expiration_date (DateField)first_name (CharField)middle_name (CharField)last_name (CharField)title (CharField)email (EmailField)phone (CharField)address_line (CharField)city (CharField)state_territory (CharField)zipcode (CharField)registrar.VerifiedByStaffRegistrarverified by staffid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)email (EmailField)requestor (ForeignKey)notes (TextField)registrar.UserGroupRegistrarUser groupid (AutoField)name (CharField)group_ptr (OneToOneField)permissions (ManyToManyField)registrar.WaffleFlagRegistrarwaffle flagid (BigAutoField)name (CharField)everyone (BooleanField)percent (DecimalField)testing (BooleanField)superusers (BooleanField)staff (BooleanField)authenticated (BooleanField)languages (TextField)rollout (BooleanField)note (TextField)created (DateTimeField)modified (DateTimeField)groups (ManyToManyField)users (ManyToManyField)registrar.DomainGroupRegistrardomain groupid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)portfolio (ForeignKey)domains (ManyToManyField)registrar.SuborganizationRegistrarsuborganizationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)portfolio (ForeignKey) \ No newline at end of file +registrarregistrar.ContactRegistrarcontactid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)first_name (CharField)middle_name (CharField)last_name (CharField)title (CharField)email (EmailField)phone (PhoneNumberField)registrar.HostRegistrarhostid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)domain (ForeignKey)registrar.DomainRegistrardomainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (DomainField)state (FSMField)expiration_date (DateField)security_contact_registry_id (TextField)deleted (DateField)first_ready (DateField)dsdata_last_change (TextField)registrar.HostIPRegistrarhost ipid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)address (CharField)host (ForeignKey)registrar.PublicContactRegistrarpublic contactid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)contact_type (CharField)registry_id (CharField)domain (ForeignKey)name (CharField)org (CharField)street1 (CharField)street2 (CharField)street3 (CharField)city (CharField)sp (CharField)pc (CharField)cc (CharField)email (EmailField)voice (CharField)fax (CharField)pw (CharField)registrar.UserDomainRoleRegistraruser domain roleid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)user (ForeignKey)domain (ForeignKey)role (TextField)registrar.UserRegistraruserid (BigAutoField)password (CharField)last_login (DateTimeField)is_superuser (BooleanField)username (CharField)first_name (CharField)last_name (CharField)email (EmailField)is_staff (BooleanField)is_active (BooleanField)date_joined (DateTimeField)status (CharField)portfolio (ForeignKey)portfolio_roles (ArrayField)portfolio_additional_permissions (ArrayField)phone (PhoneNumberField)middle_name (CharField)title (CharField)verification_type (CharField)groups (ManyToManyField)user_permissions (ManyToManyField)domains (ManyToManyField)registrar.FederalAgencyRegistrarFederal agencyid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)agency (CharField)federal_type (CharField)initials (CharField)is_fceb (BooleanField)registrar.DomainRequestRegistrardomain requestid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)status (FSMField)rejection_reason (TextField)action_needed_reason (TextField)action_needed_reason_email (TextField)federal_agency (ForeignKey)portfolio (ForeignKey)sub_organization (ForeignKey)creator (ForeignKey)investigator (ForeignKey)generic_org_type (CharField)is_election_board (BooleanField)organization_type (CharField)federally_recognized_tribe (BooleanField)state_recognized_tribe (BooleanField)tribe_name (CharField)federal_type (CharField)organization_name (CharField)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)about_your_organization (TextField)senior_official (ForeignKey)approved_domain (OneToOneField)requested_domain (OneToOneField)purpose (TextField)no_other_contacts_rationale (TextField)anything_else (TextField)has_anything_else_text (BooleanField)cisa_representative_email (EmailField)cisa_representative_first_name (CharField)cisa_representative_last_name (CharField)has_cisa_representative (BooleanField)is_policy_acknowledged (BooleanField)submission_date (DateField)notes (TextField)current_websites (ManyToManyField)alternative_domains (ManyToManyField)other_contacts (ManyToManyField)registrar.PortfolioRegistrarportfolioid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)creator (ForeignKey)organization_name (CharField)organization_type (CharField)notes (TextField)federal_agency (ForeignKey)senior_official (ForeignKey)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)security_contact_email (EmailField)registrar.SuborganizationRegistrarsuborganizationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)portfolio (ForeignKey)registrar.DraftDomainRegistrardraft domainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)registrar.WebsiteRegistrarwebsiteid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)website (CharField)registrar.DomainInformationRegistrardomain informationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)federal_agency (ForeignKey)creator (ForeignKey)portfolio (ForeignKey)sub_organization (ForeignKey)domain_request (OneToOneField)generic_org_type (CharField)organization_type (CharField)federally_recognized_tribe (BooleanField)state_recognized_tribe (BooleanField)tribe_name (CharField)federal_type (CharField)is_election_board (BooleanField)organization_name (CharField)address_line1 (CharField)address_line2 (CharField)city (CharField)state_territory (CharField)zipcode (CharField)urbanization (CharField)about_your_organization (TextField)senior_official (ForeignKey)domain (OneToOneField)purpose (TextField)no_other_contacts_rationale (TextField)anything_else (TextField)has_anything_else_text (BooleanField)cisa_representative_email (EmailField)cisa_representative_first_name (CharField)cisa_representative_last_name (CharField)has_cisa_representative (BooleanField)is_policy_acknowledged (BooleanField)notes (TextField)other_contacts (ManyToManyField)registrar.DomainInvitationRegistrardomain invitationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)email (EmailField)domain (ForeignKey)status (FSMField)registrar.PortfolioInvitationRegistrarportfolio invitationid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)email (EmailField)portfolio (ForeignKey)portfolio_roles (ArrayField)portfolio_additional_permissions (ArrayField)status (FSMField)registrar.TransitionDomainRegistrartransition domainid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)username (CharField)domain_name (CharField)status (CharField)email_sent (BooleanField)processed (BooleanField)generic_org_type (CharField)organization_name (CharField)federal_type (CharField)federal_agency (CharField)epp_creation_date (DateField)epp_expiration_date (DateField)first_name (CharField)middle_name (CharField)last_name (CharField)title (CharField)email (EmailField)phone (CharField)address_line (CharField)city (CharField)state_territory (CharField)zipcode (CharField)registrar.VerifiedByStaffRegistrarverified by staffid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)email (EmailField)requestor (ForeignKey)notes (TextField)registrar.UserGroupRegistrarUser groupid (AutoField)name (CharField)group_ptr (OneToOneField)permissions (ManyToManyField)registrar.WaffleFlagRegistrarwaffle flagid (BigAutoField)name (CharField)everyone (BooleanField)percent (DecimalField)testing (BooleanField)superusers (BooleanField)staff (BooleanField)authenticated (BooleanField)languages (TextField)rollout (BooleanField)note (TextField)created (DateTimeField)modified (DateTimeField)groups (ManyToManyField)users (ManyToManyField)registrar.SeniorOfficialRegistrarsenior officialid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)first_name (CharField)last_name (CharField)title (CharField)phone (PhoneNumberField)email (EmailField)federal_agency (ForeignKey)registrar.DomainGroupRegistrardomain groupid (BigAutoField)created_at (DateTimeField)updated_at (DateTimeField)name (CharField)portfolio (ForeignKey)domains (ManyToManyField) \ No newline at end of file diff --git a/docs/developer/README.md b/docs/developer/README.md index 358df649c..9ddb35352 100644 --- a/docs/developer/README.md +++ b/docs/developer/README.md @@ -97,6 +97,7 @@ While on production (the sandbox referred to as `stable`), an existing analyst o "username": "", "first_name": "", "last_name": "", + "email": "", }, ... ] @@ -121,6 +122,7 @@ Analysts are a variant of the admin role with limited permissions. The process f "username": "", "first_name": "", "last_name": "", + "email": "", }, ... ] @@ -131,6 +133,20 @@ Analysts are a variant of the admin role with limited permissions. The process f Do note that if you wish to have both an analyst and admin account, append `-Analyst` to your first and last name, or use a completely different first/last name to avoid confusion. Example: `Bob-Analyst` +## Adding an email address to the email whitelist (sandboxes only) +On all non-production environments, we use an email whitelist table (called `Allowed emails`). This whitelist is not case sensitive, and it provides an inclusion for +1 emails (like example.person+1@igorville.gov). The content after the `+` can be any _digit_. The whitelist checks for the "base" email (example.person) so even if you only have the +1 email defined, an email will still be sent assuming that it follows those conventions. + +To add yourself to this, you can go about it in three ways. + +Permanent (all sandboxes): +1. In src/registrar/fixtures_users.py, add the "email" field to your user in either the ADMIN or STAFF table. +2. In src/registrar/fixtures_users.py, add the desired email address to the `ADDITIONAL_ALLOWED_EMAILS` list. This route is suggested for product. + +Sandbox specific (wiped when the db is reset): +3. Create a new record on the `Allowed emails` table with your email address. This can be done through django admin. + +More detailed instructions regarding #3 can be found [here](https://docs.google.com/document/d/1ebIz4PcUuoiT7LlVy83EAyHAk_nWPEc99neMp4QjzDs). + ## Adding to CODEOWNERS (optional) The CODEOWNERS file sets the tagged individuals as default reviewers on any Pull Request that changes files that they are marked as owners of. diff --git a/docs/developer/generating-emails-guide.md b/docs/developer/generating-emails-guide.md index dd0a55e64..cc5f9d41b 100644 --- a/docs/developer/generating-emails-guide.md +++ b/docs/developer/generating-emails-guide.md @@ -14,7 +14,7 @@ - Starting Location: Home page - Workflow: (Domain requests Table) Manage domain - Workflow Step: Click "Manage" -> Click "Withdraw request" -> (confirmation prompt) -> Click "Withdraw request" (inside prompt) -- Notes: You can also do this through Django Admin by switching a domain of status "submitted" to "withdrawn", but you need to be the submitter (email listed on Your Contact Information). +- Notes: You can also do this through Django Admin by switching a domain of status "submitted" to "withdrawn", but you need to be the creator. - [Email Content](https://github.com/cisagov/manage.get.gov/blob/main/src/registrar/templates/emails/domain_request_withdrawn.txt) ### Domain Request Withdrawn Subject @@ -25,7 +25,7 @@ - Starting Location: Django Admin - Workflow: Analyst Admin - Workflow Step: Click "domain requests" -> Click a domain request in a status of "submitted", "In review", "rejected", or "ineligible" -> Click status dropdown -> (select "approved") -> click "Save" -- Notes: Note that this will send an email to the submitter (email listed on Your Contact Information). To test this with your own email, you need to create a domain request, then set the status to "approved". This will send you an email. +- Notes: Note that this will send an email to the creator. To test this with your own email, you need to create a domain request, then set the status to "approved". This will send you an email. - [Email Content](https://github.com/cisagov/manage.get.gov/blob/main/src/registrar/templates/emails/status_change_approved.txt) ### Status Change Approved Subject @@ -36,7 +36,7 @@ - Starting Location: Django Admin - Workflow: Analyst Admin - Workflow Step: Click "domain requests" -> Click a domain request in a status of "In review", or "approved" -> Click status dropdown -> (select "rejected") -> click "Save" -- Notes: Note that this will send an email to the submitter (email listed on Your Contact Information). To test this with your own email, you need to create a domain request, then set the status to "in review" (and click save). Then, go back to the same application and set the status to "rejected". This will send you an email. +- Notes: Note that this will send an email to the creator. To test this with your own email, you need to create a domain request, then set the status to "in review" (and click save). Then, go back to the same application and set the status to "rejected". This will send you an email. - [Email Content](https://github.com/cisagov/manage.get.gov/blob/main/src/registrar/templates/emails/status_change_rejected.txt) ### Status Change Rejected Subject @@ -47,7 +47,7 @@ - Starting Location: Home Page - Workflow: Start domain request - Workflow Step: Click "Start a new domain request" -> (fill out the form) -> On the last step ("Review and submit your domain request "), click "Submit your domain request" -- Notes: Note that this will send an email to the submitter (email listed on Your Contact Information) +- Notes: Note that this will send an email to the creator. - [Email Content](https://github.com/cisagov/manage.get.gov/blob/main/src/registrar/templates/emails/submission_confirmation.txt) ### Submission Confirmation Subject diff --git a/docs/developer/management_script_helpers.md b/docs/developer/management_script_helpers.md index 104e4dc13..a43bb16aa 100644 --- a/docs/developer/management_script_helpers.md +++ b/docs/developer/management_script_helpers.md @@ -62,4 +62,5 @@ The class provides the following optional configuration variables: The class also provides helper methods: - `get_class_name`: Returns a display-friendly class name for the terminal prompt - `get_failure_message`: Returns the message to display if a record fails to update -- `should_skip_record`: Defines the condition for skipping a record (by default, no records are skipped) \ No newline at end of file +- `should_skip_record`: Defines the condition for skipping a record (by default, no records are skipped) +- `custom_filter`: Allows for additional filters that cannot be expressed using django queryset field lookups \ No newline at end of file diff --git a/docs/operations/data_migration.md b/docs/operations/data_migration.md index cd748b22d..5e1aa688a 100644 --- a/docs/operations/data_migration.md +++ b/docs/operations/data_migration.md @@ -816,3 +816,99 @@ Example: `cf ssh getgov-za` | | Parameter | Description | |:-:|:-------------------------- |:-----------------------------------------------------------------------------------| | 1 | **federal_cio_csv_path** | Specifies where the federal CIO csv is | + +## Update First Ready Values +This section outlines how to run the populate_first_ready script + +### Running on sandboxes + +#### Step 1: Login to CloudFoundry +```cf login -a api.fr.cloud.gov --sso``` + +#### Step 2: SSH into your environment +```cf ssh getgov-{space}``` + +Example: `cf ssh getgov-za` + +#### Step 3: Create a shell instance +```/tmp/lifecycle/shell``` + +#### Step 4: Running the script +```./manage.py update_first_ready``` + +### Running locally +```docker-compose exec app ./manage.py update_first_ready``` + +## Populate Domain Request Dates +This section outlines how to run the populate_domain_request_dates script + +### Running on sandboxes + +#### Step 1: Login to CloudFoundry +```cf login -a api.fr.cloud.gov --sso``` + +#### Step 2: SSH into your environment +```cf ssh getgov-{space}``` + +Example: `cf ssh getgov-za` + +#### Step 3: Create a shell instance +```/tmp/lifecycle/shell``` + +#### Step 4: Running the script +```./manage.py populate_domain_request_dates``` + +### Running locally +```docker-compose exec app ./manage.py populate_domain_request_dates``` + +## Create federal portfolio +This script takes the name of a `FederalAgency` (like 'AMTRAK') and does the following: +1. Creates the portfolio record based off of data on the federal agency object itself. +2. Creates suborganizations from existing DomainInformation records. +3. Associates the SeniorOfficial record (if it exists). +4. Adds this portfolio to DomainInformation / DomainRequests or both. + +Errors: +1. ValueError: Federal agency not found in database. +2. Logged Warning: No senior official found for portfolio +3. Logged Error: No suborganizations found for portfolio. +4. Logged Warning: No new suborganizations to add. +5. Logged Warning: No valid DomainRequest records to update. +6. Logged Warning: No valid DomainInformation records to update. + +### Running on sandboxes + +#### Step 1: Login to CloudFoundry +```cf login -a api.fr.cloud.gov --sso``` + +#### Step 2: SSH into your environment +```cf ssh getgov-{space}``` + +Example: `cf ssh getgov-za` + +#### Step 3: Create a shell instance +```/tmp/lifecycle/shell``` + +#### Step 4: Upload your csv to the desired sandbox +[Follow these steps](#use-scp-to-transfer-data-to-sandboxes) to upload the federal_cio csv to a sandbox of your choice. + +#### Step 5: Running the script +```./manage.py create_federal_portfolio "{federal_agency_name}" --both``` + +Example (only requests): `./manage.py create_federal_portfolio "AMTRAK" --parse_requests` + +### Running locally + +#### Step 1: Running the script +```docker-compose exec app ./manage.py create_federal_portfolio "{federal_agency_name}" --both``` + +##### Parameters +| | Parameter | Description | +|:-:|:-------------------------- |:-------------------------------------------------------------------------------------------| +| 1 | **federal_agency_name** | Name of the FederalAgency record surrounded by quotes. For instance,"AMTRAK". | +| 2 | **both** | If True, runs parse_requests and parse_domains. | +| 3 | **parse_requests** | If True, then the created portfolio is added to all related DomainRequests. | +| 4 | **parse_domains** | If True, then the created portfolio is added to all related Domains. | + +Note: Regarding parameters #2-#3, you cannot use `--both` while using these. You must specify either `--parse_requests` or `--parse_domains` seperately. While all of these parameters are optional in that you do not need to specify all of them, +you must specify at least one to run this script. diff --git a/src/epplibwrapper/cert.py b/src/epplibwrapper/cert.py index 15ff16c06..589736a04 100644 --- a/src/epplibwrapper/cert.py +++ b/src/epplibwrapper/cert.py @@ -1,7 +1,7 @@ import os import tempfile -from django.conf import settings +from django.conf import settings # type: ignore class Cert: @@ -12,7 +12,7 @@ class Cert: variable but Python's ssl library requires a file. """ - def __init__(self, data=settings.SECRET_REGISTRY_CERT) -> None: + def __init__(self, data=settings.SECRET_REGISTRY_CERT) -> None: # type: ignore self.filename = self._write(data) def __del__(self): @@ -31,4 +31,4 @@ class Key(Cert): """Location of private key as written to disk.""" def __init__(self) -> None: - super().__init__(data=settings.SECRET_REGISTRY_KEY) + super().__init__(data=settings.SECRET_REGISTRY_KEY) # type: ignore diff --git a/src/registrar/admin.py b/src/registrar/admin.py index 5b55eee12..c1b90083e 100644 --- a/src/registrar/admin.py +++ b/src/registrar/admin.py @@ -7,9 +7,11 @@ from django import forms from django.db.models import Value, CharField, Q from django.db.models.functions import Concat, Coalesce from django.http import HttpResponseRedirect +from django.conf import settings from django.shortcuts import redirect from django_fsm import get_available_FIELD_transitions, FSMField from registrar.models.domain_information import DomainInformation +from registrar.models.user_portfolio_permission import UserPortfolioPermission from registrar.models.utility.portfolio_helper import UserPortfolioPermissionChoices, UserPortfolioRoleChoices from waffle.decorators import flag_is_active from django.contrib import admin, messages @@ -34,6 +36,7 @@ from django_fsm import TransitionNotAllowed # type: ignore from django.utils.safestring import mark_safe from django.utils.html import escape from django.contrib.auth.forms import UserChangeForm, UsernameField +from django.contrib.admin.views.main import IGNORED_PARAMS from django_admin_multiple_choice_list_filter.list_filters import MultipleChoiceListFilter from import_export import resources from import_export.admin import ImportExportModelAdmin @@ -131,14 +134,6 @@ class MyUserAdminForm(UserChangeForm): widgets = { "groups": NoAutocompleteFilteredSelectMultiple("groups", False), "user_permissions": NoAutocompleteFilteredSelectMultiple("user_permissions", False), - "portfolio_roles": FilteredSelectMultipleArrayWidget( - "portfolio_roles", is_stacked=False, choices=UserPortfolioRoleChoices.choices - ), - "portfolio_additional_permissions": FilteredSelectMultipleArrayWidget( - "portfolio_additional_permissions", - is_stacked=False, - choices=UserPortfolioPermissionChoices.choices, - ), } def __init__(self, *args, **kwargs): @@ -170,6 +165,22 @@ class MyUserAdminForm(UserChangeForm): ) +class UserPortfolioPermissionsForm(forms.ModelForm): + class Meta: + model = models.UserPortfolioPermission + fields = "__all__" + widgets = { + "roles": FilteredSelectMultipleArrayWidget( + "roles", is_stacked=False, choices=UserPortfolioRoleChoices.choices + ), + "additional_permissions": FilteredSelectMultipleArrayWidget( + "additional_permissions", + is_stacked=False, + choices=UserPortfolioPermissionChoices.choices, + ), + } + + class PortfolioInvitationAdminForm(UserChangeForm): """This form utilizes the custom widget for its class's ManyToMany UIs.""" @@ -223,7 +234,7 @@ class DomainRequestAdminForm(forms.ModelForm): "other_contacts": NoAutocompleteFilteredSelectMultiple("other_contacts", False), } labels = { - "action_needed_reason_email": "Auto-generated email", + "action_needed_reason_email": "Email", } def __init__(self, *args, **kwargs): @@ -366,7 +377,9 @@ class DomainRequestAdminForm(forms.ModelForm): class MultiFieldSortableChangeList(admin.views.main.ChangeList): """ This class overrides the behavior of column sorting in django admin tables in order - to allow for multi field sorting on admin_order_field + to allow for multi field sorting on admin_order_field. It also overrides behavior + of getting the filter params to allow portfolio filters to be executed without + displaying on the right side of the ChangeList view. Usage: @@ -428,6 +441,24 @@ class MultiFieldSortableChangeList(admin.views.main.ChangeList): return ordering + def get_filters_params(self, params=None): + """ + Add portfolio to ignored params to allow the portfolio filter while not + listing it as a filter option on the right side of Change List on the + portfolio list. + """ + params = params or self.params + lookup_params = params.copy() # a dictionary of the query string + # Remove all the parameters that are globally and systematically + # ignored. + # Remove portfolio so that it does not error as an invalid + # filter parameter. + ignored_params = list(IGNORED_PARAMS) + ["portfolio"] + for ignored in ignored_params: + if ignored in lookup_params: + del lookup_params[ignored] + return lookup_params + class CustomLogEntryAdmin(LogEntryAdmin): """Overwrite the generated LogEntry admin class""" @@ -505,7 +536,6 @@ class AdminSortFields: sort_mapping = { # == Contact == # "other_contacts": (Contact, _name_sort), - "submitter": (Contact, _name_sort), # == Senior Official == # "senior_official": (SeniorOfficial, _name_sort), # == User == # @@ -644,6 +674,19 @@ class ListHeaderAdmin(AuditedAdmin, OrderableFieldsMixin): ) except models.User.DoesNotExist: pass + elif parameter_name == "portfolio": + # Retrieves the corresponding portfolio from Portfolio + id_value = request.GET.get(param) + try: + portfolio = models.Portfolio.objects.get(id=id_value) + filters.append( + { + "parameter_name": "portfolio", + "parameter_value": portfolio.organization_name, + } + ) + except models.Portfolio.DoesNotExist: + pass else: # For other parameter names, append a dictionary with the original # parameter_name and the corresponding parameter_value @@ -710,19 +753,12 @@ class MyUserAdmin(BaseUserAdmin, ImportExportModelAdmin): "is_superuser", "groups", "user_permissions", - "portfolio", - "portfolio_roles", - "portfolio_additional_permissions", ) }, ), ("Important dates", {"fields": ("last_login", "date_joined")}), ) - autocomplete_fields = [ - "portfolio", - ] - readonly_fields = ("verification_type",) analyst_fieldsets = ( @@ -742,9 +778,6 @@ class MyUserAdmin(BaseUserAdmin, ImportExportModelAdmin): "fields": ( "is_active", "groups", - "portfolio", - "portfolio_roles", - "portfolio_additional_permissions", ) }, ), @@ -799,9 +832,6 @@ class MyUserAdmin(BaseUserAdmin, ImportExportModelAdmin): "Important dates", "last_login", "date_joined", - "portfolio", - "portfolio_roles", - "portfolio_additional_permissions", ] # TODO: delete after we merge organization feature @@ -932,7 +962,9 @@ class MyUserAdmin(BaseUserAdmin, ImportExportModelAdmin): domain_ids = user_domain_roles.values_list("domain_id", flat=True) domains = Domain.objects.filter(id__in=domain_ids).exclude(state=Domain.State.DELETED) - extra_context = {"domain_requests": domain_requests, "domains": domains} + portfolio_ids = obj.get_portfolios().values_list("portfolio", flat=True) + portfolios = models.Portfolio.objects.filter(id__in=portfolio_ids) + extra_context = {"domain_requests": domain_requests, "domains": domains, "portfolios": portfolios} return super().change_view(request, object_id, form_url, extra_context) @@ -1210,6 +1242,26 @@ class UserDomainRoleResource(resources.ModelResource): model = models.UserDomainRole +class UserPortfolioPermissionAdmin(ListHeaderAdmin): + form = UserPortfolioPermissionsForm + + class Meta: + """Contains meta information about this class""" + + model = models.UserPortfolioPermission + fields = "__all__" + + _meta = Meta() + + # Columns + list_display = [ + "user", + "portfolio", + ] + + autocomplete_fields = ["user", "portfolio"] + + class UserDomainRoleAdmin(ListHeaderAdmin, ImportExportModelAdmin): """Custom user domain role admin class.""" @@ -1390,13 +1442,9 @@ class DomainInformationAdmin(ListHeaderAdmin, ImportExportModelAdmin): "domain", "generic_org_type", "created_at", - "submitter", ] - orderable_fk_fields = [ - ("domain", "name"), - ("submitter", ["first_name", "last_name"]), - ] + orderable_fk_fields = [("domain", "name")] # Filters list_filter = ["generic_org_type"] @@ -1408,7 +1456,7 @@ class DomainInformationAdmin(ListHeaderAdmin, ImportExportModelAdmin): search_help_text = "Search by domain." fieldsets = [ - (None, {"fields": ["portfolio", "sub_organization", "creator", "submitter", "domain_request", "notes"]}), + (None, {"fields": ["portfolio", "sub_organization", "creator", "domain_request", "notes"]}), (".gov domain", {"fields": ["domain"]}), ("Contacts", {"fields": ["senior_official", "other_contacts", "no_other_contacts_rationale"]}), ("Background info", {"fields": ["anything_else"]}), @@ -1472,7 +1520,6 @@ class DomainInformationAdmin(ListHeaderAdmin, ImportExportModelAdmin): "more_organization_information", "domain", "domain_request", - "submitter", "no_other_contacts_rationale", "anything_else", "is_policy_acknowledged", @@ -1487,7 +1534,6 @@ class DomainInformationAdmin(ListHeaderAdmin, ImportExportModelAdmin): "domain_request", "senior_official", "domain", - "submitter", "portfolio", "sub_organization", ] @@ -1649,7 +1695,9 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): # Columns list_display = [ "requested_domain", - "submission_date", + "first_submitted_date", + "last_submitted_date", + "last_status_update", "status", "generic_org_type", "federal_type", @@ -1658,13 +1706,11 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): "custom_election_board", "city", "state_territory", - "submitter", "investigator", ] orderable_fk_fields = [ ("requested_domain", "name"), - ("submitter", ["first_name", "last_name"]), ("investigator", ["first_name", "last_name"]), ] @@ -1694,11 +1740,11 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): # Search search_fields = [ "requested_domain__name", - "submitter__email", - "submitter__first_name", - "submitter__last_name", + "creator__email", + "creator__first_name", + "creator__last_name", ] - search_help_text = "Search by domain or submitter." + search_help_text = "Search by domain or creator." fieldsets = [ ( @@ -1714,7 +1760,6 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): "action_needed_reason_email", "investigator", "creator", - "submitter", "approved_domain", "notes", ] @@ -1802,7 +1847,6 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): "approved_domain", "alternative_domains", "purpose", - "submitter", "no_other_contacts_rationale", "anything_else", "is_policy_acknowledged", @@ -1813,7 +1857,6 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): autocomplete_fields = [ "approved_domain", "requested_domain", - "submitter", "creator", "senior_official", "investigator", @@ -1852,7 +1895,7 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): # Table ordering # NOTE: This impacts the select2 dropdowns (combobox) # Currentl, there's only one for requests on DomainInfo - ordering = ["-submission_date", "requested_domain__name"] + ordering = ["-last_submitted_date", "requested_domain__name"] change_form_template = "django/admin/domain_request_change_form.html" @@ -1914,6 +1957,9 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): else: obj.action_needed_reason_email = default_email + if obj.status in DomainRequest.get_statuses_that_send_emails() and not settings.IS_PRODUCTION: + self._check_for_valid_email(request, obj) + # == Handle status == # if obj.status == original_obj.status: # If the status hasn't changed, let the base function take care of it @@ -1926,6 +1972,25 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): if should_save: return super().save_model(request, obj, form, change) + def _check_for_valid_email(self, request, obj): + """Certain emails are whitelisted in non-production environments, + so we should display that information using this function. + + """ + + if hasattr(obj, "creator"): + recipient = obj.creator + else: + recipient = None + + # Displays a warning in admin when an email cannot be sent + if recipient and recipient.email: + email = recipient.email + allowed = models.AllowedEmail.is_allowed_email(email) + error_message = f"Could not send email. The email '{email}' does not exist within the whitelist." + if not allowed: + messages.warning(request, error_message) + def _handle_status_change(self, request, obj, original_obj): """ Checks for various conditions when a status change is triggered. @@ -2150,10 +2215,7 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): if not action_needed_reason or action_needed_reason == DomainRequest.ActionNeededReasons.OTHER: return None - if flag_is_active(None, "profile_feature"): # type: ignore - recipient = domain_request.creator - else: - recipient = domain_request.submitter + recipient = domain_request.creator # Return the context of the rendered views context = {"domain_request": domain_request, "recipient": recipient} @@ -2236,6 +2298,17 @@ class DomainRequestAdmin(ListHeaderAdmin, ImportExportModelAdmin): use_sort = db_field.name != "senior_official" return super().formfield_for_foreignkey(db_field, request, use_admin_sort_fields=use_sort, **kwargs) + def get_queryset(self, request): + """Custom get_queryset to filter by portfolio if portfolio is in the + request params.""" + qs = super().get_queryset(request) + # Check if a 'portfolio' parameter is passed in the request + portfolio_id = request.GET.get("portfolio") + if portfolio_id: + # Further filter the queryset by the portfolio + qs = qs.filter(portfolio=portfolio_id) + return qs + class TransitionDomainAdmin(ListHeaderAdmin): """Custom transition domain admin class.""" @@ -2724,6 +2797,17 @@ class DomainAdmin(ListHeaderAdmin, ImportExportModelAdmin): return True return super().has_change_permission(request, obj) + def get_queryset(self, request): + """Custom get_queryset to filter by portfolio if portfolio is in the + request params.""" + qs = super().get_queryset(request) + # Check if a 'portfolio' parameter is passed in the request + portfolio_id = request.GET.get("portfolio") + if portfolio_id: + # Further filter the queryset by the portfolio + qs = qs.filter(domain_info__portfolio=portfolio_id) + return qs + class DraftDomainResource(resources.ModelResource): """defines how each field in the referenced model should be mapped to the corresponding fields in the @@ -2903,12 +2987,8 @@ class PortfolioAdmin(ListHeaderAdmin): fieldsets = [ # created_on is the created_at field, and portfolio_type is f"{organization_type} - {federal_type}" (None, {"fields": ["portfolio_type", "organization_name", "creator", "created_on", "notes"]}), - # TODO - uncomment in #2521 - # ("Portfolio members", { - # "classes": ("collapse", "closed"), - # "fields": ["administrators", "members"]} - # ), - ("Portfolio domains", {"classes": ("collapse", "closed"), "fields": ["domains", "domain_requests"]}), + ("Portfolio members", {"fields": ["display_admins", "display_members"]}), + ("Portfolio domains", {"fields": ["domains", "domain_requests"]}), ("Type of organization", {"fields": ["organization_type", "federal_type"]}), ( "Organization name and mailing address", @@ -2955,14 +3035,118 @@ class PortfolioAdmin(ListHeaderAdmin): readonly_fields = [ # This is the created_at field "created_on", - # Custom fields such as these must be defined as readonly. + # Django admin doesn't allow methods to be directly listed in fieldsets. We can + # display the custom methods display_admins amd display_members in the admin form if + # they are readonly. "federal_type", "domains", "domain_requests", "suborganizations", "portfolio_type", + "display_admins", + "display_members", + "creator", ] + def get_admin_users(self, obj): + # Filter UserPortfolioPermission objects related to the portfolio + admin_permissions = UserPortfolioPermission.objects.filter( + portfolio=obj, roles__contains=[UserPortfolioRoleChoices.ORGANIZATION_ADMIN] + ) + + # Get the user objects associated with these permissions + admin_users = User.objects.filter(portfolio_permissions__in=admin_permissions) + + return admin_users + + def get_non_admin_users(self, obj): + # Filter UserPortfolioPermission objects related to the portfolio that do NOT have the "Admin" role + non_admin_permissions = UserPortfolioPermission.objects.filter(portfolio=obj).exclude( + roles__contains=[UserPortfolioRoleChoices.ORGANIZATION_ADMIN] + ) + + # Get the user objects associated with these permissions + non_admin_users = User.objects.filter(portfolio_permissions__in=non_admin_permissions) + + return non_admin_users + + def display_admins(self, obj): + """Get joined users who are Admin, unpack and return an HTML block. + + 'DJA readonly can't handle querysets, so we need to unpack and return html here. + Alternatively, we could return querysets in context but that would limit where this + data would display in a custom change form without extensive template customization. + + Will be used in the field_readonly block""" + admins = self.get_admin_users(obj) + if not admins: + return format_html("

No admins found.

") + + admin_details = "" + for portfolio_admin in admins: + change_url = reverse("admin:registrar_user_change", args=[portfolio_admin.pk]) + admin_details += "
" + admin_details += f'{escape(portfolio_admin)}
' + admin_details += f"{escape(portfolio_admin.title)}
" + admin_details += f"{escape(portfolio_admin.email)}" + admin_details += "
" + admin_details += f"{escape(portfolio_admin.phone)}" + admin_details += "
" + return format_html(admin_details) + + display_admins.short_description = "Administrators" # type: ignore + + def display_members(self, obj): + """Get joined users who have roles/perms that are not Admin, unpack and return an HTML block. + + DJA readonly can't handle querysets, so we need to unpack and return html here. + Alternatively, we could return querysets in context but that would limit where this + data would display in a custom change form without extensive template customization. + + Will be used in the after_help_text block.""" + members = self.get_non_admin_users(obj) + if not members: + return "" + + member_details = ( + "" + + "" + ) + for member in members: + full_name = member.get_formatted_name() + member_details += "" + member_details += f"" + member_details += f"" + member_details += f"" + member_details += f"" + member_details += "" + member_details += "
NameTitleEmailPhoneRoles
{escape(full_name)}{escape(member.title)}{escape(member.email)}{escape(member.phone)}" + for role in member.portfolio_role_summary(obj): + member_details += f"{escape(role)} " + member_details += "
" + return format_html(member_details) + + display_members.short_description = "Members" # type: ignore + + def display_members_summary(self, obj): + """Will be passed as context and used in the field_readonly block.""" + members = self.get_non_admin_users(obj) + if not members: + return {} + + return self.get_field_links_as_list(members, "user", separator=", ") + def federal_type(self, obj: models.Portfolio): """Returns the federal_type field""" return BranchChoices.get_branch_label(obj.federal_type) if obj.federal_type else "-" @@ -2990,18 +3174,27 @@ class PortfolioAdmin(ListHeaderAdmin): suborganizations.short_description = "Suborganizations" # type: ignore def domains(self, obj: models.Portfolio): - """Returns a list of links for each related domain""" - queryset = obj.get_domains() - return self.get_field_links_as_list( - queryset, "domaininformation", link_info_attribute="get_state_display_of_domain" - ) + """Returns the count of domains with a link to view them in the admin.""" + domain_count = obj.get_domains().count() # Count the related domains + if domain_count > 0: + # Construct the URL to the admin page, filtered by portfolio + url = reverse("admin:registrar_domain_changelist") + f"?portfolio={obj.id}" + label = "domain" if domain_count == 1 else "domains" + # Create a clickable link with the domain count + return format_html('{} {}', url, domain_count, label) + return "No domains" domains.short_description = "Domains" # type: ignore def domain_requests(self, obj: models.Portfolio): - """Returns a list of links for each related domain request""" - queryset = obj.get_domain_requests() - return self.get_field_links_as_list(queryset, "domainrequest", link_info_attribute="get_status_display") + """Returns the count of domain requests with a link to view them in the admin.""" + domain_request_count = obj.get_domain_requests().count() # Count the related domain requests + if domain_request_count > 0: + # Construct the URL to the admin page, filtered by portfolio + url = reverse("admin:registrar_domainrequest_changelist") + f"?portfolio={obj.id}" + # Create a clickable link with the domain request count + return format_html('{} domain requests', url, domain_request_count) + return "No domain requests" domain_requests.short_description = "Domain requests" # type: ignore @@ -3013,7 +3206,7 @@ class PortfolioAdmin(ListHeaderAdmin): ] def get_field_links_as_list( - self, queryset, model_name, attribute_name=None, link_info_attribute=None, seperator=None + self, queryset, model_name, attribute_name=None, link_info_attribute=None, separator=None ): """ Generate HTML links for items in a queryset, using a specified attribute for link text. @@ -3045,14 +3238,14 @@ class PortfolioAdmin(ListHeaderAdmin): if link_info_attribute: link += f" ({self.value_of_attribute(item, link_info_attribute)})" - if seperator: + if separator: links.append(link) else: links.append(f"
  • {link}
  • ") - # If no seperator is specified, just return an unordered list. - if seperator: - return format_html(seperator.join(links)) if links else "-" + # If no separator is specified, just return an unordered list. + if separator: + return format_html(separator.join(links)) if links else "-" else: links = "".join(links) return format_html(f'
      {links}
    ') if links else "-" @@ -3095,8 +3288,12 @@ class PortfolioAdmin(ListHeaderAdmin): return readonly_fields def change_view(self, request, object_id, form_url="", extra_context=None): - """Add related suborganizations and domain groups""" - extra_context = {"skip_additional_contact_info": True} + """Add related suborganizations and domain groups. + Add the summary for the portfolio members field (list of members that link to change_forms).""" + obj = self.get_object(request, object_id) + extra_context = extra_context or {} + extra_context["skip_additional_contact_info"] = True + extra_context["display_members_summary"] = self.display_members_summary(obj) return super().change_view(request, object_id, form_url, extra_context) def save_model(self, request, obj, form, change): @@ -3205,6 +3402,16 @@ class SuborganizationAdmin(ListHeaderAdmin, ImportExportModelAdmin): return super().change_view(request, object_id, form_url, extra_context) +class AllowedEmailAdmin(ListHeaderAdmin): + class Meta: + model = models.AllowedEmail + + list_display = ["email"] + search_fields = ["email"] + search_help_text = "Search by email." + ordering = ["email"] + + admin.site.unregister(LogEntry) # Unregister the default registration admin.site.register(LogEntry, CustomLogEntryAdmin) @@ -3232,6 +3439,8 @@ admin.site.register(models.Portfolio, PortfolioAdmin) admin.site.register(models.DomainGroup, DomainGroupAdmin) admin.site.register(models.Suborganization, SuborganizationAdmin) admin.site.register(models.SeniorOfficial, SeniorOfficialAdmin) +admin.site.register(models.UserPortfolioPermission, UserPortfolioPermissionAdmin) +admin.site.register(models.AllowedEmail, AllowedEmailAdmin) # Register our custom waffle implementations admin.site.register(models.WaffleFlag, WaffleFlagAdmin) diff --git a/src/registrar/assets/js/get-gov-admin-extra.js b/src/registrar/assets/js/get-gov-admin-extra.js new file mode 100644 index 000000000..14059267b --- /dev/null +++ b/src/registrar/assets/js/get-gov-admin-extra.js @@ -0,0 +1,14 @@ +// Use Django's jQuery with Select2 to make the user select on the user transfer view a combobox +(function($) { + $(document).ready(function() { + if ($) { + $("#selected_user").select2({ + width: 'resolve', + placeholder: 'Select a user', + allowClear: true + }); + } else { + console.error('jQuery is not available'); + } + }); +})(window.jQuery); diff --git a/src/registrar/assets/js/get-gov-admin.js b/src/registrar/assets/js/get-gov-admin.js index 01c93abf6..7ff02ba1f 100644 --- a/src/registrar/assets/js/get-gov-admin.js +++ b/src/registrar/assets/js/get-gov-admin.js @@ -172,40 +172,39 @@ function addOrRemoveSessionBoolean(name, add){ ** To perform data operations on this - we need to use jQuery rather than vanilla js. */ (function (){ - let selector = django.jQuery("#id_investigator") - let assignSelfButton = document.querySelector("#investigator__assign_self"); - if (!selector || !assignSelfButton) { - return; - } - - let currentUserId = assignSelfButton.getAttribute("data-user-id"); - let currentUserName = assignSelfButton.getAttribute("data-user-name"); - if (!currentUserId || !currentUserName){ - console.error("Could not assign current user: no values found.") - return; - } - - // Hook a click listener to the "Assign to me" button. - // Logic borrowed from here: https://select2.org/programmatic-control/add-select-clear-items#create-if-not-exists - assignSelfButton.addEventListener("click", function() { - if (selector.find(`option[value='${currentUserId}']`).length) { - // Select the value that is associated with the current user. - selector.val(currentUserId).trigger("change"); - } else { - // Create a DOM Option that matches the desired user. Then append it and select it. - let userOption = new Option(currentUserName, currentUserId, true, true); - selector.append(userOption).trigger("change"); + if (document.getElementById("id_investigator") && django && django.jQuery) { + let selector = django.jQuery("#id_investigator") + let assignSelfButton = document.querySelector("#investigator__assign_self"); + if (!selector || !assignSelfButton) { + return; } - }); - // Listen to any change events, and hide the parent container if investigator has a value. - selector.on('change', function() { - // The parent container has display type flex. - assignSelfButton.parentElement.style.display = this.value === currentUserId ? "none" : "flex"; - }); - - + let currentUserId = assignSelfButton.getAttribute("data-user-id"); + let currentUserName = assignSelfButton.getAttribute("data-user-name"); + if (!currentUserId || !currentUserName){ + console.error("Could not assign current user: no values found.") + return; + } + // Hook a click listener to the "Assign to me" button. + // Logic borrowed from here: https://select2.org/programmatic-control/add-select-clear-items#create-if-not-exists + assignSelfButton.addEventListener("click", function() { + if (selector.find(`option[value='${currentUserId}']`).length) { + // Select the value that is associated with the current user. + selector.val(currentUserId).trigger("change"); + } else { + // Create a DOM Option that matches the desired user. Then append it and select it. + let userOption = new Option(currentUserName, currentUserId, true, true); + selector.append(userOption).trigger("change"); + } + }); + + // Listen to any change events, and hide the parent container if investigator has a value. + selector.on('change', function() { + // The parent container has display type flex. + assignSelfButton.parentElement.style.display = this.value === currentUserId ? "none" : "flex"; + }); + } })(); /** An IIFE for pages in DjangoAdmin that use a clipboard button @@ -215,7 +214,6 @@ function addOrRemoveSessionBoolean(name, add){ function copyToClipboardAndChangeIcon(button) { // Assuming the input is the previous sibling of the button let input = button.previousElementSibling; - let userId = input.getAttribute("user-id") // Copy input value to clipboard if (input) { navigator.clipboard.writeText(input.value).then(function() { @@ -353,7 +351,7 @@ function initializeWidgetOnList(list, parentId) { let rejectionReasonFormGroup = document.querySelector('.field-rejection_reason') // This is the "action needed reason" field let actionNeededReasonFormGroup = document.querySelector('.field-action_needed_reason'); - // This is the "auto-generated email" field + // This is the "Email" field let actionNeededReasonEmailFormGroup = document.querySelector('.field-action_needed_reason_email') if (rejectionReasonFormGroup && actionNeededReasonFormGroup && actionNeededReasonEmailFormGroup) { @@ -509,22 +507,37 @@ function initializeWidgetOnList(list, parentId) { (function () { // Since this is an iife, these vars will be removed from memory afterwards var actionNeededReasonDropdown = document.querySelector("#id_action_needed_reason"); - var actionNeededEmail = document.querySelector("#id_action_needed_reason_email"); - var readonlyView = document.querySelector("#action-needed-reason-email-readonly"); + + // Placeholder text (for certain "action needed" reasons that do not involve e=mails) + var placeholderText = document.querySelector("#action-needed-reason-email-placeholder-text") + + // E-mail divs and textarea components + var actionNeededEmail = document.querySelector("#id_action_needed_reason_email") + var actionNeededEmailReadonly = document.querySelector("#action-needed-reason-email-readonly") + var actionNeededEmailReadonlyTextarea = document.querySelector("#action-needed-reason-email-readonly-textarea") + + // Edit e-mail modal (and its confirmation button) + var confirmEditEmailButton = document.querySelector("#email-already-sent-modal_continue-editing-button") + + // Headers and footers (which change depending on if the e-mail was sent or not) + var actionNeededEmailHeader = document.querySelector("#action-needed-email-header") + var actionNeededEmailHeaderOnSave = document.querySelector("#action-needed-email-header-email-sent") + var actionNeededEmailFooter = document.querySelector("#action-needed-email-footer") let emailWasSent = document.getElementById("action-needed-email-sent"); + let lastSentEmailText = document.getElementById("action-needed-email-last-sent-text"); + // Get the list of e-mails associated with each action-needed dropdown value let emailData = document.getElementById('action-needed-emails-data'); if (!emailData) { return; } - let actionNeededEmailData = emailData.textContent; if(!actionNeededEmailData) { return; } - let actionNeededEmailsJson = JSON.parse(actionNeededEmailData); + const domainRequestId = actionNeededReasonDropdown ? document.querySelector("#domain_request_id").value : null const emailSentSessionVariableName = `actionNeededEmailSent-${domainRequestId}`; const oldDropdownValue = actionNeededReasonDropdown ? actionNeededReasonDropdown.value : null; @@ -540,58 +553,117 @@ function initializeWidgetOnList(list, parentId) { // An email was sent out - store that information in a session variable addOrRemoveSessionBoolean(emailSentSessionVariableName, add=true); } - + // Show an editable email field or a readonly one updateActionNeededEmailDisplay(reason) }); + // editEmailButton.addEventListener("click", function() { + // if (!checkEmailAlreadySent()) { + // showEmail(canEdit=true) + // } + // }); + + confirmEditEmailButton.addEventListener("click", function() { + // Show editable view + showEmail(canEdit=true) + }); + + // Add a change listener to the action needed reason dropdown actionNeededReasonDropdown.addEventListener("change", function() { let reason = actionNeededReasonDropdown.value; let emailBody = reason in actionNeededEmailsJson ? actionNeededEmailsJson[reason] : null; + if (reason && emailBody) { - // Replace the email content - actionNeededEmail.value = emailBody; - // Reset the session object on change since change refreshes the email content. if (oldDropdownValue !== actionNeededReasonDropdown.value || oldEmailValue !== actionNeededEmail.value) { - let emailSent = sessionStorage.getItem(emailSentSessionVariableName) - if (emailSent !== null){ - addOrRemoveSessionBoolean(emailSentSessionVariableName, add=false) - } + // Replace the email content + actionNeededEmail.value = emailBody; + actionNeededEmailReadonlyTextarea.value = emailBody; + hideEmailAlreadySentView(); } } - // Show an editable email field or a readonly one + // Show either a preview of the email or some text describing no email will be sent updateActionNeededEmailDisplay(reason) }); } - // Shows an editable email field or a readonly one. + function checkEmailAlreadySent() + { + lastEmailSent = lastSentEmailText.value.replace(/\s+/g, '') + currentEmailInTextArea = actionNeededEmail.value.replace(/\s+/g, '') + return lastEmailSent === currentEmailInTextArea + } + + // Shows a readonly preview of the email with updated messaging to indicate this email was sent + function showEmailAlreadySentView() + { + hideElement(actionNeededEmailHeader) + showElement(actionNeededEmailHeaderOnSave) + actionNeededEmailFooter.innerHTML = "This email has been sent to the creator of this request"; + } + + // Shows a readonly preview of the email with updated messaging to indicate this email was sent + function hideEmailAlreadySentView() + { + showElement(actionNeededEmailHeader) + hideElement(actionNeededEmailHeaderOnSave) + actionNeededEmailFooter.innerHTML = "This email will be sent to the creator of this request after saving"; + } + + // Shows either a preview of the email or some text describing no email will be sent. // If the email doesn't exist or if we're of reason "other", display that no email was sent. - // Likewise, if we've sent this email before, we should just display the content. function updateActionNeededEmailDisplay(reason) { - let emailHasBeenSentBefore = sessionStorage.getItem(emailSentSessionVariableName) !== null; - let collapseableDiv = readonlyView.querySelector(".collapse--dgsimple"); - let showMoreButton = document.querySelector("#action_needed_reason_email__show_details"); - if ((reason && reason != "other") && !emailHasBeenSentBefore) { - showElement(actionNeededEmail.parentElement) - hideElement(readonlyView) - hideElement(showMoreButton) - } else { - if (!reason || reason === "other") { - collapseableDiv.innerHTML = reason ? "No email will be sent." : "-"; - hideElement(showMoreButton) - if (collapseableDiv.classList.contains("collapsed")) { - showMoreButton.click() - } - }else { - showElement(showMoreButton) + hideElement(actionNeededEmail.parentElement) + + if (reason) { + if (reason === "other") { + // Hide email preview and show this text instead + showPlaceholderText("No email will be sent"); } - hideElement(actionNeededEmail.parentElement) - showElement(readonlyView) + else { + // Always show readonly view of email to start + showEmail(canEdit=false) + if(checkEmailAlreadySent()) + { + showEmailAlreadySentView(); + } + } + } else { + // Hide email preview and show this text instead + showPlaceholderText("Select an action needed reason to see email"); } } + + // Shows either a readonly view (canEdit=false) or editable view (canEdit=true) of the action needed email + function showEmail(canEdit) + { + if(!canEdit) + { + showElement(actionNeededEmailReadonly) + hideElement(actionNeededEmail.parentElement) + } + else + { + hideElement(actionNeededEmailReadonly) + showElement(actionNeededEmail.parentElement) + } + showElement(actionNeededEmailFooter) // this is the same for both views, so it was separated out + hideElement(placeholderText) + } + + // Hides preview of action needed email and instead displays the given text (innerHTML) + function showPlaceholderText(innerHTML) + { + hideElement(actionNeededEmail.parentElement) + hideElement(actionNeededEmailReadonly) + hideElement(actionNeededEmailFooter) + + placeholderText.innerHTML = innerHTML; + showElement(placeholderText) + } })(); @@ -676,7 +748,10 @@ function initializeWidgetOnList(list, parentId) { //------ Requested Domains const requestedDomainElement = document.getElementById('id_requested_domain'); - const requestedDomain = requestedDomainElement.options[requestedDomainElement.selectedIndex].text; + // We have to account for different superuser and analyst markups + const requestedDomain = requestedDomainElement.options + ? requestedDomainElement.options[requestedDomainElement.selectedIndex].text + : requestedDomainElement.text; //------ Submitter // Function to extract text by ID and handle missing elements @@ -690,7 +765,10 @@ function initializeWidgetOnList(list, parentId) { // Extract the submitter name, title, email, and phone number const submitterDiv = document.querySelector('.form-row.field-submitter'); const submitterNameElement = document.getElementById('id_submitter'); - const submitterName = submitterNameElement.options[submitterNameElement.selectedIndex].text; + // We have to account for different superuser and analyst markups + const submitterName = submitterNameElement + ? submitterNameElement.options[submitterNameElement.selectedIndex].text + : submitterDiv.querySelector('a').text; const submitterTitle = extractTextById('contact_info_title', submitterDiv); const submitterEmail = extractTextById('contact_info_email', submitterDiv); const submitterPhone = extractTextById('contact_info_phone', submitterDiv); @@ -833,10 +911,28 @@ function initializeWidgetOnList(list, parentId) { return; } + // Determine if any changes are necessary to the display of portfolio type or federal type + // based on changes to the Federal Agency + let federalPortfolioApi = document.getElementById("federal_and_portfolio_types_from_agency_json_url").value; + fetch(`${federalPortfolioApi}?organization_type=${organizationType.value}&agency_name=${selectedText}`) + .then(response => { + const statusCode = response.status; + return response.json().then(data => ({ statusCode, data })); + }) + .then(({ statusCode, data }) => { + if (data.error) { + console.error("Error in AJAX call: " + data.error); + return; + } + updateReadOnly(data.federal_type, '.field-federal_type'); + updateReadOnly(data.portfolio_type, '.field-portfolio_type'); + }) + .catch(error => console.error("Error fetching federal and portfolio types: ", error)); + // Hide the contactList initially. // If we can update the contact information, it'll be shown again. hideElement(contactList.parentElement); - + let seniorOfficialApi = document.getElementById("senior_official_from_agency_json_url").value; fetch(`${seniorOfficialApi}?agency_name=${selectedText}`) .then(response => { @@ -879,6 +975,7 @@ function initializeWidgetOnList(list, parentId) { } }) .catch(error => console.error("Error fetching senior official: ", error)); + } function handleStateTerritoryChange(stateTerritory, urbanizationField) { @@ -890,6 +987,26 @@ function initializeWidgetOnList(list, parentId) { } } + /** + * Utility that selects a div from the DOM using selectorString, + * and updates a div within that div which has class of 'readonly' + * so that the text of the div is updated to updateText + * @param {*} updateText + * @param {*} selectorString + */ + function updateReadOnly(updateText, selectorString) { + // find the div by selectorString + const selectedDiv = document.querySelector(selectorString); + if (selectedDiv) { + // find the nested div with class 'readonly' inside the selectorString div + const readonlyDiv = selectedDiv.querySelector('.readonly'); + if (readonlyDiv) { + // Update the text content of the readonly div + readonlyDiv.textContent = updateText !== null ? updateText : '-'; + } + } + } + function updateContactInfo(data) { if (!contactList) return; diff --git a/src/registrar/assets/js/get-gov.js b/src/registrar/assets/js/get-gov.js index f3b41eb51..cd42fd322 100644 --- a/src/registrar/assets/js/get-gov.js +++ b/src/registrar/assets/js/get-gov.js @@ -1168,7 +1168,6 @@ document.addEventListener('DOMContentLoaded', function() { const statusCheckboxes = document.querySelectorAll('input[name="filter-status"]'); const statusIndicator = document.querySelector('.domain__filter-indicator'); const statusToggle = document.querySelector('.usa-button--filter'); - const noPortfolioFlag = document.getElementById('no-portfolio-js-flag'); const portfolioElement = document.getElementById('portfolio-js-value'); const portfolioValue = portfolioElement ? portfolioElement.getAttribute('data-portfolio') : null; @@ -1220,16 +1219,16 @@ document.addEventListener('DOMContentLoaded', function() { const expirationDateFormatted = expirationDate ? expirationDate.toLocaleDateString('en-US', options) : ''; const expirationDateSortValue = expirationDate ? expirationDate.getTime() : ''; const actionUrl = domain.action_url; - const suborganization = domain.suborganization ? domain.suborganization : ''; + const suborganization = domain.domain_info__sub_organization ? domain.domain_info__sub_organization : '⎯'; const row = document.createElement('tr'); let markupForSuborganizationRow = ''; - if (!noPortfolioFlag) { + if (portfolioValue) { markupForSuborganizationRow = ` - ${suborganization} + ${suborganization} ` } @@ -1427,9 +1426,9 @@ document.addEventListener('DOMContentLoaded', function() { // NOTE: We may need to evolve this as we add more filters. document.addEventListener('focusin', function(event) { const accordion = document.querySelector('.usa-accordion--select'); - const accordionIsOpen = document.querySelector('.usa-button--filter[aria-expanded="true"]'); + const accordionThatIsOpen = document.querySelector('.usa-button--filter[aria-expanded="true"]'); - if (accordionIsOpen && !accordion.contains(event.target)) { + if (accordionThatIsOpen && !accordion.contains(event.target)) { closeFilters(); } }); @@ -1438,9 +1437,9 @@ document.addEventListener('DOMContentLoaded', function() { // NOTE: We may need to evolve this as we add more filters. document.addEventListener('click', function(event) { const accordion = document.querySelector('.usa-accordion--select'); - const accordionIsOpen = document.querySelector('.usa-button--filter[aria-expanded="true"]'); + const accordionThatIsOpen = document.querySelector('.usa-button--filter[aria-expanded="true"]'); - if (accordionIsOpen && !accordion.contains(event.target)) { + if (accordionThatIsOpen && !accordion.contains(event.target)) { closeFilters(); } }); @@ -1485,6 +1484,8 @@ document.addEventListener('DOMContentLoaded', function() { const tableHeaders = document.querySelectorAll('.domain-requests__table th[data-sortable]'); const tableAnnouncementRegion = document.querySelector('.domain-requests__table-wrapper .usa-table__announcement-region'); const resetSearchButton = document.querySelector('.domain-requests__reset-search'); + const portfolioElement = document.getElementById('portfolio-js-value'); + const portfolioValue = portfolioElement ? portfolioElement.getAttribute('data-portfolio') : null; /** * Delete is actually a POST API that requires a csrf token. The token will be waiting for us in the template as a hidden input. @@ -1533,7 +1534,7 @@ document.addEventListener('DOMContentLoaded', function() { * @param {*} scroll - control for the scrollToElement functionality * @param {*} searchTerm - the search term */ - function loadDomainRequests(page, sortBy = currentSortBy, order = currentOrder, scroll = scrollToTable, searchTerm = currentSearchTerm) { + function loadDomainRequests(page, sortBy = currentSortBy, order = currentOrder, scroll = scrollToTable, searchTerm = currentSearchTerm, portfolio = portfolioValue) { // fetch json of page of domain requests, given params let baseUrl = document.getElementById("get_domain_requests_json_url"); if (!baseUrl) { @@ -1545,7 +1546,12 @@ document.addEventListener('DOMContentLoaded', function() { return; } - fetch(`${baseUrlValue}?page=${page}&sort_by=${sortBy}&order=${order}&search_term=${searchTerm}`) + // fetch json of page of requests, given params + let url = `${baseUrlValue}?page=${page}&sort_by=${sortBy}&order=${order}&search_term=${searchTerm}` + if (portfolio) + url += `&portfolio=${portfolio}` + + fetch(url) .then(response => response.json()) .then(data => { if (data.error) { @@ -1599,12 +1605,23 @@ document.addEventListener('DOMContentLoaded', function() { const domainName = request.requested_domain ? request.requested_domain : `New domain request
    (${utcDateString(request.created_at)})`; const actionUrl = request.action_url; const actionLabel = request.action_label; - const submissionDate = request.submission_date ? new Date(request.submission_date).toLocaleDateString('en-US', options) : `Not submitted`; + const submissionDate = request.last_submitted_date ? new Date(request.last_submitted_date).toLocaleDateString('en-US', options) : `Not submitted`; - // Even if the request is not deletable, we may need this empty string for the td if the deletable column is displayed + // The markup for the delete function either be a simple trigger or a 3 dots menu with a hidden trigger (in the case of portfolio requests page) + // Even if the request is not deletable, we may need these empty strings for the td if the deletable column is displayed let modalTrigger = ''; - // If the request is deletable, create modal body and insert it + let markupCreatorRow = ''; + + if (portfolioValue) { + markupCreatorRow = ` + + ${request.creator ? request.creator : ''} + + ` + } + + // If the request is deletable, create modal body and insert it. This is true for both requests and portfolio requests pages if (request.is_deletable) { let modalHeading = ''; let modalDescription = ''; @@ -1627,7 +1644,7 @@ document.addEventListener('DOMContentLoaded', function() { role="button" id="button-toggle-delete-domain-alert-${request.id}" href="#toggle-delete-domain-alert-${request.id}" - class="usa-button--unstyled text-no-underline late-loading-modal-trigger" + class="usa-button text-secondary usa-button--unstyled text-no-underline late-loading-modal-trigger line-height-sans-5" aria-controls="toggle-delete-domain-alert-${request.id}" data-open-modal > @@ -1692,16 +1709,66 @@ document.addEventListener('DOMContentLoaded', function() { ` domainRequestsSectionWrapper.appendChild(modal); + + // Request is deletable, modal and modalTrigger are built. Now check if we are on the portfolio requests page (by seeing if there is a portfolio value) and enhance the modalTrigger accordingly + if (portfolioValue) { + modalTrigger = ` + + Delete ${domainName} + + +
    +
    + +
    + +
    + ` + } } + const row = document.createElement('tr'); row.innerHTML = ` ${domainName} - + ${submissionDate} + ${markupCreatorRow} ${request.status} @@ -1817,6 +1884,32 @@ document.addEventListener('DOMContentLoaded', function() { }); } + function closeMoreActionMenu(accordionThatIsOpen) { + if (accordionThatIsOpen.getAttribute("aria-expanded") === "true") { + accordionThatIsOpen.click(); + } + } + + document.addEventListener('focusin', function(event) { + closeOpenAccordions(event); + }); + + document.addEventListener('click', function(event) { + closeOpenAccordions(event); + }); + + function closeOpenAccordions(event) { + const openAccordions = document.querySelectorAll('.usa-button--more-actions[aria-expanded="true"]'); + openAccordions.forEach((openAccordionButton) => { + // Find the corresponding accordion + const accordion = openAccordionButton.closest('.usa-accordion--more-actions'); + if (accordion && !accordion.contains(event.target)) { + // Close the accordion if the click is outside + closeMoreActionMenu(openAccordionButton); + } + }); + } + // Initial load loadDomainRequests(1); } @@ -1910,7 +2003,7 @@ document.addEventListener('DOMContentLoaded', function() { let editableFormGroup = button.parentElement.parentElement.parentElement; if (editableFormGroup){ - let readonlyField = editableFormGroup.querySelector(".input-with-edit-button__readonly-field") + let readonlyField = editableFormGroup.querySelector(".toggleable_input__readonly-field") let inputField = document.getElementById(`id_${fieldName}`); if (!inputField || !readonlyField) { return; @@ -1936,8 +2029,8 @@ document.addEventListener('DOMContentLoaded', function() { // Keep the path before '#' and replace the part after '#' with 'invalid' const newHref = parts[0] + '#error'; svg.setAttribute('xlink:href', newHref); - fullNameField.classList.add("input-with-edit-button__error") - label = fullNameField.querySelector(".input-with-edit-button__readonly-field") + fullNameField.classList.add("toggleable_input__error") + label = fullNameField.querySelector(".toggleable_input__readonly-field") label.innerHTML = "Unknown"; } } @@ -2043,11 +2136,11 @@ document.addEventListener('DOMContentLoaded', function() { // Due to the nature of how uswds works, this is slightly hacky. // Use a MutationObserver to watch for changes in the dropdown list - const dropdownList = document.querySelector(`#${input.id}--list`); + const dropdownList = comboBox.querySelector(`#${input.id}--list`); const observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type === "childList") { - addBlankOption(clearInputButton, dropdownList, initialValue); + addBlankOption(clearInputButton, dropdownList, initialValue); } }); }); @@ -2111,7 +2204,7 @@ document.addEventListener('DOMContentLoaded', function() { if (!initialValue){ blankOption.classList.add("usa-combo-box__list-option--selected") } - blankOption.textContent = "---------"; + blankOption.textContent = "⎯"; dropdownList.insertBefore(blankOption, dropdownList.firstChild); blankOption.addEventListener("click", (e) => { diff --git a/src/registrar/assets/sass/_theme/_accordions.scss b/src/registrar/assets/sass/_theme/_accordions.scss index 839d7ac42..df4f686d8 100644 --- a/src/registrar/assets/sass/_theme/_accordions.scss +++ b/src/registrar/assets/sass/_theme/_accordions.scss @@ -1,6 +1,7 @@ @use "uswds-core" as *; -.usa-accordion--select { +.usa-accordion--select, +.usa-accordion--more-actions { display: inline-block; width: auto; position: relative; @@ -14,7 +15,6 @@ // Note, width is determined by a custom width class on one of the children position: absolute; z-index: 1; - top: 33.88px; left: 0; border-radius: 4px; border: solid 1px color('base-lighter'); @@ -31,3 +31,17 @@ margin-top: 0 !important; } } + +.usa-accordion--select .usa-accordion__content { + top: 33.88px; +} + +.usa-accordion--more-actions .usa-accordion__content { + top: 30px; +} + +tr:last-child .usa-accordion--more-actions .usa-accordion__content { + top: auto; + bottom: -10px; + right: 30px; +} diff --git a/src/registrar/assets/sass/_theme/_admin.scss b/src/registrar/assets/sass/_theme/_admin.scss index 8ca6b5465..ef1a810ac 100644 --- a/src/registrar/assets/sass/_theme/_admin.scss +++ b/src/registrar/assets/sass/_theme/_admin.scss @@ -66,6 +66,9 @@ html[data-theme="light"] { // --object-tools-fg: var(--button-fg); // --object-tools-bg: var(--close-button-bg); // --object-tools-hover-bg: var(--close-button-hover-bg); + + --summary-box-bg: #f1f1f1; + --summary-box-border: #d1d2d2; } // Fold dark theme settings into our main CSS @@ -104,6 +107,9 @@ html[data-theme="light"] { --close-button-bg: #333333; --close-button-hover-bg: #666666; + + --summary-box-bg: #121212; + --summary-box-border: #666666; } // Dark mode django (bug due to scss cascade) and USWDS tables @@ -120,7 +126,7 @@ html[data-theme="light"] { body.dashboard, body.change-list, body.change-form, - .analytics { + .custom-admin-template, dt { color: var(--body-fg); } .usa-table td { @@ -149,7 +155,7 @@ html[data-theme="dark"] { body.dashboard, body.change-list, body.change-form, - .analytics { + .custom-admin-template, dt { color: var(--body-fg); } .usa-table td { @@ -160,7 +166,7 @@ html[data-theme="dark"] { // Remove when dark mode successfully applies to Django delete page. .delete-confirmation .content a:not(.button) { color: color('primary'); - } + } } @@ -364,14 +370,60 @@ input.admin-confirm-button { list-style-type: none; line-height: normal; } - .button { - display: inline-block; - padding: 10px 8px; - line-height: normal; - } - a.button:active, a.button:focus { - text-decoration: none; - } +} + +// This block resolves some of the issues we're seeing on buttons due to css +// conflicts between DJ and USWDS +a.button, +.usa-button--dja { + display: inline-block; + padding: 10px 15px; + font-size: 14px; + line-height: 16.1px; + font-kerning: auto; + font-family: inherit; + font-weight: normal; +} +.button svg, +.button span, +.usa-button--dja svg, +.usa-button--dja span { + vertical-align: middle; +} +.usa-button--dja:not(.usa-button--unstyled, .usa-button--outline, .usa-modal__close, .usa-button--secondary) { + background: var(--button-bg); +} +.usa-button--dja span { + font-size: 14px; +} +.usa-button--dja:not(.usa-button--unstyled, .usa-button--outline, .usa-modal__close, .usa-button--secondary):hover { + background: var(--button-hover-bg); +} +a.button:active, a.button:focus { + text-decoration: none; +} +.usa-modal { + font-family: inherit; +} +input[type=submit].button--dja-toolbar { + border: 1px solid var(--border-color); + font-size: 0.8125rem; + padding: 4px 8px; + margin: 0; + vertical-align: middle; + background: var(--body-bg); + box-shadow: 0 -15px 20px -10px rgba(0, 0, 0, 0.15) inset; + cursor: pointer; + color: var(--body-fg); +} +input[type=submit].button--dja-toolbar:focus, input[type=submit].button--dja-toolbar:hover { + border-color: var(--body-quiet-color); +} +// Targets the DJA buttom with a nested icon +button .usa-icon, +.button .usa-icon, +.button--clipboard .usa-icon { + vertical-align: middle; } .module--custom { @@ -465,13 +517,6 @@ address.dja-address-contact-list { color: var(--link-fg); } -// Targets the DJA buttom with a nested icon -button .usa-icon, -.button .usa-icon, -.button--clipboard .usa-icon { - vertical-align: middle; -} - .errors span.select2-selection { border: 1px solid var(--error-fg) !important; } @@ -540,7 +585,7 @@ button .usa-icon, #submitRowToggle { color: var(--body-fg); } - .requested-domain-sticky { + .submit-row-sticky { max-width: 325px; overflow: hidden; white-space: nowrap; @@ -732,7 +777,7 @@ div.dja__model-description{ li { list-style-type: disc; - font-family: Source Sans Pro Web,Helvetica Neue,Helvetica,Roboto,Arial,sans-serif; + font-family: family('sans'); } a, a:link, a:visited { @@ -848,7 +893,40 @@ div.dja__model-description{ } } +.vertical-separator { + min-height: 20px; + height: 100%; + width: 1px; + background-color: #d1d2d2; + vertical-align: middle +} + +.usa-summary-box_admin { + color: var(--body-fg); + border-color: var(--summary-box-border); + background-color: var(--summary-box-bg); + min-width: fit-content; + padding: .5rem; + border-radius: .25rem; +} + +.text-faded { + color: #{$dhs-gray-60}; +} ul.add-list-reset { padding: 0 !important; margin: 0 !important; } + +// Fix the combobox when deployed outside admin (eg user transfer) +.submit-row .select2, +.submit-row .select2 span { + margin-top: 0; +} +.transfer-user-selector .select2-selection__placeholder { + color: #3d4551!important; +} + +.dl-dja dt { + font-size: 14px; +} diff --git a/src/registrar/assets/sass/_theme/_base.scss b/src/registrar/assets/sass/_theme/_base.scss index 9f8a0cbb6..9d2ed4177 100644 --- a/src/registrar/assets/sass/_theme/_base.scss +++ b/src/registrar/assets/sass/_theme/_base.scss @@ -33,16 +33,19 @@ body { } #wrapper.dashboard--portfolio { - background-color: color('gray-1'); padding-top: units(4)!important; } +#wrapper.dashboard--grey-1 { + background-color: color('gray-1'); +} -.section--outlined { + +.section-outlined { background-color: color('white'); border: 1px solid color('base-lighter'); border-radius: 4px; - padding: 0 units(2) units(3); + padding: 0 units(4) units(3) units(2); margin-top: units(3); &.margin-top-0 { @@ -72,9 +75,13 @@ body { } } -.section--outlined__header--no-portfolio { - .section--outlined__search, - .section--outlined__utility-button { +.section-outlined--border-base-light { + border: 1px solid color('base-light'); +} + +.section-outlined__header--no-portfolio { + .section-outlined__search, + .section-outlined__utility-button { margin-top: units(2); } @@ -82,11 +89,11 @@ body { display: flex; column-gap: units(3); - .section--outlined__search, - .section--outlined__utility-button { + .section-outlined__search, + .section-outlined__utility-button { margin-top: 0; } - .section--outlined__search { + .section-outlined__search { flex-grow: 4; // Align right max-width: 383px; @@ -152,6 +159,23 @@ abbr[title] { } } +.hidden-mobile-flex { + display: none!important; +} +.visible-mobile-flex { + display: flex!important; +} + +@include at-media(tablet) { + .hidden-mobile-flex { + display: flex!important; + } + .visible-mobile-flex { + display: none!important; + } +} + + .flex-end { align-items: flex-end; } @@ -192,3 +216,12 @@ abbr[title] { max-width: 50ch; } } + +// Boost this USWDS utility class for the accordions in the portfolio requests table +.left-auto { + left: auto!important; +} + +.break-word { + word-break: break-word; +} diff --git a/src/registrar/assets/sass/_theme/_buttons.scss b/src/registrar/assets/sass/_theme/_buttons.scss index d246366d8..d431bfa41 100644 --- a/src/registrar/assets/sass/_theme/_buttons.scss +++ b/src/registrar/assets/sass/_theme/_buttons.scss @@ -124,10 +124,6 @@ a.withdraw:active { background-color: color('error-darker'); } -.usa-button--unstyled .usa-icon { - vertical-align: bottom; -} - a.usa-button--unstyled:visited { color: color('primary'); } @@ -162,14 +158,14 @@ a.usa-button--unstyled:visited { } } -.input-with-edit-button { +.toggleable_input { svg.usa-icon { width: 1.5em !important; height: 1.5em !important; color: #{$dhs-green}; position: absolute; } - &.input-with-edit-button__error { + &.toggleable_input__error { svg.usa-icon { color: #{$dhs-red}; } @@ -205,12 +201,31 @@ a.usa-button--unstyled:visited { } } +.dotgov-table a, +.usa-link--icon, +.usa-button--with-icon { + display: flex; + align-items: flex-start; + color: color('primary'); + column-gap: units(.5); + align-items: center; +} + +.dotgov-table a +a .usa-icon, +.usa-button--with-icon .usa-icon { + height: 1.3em; + width: 1.3em; +} + .usa-icon.usa-icon--big { margin: 0; height: 1.5em; width: 1.5em; } -.margin-right-neg-4px { - margin-right: -4px; -} \ No newline at end of file +button.text-secondary, +button.text-secondary:hover, +.dotgov-table a.text-secondary { + color: $theme-color-error; +} diff --git a/src/registrar/assets/sass/_theme/_header.scss b/src/registrar/assets/sass/_theme/_header.scss index 3d72a09cf..d79774d98 100644 --- a/src/registrar/assets/sass/_theme/_header.scss +++ b/src/registrar/assets/sass/_theme/_header.scss @@ -89,16 +89,24 @@ .usa-nav__primary { .usa-nav-link, .usa-nav-link:hover, - .usa-nav-link:active { + .usa-nav-link:active, + button { color: color('primary'); font-weight: font-weight('normal'); font-size: 16px; } .usa-current, .usa-current:hover, - .usa-current:active { + .usa-current:active, + button.usa-current { font-weight: font-weight('bold'); } + button[aria-expanded="true"] { + color: color('white'); + } + button:not(.usa-current):hover::after { + display: none!important; + } } .usa-nav__secondary { // I don't know why USWDS has this at 2 rem, which puts it out of alignment diff --git a/src/registrar/assets/sass/_theme/_links.scss b/src/registrar/assets/sass/_theme/_links.scss deleted file mode 100644 index fd1c3dee9..000000000 --- a/src/registrar/assets/sass/_theme/_links.scss +++ /dev/null @@ -1,18 +0,0 @@ -@use "uswds-core" as *; - -.dotgov-table a, -.usa-link--icon { - display: flex; - align-items: flex-start; - color: color('primary'); - - &:visited { - color: color('primary'); - } - .usa-icon { - // align icon with x height - margin-top: units(0.5); - margin-right: units(0.5); - } -} - diff --git a/src/registrar/assets/sass/_theme/_tables.scss b/src/registrar/assets/sass/_theme/_tables.scss index e78715da8..d57b51117 100644 --- a/src/registrar/assets/sass/_theme/_tables.scss +++ b/src/registrar/assets/sass/_theme/_tables.scss @@ -1,5 +1,10 @@ @use "uswds-core" as *; +td, +th { + vertical-align: top; +} + .dotgov-table--stacked { td, th { padding: units(1) units(2) units(2px) 0; @@ -12,7 +17,7 @@ tr { border-bottom: none; - border-top: 2px solid color('base-light'); + border-top: 2px solid color('base-lighter'); margin-top: units(2); &:first-child { @@ -39,10 +44,6 @@ .dotgov-table { width: 100%; - th[data-sortable]:not([aria-sort]) .usa-table__header__button { - right: auto; - } - tbody th { word-break: break-word; } @@ -56,7 +57,7 @@ } td, th { - border-bottom: 1px solid color('base-light'); + border-bottom: 1px solid color('base-lighter'); } thead th { @@ -72,11 +73,17 @@ td, th, .usa-tabel th{ - padding: units(2) units(2) units(2) 0; + padding: units(2) units(4) units(2) 0; } thead tr:first-child th:first-child { border-top: none; } } + + @include at-media(tablet-lg) { + th[data-sortable]:not([aria-sort]) .usa-table__header__button { + right: auto; + } + } } diff --git a/src/registrar/assets/sass/_theme/styles.scss b/src/registrar/assets/sass/_theme/styles.scss index f9df015b4..5616b7509 100644 --- a/src/registrar/assets/sass/_theme/styles.scss +++ b/src/registrar/assets/sass/_theme/styles.scss @@ -10,7 +10,6 @@ --- Custom Styles ---------------------------------*/ @forward "base"; @forward "typography"; -@forward "links"; @forward "lists"; @forward "accordions"; @forward "buttons"; diff --git a/src/registrar/config/settings.py b/src/registrar/config/settings.py index 73aecad7a..96740a15c 100644 --- a/src/registrar/config/settings.py +++ b/src/registrar/config/settings.py @@ -23,6 +23,9 @@ from cfenv import AppEnv # type: ignore from pathlib import Path from typing import Final from botocore.config import Config +import json +import logging +from django.utils.log import ServerFormatter # # # ### # Setup code goes here # @@ -57,7 +60,7 @@ env_db_url = env.dj_db_url("DATABASE_URL") env_debug = env.bool("DJANGO_DEBUG", default=False) env_is_production = env.bool("IS_PRODUCTION", default=False) env_log_level = env.str("DJANGO_LOG_LEVEL", "DEBUG") -env_base_url = env.str("DJANGO_BASE_URL") +env_base_url: str = env.str("DJANGO_BASE_URL") env_getgov_public_site_url = env.str("GETGOV_PUBLIC_SITE_URL", "") env_oidc_active_provider = env.str("OIDC_ACTIVE_PROVIDER", "identity sandbox") @@ -192,7 +195,7 @@ MIDDLEWARE = [ "registrar.registrar_middleware.CheckPortfolioMiddleware", ] -# application object used by Django’s built-in servers (e.g. `runserver`) +# application object used by Django's built-in servers (e.g. `runserver`) WSGI_APPLICATION = "registrar.config.wsgi.application" # endregion @@ -357,13 +360,18 @@ CSP_FORM_ACTION = allowed_sources # and inline with a nonce, as well as allowing connections back to their domain. # Note: If needed, we can embed chart.js instead of using the CDN CSP_DEFAULT_SRC = ("'self'",) -CSP_STYLE_SRC = ["'self'", "https://www.ssa.gov/accessibility/andi/andi.css"] +CSP_STYLE_SRC = [ + "'self'", + "https://www.ssa.gov/accessibility/andi/andi.css", + "https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css", +] CSP_SCRIPT_SRC_ELEM = [ "'self'", "https://www.googletagmanager.com/", "https://cdn.jsdelivr.net/npm/chart.js", "https://www.ssa.gov", "https://ajax.googleapis.com", + "https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js", ] CSP_CONNECT_SRC = ["'self'", "https://www.google-analytics.com/", "https://www.ssa.gov/accessibility/andi/andi.js"] CSP_INCLUDE_NONCE_IN = ["script-src-elem", "style-src"] @@ -410,7 +418,7 @@ LANGUAGE_COOKIE_SECURE = True # and to interpret datetimes entered in forms TIME_ZONE = "UTC" -# enable Django’s translation system +# enable Django's translation system USE_I18N = True # enable localized formatting of numbers and dates @@ -445,6 +453,40 @@ PHONENUMBER_DEFAULT_REGION = "US" # logger.error("Can't do this important task. Something is very wrong.") # logger.critical("Going to crash now.") + +class JsonFormatter(logging.Formatter): + """Formats logs into JSON for better parsing""" + + def __init__(self): + super().__init__(datefmt="%d/%b/%Y %H:%M:%S") + + def format(self, record): + log_record = { + "timestamp": self.formatTime(record, self.datefmt), + "level": record.levelname, + "name": record.name, + "lineno": record.lineno, + "message": record.getMessage(), + } + return json.dumps(log_record) + + +class JsonServerFormatter(ServerFormatter): + """Formats server logs into JSON for better parsing""" + + def format(self, record): + formatted_record = super().format(record) + log_entry = {"server_time": record.server_time, "level": record.levelname, "message": formatted_record} + return json.dumps(log_entry) + + +# default to json formatted logs +server_formatter, console_formatter = "json.server", "json" + +# don't use json format locally, it makes logs hard to read in console +if "localhost" in env_base_url: + server_formatter, console_formatter = "django.server", "verbose" + LOGGING = { "version": 1, # Don't import Django's existing loggers @@ -464,6 +506,12 @@ LOGGING = { "format": "[{server_time}] {message}", "style": "{", }, + "json.server": { + "()": JsonServerFormatter, + }, + "json": { + "()": JsonFormatter, + }, }, # define where log messages will be sent; # each logger can have one or more handlers @@ -471,12 +519,12 @@ LOGGING = { "console": { "level": env_log_level, "class": "logging.StreamHandler", - "formatter": "verbose", + "formatter": console_formatter, }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", - "formatter": "django.server", + "formatter": server_formatter, }, # No file logger is configured, # because containerized apps diff --git a/src/registrar/config/urls.py b/src/registrar/config/urls.py index 413449896..9b9ed569e 100644 --- a/src/registrar/config/urls.py +++ b/src/registrar/config/urls.py @@ -24,7 +24,11 @@ from registrar.views.report_views import ( from registrar.views.domain_request import Step 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.transfer_user import TransferUserView +from registrar.views.utility.api_views import ( + get_senior_official_from_federal_agency_json, + get_federal_and_portfolio_types_from_federal_agency_json, +) from registrar.views.domains_json import get_domains_json from registrar.views.utility import always_404 from api.views import available, get_current_federal, get_current_full @@ -49,7 +53,6 @@ for step, view in [ (Step.CURRENT_SITES, views.CurrentSites), (Step.DOTGOV_DOMAIN, views.DotgovDomain), (Step.PURPOSE, views.Purpose), - (Step.YOUR_CONTACT, views.YourContact), (Step.OTHER_CONTACTS, views.OtherContacts), (Step.ADDITIONAL_DETAILS, views.AdditionalDetails), (Step.REQUIREMENTS, views.Requirements), @@ -75,6 +78,11 @@ urlpatterns = [ views.PortfolioDomainRequestsView.as_view(), name="domain-requests", ), + path( + "no-organization-requests/", + views.PortfolioNoDomainRequestsView.as_view(), + name="no-portfolio-requests", + ), path( "organization/", views.PortfolioOrganizationView.as_view(), @@ -134,11 +142,17 @@ urlpatterns = [ AnalyticsView.as_view(), name="analytics", ), + path("admin/registrar/user//transfer/", TransferUserView.as_view(), name="transfer_user"), path( "admin/api/get-senior-official-from-federal-agency-json/", get_senior_official_from_federal_agency_json, name="get-senior-official-from-federal-agency-json", ), + path( + "admin/api/get-federal-and-portfolio-types-from-federal-agency-json/", + get_federal_and_portfolio_types_from_federal_agency_json, + name="get-federal-and-portfolio-types-from-federal-agency-json", + ), path("admin/", admin.site.urls), path( "reports/export_data_type_user/", @@ -198,11 +212,6 @@ urlpatterns = [ views.DomainDsDataView.as_view(), name="domain-dns-dnssec-dsdata", ), - path( - "domain//your-contact-information", - views.DomainYourContactInformationView.as_view(), - name="domain-your-contact-information", - ), path( "domain//org-name-address", views.DomainOrgNameAddressView.as_view(), diff --git a/src/registrar/context_processors.py b/src/registrar/context_processors.py index ee5f8aee1..41046ed1c 100644 --- a/src/registrar/context_processors.py +++ b/src/registrar/context_processors.py @@ -60,28 +60,42 @@ def add_has_profile_feature_flag_to_context(request): def portfolio_permissions(request): """Make portfolio permissions for the request user available in global context""" + portfolio_context = { + "has_base_portfolio_permission": False, + "has_any_domains_portfolio_permission": False, + "has_any_requests_portfolio_permission": False, + "has_edit_request_portfolio_permission": False, + "has_view_suborganization_portfolio_permission": False, + "has_edit_suborganization_portfolio_permission": False, + "has_view_members_portfolio_permission": False, + "has_edit_members_portfolio_permission": False, + "portfolio": None, + "has_organization_feature_flag": False, + "has_organization_requests_flag": False, + "has_organization_members_flag": False, + } try: - if not request.user or not request.user.is_authenticated or not flag_is_active(request, "organization_feature"): + portfolio = request.session.get("portfolio") + # Linting: line too long + view_suborg = request.user.has_view_suborganization_portfolio_permission(portfolio) + edit_suborg = request.user.has_edit_suborganization_portfolio_permission(portfolio) + if portfolio: return { - "has_base_portfolio_permission": False, - "has_domains_portfolio_permission": False, - "has_domain_requests_portfolio_permission": False, - "portfolio": None, - "has_organization_feature_flag": False, + "has_base_portfolio_permission": request.user.has_base_portfolio_permission(portfolio), + "has_edit_request_portfolio_permission": request.user.has_edit_request_portfolio_permission(portfolio), + "has_view_suborganization_portfolio_permission": view_suborg, + "has_edit_suborganization_portfolio_permission": edit_suborg, + "has_any_domains_portfolio_permission": request.user.has_any_domains_portfolio_permission(portfolio), + "has_any_requests_portfolio_permission": request.user.has_any_requests_portfolio_permission(portfolio), + "has_view_members_portfolio_permission": request.user.has_view_members_portfolio_permission(portfolio), + "has_edit_members_portfolio_permission": request.user.has_edit_members_portfolio_permission(portfolio), + "portfolio": portfolio, + "has_organization_feature_flag": True, + "has_organization_requests_flag": request.user.has_organization_requests_flag(), + "has_organization_members_flag": request.user.has_organization_members_flag(), } - return { - "has_base_portfolio_permission": request.user.has_base_portfolio_permission(), - "has_domains_portfolio_permission": request.user.has_domains_portfolio_permission(), - "has_domain_requests_portfolio_permission": request.user.has_domain_requests_portfolio_permission(), - "portfolio": request.user.portfolio, - "has_organization_feature_flag": True, - } + return portfolio_context + except AttributeError: # Handles cases where request.user might not exist - return { - "has_base_portfolio_permission": False, - "has_domains_portfolio_permission": False, - "has_domain_requests_portfolio_permission": False, - "portfolio": None, - "has_organization_feature_flag": False, - } + return portfolio_context diff --git a/src/registrar/fixtures_domain_requests.py b/src/registrar/fixtures_domain_requests.py index 50f611474..44dd13e4c 100644 --- a/src/registrar/fixtures_domain_requests.py +++ b/src/registrar/fixtures_domain_requests.py @@ -37,7 +37,6 @@ class DomainRequestFixture: # "anything_else": None, # "is_policy_acknowledged": None, # "senior_official": None, - # "submitter": None, # "other_contacts": [], # "current_websites": [], # "alternative_domains": [], @@ -95,7 +94,7 @@ class DomainRequestFixture: # TODO for a future ticket: Allow for more than just "federal" here da.generic_org_type = app["generic_org_type"] if "generic_org_type" in app else "federal" - da.submission_date = fake.date() + da.last_submitted_date = fake.date() da.federal_type = ( app["federal_type"] if "federal_type" in app @@ -123,12 +122,6 @@ class DomainRequestFixture: else: da.senior_official = Contact.objects.create(**cls.fake_contact()) - if not da.submitter: - if "submitter" in app and app["submitter"] is not None: - da.submitter, _ = Contact.objects.get_or_create(**app["submitter"]) - else: - da.submitter = Contact.objects.create(**cls.fake_contact()) - if not da.requested_domain: if "requested_domain" in app and app["requested_domain"] is not None: da.requested_domain, _ = DraftDomain.objects.get_or_create(name=app["requested_domain"]) diff --git a/src/registrar/fixtures_users.py b/src/registrar/fixtures_users.py index 0fc203248..7fbf41223 100644 --- a/src/registrar/fixtures_users.py +++ b/src/registrar/fixtures_users.py @@ -6,6 +6,7 @@ from registrar.models import ( User, UserGroup, ) +from registrar.models.allowed_email import AllowedEmail fake = Faker() @@ -32,6 +33,7 @@ class UserFixture: "username": "aad084c3-66cc-4632-80eb-41cdf5c5bcbf", "first_name": "Aditi", "last_name": "Green", + "email": "aditidevelops+01@gmail.com", }, { "username": "be17c826-e200-4999-9389-2ded48c43691", @@ -42,16 +44,19 @@ class UserFixture: "username": "5f283494-31bd-49b5-b024-a7e7cae00848", "first_name": "Rachid", "last_name": "Mrad", + "email": "rachid.mrad@associates.cisa.dhs.gov", }, { "username": "eb2214cd-fc0c-48c0-9dbd-bc4cd6820c74", "first_name": "Alysia", "last_name": "Broddrick", + "email": "abroddrick@truss.works", }, { "username": "8f8e7293-17f7-4716-889b-1990241cbd39", "first_name": "Katherine", "last_name": "Osos", + "email": "kosos@truss.works", }, { "username": "70488e0a-e937-4894-a28c-16f5949effd4", @@ -63,6 +68,7 @@ class UserFixture: "username": "83c2b6dd-20a2-4cac-bb40-e22a72d2955c", "first_name": "Cameron", "last_name": "Dixon", + "email": "cameron.dixon@cisa.dhs.gov", }, { "username": "0353607a-cbba-47d2-98d7-e83dcd5b90ea", @@ -83,16 +89,19 @@ class UserFixture: "username": "2a88a97b-be96-4aad-b99e-0b605b492c78", "first_name": "Rebecca", "last_name": "Hsieh", + "email": "rebecca.hsieh@truss.works", }, { "username": "fa69c8e8-da83-4798-a4f2-263c9ce93f52", "first_name": "David", "last_name": "Kennedy", + "email": "david.kennedy@ecstech.com", }, { "username": "f14433d8-f0e9-41bf-9c72-b99b110e665d", "first_name": "Nicolle", "last_name": "LeClair", + "email": "nicolle.leclair@ecstech.com", }, { "username": "24840450-bf47-4d89-8aa9-c612fe68f9da", @@ -141,6 +150,7 @@ class UserFixture: "username": "ffec5987-aa84-411b-a05a-a7ee5cbcde54", "first_name": "Aditi-Analyst", "last_name": "Green-Analyst", + "email": "aditidevelops+02@gmail.com", }, { "username": "d6bf296b-fac5-47ff-9c12-f88ccc5c1b99", @@ -162,7 +172,7 @@ class UserFixture: "username": "91a9b97c-bd0a-458d-9823-babfde7ebf44", "first_name": "Katherine-Analyst", "last_name": "Osos-Analyst", - "email": "kosos@truss.works", + "email": "kosos+1@truss.works", }, { "username": "2cc0cde8-8313-4a50-99d8-5882e71443e8", @@ -183,6 +193,7 @@ class UserFixture: "username": "5dc6c9a6-61d9-42b4-ba54-4beff28bac3c", "first_name": "David-Analyst", "last_name": "Kennedy-Analyst", + "email": "david.kennedy@associates.cisa.dhs.gov", }, { "username": "0eb6f326-a3d4-410f-a521-aa4c1fad4e47", @@ -194,7 +205,7 @@ class UserFixture: "username": "cfe7c2fc-e24a-480e-8b78-28645a1459b3", "first_name": "Nicolle-Analyst", "last_name": "LeClair-Analyst", - "email": "nicolle.leclair@ecstech.com", + "email": "nicolle.leclair@gmail.com", }, { "username": "378d0bc4-d5a7-461b-bd84-3ae6f6864af9", @@ -240,6 +251,9 @@ class UserFixture: }, ] + # Additional emails to add to the AllowedEmail whitelist. + ADDITIONAL_ALLOWED_EMAILS: list[str] = ["davekenn4242@gmail.com", "rachid_mrad@hotmail.com"] + def load_users(cls, users, group_name, are_superusers=False): logger.info(f"Going to load {len(users)} users in group {group_name}") for user_data in users: @@ -264,6 +278,32 @@ class UserFixture: logger.warning(e) logger.info(f"All users in group {group_name} loaded.") + def load_allowed_emails(cls, users, additional_emails): + """Populates a whitelist of allowed emails (as defined in this list)""" + logger.info(f"Going to load allowed emails for {len(users)} users") + if additional_emails: + logger.info(f"Going to load {len(additional_emails)} additional allowed emails") + + # Load user emails + allowed_emails = [] + for user_data in users: + user_email = user_data.get("email") + if user_email and user_email not in allowed_emails: + allowed_emails.append(AllowedEmail(email=user_email)) + else: + first_name = user_data.get("first_name") + last_name = user_data.get("last_name") + logger.warning(f"Could not add email to whitelist for {first_name} {last_name}.") + + # Load additional emails + allowed_emails.extend([AllowedEmail(email=email) for email in additional_emails]) + + if allowed_emails: + AllowedEmail.objects.bulk_create(allowed_emails) + logger.info(f"Loaded {len(allowed_emails)} allowed emails") + else: + logger.info("No allowed emails to load") + @classmethod def load(cls): # Lumped under .atomic to ensure we don't make redundant DB calls. @@ -275,3 +315,7 @@ class UserFixture: with transaction.atomic(): cls.load_users(cls, cls.ADMINS, "full_access_group", are_superusers=True) cls.load_users(cls, cls.STAFF, "cisa_analysts_group") + + # Combine ADMINS and STAFF lists + all_users = cls.ADMINS + cls.STAFF + cls.load_allowed_emails(cls, all_users, additional_emails=cls.ADDITIONAL_ALLOWED_EMAILS) diff --git a/src/registrar/forms/domain.py b/src/registrar/forms/domain.py index a7a006788..84fcbe973 100644 --- a/src/registrar/forms/domain.py +++ b/src/registrar/forms/domain.py @@ -417,7 +417,7 @@ class SeniorOfficialContactForm(ContactForm): # This action should be blocked by the UI, as the text fields are readonly. # If they get past this point, we forbid it this way. # This could be malicious, so lets reserve information for the backend only. - raise ValueError("Senior Official cannot be modified for federal or tribal domains.") + raise ValueError("Senior official cannot be modified for federal or tribal domains.") elif db_so.has_more_than_one_join("information_senior_official"): # Handle the case where the domain information object is available and the SO Contact # has more than one joined object. diff --git a/src/registrar/forms/domain_request_wizard.py b/src/registrar/forms/domain_request_wizard.py index d97dd0de7..f2fdd32bc 100644 --- a/src/registrar/forms/domain_request_wizard.py +++ b/src/registrar/forms/domain_request_wizard.py @@ -386,64 +386,6 @@ class PurposeForm(RegistrarForm): ) -class YourContactForm(RegistrarForm): - JOIN = "submitter" - - def to_database(self, obj): - if not self.is_valid(): - return - contact = getattr(obj, "submitter", None) - if contact is not None and not contact.has_more_than_one_join("submitted_domain_requests"): - # if contact exists in the database and is not joined to other entities - super().to_database(contact) - else: - # no contact exists OR contact exists which is joined also to other entities; - # in either case, create a new contact and update it - contact = Contact() - super().to_database(contact) - obj.submitter = contact - obj.save() - - @classmethod - def from_database(cls, obj): - contact = getattr(obj, "submitter", None) - return super().from_database(contact) - - first_name = forms.CharField( - label="First name / given name", - error_messages={"required": "Enter your first name / given name."}, - ) - middle_name = forms.CharField( - required=False, - label="Middle name (optional)", - ) - last_name = forms.CharField( - label="Last name / family name", - error_messages={"required": "Enter your last name / family name."}, - ) - title = forms.CharField( - label="Title or role in your organization", - error_messages={ - "required": ("Enter your title or role in your organization (e.g., Chief Information Officer).") - }, - ) - email = forms.EmailField( - label="Email", - max_length=None, - error_messages={"invalid": ("Enter your email address in the required format, like name@example.com.")}, - validators=[ - MaxLengthValidator( - 320, - message="Response must be less than 320 characters.", - ) - ], - ) - phone = PhoneNumberField( - label="Phone", - error_messages={"invalid": "Enter a valid 10-digit phone number.", "required": "Enter your phone number."}, - ) - - class OtherContactsYesNoForm(BaseYesNoForm): """The yes/no field for the OtherContacts form.""" diff --git a/src/registrar/management/commands/clean_tables.py b/src/registrar/management/commands/clean_tables.py index 5d4439d95..66b3e772f 100644 --- a/src/registrar/management/commands/clean_tables.py +++ b/src/registrar/management/commands/clean_tables.py @@ -21,7 +21,7 @@ class Command(BaseCommand): TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=""" + prompt_message=""" This script will delete all rows from the following tables: * Contact * Domain diff --git a/src/registrar/management/commands/create_federal_portfolio.py b/src/registrar/management/commands/create_federal_portfolio.py new file mode 100644 index 000000000..d05a2911b --- /dev/null +++ b/src/registrar/management/commands/create_federal_portfolio.py @@ -0,0 +1,255 @@ +"""Loads files from /tmp into our sandboxes""" + +import argparse +import logging +from django.core.management import BaseCommand, CommandError +from registrar.management.commands.utility.terminal_helper import TerminalColors, TerminalHelper +from registrar.models import DomainInformation, DomainRequest, FederalAgency, Suborganization, Portfolio, User + + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand): + help = "Creates a federal portfolio given a FederalAgency name" + + def add_arguments(self, parser): + """Add three arguments: + 1. agency_name => the value of FederalAgency.agency + 2. --parse_requests => if true, adds the given portfolio to each related DomainRequest + 3. --parse_domains => if true, adds the given portfolio to each related DomainInformation + """ + parser.add_argument( + "agency_name", + help="The name of the FederalAgency to add", + ) + parser.add_argument( + "--parse_requests", + action=argparse.BooleanOptionalAction, + help="Adds portfolio to DomainRequests", + ) + parser.add_argument( + "--parse_domains", + action=argparse.BooleanOptionalAction, + help="Adds portfolio to DomainInformation", + ) + parser.add_argument( + "--both", + action=argparse.BooleanOptionalAction, + help="Adds portfolio to both requests and domains", + ) + + def handle(self, agency_name, **options): + parse_requests = options.get("parse_requests") + parse_domains = options.get("parse_domains") + both = options.get("both") + + if not both: + if not parse_requests and not parse_domains: + raise CommandError("You must specify at least one of --parse_requests or --parse_domains.") + else: + if parse_requests or parse_domains: + raise CommandError("You cannot pass --parse_requests or --parse_domains when passing --both.") + + federal_agency = FederalAgency.objects.filter(agency__iexact=agency_name).first() + if not federal_agency: + raise ValueError( + f"Cannot find the federal agency '{agency_name}' in our database. " + "The value you enter for `agency_name` must be " + "prepopulated in the FederalAgency table before proceeding." + ) + + portfolio = self.create_or_modify_portfolio(federal_agency) + self.create_suborganizations(portfolio, federal_agency) + + if parse_requests or both: + self.handle_portfolio_requests(portfolio, federal_agency) + + if parse_domains or both: + self.handle_portfolio_domains(portfolio, federal_agency) + + def create_or_modify_portfolio(self, federal_agency): + """Creates or modifies a portfolio record based on a federal agency.""" + portfolio_args = { + "federal_agency": federal_agency, + "organization_name": federal_agency.agency, + "organization_type": DomainRequest.OrganizationChoices.FEDERAL, + "creator": User.get_default_user(), + "notes": "Auto-generated record", + } + + if federal_agency.so_federal_agency.exists(): + portfolio_args["senior_official"] = federal_agency.so_federal_agency.first() + + portfolio, created = Portfolio.objects.get_or_create( + organization_name=portfolio_args.get("organization_name"), defaults=portfolio_args + ) + + if created: + message = f"Created portfolio '{portfolio}'" + TerminalHelper.colorful_logger(logger.info, TerminalColors.OKGREEN, message) + + if portfolio_args.get("senior_official"): + message = f"Added senior official '{portfolio_args['senior_official']}'" + TerminalHelper.colorful_logger(logger.info, TerminalColors.OKGREEN, message) + else: + message = ( + f"No senior official added to portfolio '{portfolio}'. " + "None was returned for the reverse relation `FederalAgency.so_federal_agency.first()`" + ) + TerminalHelper.colorful_logger(logger.info, TerminalColors.YELLOW, message) + else: + proceed = TerminalHelper.prompt_for_execution( + system_exit_on_terminate=False, + prompt_message=f""" + The given portfolio '{federal_agency.agency}' already exists in our DB. + If you cancel, the rest of the script will still execute but this record will not update. + """, + prompt_title="Do you wish to modify this record?", + ) + if proceed: + + # Don't override the creator and notes fields + if portfolio.creator: + portfolio_args.pop("creator") + + if portfolio.notes: + portfolio_args.pop("notes") + + # Update everything else + for key, value in portfolio_args.items(): + setattr(portfolio, key, value) + + portfolio.save() + message = f"Modified portfolio '{portfolio}'" + TerminalHelper.colorful_logger(logger.info, TerminalColors.MAGENTA, message) + + if portfolio_args.get("senior_official"): + message = f"Added/modified senior official '{portfolio_args['senior_official']}'" + TerminalHelper.colorful_logger(logger.info, TerminalColors.MAGENTA, message) + + return portfolio + + def create_suborganizations(self, portfolio: Portfolio, federal_agency: FederalAgency): + """Create Suborganizations tied to the given portfolio based on DomainInformation objects""" + valid_agencies = DomainInformation.objects.filter( + federal_agency=federal_agency, organization_name__isnull=False + ) + org_names = set(valid_agencies.values_list("organization_name", flat=True)) + + if not org_names: + message = ( + "Could not add any suborganizations." + f"\nNo suborganizations were found for '{federal_agency}' when filtering on this name, " + "and excluding null organization_name records." + ) + TerminalHelper.colorful_logger(logger.warning, TerminalColors.FAIL, message) + return + + # Check if we need to update any existing suborgs first. This step is optional. + existing_suborgs = Suborganization.objects.filter(name__in=org_names) + if existing_suborgs.exists(): + self._update_existing_suborganizations(portfolio, existing_suborgs) + + # Create new suborgs, as long as they don't exist in the db already + new_suborgs = [] + for name in org_names - set(existing_suborgs.values_list("name", flat=True)): + # Stored in variables due to linter wanting type information here. + portfolio_name: str = portfolio.organization_name if portfolio.organization_name is not None else "" + if name is not None and name.lower() == portfolio_name.lower(): + # You can use this to populate location information, when this occurs. + # However, this isn't needed for now so we can skip it. + message = ( + f"Skipping suborganization create on record '{name}'. " + "The federal agency name is the same as the portfolio name." + ) + TerminalHelper.colorful_logger(logger.warning, TerminalColors.YELLOW, message) + else: + new_suborgs.append(Suborganization(name=name, portfolio=portfolio)) # type: ignore + + if new_suborgs: + Suborganization.objects.bulk_create(new_suborgs) + TerminalHelper.colorful_logger( + logger.info, TerminalColors.OKGREEN, f"Added {len(new_suborgs)} suborganizations" + ) + else: + TerminalHelper.colorful_logger(logger.warning, TerminalColors.YELLOW, "No suborganizations added") + + def _update_existing_suborganizations(self, portfolio, orgs_to_update): + """ + Update existing suborganizations with new portfolio. + Prompts for user confirmation before proceeding. + """ + proceed = TerminalHelper.prompt_for_execution( + system_exit_on_terminate=False, + prompt_message=f"""Some suborganizations already exist in our DB. + If you cancel, the rest of the script will still execute but these records will not update. + + ==Proposed Changes== + The following suborgs will be updated: {[org.name for org in orgs_to_update]} + """, + prompt_title="Do you wish to modify existing suborganizations?", + ) + if proceed: + for org in orgs_to_update: + org.portfolio = portfolio + + Suborganization.objects.bulk_update(orgs_to_update, ["portfolio"]) + message = f"Updated {len(orgs_to_update)} suborganizations." + TerminalHelper.colorful_logger(logger.info, TerminalColors.MAGENTA, message) + + def handle_portfolio_requests(self, portfolio: Portfolio, federal_agency: FederalAgency): + """ + Associate portfolio with domain requests for a federal agency. + Updates all relevant domain request records. + """ + invalid_states = [ + DomainRequest.DomainRequestStatus.STARTED, + DomainRequest.DomainRequestStatus.INELIGIBLE, + DomainRequest.DomainRequestStatus.REJECTED, + ] + domain_requests = DomainRequest.objects.filter(federal_agency=federal_agency).exclude(status__in=invalid_states) + if not domain_requests.exists(): + message = f""" + Portfolios not added to domain requests: no valid records found. + This means that a filter on DomainInformation for the federal_agency '{federal_agency}' returned no results. + Excluded statuses: STARTED, INELIGIBLE, REJECTED. + """ + TerminalHelper.colorful_logger(logger.info, TerminalColors.YELLOW, message) + return None + + # Get all suborg information and store it in a dict to avoid doing a db call + suborgs = Suborganization.objects.filter(portfolio=portfolio).in_bulk(field_name="name") + for domain_request in domain_requests: + domain_request.portfolio = portfolio + if domain_request.organization_name in suborgs: + domain_request.sub_organization = suborgs.get(domain_request.organization_name) + + DomainRequest.objects.bulk_update(domain_requests, ["portfolio", "sub_organization"]) + message = f"Added portfolio '{portfolio}' to {len(domain_requests)} domain requests." + TerminalHelper.colorful_logger(logger.info, TerminalColors.OKGREEN, message) + + def handle_portfolio_domains(self, portfolio: Portfolio, federal_agency: FederalAgency): + """ + Associate portfolio with domains for a federal agency. + Updates all relevant domain information records. + """ + domain_infos = DomainInformation.objects.filter(federal_agency=federal_agency) + if not domain_infos.exists(): + message = f""" + Portfolios not added to domains: no valid records found. + This means that a filter on DomainInformation for the federal_agency '{federal_agency}' returned no results. + """ + TerminalHelper.colorful_logger(logger.info, TerminalColors.YELLOW, message) + return None + + # Get all suborg information and store it in a dict to avoid doing a db call + suborgs = Suborganization.objects.filter(portfolio=portfolio).in_bulk(field_name="name") + for domain_info in domain_infos: + domain_info.portfolio = portfolio + if domain_info.organization_name in suborgs: + domain_info.sub_organization = suborgs.get(domain_info.organization_name) + + DomainInformation.objects.bulk_update(domain_infos, ["portfolio", "sub_organization"]) + message = f"Added portfolio '{portfolio}' to {len(domain_infos)} domains" + TerminalHelper.colorful_logger(logger.info, TerminalColors.OKGREEN, message) diff --git a/src/registrar/management/commands/extend_expiration_dates.py b/src/registrar/management/commands/extend_expiration_dates.py index cefc38b9e..ac083da1d 100644 --- a/src/registrar/management/commands/extend_expiration_dates.py +++ b/src/registrar/management/commands/extend_expiration_dates.py @@ -130,7 +130,7 @@ class Command(BaseCommand): """Asks if the user wants to proceed with this action""" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Extension Amount== Period: {extension_amount} year(s) diff --git a/src/registrar/management/commands/load_organization_data.py b/src/registrar/management/commands/load_organization_data.py index 122795400..35cc248ee 100644 --- a/src/registrar/management/commands/load_organization_data.py +++ b/src/registrar/management/commands/load_organization_data.py @@ -64,7 +64,7 @@ class Command(BaseCommand): # Will sys.exit() when prompt is "n" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Master data file== domain_additional_filename: {org_args.domain_additional_filename} @@ -84,7 +84,7 @@ class Command(BaseCommand): # Will sys.exit() when prompt is "n" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Master data file== domain_additional_filename: {org_args.domain_additional_filename} diff --git a/src/registrar/management/commands/load_senior_official_table.py b/src/registrar/management/commands/load_senior_official_table.py index 43f61d57a..cdbc607bf 100644 --- a/src/registrar/management/commands/load_senior_official_table.py +++ b/src/registrar/management/commands/load_senior_official_table.py @@ -27,7 +27,7 @@ class Command(BaseCommand): TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Proposed Changes== CSV: {federal_cio_csv_path} diff --git a/src/registrar/management/commands/load_transition_domain.py b/src/registrar/management/commands/load_transition_domain.py index 4132096c8..c2dd66f55 100644 --- a/src/registrar/management/commands/load_transition_domain.py +++ b/src/registrar/management/commands/load_transition_domain.py @@ -651,7 +651,7 @@ class Command(BaseCommand): title = "Do you wish to load additional data for TransitionDomains?" proceed = TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" !!! ENSURE THAT ALL FILENAMES ARE CORRECT BEFORE PROCEEDING ==Master data file== domain_additional_filename: {domain_additional_filename} diff --git a/src/registrar/management/commands/patch_federal_agency_info.py b/src/registrar/management/commands/patch_federal_agency_info.py index b286f1516..51a98ffaa 100644 --- a/src/registrar/management/commands/patch_federal_agency_info.py +++ b/src/registrar/management/commands/patch_federal_agency_info.py @@ -91,7 +91,7 @@ class Command(BaseCommand): # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Proposed Changes== Number of DomainInformation objects to change: {len(human_readable_domain_names)} The following DomainInformation objects will be modified: {human_readable_domain_names} @@ -148,7 +148,7 @@ class Command(BaseCommand): # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==File location== current-full.csv filepath: {file_path} diff --git a/src/registrar/management/commands/populate_domain_request_dates.py b/src/registrar/management/commands/populate_domain_request_dates.py new file mode 100644 index 000000000..d975a035d --- /dev/null +++ b/src/registrar/management/commands/populate_domain_request_dates.py @@ -0,0 +1,45 @@ +import logging +from django.core.management import BaseCommand +from registrar.management.commands.utility.terminal_helper import PopulateScriptTemplate, TerminalColors +from registrar.models import DomainRequest +from auditlog.models import LogEntry + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand, PopulateScriptTemplate): + help = "Loops through each domain request object and populates the last_status_update and first_submitted_date" + + def handle(self, **kwargs): + """Loops through each DomainRequest object and populates + its last_status_update and first_submitted_date values""" + self.mass_update_records(DomainRequest, None, ["last_status_update", "first_submitted_date"]) + + def update_record(self, record: DomainRequest): + """Defines how we update the first_submitted_date and last_status_update fields""" + + # Retrieve and order audit log entries by timestamp in descending order + audit_log_entries = LogEntry.objects.filter(object_pk=record.pk).order_by("-timestamp") + # Loop through logs in descending order to find most recent status change + for log_entry in audit_log_entries: + if "status" in log_entry.changes_dict: + record.last_status_update = log_entry.timestamp.date() + break + + # Loop through logs in ascending order to find first submission + for log_entry in audit_log_entries.reverse(): + status = log_entry.changes_dict.get("status") + if status and status[1] == "submitted": + record.first_submitted_date = log_entry.timestamp.date() + break + + logger.info( + f"""{TerminalColors.OKCYAN}Updating {record} => + first submitted date: {record.first_submitted_date}, + last status update: {record.last_status_update}{TerminalColors.ENDC} + """ + ) + + def should_skip_record(self, record) -> bool: + # make sure the record had some kind of history + return not LogEntry.objects.filter(object_pk=record.pk).exists() diff --git a/src/registrar/management/commands/populate_first_ready.py b/src/registrar/management/commands/populate_first_ready.py index 9636476c2..04468029a 100644 --- a/src/registrar/management/commands/populate_first_ready.py +++ b/src/registrar/management/commands/populate_first_ready.py @@ -31,7 +31,7 @@ class Command(BaseCommand): # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Proposed Changes== Number of Domain objects to change: {len(domains)} """, diff --git a/src/registrar/management/commands/populate_organization_type.py b/src/registrar/management/commands/populate_organization_type.py index a7dd98b24..60d179cb8 100644 --- a/src/registrar/management/commands/populate_organization_type.py +++ b/src/registrar/management/commands/populate_organization_type.py @@ -54,7 +54,7 @@ class Command(BaseCommand): # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Proposed Changes== Number of DomainRequest objects to change: {len(domain_requests)} @@ -72,7 +72,7 @@ class Command(BaseCommand): # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" + prompt_message=f""" ==Proposed Changes== Number of DomainInformation objects to change: {len(domain_infos)} diff --git a/src/registrar/management/commands/transfer_transition_domains_to_domains.py b/src/registrar/management/commands/transfer_transition_domains_to_domains.py index 615df50a5..727db6dab 100644 --- a/src/registrar/management/commands/transfer_transition_domains_to_domains.py +++ b/src/registrar/management/commands/transfer_transition_domains_to_domains.py @@ -423,7 +423,7 @@ class Command(BaseCommand): valid_fed_type = fed_type in fed_choices valid_fed_agency = fed_agency in agency_choices - default_creator, _ = User.objects.get_or_create(username="System") + default_creator = User.get_default_user() new_domain_info_data = { "domain": domain, diff --git a/src/registrar/management/commands/update_first_ready.py b/src/registrar/management/commands/update_first_ready.py new file mode 100644 index 000000000..0a4ea10a7 --- /dev/null +++ b/src/registrar/management/commands/update_first_ready.py @@ -0,0 +1,38 @@ +import logging +from django.core.management import BaseCommand +from registrar.management.commands.utility.terminal_helper import PopulateScriptTemplate, TerminalColors +from registrar.models import Domain, TransitionDomain + + +logger = logging.getLogger(__name__) + + +class Command(BaseCommand, PopulateScriptTemplate): + help = "Loops through each domain object and populates the last_status_update and first_submitted_date" + + def handle(self, **kwargs): + """Loops through each valid Domain object and updates it's first_ready value if it is out of sync""" + filter_conditions = {"state__in": [Domain.State.READY, Domain.State.ON_HOLD, Domain.State.DELETED]} + self.mass_update_records(Domain, filter_conditions, ["first_ready"], verbose=True) + + def update_record(self, record: Domain): + """Defines how we update the first_ready field""" + # update the first_ready value based on the creation date. + record.first_ready = record.created_at.date() + + logger.info( + f"{TerminalColors.OKCYAN}Updating {record} => first_ready: " f"{record.first_ready}{TerminalColors.ENDC}" + ) + + # check if a transition domain object for this domain name exists, + # or if so whether its first_ready value matches its created_at date + def custom_filter(self, records): + to_include_pks = [] + for record in records: + if ( + TransitionDomain.objects.filter(domain_name=record.name).exists() + and record.first_ready != record.created_at.date() + ): # noqa + to_include_pks.append(record.pk) + + return records.filter(pk__in=to_include_pks) diff --git a/src/registrar/management/commands/utility/terminal_helper.py b/src/registrar/management/commands/utility/terminal_helper.py index 2c69e1080..fa7cde683 100644 --- a/src/registrar/management/commands/utility/terminal_helper.py +++ b/src/registrar/management/commands/utility/terminal_helper.py @@ -2,9 +2,12 @@ import logging import sys from abc import ABC, abstractmethod from django.core.paginator import Paginator +from django.db.models import Model +from django.db.models.manager import BaseManager from typing import List from registrar.utility.enums import LogCode + logger = logging.getLogger(__name__) @@ -76,27 +79,60 @@ class PopulateScriptTemplate(ABC): @abstractmethod def update_record(self, record): - """Defines how we update each field. Must be defined before using mass_update_records.""" + """Defines how we update each field. + + raises: + NotImplementedError: If not defined before calling mass_update_records. + """ raise NotImplementedError - def mass_update_records(self, object_class, filter_conditions, fields_to_update, debug=True): + def mass_update_records(self, object_class, filter_conditions, fields_to_update, debug=True, verbose=False): """Loops through each valid "object_class" object - specified by filter_conditions - and updates fields defined by fields_to_update using update_record. - You must define update_record before you can use this function. + Parameters: + object_class: The Django model class that you want to perform the bulk update on. + This should be the actual class, not a string of the class name. + + filter_conditions: dictionary of valid Django Queryset filter conditions + (e.g. {'verification_type__isnull'=True}). + + fields_to_update: List of strings specifying which fields to update. + (e.g. ["first_ready_date", "last_submitted_date"]) + + debug: Whether to log script run summary in debug mode. + Default: True. + + verbose: Whether to print a detailed run summary *before* run confirmation. + Default: False. + + Raises: + NotImplementedError: If you do not define update_record before using this function. + TypeError: If custom_filter is not Callable. """ - records = object_class.objects.filter(**filter_conditions) + records = object_class.objects.filter(**filter_conditions) if filter_conditions else object_class.objects.all() + + # apply custom filter + records = self.custom_filter(records) + readable_class_name = self.get_class_name(object_class) + # for use in the execution prompt. + proposed_changes = f"""==Proposed Changes== + Number of {readable_class_name} objects to change: {len(records)} + These fields will be updated on each record: {fields_to_update} + """ + + if verbose: + proposed_changes = f"""{proposed_changes} + These records will be updated: {list(records.all())} + """ + # Code execution will stop here if the user prompts "N" TerminalHelper.prompt_for_execution( system_exit_on_terminate=True, - info_to_inspect=f""" - ==Proposed Changes== - Number of {readable_class_name} objects to change: {len(records)} - These fields will be updated on each record: {fields_to_update} - """, + prompt_message=proposed_changes, prompt_title=self.prompt_title, ) logger.info("Updating...") @@ -141,10 +177,17 @@ class PopulateScriptTemplate(ABC): return f"{TerminalColors.FAIL}" f"Failed to update {record}" f"{TerminalColors.ENDC}" def should_skip_record(self, record) -> bool: # noqa - """Defines the condition in which we should skip updating a record. Override as needed.""" + """Defines the condition in which we should skip updating a record. Override as needed. + The difference between this and custom_filter is that records matching these conditions + *will* be included in the run but will be skipped (and logged as such).""" # By default - don't skip return False + def custom_filter(self, records: BaseManager[Model]) -> BaseManager[Model]: + """Override to define filters that can't be represented by django queryset field lookups. + Applied to individual records *after* filter_conditions. True means""" + return records + class TerminalHelper: @staticmethod @@ -220,6 +263,9 @@ class TerminalHelper: an answer is required of the user). The "answer" return value is True for "yes" or False for "no". + + Raises: + ValueError: When "default" is not "yes", "no", or None. """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: @@ -244,6 +290,7 @@ class TerminalHelper: @staticmethod def query_yes_no_exit(question: str, default="yes"): """Ask a yes/no question via raw_input() and return their answer. + Allows for answer "e" to exit. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits . @@ -251,6 +298,9 @@ class TerminalHelper: an answer is required of the user). The "answer" return value is True for "yes" or False for "no". + + Raises: + ValueError: When "default" is not "yes", "no", or None. """ valid = { "yes": True, @@ -317,9 +367,8 @@ class TerminalHelper: case _: logger.info(print_statement) - # TODO - "info_to_inspect" should be refactored to "prompt_message" @staticmethod - def prompt_for_execution(system_exit_on_terminate: bool, info_to_inspect: str, prompt_title: str) -> bool: + def prompt_for_execution(system_exit_on_terminate: bool, prompt_message: str, prompt_title: str) -> bool: """Create to reduce code complexity. Prompts the user to inspect the given string and asks if they wish to proceed. @@ -340,7 +389,7 @@ class TerminalHelper: ===================================================== *** IMPORTANT: VERIFY THE FOLLOWING LOOKS CORRECT *** - {info_to_inspect} + {prompt_message} {TerminalColors.FAIL} Proceed? (Y = proceed, N = {action_description_for_selecting_no}) {TerminalColors.ENDC}""" diff --git a/src/registrar/migrations/0119_remove_user_portfolio_and_more.py b/src/registrar/migrations/0119_remove_user_portfolio_and_more.py new file mode 100644 index 000000000..84ed45cd1 --- /dev/null +++ b/src/registrar/migrations/0119_remove_user_portfolio_and_more.py @@ -0,0 +1,97 @@ +# Generated by Django 4.2.10 on 2024-08-19 20:24 + +from django.conf import settings +import django.contrib.postgres.fields +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0118_alter_portfolio_options_alter_portfolio_creator_and_more"), + ] + + operations = [ + migrations.RemoveField( + model_name="user", + name="portfolio", + ), + migrations.RemoveField( + model_name="user", + name="portfolio_additional_permissions", + ), + migrations.RemoveField( + model_name="user", + name="portfolio_roles", + ), + migrations.CreateModel( + name="UserPortfolioPermission", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ( + "roles", + django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("organization_admin", "Admin"), + ("organization_admin_read_only", "Admin read only"), + ("organization_member", "Member"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more roles.", + null=True, + size=None, + ), + ), + ( + "additional_permissions", + django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("view_all_domains", "View all domains and domain reports"), + ("view_managed_domains", "View managed domains"), + ("view_member", "View members"), + ("edit_member", "Create and edit members"), + ("view_all_requests", "View all requests"), + ("view_created_requests", "View created requests"), + ("edit_requests", "Create and edit requests"), + ("view_portfolio", "View organization"), + ("edit_portfolio", "Edit organization"), + ("view_suborganization", "View suborganization"), + ("edit_suborganization", "Edit suborganization"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more additional permissions.", + null=True, + size=None, + ), + ), + ( + "portfolio", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="portfolio_users", + to="registrar.portfolio", + ), + ), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="portfolio_permissions", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "unique_together": {("user", "portfolio")}, + }, + ), + ] diff --git a/src/registrar/migrations/0120_add_domainrequest_submission_dates.py b/src/registrar/migrations/0120_add_domainrequest_submission_dates.py new file mode 100644 index 000000000..df409cf39 --- /dev/null +++ b/src/registrar/migrations/0120_add_domainrequest_submission_dates.py @@ -0,0 +1,47 @@ +# Generated by Django 4.2.10 on 2024-08-16 15:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0119_remove_user_portfolio_and_more"), + ] + + operations = [ + migrations.RenameField( + model_name="domainrequest", + old_name="submission_date", + new_name="last_submitted_date", + ), + migrations.AlterField( + model_name="domainrequest", + name="last_submitted_date", + field=models.DateField( + blank=True, default=None, help_text="Date last submitted", null=True, verbose_name="last submitted on" + ), + ), + migrations.AddField( + model_name="domainrequest", + name="first_submitted_date", + field=models.DateField( + blank=True, + default=None, + help_text="Date initially submitted", + null=True, + verbose_name="first submitted on", + ), + ), + migrations.AddField( + model_name="domainrequest", + name="last_status_update", + field=models.DateField( + blank=True, + default=None, + help_text="Date of the last status update", + null=True, + verbose_name="last updated on", + ), + ), + ] diff --git a/src/registrar/migrations/0121_allowedemail.py b/src/registrar/migrations/0121_allowedemail.py new file mode 100644 index 000000000..ebed1ac15 --- /dev/null +++ b/src/registrar/migrations/0121_allowedemail.py @@ -0,0 +1,25 @@ +# Generated by Django 4.2.10 on 2024-08-29 18:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0120_add_domainrequest_submission_dates"), + ] + + operations = [ + migrations.CreateModel( + name="AllowedEmail", + fields=[ + ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("updated_at", models.DateTimeField(auto_now=True)), + ("email", models.EmailField(max_length=320, unique=True)), + ], + options={ + "abstract": False, + }, + ), + ] diff --git a/src/registrar/migrations/0122_create_groups_v16.py b/src/registrar/migrations/0122_create_groups_v16.py new file mode 100644 index 000000000..82c750976 --- /dev/null +++ b/src/registrar/migrations/0122_create_groups_v16.py @@ -0,0 +1,37 @@ +# This migration creates the create_full_access_group and create_cisa_analyst_group groups +# It is dependent on 0079 (which populates federal agencies) +# If permissions on the groups need changing, edit CISA_ANALYST_GROUP_PERMISSIONS +# in the user_group model then: +# [NOT RECOMMENDED] +# step 1: docker-compose exec app ./manage.py migrate --fake registrar 0035_contenttypes_permissions +# step 2: docker-compose exec app ./manage.py migrate registrar 0036_create_groups +# step 3: fake run the latest migration in the migrations list +# [RECOMMENDED] +# Alternatively: +# step 1: duplicate the migration that loads data +# step 2: docker-compose exec app ./manage.py migrate + +from django.db import migrations +from registrar.models import UserGroup +from typing import Any + + +# For linting: RunPython expects a function reference, +# so let's give it one +def create_groups(apps, schema_editor) -> Any: + UserGroup.create_cisa_analyst_group(apps, schema_editor) + UserGroup.create_full_access_group(apps, schema_editor) + + +class Migration(migrations.Migration): + dependencies = [ + ("registrar", "0121_allowedemail"), + ] + + operations = [ + migrations.RunPython( + create_groups, + reverse_code=migrations.RunPython.noop, + atomic=True, + ), + ] diff --git a/src/registrar/migrations/0123_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py b/src/registrar/migrations/0123_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py new file mode 100644 index 000000000..c14a70ab0 --- /dev/null +++ b/src/registrar/migrations/0123_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py @@ -0,0 +1,66 @@ +# Generated by Django 4.2.10 on 2024-09-04 21:29 + +import django.contrib.postgres.fields +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0122_create_groups_v16"), + ] + + operations = [ + migrations.AlterField( + model_name="portfolioinvitation", + name="portfolio_additional_permissions", + field=django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("view_all_domains", "View all domains and domain reports"), + ("view_managed_domains", "View managed domains"), + ("view_members", "View members"), + ("edit_members", "Create and edit members"), + ("view_all_requests", "View all requests"), + ("view_created_requests", "View created requests"), + ("edit_requests", "Create and edit requests"), + ("view_portfolio", "View organization"), + ("edit_portfolio", "Edit organization"), + ("view_suborganization", "View suborganization"), + ("edit_suborganization", "Edit suborganization"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more additional permissions.", + null=True, + size=None, + ), + ), + migrations.AlterField( + model_name="userportfoliopermission", + name="additional_permissions", + field=django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("view_all_domains", "View all domains and domain reports"), + ("view_managed_domains", "View managed domains"), + ("view_members", "View members"), + ("edit_members", "Create and edit members"), + ("view_all_requests", "View all requests"), + ("view_created_requests", "View created requests"), + ("edit_requests", "Create and edit requests"), + ("view_portfolio", "View organization"), + ("edit_portfolio", "Edit organization"), + ("view_suborganization", "View suborganization"), + ("edit_suborganization", "Edit suborganization"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more additional permissions.", + null=True, + size=None, + ), + ), + ] diff --git a/src/registrar/migrations/0124_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py b/src/registrar/migrations/0124_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py new file mode 100644 index 000000000..aab162de9 --- /dev/null +++ b/src/registrar/migrations/0124_alter_portfolioinvitation_portfolio_additional_permissions_and_more.py @@ -0,0 +1,64 @@ +# Generated by Django 4.2.10 on 2024-09-09 14:48 + +import django.contrib.postgres.fields +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0123_alter_portfolioinvitation_portfolio_additional_permissions_and_more"), + ] + + operations = [ + migrations.AlterField( + model_name="portfolioinvitation", + name="portfolio_additional_permissions", + field=django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("view_all_domains", "View all domains and domain reports"), + ("view_managed_domains", "View managed domains"), + ("view_members", "View members"), + ("edit_members", "Create and edit members"), + ("view_all_requests", "View all requests"), + ("edit_requests", "Create and edit requests"), + ("view_portfolio", "View organization"), + ("edit_portfolio", "Edit organization"), + ("view_suborganization", "View suborganization"), + ("edit_suborganization", "Edit suborganization"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more additional permissions.", + null=True, + size=None, + ), + ), + migrations.AlterField( + model_name="userportfoliopermission", + name="additional_permissions", + field=django.contrib.postgres.fields.ArrayField( + base_field=models.CharField( + choices=[ + ("view_all_domains", "View all domains and domain reports"), + ("view_managed_domains", "View managed domains"), + ("view_members", "View members"), + ("edit_members", "Create and edit members"), + ("view_all_requests", "View all requests"), + ("edit_requests", "Create and edit requests"), + ("view_portfolio", "View organization"), + ("edit_portfolio", "Edit organization"), + ("view_suborganization", "View suborganization"), + ("edit_suborganization", "Edit suborganization"), + ], + max_length=50, + ), + blank=True, + help_text="Select one or more additional permissions.", + null=True, + size=None, + ), + ), + ] diff --git a/src/registrar/migrations/0125_alter_domaininformation_submitter_and_more.py b/src/registrar/migrations/0125_alter_domaininformation_submitter_and_more.py new file mode 100644 index 000000000..ea95cbc05 --- /dev/null +++ b/src/registrar/migrations/0125_alter_domaininformation_submitter_and_more.py @@ -0,0 +1,38 @@ +# Generated by Django 4.2.10 on 2024-08-29 23:17 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0124_alter_portfolioinvitation_portfolio_additional_permissions_and_more"), + ] + + operations = [ + migrations.AlterField( + model_name="domaininformation", + name="submitter", + field=models.ForeignKey( + blank=True, + help_text='Person listed under "your contact information" in the request form', + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="submitted_domain_requests_information", + to="registrar.contact", + ), + ), + migrations.AlterField( + model_name="domainrequest", + name="submitter", + field=models.ForeignKey( + blank=True, + help_text='Person listed under "your contact information" in the request form; will receive email updates', + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="submitted_domain_requests", + to="registrar.contact", + ), + ), + ] diff --git a/src/registrar/migrations/0126_delete_cascade_submitter_contacts.py b/src/registrar/migrations/0126_delete_cascade_submitter_contacts.py new file mode 100644 index 000000000..d798ae283 --- /dev/null +++ b/src/registrar/migrations/0126_delete_cascade_submitter_contacts.py @@ -0,0 +1,27 @@ +from django.db import migrations +from django.db.models import Q +from typing import Any + + +# Deletes Contact objects associated with a submitter which we are deprecating +def cascade_delete_submitter_contacts(apps, schema_editor) -> Any: + contacts_model = apps.get_model("registrar", "Contact") + submitter_contacts = contacts_model.objects.filter( + Q(submitted_domain_requests__isnull=False) | Q(submitted_domain_requests_information__isnull=False) + ).filter( + information_senior_official__isnull=True, + senior_official__isnull=True, + contact_domain_requests_information__isnull=True, + contact_domain_requests__isnull=True, + ) + submitter_contacts.delete() + + +class Migration(migrations.Migration): + dependencies = [ + ("registrar", "0125_alter_domaininformation_submitter_and_more"), + ] + + operations = [ + migrations.RunPython(cascade_delete_submitter_contacts, reverse_code=migrations.RunPython.noop, atomic=True), + ] diff --git a/src/registrar/migrations/0127_remove_domaininformation_submitter_and_more.py b/src/registrar/migrations/0127_remove_domaininformation_submitter_and_more.py new file mode 100644 index 000000000..78c764e0f --- /dev/null +++ b/src/registrar/migrations/0127_remove_domaininformation_submitter_and_more.py @@ -0,0 +1,33 @@ +# Generated by Django 4.2.10 on 2024-08-29 24:13 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ("registrar", "0126_delete_cascade_submitter_contacts"), + ] + + operations = [ + migrations.RemoveField( + model_name="domaininformation", + name="submitter", + ), + migrations.RemoveField( + model_name="domainrequest", + name="submitter", + ), + migrations.AlterField( + model_name="domainrequest", + name="creator", + field=models.ForeignKey( + help_text="Person who submitted the domain request. Will receive email updates.", + on_delete=django.db.models.deletion.PROTECT, + related_name="domain_requests_created", + to=settings.AUTH_USER_MODEL, + ), + ), + ] diff --git a/src/registrar/models/__init__.py b/src/registrar/models/__init__.py index 1e0aad0b1..a1738cc76 100644 --- a/src/registrar/models/__init__.py +++ b/src/registrar/models/__init__.py @@ -21,6 +21,8 @@ from .portfolio import Portfolio from .domain_group import DomainGroup from .suborganization import Suborganization from .senior_official import SeniorOfficial +from .user_portfolio_permission import UserPortfolioPermission +from .allowed_email import AllowedEmail __all__ = [ @@ -46,6 +48,8 @@ __all__ = [ "DomainGroup", "Suborganization", "SeniorOfficial", + "UserPortfolioPermission", + "AllowedEmail", ] auditlog.register(Contact) @@ -70,3 +74,5 @@ auditlog.register(Portfolio) auditlog.register(DomainGroup) auditlog.register(Suborganization) auditlog.register(SeniorOfficial) +auditlog.register(UserPortfolioPermission) +auditlog.register(AllowedEmail) diff --git a/src/registrar/models/allowed_email.py b/src/registrar/models/allowed_email.py new file mode 100644 index 000000000..6622bcc55 --- /dev/null +++ b/src/registrar/models/allowed_email.py @@ -0,0 +1,52 @@ +from django.db import models +from django.db.models import Q +import re +from .utility.time_stamped_model import TimeStampedModel + + +class AllowedEmail(TimeStampedModel): + """ + AllowedEmail is a whitelist for email addresses that we can send to + in non-production environments. + """ + + email = models.EmailField( + unique=True, + null=False, + blank=False, + max_length=320, + ) + + @classmethod + def is_allowed_email(cls, email): + """Given an email, check if this email exists within our AllowEmail whitelist""" + + if not email: + return False + + # Split the email into a local part and a domain part + local, domain = email.split("@") + + # If the email exists within the whitelist, then do nothing else. + email_exists = cls.objects.filter(email__iexact=email).exists() + if email_exists: + return True + + # Check if there's a '+' in the local part + if "+" in local: + base_local = local.split("+")[0] + base_email_exists = cls.objects.filter(Q(email__iexact=f"{base_local}@{domain}")).exists() + + # Given an example email, such as "joe.smoe+1@igorville.com" + # The full regex statement will be: "^joe.smoe\\+\\d+@igorville.com$" + pattern = f"^{re.escape(base_local)}\\+\\d+@{re.escape(domain)}$" + return base_email_exists and re.match(pattern, email) + else: + # Edge case, the +1 record exists but the base does not, + # and the record we are checking is the base record. + pattern = f"^{re.escape(local)}\\+\\d+@{re.escape(domain)}$" + plus_email_exists = cls.objects.filter(Q(email__iregex=pattern)).exists() + return plus_email_exists + + def __str__(self): + return str(self.email) diff --git a/src/registrar/models/domain_information.py b/src/registrar/models/domain_information.py index 774dba897..03b8cc047 100644 --- a/src/registrar/models/domain_information.py +++ b/src/registrar/models/domain_information.py @@ -48,8 +48,7 @@ class DomainInformation(TimeStampedModel): null=True, ) - # This is the domain request user who created this domain request. The contact - # information that they gave is in the `submitter` field + # This is the domain request user who created this domain request. creator = models.ForeignKey( "registrar.User", on_delete=models.PROTECT, @@ -197,17 +196,6 @@ class DomainInformation(TimeStampedModel): related_name="domain_info", ) - # This is the contact information provided by the domain requestor. The - # user who created the domain request is in the `creator` field. - submitter = models.ForeignKey( - "registrar.Contact", - null=True, - blank=True, - related_name="submitted_domain_requests_information", - on_delete=models.PROTECT, - help_text='Person listed under "your contact information" in the request form', - ) - purpose = models.TextField( null=True, blank=True, diff --git a/src/registrar/models/domain_request.py b/src/registrar/models/domain_request.py index 966c880d7..babc955aa 100644 --- a/src/registrar/models/domain_request.py +++ b/src/registrar/models/domain_request.py @@ -6,7 +6,6 @@ from django.conf import settings from django.db import models from django_fsm import FSMField, transition # type: ignore from django.utils import timezone -from waffle import flag_is_active from registrar.models.domain import Domain from registrar.models.federal_agency import FederalAgency from registrar.models.utility.generic_helper import CreateOrUpdateOrganizationTypeHelper @@ -339,13 +338,12 @@ class DomainRequest(TimeStampedModel): help_text="The suborganization that this domain request is included under", ) - # This is the domain request user who created this domain request. The contact - # information that they gave is in the `submitter` field + # This is the domain request user who created this domain request. creator = models.ForeignKey( "registrar.User", on_delete=models.PROTECT, related_name="domain_requests_created", - help_text="Person who submitted the domain request; will not receive email updates", + help_text="Person who submitted the domain request. Will receive email updates.", ) investigator = models.ForeignKey( @@ -483,17 +481,6 @@ class DomainRequest(TimeStampedModel): help_text="Other domain names the creator provided for consideration", ) - # This is the contact information provided by the domain requestor. The - # user who created the domain request is in the `creator` field. - submitter = models.ForeignKey( - "registrar.Contact", - null=True, - blank=True, - related_name="submitted_domain_requests", - on_delete=models.PROTECT, - help_text='Person listed under "your contact information" in the request form; will receive email updates', - ) - purpose = models.TextField( null=True, blank=True, @@ -563,20 +550,43 @@ class DomainRequest(TimeStampedModel): help_text="Acknowledged .gov acceptable use policy", ) - # submission date records when domain request is submitted - submission_date = models.DateField( + # Records when the domain request was first submitted + first_submitted_date = models.DateField( null=True, blank=True, default=None, - verbose_name="submitted at", - help_text="Date submitted", + verbose_name="first submitted on", + help_text="Date initially submitted", ) + # Records when domain request was last submitted + last_submitted_date = models.DateField( + null=True, + blank=True, + default=None, + verbose_name="last submitted on", + help_text="Date last submitted", + ) + + # Records when domain request status was last updated by an admin or analyst + last_status_update = models.DateField( + null=True, + blank=True, + default=None, + verbose_name="last updated on", + help_text="Date of the last status update", + ) notes = models.TextField( null=True, blank=True, ) + @classmethod + def get_statuses_that_send_emails(cls): + """Returns a list of statuses that send an email to the user""" + excluded_statuses = [cls.DomainRequestStatus.INELIGIBLE, cls.DomainRequestStatus.IN_REVIEW] + return [status for status in cls.DomainRequestStatus if status not in excluded_statuses] + def sync_organization_type(self): """ Updates the organization_type (without saving) to match @@ -621,6 +631,9 @@ class DomainRequest(TimeStampedModel): self.sync_organization_type() self.sync_yes_no_form_fields() + if self._cached_status != self.status: + self.last_status_update = timezone.now().date() + super().save(*args, **kwargs) # Handle the action needed email. @@ -715,9 +728,6 @@ class DomainRequest(TimeStampedModel): contact information. If there is not creator information, then do nothing. - If the waffle flag "profile_feature" is active, then this email will be sent to the - domain request creator rather than the submitter - Optional args: bcc_address: str -> the address to bcc to @@ -732,7 +742,7 @@ class DomainRequest(TimeStampedModel): custom_email_content: str -> Renders an email with the content of this string as its body text. """ - recipient = self.creator if flag_is_active(None, "profile_feature") else self.submitter + recipient = self.creator if recipient is None or recipient.email is None: logger.warning( f"Cannot send {new_status} email, no creator email address for domain request with pk: {self.pk}." @@ -803,8 +813,12 @@ class DomainRequest(TimeStampedModel): if not DraftDomain.string_could_be_domain(self.requested_domain.name): raise ValueError("Requested domain is not a valid domain name.") - # Update submission_date to today - self.submission_date = timezone.now().date() + # if the domain has not been submitted before this must be the first time + if not self.first_submitted_date: + self.first_submitted_date = timezone.now().date() + + # Update last_submitted_date to today + self.last_submitted_date = timezone.now().date() self.save() # Limit email notifications to transitions from Started and Withdrawn @@ -1152,6 +1166,10 @@ class DomainRequest(TimeStampedModel): # Special District -> "Election office" and "About your organization" page can't be empty return self.is_election_board is not None and self.about_your_organization is not None + # Do we still want to test this after creator is autogenerated? Currently it went back to being selectable + def _is_creator_complete(self): + return self.creator is not None + def _is_organization_name_and_address_complete(self): return not ( self.organization_name is None @@ -1170,9 +1188,6 @@ class DomainRequest(TimeStampedModel): def _is_purpose_complete(self): return self.purpose is not None - def _is_submitter_complete(self): - return self.submitter is not None - def _has_other_contacts_and_filled(self): # Other Contacts Radio button is Yes and if all required fields are filled return ( @@ -1221,14 +1236,12 @@ class DomainRequest(TimeStampedModel): return self.is_policy_acknowledged is not None def _is_general_form_complete(self, request): - has_profile_feature_flag = flag_is_active(request, "profile_feature") return ( - self._is_organization_name_and_address_complete() + self._is_creator_complete() + and self._is_organization_name_and_address_complete() and self._is_senior_official_complete() and self._is_requested_domain_complete() and self._is_purpose_complete() - # NOTE: This flag leaves submitter as empty (request wont submit) hence set to True - and (self._is_submitter_complete() if not has_profile_feature_flag else True) and self._is_other_contacts_complete() and self._is_additional_details_complete() and self._is_policy_acknowledgement_complete() diff --git a/src/registrar/models/portfolio.py b/src/registrar/models/portfolio.py index 0f9904c31..fadcf8cac 100644 --- a/src/registrar/models/portfolio.py +++ b/src/registrar/models/portfolio.py @@ -131,9 +131,13 @@ class Portfolio(TimeStampedModel): Returns a combination of organization_type / federal_type, seperated by ' - '. If no federal_type is found, we just return the org type. """ - org_type_label = self.OrganizationChoices.get_org_label(self.organization_type) - agency_type_label = BranchChoices.get_branch_label(self.federal_type) - if self.organization_type == self.OrganizationChoices.FEDERAL and agency_type_label: + return self.get_portfolio_type(self.organization_type, self.federal_type) + + @classmethod + def get_portfolio_type(cls, organization_type, federal_type): + org_type_label = cls.OrganizationChoices.get_org_label(organization_type) + agency_type_label = BranchChoices.get_branch_label(federal_type) + if organization_type == cls.OrganizationChoices.FEDERAL and agency_type_label: return " - ".join([org_type_label, agency_type_label]) else: return org_type_label @@ -141,7 +145,11 @@ class Portfolio(TimeStampedModel): @property def federal_type(self): """Returns the federal_type value on the underlying federal_agency field""" - return self.federal_agency.federal_type if self.federal_agency else None + return self.get_federal_type(self.federal_agency) + + @classmethod + def get_federal_type(cls, federal_agency): + return federal_agency.federal_type if federal_agency else None # == Getters for domains == # def get_domains(self): diff --git a/src/registrar/models/portfolio_invitation.py b/src/registrar/models/portfolio_invitation.py index 2ad780429..46d7bf124 100644 --- a/src/registrar/models/portfolio_invitation.py +++ b/src/registrar/models/portfolio_invitation.py @@ -1,13 +1,11 @@ """People are invited by email to administer domains.""" import logging - from django.contrib.auth import get_user_model from django.db import models - from django_fsm import FSMField, transition +from registrar.models.user_portfolio_permission import UserPortfolioPermission from .utility.portfolio_helper import UserPortfolioPermissionChoices, UserPortfolioRoleChoices # type: ignore - from .utility.time_stamped_model import TimeStampedModel from django.contrib.postgres.fields import ArrayField @@ -87,9 +85,11 @@ class PortfolioInvitation(TimeStampedModel): raise RuntimeError("Cannot find the user to retrieve this portfolio invitation.") # and create a role for that user on this portfolio - user.portfolio = self.portfolio + user_portfolio_permission, _ = UserPortfolioPermission.objects.get_or_create( + portfolio=self.portfolio, user=user + ) if self.portfolio_roles and len(self.portfolio_roles) > 0: - user.portfolio_roles = self.portfolio_roles + user_portfolio_permission.roles = self.portfolio_roles if self.portfolio_additional_permissions and len(self.portfolio_additional_permissions) > 0: - user.portfolio_additional_permissions = self.portfolio_additional_permissions - user.save() + user_portfolio_permission.additional_permissions = self.portfolio_additional_permissions + user_portfolio_permission.save() diff --git a/src/registrar/models/user.py b/src/registrar/models/user.py index 81d3b9b61..929a63525 100644 --- a/src/registrar/models/user.py +++ b/src/registrar/models/user.py @@ -3,11 +3,10 @@ import logging from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import Q -from django.forms import ValidationError +from django.http import HttpRequest -from registrar.models.domain_information import DomainInformation -from registrar.models.user_domain_role import UserDomainRole -from registrar.models.utility.portfolio_helper import UserPortfolioPermissionChoices, UserPortfolioRoleChoices +from registrar.models import DomainInformation, UserDomainRole +from registrar.models.utility.portfolio_helper import UserPortfolioPermissionChoices from .domain_invitation import DomainInvitation from .portfolio_invitation import PortfolioInvitation @@ -15,7 +14,6 @@ from .transition_domain import TransitionDomain from .verified_by_staff import VerifiedByStaff from .domain import Domain from .domain_request import DomainRequest -from django.contrib.postgres.fields import ArrayField from waffle.decorators import flag_is_active from phonenumber_field.modelfields import PhoneNumberField # type: ignore @@ -66,32 +64,6 @@ class User(AbstractUser): # after they login. FIXTURE_USER = "fixture_user", "Created by fixtures" - PORTFOLIO_ROLE_PERMISSIONS = { - UserPortfolioRoleChoices.ORGANIZATION_ADMIN: [ - UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS, - UserPortfolioPermissionChoices.VIEW_MEMBER, - UserPortfolioPermissionChoices.EDIT_MEMBER, - UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS, - UserPortfolioPermissionChoices.EDIT_REQUESTS, - UserPortfolioPermissionChoices.VIEW_PORTFOLIO, - UserPortfolioPermissionChoices.EDIT_PORTFOLIO, - # Domain: field specific permissions - UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION, - UserPortfolioPermissionChoices.EDIT_SUBORGANIZATION, - ], - UserPortfolioRoleChoices.ORGANIZATION_ADMIN_READ_ONLY: [ - UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS, - UserPortfolioPermissionChoices.VIEW_MEMBER, - UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS, - UserPortfolioPermissionChoices.VIEW_PORTFOLIO, - # Domain: field specific permissions - UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION, - ], - UserPortfolioRoleChoices.ORGANIZATION_MEMBER: [ - UserPortfolioPermissionChoices.VIEW_PORTFOLIO, - ], - } - # #### Constants for choice fields #### RESTRICTED = "restricted" STATUS_CHOICES = ((RESTRICTED, RESTRICTED),) @@ -112,34 +84,6 @@ class User(AbstractUser): related_name="users", ) - portfolio = models.ForeignKey( - "registrar.Portfolio", - null=True, - blank=True, - related_name="user", - on_delete=models.SET_NULL, - ) - - portfolio_roles = ArrayField( - models.CharField( - max_length=50, - choices=UserPortfolioRoleChoices.choices, - ), - null=True, - blank=True, - help_text="Select one or more roles.", - ) - - portfolio_additional_permissions = ArrayField( - models.CharField( - max_length=50, - choices=UserPortfolioPermissionChoices.choices, - ), - null=True, - blank=True, - help_text="Select one or more additional permissions.", - ) - phone = PhoneNumberField( null=True, blank=True, @@ -187,6 +131,12 @@ class User(AbstractUser): else: return self.username + @classmethod + def get_default_user(cls): + """Returns the default "system" user""" + default_creator, _ = User.objects.get_or_create(username="System") + return default_creator + def restrict_user(self): self.status = self.RESTRICTED self.save() @@ -230,68 +180,134 @@ class User(AbstractUser): def has_contact_info(self): return bool(self.title or self.email or self.phone) - def clean(self): - """Extends clean method to perform additional validation, which can raise errors in django admin.""" - super().clean() - - if self.portfolio is None and self._get_portfolio_permissions(): - raise ValidationError("When portfolio roles or additional permissions are assigned, portfolio is required.") - - if self.portfolio is not None and not self._get_portfolio_permissions(): - raise ValidationError("When portfolio is assigned, portfolio roles or additional permissions are required.") - - def _get_portfolio_permissions(self): - """ - Retrieve the permissions for the user's portfolio roles. - """ - portfolio_permissions = set() # Use a set to avoid duplicate permissions - - if self.portfolio_roles: - for role in self.portfolio_roles: - if role in self.PORTFOLIO_ROLE_PERMISSIONS: - portfolio_permissions.update(self.PORTFOLIO_ROLE_PERMISSIONS[role]) - if self.portfolio_additional_permissions: - portfolio_permissions.update(self.portfolio_additional_permissions) - return list(portfolio_permissions) # Convert back to list if necessary - - def _has_portfolio_permission(self, portfolio_permission): + def _has_portfolio_permission(self, portfolio, portfolio_permission): """The views should only call this function when testing for perms and not rely on roles.""" - if not self.portfolio: + if not portfolio: return False - portfolio_permissions = self._get_portfolio_permissions() + user_portfolio_perms = self.portfolio_permissions.filter(portfolio=portfolio, user=self).first() + if not user_portfolio_perms: + return False - return portfolio_permission in portfolio_permissions + return portfolio_permission in user_portfolio_perms._get_portfolio_permissions() - # the methods below are checks for individual portfolio permissions. They are defined here - # to make them easier to call elsewhere throughout the application - def has_base_portfolio_permission(self): - return self._has_portfolio_permission(UserPortfolioPermissionChoices.VIEW_PORTFOLIO) + def has_base_portfolio_permission(self, portfolio): + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_PORTFOLIO) - def has_edit_org_portfolio_permission(self): - return self._has_portfolio_permission(UserPortfolioPermissionChoices.EDIT_PORTFOLIO) + def has_edit_org_portfolio_permission(self, portfolio): + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.EDIT_PORTFOLIO) - def has_domains_portfolio_permission(self): + def has_any_domains_portfolio_permission(self, portfolio): return self._has_portfolio_permission( - UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS - ) or self._has_portfolio_permission(UserPortfolioPermissionChoices.VIEW_MANAGED_DOMAINS) + portfolio, UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS + ) or self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_MANAGED_DOMAINS) - def has_domain_requests_portfolio_permission(self): - return self._has_portfolio_permission( - UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS - ) or self._has_portfolio_permission(UserPortfolioPermissionChoices.VIEW_CREATED_REQUESTS) + def has_organization_requests_flag(self): + request = HttpRequest() + request.user = self + return flag_is_active(request, "organization_requests") - def has_view_all_domains_permission(self): + def has_organization_members_flag(self): + request = HttpRequest() + request.user = self + return flag_is_active(request, "organization_members") + + def has_view_members_portfolio_permission(self, portfolio): + # BEGIN + # Note code below is to add organization_request feature + if not self.has_organization_members_flag(): + return False + # END + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_MEMBERS) + + def has_edit_members_portfolio_permission(self, portfolio): + # BEGIN + # Note code below is to add organization_request feature + if not self.has_organization_members_flag(): + return False + # END + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.EDIT_MEMBERS) + + def has_view_all_domains_portfolio_permission(self, portfolio): """Determines if the current user can view all available domains in a given portfolio""" - return self._has_portfolio_permission(UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS) + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS) + + def has_any_requests_portfolio_permission(self, portfolio): + # BEGIN + # Note code below is to add organization_request feature + if not self.has_organization_requests_flag(): + return False + # END + return self._has_portfolio_permission( + portfolio, UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS + ) or self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.EDIT_REQUESTS) + + def has_view_all_requests_portfolio_permission(self, portfolio): + """Determines if the current user can view all available domain requests in a given portfolio""" + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS) + + def has_edit_request_portfolio_permission(self, portfolio): + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.EDIT_REQUESTS) # Field specific permission checks - def has_view_suborganization(self): - return self._has_portfolio_permission(UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION) + def has_view_suborganization_portfolio_permission(self, portfolio): + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION) - def has_edit_suborganization(self): - return self._has_portfolio_permission(UserPortfolioPermissionChoices.EDIT_SUBORGANIZATION) + def has_edit_suborganization_portfolio_permission(self, portfolio): + return self._has_portfolio_permission(portfolio, UserPortfolioPermissionChoices.EDIT_SUBORGANIZATION) + + def get_first_portfolio(self): + permission = self.portfolio_permissions.first() + if permission: + return permission.portfolio + return None + + def portfolio_role_summary(self, portfolio): + """Returns a list of roles based on the user's permissions.""" + roles = [] + + # Define the conditions and their corresponding roles + conditions_roles = [ + (self.has_edit_suborganization_portfolio_permission(portfolio), ["Admin"]), + ( + self.has_view_all_domains_portfolio_permission(portfolio) + and self.has_any_requests_portfolio_permission(portfolio) + and self.has_edit_request_portfolio_permission(portfolio), + ["View-only admin", "Domain requestor"], + ), + ( + self.has_view_all_domains_portfolio_permission(portfolio) + and self.has_any_requests_portfolio_permission(portfolio), + ["View-only admin"], + ), + ( + self.has_base_portfolio_permission(portfolio) + and self.has_edit_request_portfolio_permission(portfolio) + and self.has_any_domains_portfolio_permission(portfolio), + ["Domain requestor", "Domain manager"], + ), + ( + self.has_base_portfolio_permission(portfolio) and self.has_edit_request_portfolio_permission(portfolio), + ["Domain requestor"], + ), + ( + self.has_base_portfolio_permission(portfolio) and self.has_any_domains_portfolio_permission(portfolio), + ["Domain manager"], + ), + (self.has_base_portfolio_permission(portfolio), ["Member"]), + ] + + # Evaluate conditions and add roles + for condition, role_list in conditions_roles: + if condition: + roles.extend(role_list) + break + + return roles + + def get_portfolios(self): + return self.portfolio_permissions.all() @classmethod def needs_identity_verification(cls, email, uuid): @@ -406,7 +422,14 @@ class User(AbstractUser): for invitation in PortfolioInvitation.objects.filter( email__iexact=self.email, status=PortfolioInvitation.PortfolioInvitationStatus.INVITED ): - if self.portfolio is None: + # need to create a bogus request and assign user to it, in order to pass request + # to flag_is_active + request = HttpRequest() + request.user = self + only_single_portfolio = ( + not flag_is_active(request, "multiple_portfolios") and self.get_first_portfolio() is None + ) + if only_single_portfolio or flag_is_active(None, "multiple_portfolios"): try: invitation.retrieve() invitation.save() @@ -433,11 +456,13 @@ class User(AbstractUser): def is_org_user(self, request): has_organization_feature_flag = flag_is_active(request, "organization_feature") - return has_organization_feature_flag and self.has_base_portfolio_permission() + portfolio = request.session.get("portfolio") + return has_organization_feature_flag and self.has_base_portfolio_permission(portfolio) def get_user_domain_ids(self, request): """Returns either the domains ids associated with this user on UserDomainRole or Portfolio""" - if self.is_org_user(request) and self.has_view_all_domains_permission(): - return DomainInformation.objects.filter(portfolio=self.portfolio).values_list("domain_id", flat=True) + portfolio = request.session.get("portfolio") + if self.is_org_user(request) and self.has_view_all_domains_portfolio_permission(portfolio): + return DomainInformation.objects.filter(portfolio=portfolio).values_list("domain_id", flat=True) else: return UserDomainRole.objects.filter(user=self).values_list("domain_id", flat=True) diff --git a/src/registrar/models/user_portfolio_permission.py b/src/registrar/models/user_portfolio_permission.py new file mode 100644 index 000000000..0c2487df3 --- /dev/null +++ b/src/registrar/models/user_portfolio_permission.py @@ -0,0 +1,119 @@ +from django.db import models +from django.forms import ValidationError +from django.http import HttpRequest +from waffle import flag_is_active +from registrar.models.utility.portfolio_helper import UserPortfolioPermissionChoices, UserPortfolioRoleChoices +from .utility.time_stamped_model import TimeStampedModel +from django.contrib.postgres.fields import ArrayField + + +class UserPortfolioPermission(TimeStampedModel): + """This is a linking table that connects a user with a role on a portfolio.""" + + class Meta: + unique_together = ["user", "portfolio"] + + PORTFOLIO_ROLE_PERMISSIONS = { + UserPortfolioRoleChoices.ORGANIZATION_ADMIN: [ + UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS, + UserPortfolioPermissionChoices.VIEW_MEMBERS, + UserPortfolioPermissionChoices.EDIT_MEMBERS, + UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS, + UserPortfolioPermissionChoices.EDIT_REQUESTS, + UserPortfolioPermissionChoices.VIEW_PORTFOLIO, + UserPortfolioPermissionChoices.EDIT_PORTFOLIO, + # Domain: field specific permissions + UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION, + UserPortfolioPermissionChoices.EDIT_SUBORGANIZATION, + ], + UserPortfolioRoleChoices.ORGANIZATION_ADMIN_READ_ONLY: [ + UserPortfolioPermissionChoices.VIEW_ALL_DOMAINS, + UserPortfolioPermissionChoices.VIEW_MEMBERS, + UserPortfolioPermissionChoices.VIEW_ALL_REQUESTS, + UserPortfolioPermissionChoices.VIEW_PORTFOLIO, + # Domain: field specific permissions + UserPortfolioPermissionChoices.VIEW_SUBORGANIZATION, + ], + UserPortfolioRoleChoices.ORGANIZATION_MEMBER: [ + UserPortfolioPermissionChoices.VIEW_PORTFOLIO, + ], + } + + user = models.ForeignKey( + "registrar.User", + null=False, + # when a user is deleted, permissions are too + on_delete=models.CASCADE, + related_name="portfolio_permissions", + ) + + portfolio = models.ForeignKey( + "registrar.Portfolio", + null=False, + # when a portfolio is deleted, permissions are too + on_delete=models.CASCADE, + related_name="portfolio_users", + ) + + roles = ArrayField( + models.CharField( + max_length=50, + choices=UserPortfolioRoleChoices.choices, + ), + null=True, + blank=True, + help_text="Select one or more roles.", + ) + + additional_permissions = ArrayField( + models.CharField( + max_length=50, + choices=UserPortfolioPermissionChoices.choices, + ), + null=True, + blank=True, + help_text="Select one or more additional permissions.", + ) + + def __str__(self): + return f"User '{self.user}' on Portfolio '{self.portfolio}' " f"" if self.roles else "" + + def _get_portfolio_permissions(self): + """ + Retrieve the permissions for the user's portfolio roles. + """ + # Use a set to avoid duplicate permissions + portfolio_permissions = set() + + if self.roles: + for role in self.roles: + portfolio_permissions.update(self.PORTFOLIO_ROLE_PERMISSIONS.get(role, [])) + + if self.additional_permissions: + portfolio_permissions.update(self.additional_permissions) + + return list(portfolio_permissions) + + def clean(self): + """Extends clean method to perform additional validation, which can raise errors in django admin.""" + super().clean() + + # Check if a user is set without accessing the related object. + has_user = bool(self.user_id) + if self.pk is None and has_user: + # Have to create a bogus request to set the user and pass to flag_is_active + request = HttpRequest() + request.user = self.user + existing_permissions = UserPortfolioPermission.objects.filter(user=self.user) + if not flag_is_active(request, "multiple_portfolios") and existing_permissions.exists(): + raise ValidationError( + "Only one portfolio permission is allowed per user when multiple portfolios are disabled." + ) + + # Check if portfolio is set without accessing the related object. + has_portfolio = bool(self.portfolio_id) + if not has_portfolio and self._get_portfolio_permissions(): + raise ValidationError("When portfolio roles or additional permissions are assigned, portfolio is required.") + + if has_portfolio and not self._get_portfolio_permissions(): + raise ValidationError("When portfolio is assigned, portfolio roles or additional permissions are required.") diff --git a/src/registrar/models/utility/portfolio_helper.py b/src/registrar/models/utility/portfolio_helper.py index 86aaa5e16..7f34221fd 100644 --- a/src/registrar/models/utility/portfolio_helper.py +++ b/src/registrar/models/utility/portfolio_helper.py @@ -17,11 +17,10 @@ class UserPortfolioPermissionChoices(models.TextChoices): VIEW_ALL_DOMAINS = "view_all_domains", "View all domains and domain reports" VIEW_MANAGED_DOMAINS = "view_managed_domains", "View managed domains" - VIEW_MEMBER = "view_member", "View members" - EDIT_MEMBER = "edit_member", "Create and edit members" + VIEW_MEMBERS = "view_members", "View members" + EDIT_MEMBERS = "edit_members", "Create and edit members" VIEW_ALL_REQUESTS = "view_all_requests", "View all requests" - VIEW_CREATED_REQUESTS = "view_created_requests", "View created requests" EDIT_REQUESTS = "edit_requests", "Create and edit requests" VIEW_PORTFOLIO = "view_portfolio", "View organization" diff --git a/src/registrar/registrar_middleware.py b/src/registrar/registrar_middleware.py index 3bcb1dc23..6207591ba 100644 --- a/src/registrar/registrar_middleware.py +++ b/src/registrar/registrar_middleware.py @@ -6,7 +6,7 @@ import logging from urllib.parse import parse_qs from django.urls import reverse from django.http import HttpResponseRedirect -from registrar.models.user import User +from registrar.models import User from waffle.decorators import flag_is_active from registrar.models.utility.generic_helper import replace_url_queryparams @@ -125,8 +125,9 @@ class CheckUserProfileMiddleware: class CheckPortfolioMiddleware: """ - Checks if the current user has a portfolio - If they do, redirect them to the portfolio homepage when they navigate to home. + this middleware should serve two purposes: + 1 - set the portfolio in session if appropriate # views will need the session portfolio + 2 - if path is home and session portfolio is set, redirect based on permissions of user """ def __init__(self, get_response): @@ -140,19 +141,33 @@ class CheckPortfolioMiddleware: def process_view(self, request, view_func, view_args, view_kwargs): current_path = request.path - if current_path == self.home and request.user.is_authenticated and request.user.is_org_user(request): + if not request.user.is_authenticated: + return None - if request.user.has_base_portfolio_permission(): - portfolio = request.user.portfolio + # if multiple portfolios are allowed for this user + if flag_is_active(request, "organization_feature"): + self.set_portfolio_in_session(request) + elif request.session.get("portfolio"): + # Edge case: User disables flag while already logged in + request.session["portfolio"] = None + elif "portfolio" not in request.session: + # Set the portfolio in the session if its not already in it + request.session["portfolio"] = None - # Add the portfolio to the request object - request.portfolio = portfolio - - if request.user.has_domains_portfolio_permission(): + if request.user.is_org_user(request): + if current_path == self.home: + if request.user.has_any_domains_portfolio_permission(request.session["portfolio"]): portfolio_redirect = reverse("domains") else: portfolio_redirect = reverse("no-portfolio-domains") - return HttpResponseRedirect(portfolio_redirect) return None + + def set_portfolio_in_session(self, request): + # NOTE: we will want to change later to have a workflow for selecting + # portfolio and another for switching portfolio; for now, select first + if flag_is_active(request, "multiple_portfolios"): + request.session["portfolio"] = request.user.get_first_portfolio() + else: + request.session["portfolio"] = request.user.get_first_portfolio() diff --git a/src/registrar/templates/admin/analytics.html b/src/registrar/templates/admin/analytics.html index 13db3b60a..7c1a09c78 100644 --- a/src/registrar/templates/admin/analytics.html +++ b/src/registrar/templates/admin/analytics.html @@ -5,7 +5,7 @@ {% block content %} -
    +
    @@ -25,7 +25,7 @@ Template for an input field with a clipboard {% endif %} \ No newline at end of file diff --git a/src/registrar/templates/admin/model_descriptions.html b/src/registrar/templates/admin/model_descriptions.html index 4b61e21bd..9f13245fe 100644 --- a/src/registrar/templates/admin/model_descriptions.html +++ b/src/registrar/templates/admin/model_descriptions.html @@ -32,6 +32,8 @@ {% include "django/admin/includes/descriptions/website_description.html" %} {% elif opts.model_name == 'portfolioinvitation' %} {% include "django/admin/includes/descriptions/portfolio_invitation_description.html" %} + {% elif opts.model_name == 'allowedemail' %} + {% include "django/admin/includes/descriptions/allowed_email_description.html" %} {% else %}

    This table does not have a description yet.

    {% endif %} diff --git a/src/registrar/templates/admin/transfer_user.html b/src/registrar/templates/admin/transfer_user.html new file mode 100644 index 000000000..9e55346e7 --- /dev/null +++ b/src/registrar/templates/admin/transfer_user.html @@ -0,0 +1,260 @@ +{% extends 'admin/base_site.html' %} +{% load i18n static %} + +{% block content_title %}

    Transfer user

    {% endblock %} + +{% block extrastyle %} + +{{ block.super }} + +{% endblock %} + +{% block extrahead %} + {{ block.super }} + + + + + + + + + +{% endblock %} + +{% block breadcrumbs %} +
    +{% endblock %} + +{% block content %} +
    + +
    + +
    +
    + + + +
    +
    +
    + {% if selected_user %} + + Transfer and delete user + + {% endif %} +
    +
    + +
    + +
    +
    +

    User to transfer data from

    +
    + {% if selected_user %} +
    +
    Username:
    +
    {{ selected_user.username }}
    +
    Created at:
    +
    {{ selected_user.created_at }}
    +
    Last login:
    +
    {{ selected_user.last_login }}
    +
    First name:
    +
    {{ selected_user.first_name }}
    +
    Middle name:
    +
    {{ selected_user.middle_name }}
    +
    Last name:
    +
    {{ selected_user.last_name }}
    +
    Title:
    +
    {{ selected_user.title }}
    +
    Email:
    +
    {{ selected_user.email }}
    +
    Phone:
    +
    {{ selected_user.phone }}
    +

    Data that will get transferred:

    +
    Domains:
    +
    + {% if selected_user_domains %} +
      + {% for domain in selected_user_domains %} +
    • {{ domain }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    Domain requests:
    +
    + {% if selected_user_domain_requests %} +
      + {% for request in selected_user_domain_requests %} +
    • {{ request }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    Portfolios:
    +
    + {% if selected_user_portfolios %} +
      + {% for portfolio in selected_user_portfolios %} +
    • {{ portfolio.portfolio }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    + {% else %} +

    No user selected yet.

    + {% endif %} +
    +
    +
    + +
    +
    +

    User to receive data

    +
    +
    +
    Username:
    +
    {{ current_user.username }}
    +
    Created at:
    +
    {{ current_user.created_at }}
    +
    Last login:
    +
    {{ current_user.last_login }}
    +
    First name:
    +
    {{ current_user.first_name }}
    +
    Middle name:
    +
    {{ current_user.middle_name }}
    +
    Last name:
    +
    {{ current_user.last_name }}
    +
    Title:
    +
    {{ current_user.title }}
    +
    Email:
    +
    {{ current_user.email }}
    +
    Phone:
    +
    {{ current_user.phone }}
    +

     

    +
    Domains:
    +
    + {% if current_user_domains %} +
      + {% for domain in current_user_domains %} +
    • {{ domain }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    Domain requests:
    +
    + {% if current_user_domain_requests %} +
      + {% for request in current_user_domain_requests %} +
    • {{ request }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    Portfolios:
    +
    + {% if current_user_portfolios %} +
      + {% for portfolio in current_user_portfolios %} +
    • {{ portfolio.portfolio }}
    • + {% endfor %} +
    + {% else %} + None + {% endif %} +
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +

    + Are you sure you want to transfer data and delete this user? +

    +
    + {% if selected_user != logged_in_user %} +

    Username: {{ selected_user.username }}
    + Name: {{ selected_user.first_name }} {{ selected_user.last_name }}
    + Email: {{ selected_user.email }}

    +

    This action cannot be undone.

    + {% else %} +

    Don't do it!

    + {% endif %} +
    + + +
    + +
    +
    +{% endblock %} diff --git a/src/registrar/templates/django/admin/domain_request_change_form.html b/src/registrar/templates/django/admin/domain_request_change_form.html index a7d59d22c..0396326d9 100644 --- a/src/registrar/templates/django/admin/domain_request_change_form.html +++ b/src/registrar/templates/django/admin/domain_request_change_form.html @@ -120,7 +120,7 @@ -

    +

    Requested domain: {{ original.requested_domain.name }}

    {{ block.super }} diff --git a/src/registrar/templates/django/admin/includes/descriptions/allowed_email_description.html b/src/registrar/templates/django/admin/includes/descriptions/allowed_email_description.html new file mode 100644 index 000000000..602935ab7 --- /dev/null +++ b/src/registrar/templates/django/admin/includes/descriptions/allowed_email_description.html @@ -0,0 +1,6 @@ +

    This table is an email allow list for non-production environments.

    +

    + If an email is sent out and the email does not exist within this table (or is not a subset of it), + then no email will be sent. +

    +

    If this table is populated in a production environment, no change will occur as it will simply be ignored.

    diff --git a/src/registrar/templates/django/admin/includes/detail_table_fieldset.html b/src/registrar/templates/django/admin/includes/detail_table_fieldset.html index 683f33117..e22bcb571 100644 --- a/src/registrar/templates/django/admin/includes/detail_table_fieldset.html +++ b/src/registrar/templates/django/admin/includes/detail_table_fieldset.html @@ -70,7 +70,7 @@ This is using a custom implementation fieldset.html (see admin/fieldset.html)
    +
    + {{ field.field }} + + +
    +
    + + {% if not action_needed_email_sent %} + This email will be sent to the creator of this request after saving + {% else %} + This email has been sent to the creator of this request + {% endif %} +
    {% else %} {{ field.field }} @@ -187,11 +287,6 @@ This is using a custom implementation fieldset.html (see admin/fieldset.html) {% if not skip_additional_contact_info %} {% include "django/admin/includes/user_detail_list.html" with user=original_object.creator no_title_top_padding=field.is_readonly %} {% endif%} - {% elif field.field.name == "submitter" %} -
    - - {% include "django/admin/includes/contact_detail_list.html" with user=original_object.submitter no_title_top_padding=field.is_readonly %} -
    {% elif field.field.name == "senior_official" %}
    @@ -240,7 +335,14 @@ This is using a custom implementation fieldset.html (see admin/fieldset.html) {% endif %} {% endwith %} - {% elif field.field.name == "state_territory" %} + {% elif field.field.name == "display_members" and field.contents %} +
    + Details +
    + {{ field.contents|safe }} +
    +
    + {% elif field.field.name == "state_territory" and original_object|model_name_lowercase != 'portfolio' %}
    CISA region: diff --git a/src/registrar/templates/django/admin/portfolio_change_form.html b/src/registrar/templates/django/admin/portfolio_change_form.html index 9d59aae42..8dae8a080 100644 --- a/src/registrar/templates/django/admin/portfolio_change_form.html +++ b/src/registrar/templates/django/admin/portfolio_change_form.html @@ -1,10 +1,13 @@ {% extends 'django/admin/email_clipboard_change_form.html' %} +{% load custom_filters %} {% load i18n static %} {% block content %} {% comment %} Stores the json endpoint in a url for easier access {% endcomment %} {% url 'get-senior-official-from-federal-agency-json' as url %} + {% url 'get-federal-and-portfolio-types-from-federal-agency-json' as url %} + {{ block.super }} {% endblock content %} @@ -14,10 +17,28 @@ This is a placeholder for now. Disclaimer: - When extending the fieldset view - *make a new one* that extends from detail_table_fieldset. - For instance, "portfolio_fieldset.html". + When extending the fieldset view consider whether you need to make a new one that extends from detail_table_fieldset. detail_table_fieldset is used on multiple admin pages, so a change there can have unintended consequences. {% endcomment %} {% include "django/admin/includes/detail_table_fieldset.html" with original_object=original %} {% endfor %} {% endblock %} + +{% block submit_buttons_bottom %} +
    + + + + +

    + Organization Name: {{ original.organization_name }} +

    + {{ block.super }} +
    + +{% endblock %} diff --git a/src/registrar/templates/django/admin/user_change_form.html b/src/registrar/templates/django/admin/user_change_form.html index 005d67aec..736f12ba4 100644 --- a/src/registrar/templates/django/admin/user_change_form.html +++ b/src/registrar/templates/django/admin/user_change_form.html @@ -1,7 +1,42 @@ {% extends 'django/admin/email_clipboard_change_form.html' %} {% load i18n static %} + +{% block field_sets %} + + + {% for fieldset in adminform %} + {% include "django/admin/includes/domain_fieldset.html" with state_help_message=state_help_message %} + {% endfor %} +{% endblock %} + {% block after_related_objects %} + {% if portfolios %} +
    +

    Portfolio information

    +
    +
    +

    Portfolios

    + +
    +
    +
    + {% endif %} +

    Associated requests and domains

    diff --git a/src/registrar/templates/django/forms/widgets/combobox.html b/src/registrar/templates/django/forms/widgets/combobox.html index 107c2e14e..7ff31945b 100644 --- a/src/registrar/templates/django/forms/widgets/combobox.html +++ b/src/registrar/templates/django/forms/widgets/combobox.html @@ -7,7 +7,9 @@ for now we just carry the attribute to both the parent element and the select.
    {% include "django/forms/widgets/select.html" %} diff --git a/src/registrar/templates/domain_detail.html b/src/registrar/templates/domain_detail.html index 19f196e40..dd08004a3 100644 --- a/src/registrar/templates/domain_detail.html +++ b/src/registrar/templates/domain_detail.html @@ -72,9 +72,9 @@ {% include "includes/summary_item.html" with title='DNSSEC' value='Not Enabled' edit_link=url editable=is_editable %} {% endif %} - {% if portfolio and has_domains_portfolio_permission and request.user.has_view_suborganization %} + {% if portfolio and has_any_domains_portfolio_permission and has_view_suborganization_portfolio_permission %} {% url 'domain-suborganization' pk=domain.id as url %} - {% include "includes/summary_item.html" with title='Suborganization' value=domain.domain_info.sub_organization edit_link=url editable=is_editable|and:request.user.has_edit_suborganization %} + {% include "includes/summary_item.html" with title='Suborganization' value=domain.domain_info.sub_organization edit_link=url editable=is_editable|and:has_edit_suborganization_portfolio_permission %} {% else %} {% url 'domain-org-name-address' pk=domain.id as url %} {% include "includes/summary_item.html" with title='Organization name and mailing address' value=domain.domain_info address='true' edit_link=url editable=is_editable %} diff --git a/src/registrar/templates/domain_dsdata.html b/src/registrar/templates/domain_dsdata.html index b62ad7ec5..6e18bce13 100644 --- a/src/registrar/templates/domain_dsdata.html +++ b/src/registrar/templates/domain_dsdata.html @@ -63,10 +63,10 @@
    -
    @@ -74,10 +74,10 @@ {% endfor %} -
    {% endfor %} - {% comment %} Work around USWDS' button margins to add some spacing between the submit and the 'add more' diff --git a/src/registrar/templates/domain_org_name_address.html b/src/registrar/templates/domain_org_name_address.html index 1e6176aa0..a7eb02b59 100644 --- a/src/registrar/templates/domain_org_name_address.html +++ b/src/registrar/templates/domain_org_name_address.html @@ -42,7 +42,7 @@ {% input_with_errors form.state_territory %} - {% with add_class="usa-input--small" %} + {% with add_class="usa-input--small" sublabel_text="Enter a zip code in the required format, like 12345 or 12345-6789." %} {% input_with_errors form.zipcode %} {% endwith %} diff --git a/src/registrar/templates/domain_request_form.html b/src/registrar/templates/domain_request_form.html index 17948a110..9228e51db 100644 --- a/src/registrar/templates/domain_request_form.html +++ b/src/registrar/templates/domain_request_form.html @@ -16,6 +16,26 @@ Previous step + {% comment %} + TODO: uncomment in #2596 + {% else %} + {% if portfolio %} + {% url 'domain-requests' as url_2 %} + + {% endif %} {% endcomment %} {% endif %} {% block form_messages %} diff --git a/src/registrar/templates/domain_request_org_contact.html b/src/registrar/templates/domain_request_org_contact.html index f145ee3bf..d4f3c2071 100644 --- a/src/registrar/templates/domain_request_org_contact.html +++ b/src/registrar/templates/domain_request_org_contact.html @@ -33,7 +33,7 @@ {% input_with_errors forms.0.state_territory %} - {% with add_class="usa-input--small" %} + {% with add_class="usa-input--small" sublabel_text="Enter a zip code in the required format, like 12345 or 12345-6789." %} {% input_with_errors forms.0.zipcode %} {% endwith %} diff --git a/src/registrar/templates/domain_request_other_contacts.html b/src/registrar/templates/domain_request_other_contacts.html index 4189e8c73..72e4abd8b 100644 --- a/src/registrar/templates/domain_request_other_contacts.html +++ b/src/registrar/templates/domain_request_other_contacts.html @@ -40,7 +40,7 @@

    Organization contact {{ forloop.counter }}

    -