Skip to content

feat: add bulk certificate exceptions CSV upload endpoint#38464

Merged
wgu-taylor-payne merged 34 commits intoopenedx:masterfrom
WGU-Open-edX:wgu-jesse-stewart/instructor_dashboard_certificates_bulk
May 1, 2026
Merged

feat: add bulk certificate exceptions CSV upload endpoint#38464
wgu-taylor-payne merged 34 commits intoopenedx:masterfrom
WGU-Open-edX:wgu-jesse-stewart/instructor_dashboard_certificates_bulk

Conversation

@wgu-jesse-stewart
Copy link
Copy Markdown
Contributor

@wgu-jesse-stewart wgu-jesse-stewart commented Apr 28, 2026

feat: add bulk certificate exceptions endpoint and stabilize JWT tests

Description

Adds a new v2 instructor API endpoint for granting certificate exceptions in bulk via CSV upload, and refactors the JWT test module to avoid a stale-timestamp issue.

New endpoint: BulkCertificateExceptionsView

POST /api/instructor/v2/courses/{course_id}/certificates/exceptions/bulk

Accepts a multipart form upload with a file field containing a CSV. Each row is username_or_email[,notes]. The view:

  • Validates that the upload is present and named *.csv.
  • Decodes with utf-8-sig so Excel-exported files with a BOM work without the user having to think about it.
  • Skips empty rows.
  • Resolves all identifiers via _resolve_learners_to_users and validates them via _validate_learners_for_certificate_exceptions before any writes — same helpers used by the single-learner path, so behavior stays consistent.
  • Calls certs_api.create_or_update_certificate_allowlist_entry for each valid learner and aggregates results into a single { "success": [...], "errors": [...] } payload.
  • Logs each grant with the acting instructor, target user, and course key for audit traceability.

Errors during a single row are caught and reported in errors rather than aborting the batch — partial success is the expected mode for CSV imports.

Permission checks reuse permissions.InstructorPermission and CERTIFICATE_EXCEPTION_VIEW, matching the existing single-exception endpoint.

Test stabilization: test_jwt.py

The module previously computed test_now = int(time()) once at import and reused it across every test, along with a module-level expected_full_token dict built from that timestamp. That makes the suite sensitive to import-vs-execution timing and to test reordering — and means any test that mutates expected_full_token would leak into others.

Replaced both module-level constants with two helpers:

  • get_test_now() — returns the current time when the test runs.
  • get_expected_full_token(test_now) — returns a fresh expected payload bound to that timestamp.

Each test now grabs its own test_now at the top and builds its expected payload from it. No behavior change to the JWT code itself.

User roles impacted

  • Course staff / instructors: gain a bulk-upload path for certificate exceptions. The existing single-learner flow is unchanged.
  • Developers: new endpoint to wire into the instructor dashboard MFE / any frontend that drives certificate management.
  • Operators: no config or migration changes.

Supporting information

  • Builds on the existing v2 instructor API surface and the _resolve_learners_to_users / _validate_learners_for_certificate_exceptions helpers introduced earlier in the v2 redesign.
  • Mirrors the request/response shape used by other bulk CSV endpoints in the instructor API for consistency.

Testing instructions

Bulk certificate exceptions endpoint

  1. Bring up devstack / Tutor with a course that has at least three enrolled learners.
  2. Authenticate as a user with instructor permissions on that course.
  3. Prepare a CSV (exceptions.csv):
    learner1@example.com,Manual review approved
    learner2,
    nonexistent@example.com,Should fail
    
  4. POST it:
    curl -X POST \
      -H "Authorization: JWT <token>" \
      -F "file=@exceptions.csv" \
      https://<lms-host>/api/instructor/v2/courses/<course_id>/certificates/exceptions/bulk
    
  5. Verify the response is 200 with success containing the two valid learners and errors containing the unknown email with a clear message.
  6. Confirm in Django admin (or via the single-exception GET) that allowlist entries exist for the two valid learners with the supplied notes.
  7. Negative cases to verify return 400:
    • No file field in the request.
    • File without a .csv extension.
    • Empty CSV / CSV containing only blank lines.
  8. Verify a non-instructor user receives 403.
  9. Tail the LMS logs and confirm one Certificate exception granted ... info line per successful row, naming the acting instructor.

JWT tests

Run the affected module:

pytest openedx/core/lib/tests/test_jwt.py -v

All tests should pass. Optionally re-run several times in a row, or with -p no:randomly reversed (random order), to confirm there's no ordering sensitivity.

Deadline

None.

