# Certificate approval fix

## Findings

The transcript helper ran `CREATE TABLE IF NOT EXISTS official_transcripts` from inside certificate approval transactions. MySQL implicitly commits this statement even when the table already exists. The final `commit()` then failed with `There is no active transaction`, which the page replaced with `Error approving certificate`. Earlier writes could already have been committed despite the error message.

The same generic message also hid normal eligibility failures. The local pending request inspected during diagnosis had passed 0 of 1 required exams. This request must meet the existing requirements before approval: the student must be assigned to the program, all five active grading steps must be passed, and every required active examination must have a qualifying submitted attempt. The fix does not change these rules or student marks.

## Changes

- Existing transcript tables are checked with a read, not a schema statement. Missing tables are initialized before transactions start.
- Certificate and transcript decisions commit or roll back together.
- Pending certificates are locked while processing; repeat approval is blocked.
- Expected eligibility and state failures are shown to the admin. SQL/internal failures remain in the PHP error log.
- Bulk approval reports the actual number approved and explains skipped requests.
- Exam-linked certificates with no explicit program resolve their program through the exam module, falling back to the student's program.
- The five-step certificate generation page initializes the transcript table before its transactions too.

## Upload to the server

Back up the existing files, then extract `certificate-approval-update.zip` into your application's root directory, preserving these paths:

1. `core/CompletionEligibility.php`
2. `core/CertificateApproval.php` (new)
3. `public/modules/pending_certificates.php`
4. `public/modules/step_certificate.php`

No database re-import is needed. If `official_transcripts` is absent, it is created before the transaction using the existing schema. The database user needs CREATE permission for this first-time setup only.

Open Pending Certificates and approve an eligible request. Check both the certificate and transcript. If the earlier error already moved a certificate to Approved, inspect its current status before generating a replacement. Ineligible requests will show what remains incomplete; do not change marks just to dismiss an error.

The local source files are updated. The hosted files must still be uploaded. Tests use MySQL temporary tables and do not approve or reject real certificates.

## Checks

`php tests/certificate_approval_test.php` tests transaction preservation, eligible approval, transcript decisions, repeat requests, eligibility blocks, complete rollback on database failure, bulk counts, missing-program resolution and rejection. PHP syntax checks also pass for the changed files.