Other information

  • No database migrations.
  • No new settings or feature flags — the endpoint is gated by the same instructor permission as the existing certificate exception endpoints.
  • The BulkCertificateExceptionsView follows the same broad-except pattern as neighboring views in api_v2.py (with pylint: disable=broad-except) so per-row failures don't abort the batch. Each caught exception is logged via log.exception with the user and course key.
  • CSV is read fully into memory (uploaded_file.read()); for very large rosters this may want a streamed parser later, but matches the existing bulk-CSV endpoints in this module.
  • No frontend changes in this PR — consumer MFE work will land separately.

- Add ToggleCertificateGenerationView endpoint to enable/disable certificate generation
- Add CertificateExceptionsView endpoint to grant and remove certificate exceptions (allowlist)
- Add CertificateInvalidationsView endpoint to invalidate and re-validate certificates
- Update certificate status labels to be more user-friendly (e.g., "Received" instead of "already received")
- Update certificate generation history labels (e.g., "All Learners" instead of "All learners")
- Add invalidation notes to IssuedCertificateSerializer
- Add certificatesEnabled flag to CourseInformationSerializerV2
@openedx-webhooks openedx-webhooks added open-source-contribution PR author is not from Axim or 2U core contributor PR author is a Core Contributor (who may or may not have write access to this repo). labels Apr 28, 2026
@openedx-webhooks
Copy link
Copy Markdown

openedx-webhooks commented Apr 28, 2026

Thanks for the pull request, @wgu-jesse-stewart!

This repository is currently maintained by @openedx/wg-maintenance-openedx-platform.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

@wgu-jesse-stewart wgu-jesse-stewart marked this pull request as ready for review April 29, 2026 00:41
@mphilbrick211 mphilbrick211 added the mao-onboarding Reviewing this will help onboard devs from an Axim mission-aligned organization (MAO). label Apr 29, 2026
@mphilbrick211 mphilbrick211 moved this from Needs Triage to Ready for Review in Contributions Apr 29, 2026
@mphilbrick211 mphilbrick211 added the needs reviewer assigned PR needs to be (re-)assigned a new reviewer label Apr 29, 2026
Copy link
Copy Markdown
Contributor

@wgu-taylor-payne wgu-taylor-payne left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! The JWT test stabilization looks good. A few items on the bulk endpoint:

1. O(n²) notes lookup (bug) — The next() linear scan inside the creation loop makes the notes lookup O(n) per learner, O(n²) overall. For a bulk CSV endpoint this should be a dict lookup. See inline suggestion.

2. Missing tests (blocking) — The new BulkCertificateExceptionsView has no test coverage. At minimum: happy-path CSV, empty CSV, non-CSV file type, unresolvable learners, and partial success (mix of valid and invalid rows).

3. Duplicate CSV identifiers (nit) — If the same identifier appears twice with different notes, _resolve_learners_to_users deduplicates via dict (last mapping wins), but the next() scan picks the first match's notes. Minor inconsistency — building a notes_by_learner dict (see suggestion for number 1) also fixes this since dict assignment keeps the last value.

4. PR title — Currently the raw branch name. Consider something descriptive like "feat: add bulk certificate exceptions CSV upload endpoint".

Review assisted by Kiro

Comment thread lms/djangoapps/instructor/views/api_v2.py Outdated
Comment thread lms/djangoapps/instructor/views/api_v2.py Outdated
@wgu-jesse-stewart wgu-jesse-stewart changed the title Wgu jesse stewart/instructor dashboard certificates bulk feat: add bulk certificate exceptions CSV upload endpoint Apr 30, 2026
@wgu-jesse-stewart
Copy link
Copy Markdown
Contributor Author

wgu-jesse-stewart commented Apr 30, 2026

Thanks for the PR! The JWT test stabilization looks good. A few items on the bulk endpoint:

1. O(n²) notes lookup (bug) — The next() linear scan inside the creation loop makes the notes lookup O(n) per learner, O(n²) overall. For a bulk CSV endpoint this should be a dict lookup. See inline suggestion.

2. Missing tests (blocking) — The new BulkCertificateExceptionsView has no test coverage. At minimum: happy-path CSV, empty CSV, non-CSV file type, unresolvable learners, and partial success (mix of valid and invalid rows).

3. Duplicate CSV identifiers (nit) — If the same identifier appears twice with different notes, _resolve_learners_to_users deduplicates via dict (last mapping wins), but the next() scan picks the first match's notes. Minor inconsistency — building a notes_by_learner dict (see suggestion for number 1) also fixes this since dict assignment keeps the last value.

4. PR title — Currently the raw branch name. Consider something descriptive like "feat: add bulk certificate exceptions CSV upload endpoint".

Review assisted by Kiro

thank you for the feedback. I have addressed those issues.

@wgu-jesse-stewart wgu-jesse-stewart force-pushed the wgu-jesse-stewart/instructor_dashboard_certificates_bulk branch from dfba239 to 4e74557 Compare April 30, 2026 22:39
Copy link
Copy Markdown
Contributor

@wgu-taylor-payne wgu-taylor-payne left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two more nits from a closer read.

Review assisted by Kiro

csv_reader = csv.reader(file_content.splitlines())

learners_with_notes = []
for _row_num, row in enumerate(csv_reader, start=1):
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: _row_num is unused. Either drop the enumerate or use the row number in error messages (the latter would be more useful for users debugging a bad CSV).

Suggested change
for _row_num, row in enumerate(csv_reader, start=1):
for row in csv_reader:

Comment on lines +2172 to +2235
try:
# Read and parse CSV file
file_content = uploaded_file.read().decode('utf-8-sig')
csv_reader = csv.reader(file_content.splitlines())

learners_with_notes = []
for _row_num, row in enumerate(csv_reader, start=1):
if not row or not row[0].strip():
continue # Skip empty rows

learner = row[0].strip()
notes = row[1].strip() if len(row) > 1 and row[1].strip() else ''

learners_with_notes.append((learner, notes))

if not learners_with_notes:
return Response(
{'message': _('CSV file is empty or contains no valid entries')},
status=status.HTTP_400_BAD_REQUEST
)

# Extract learners for resolution and build a notes lookup
learners = [learner for learner, _ in learners_with_notes]
notes_by_learner = dict(learners_with_notes)

# Resolve all usernames/emails to users upfront
learner_to_user, user_errors = _resolve_learners_to_users(learners)
results['errors'].extend(user_errors)

# Validate learners for certificate exceptions
exceptions_to_create, validation_errors = _validate_learners_for_certificate_exceptions(
learner_to_user, course_key
)
results['errors'].extend(validation_errors)

# Create all exceptions using the certificates API
for learner, user in exceptions_to_create:
notes = notes_by_learner.get(learner, '')

try:
certs_api.create_or_update_certificate_allowlist_entry(user, course_key, notes)
log.info(
"Certificate exception granted for user %s (%s) in course %s by %s via CSV upload",
user.id, learner, course_key, request.user.username
)
results['success'].append(learner)
except Exception as exc: # pylint: disable=broad-except
log.exception(
"Error creating certificate exception for user %s in course %s",
user.id, course_key
)
results['errors'].append({
'learner': learner,
'message': str(exc)
})

return Response(results, status=status.HTTP_200_OK)

except Exception as exc: # pylint: disable=broad-except
log.exception("Error processing CSV file for certificate exceptions")
return Response(
{'message': _('Error processing CSV file: {error}').format(error=str(exc))},
status=status.HTTP_400_BAD_REQUEST
)
Copy link
Copy Markdown
Contributor

@wgu-taylor-payne wgu-taylor-payne May 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The outer try/except Exception wraps the entire method body — parsing, resolution, validation, and creation — and flattens everything into a generic 400. The resolution/validation/creation steps already have their own error handling, so this only needs to cover the decode + CSV parse, which are the only parts that can fail from untrusted input.

Narrowing the scope and catching specific exceptions avoids masking real bugs as 400s:

        try:
            file_content = uploaded_file.read().decode('utf-8-sig')
            csv_reader = list(csv.reader(file_content.splitlines()))
        except (UnicodeDecodeError, csv.Error) as exc:
            log.exception("Error processing CSV file for certificate exceptions")
            return Response(
                {'message': _('Error processing CSV file: {error}').format(error=str(exc))},
                status=status.HTTP_400_BAD_REQUEST
            )

Then the rest of the method (from learners_with_notes = [] through the return Response(results, ...)) lives outside the try/except at the same indentation level.

Copy link
Copy Markdown
Contributor

@wgu-taylor-payne wgu-taylor-payne left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@wgu-taylor-payne wgu-taylor-payne enabled auto-merge (squash) May 1, 2026 20:54
@wgu-taylor-payne wgu-taylor-payne merged commit ddedf44 into openedx:master May 1, 2026
41 checks passed
@github-project-automation github-project-automation Bot moved this from Ready for Review to Done in Contributions May 1, 2026
@openedx-webhooks openedx-webhooks removed the needs reviewer assigned PR needs to be (re-)assigned a new reviewer label May 1, 2026
@wgu-jesse-stewart wgu-jesse-stewart deleted the wgu-jesse-stewart/instructor_dashboard_certificates_bulk branch May 1, 2026 21:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core contributor PR author is a Core Contributor (who may or may not have write access to this repo). mao-onboarding Reviewing this will help onboard devs from an Axim mission-aligned organization (MAO). open-source-contribution PR author is not from Axim or 2U

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants