A multi-tier government e-services web portal for the Department of Environment and Natural Resources (DENR) of the Philippines. Citizens can apply for environmental permits and licenses online, while DENR staff at the municipal, regional, national, and super-admin levels process, approve, and track those applications through a structured workflow.
TLPH is a full-stack Flask web application backed by Google Cloud Firestore as the primary database and Firebase Authentication for identity management. It covers the complete lifecycle of DENR permit applications β from citizen submission and fee payment all the way through multi-level government review and final approval β while also providing integrated modules for Human Resource Management (HRM), Municipal Accounting, Inventory, System Logs, and a DENR-branded document print/PDF system.
| Property | Value |
|---|---|
| Frontend | HTML5, CSS3, JavaScript (ES6+) |
| Backend | Flask 3.0 (Python 3.8+) |
| Database | Google Cloud Firestore (NoSQL) |
| Authentication | Firebase Auth (Pyrebase4 client-side + Firebase Admin server-side) |
| Storage | Firebase Cloud Storage |
| Payment Gateway | Xendit (Philippine fintech) |
| Email Service | Flask-Mail with Gmail SMTP |
| PDF Generation | ReportLab |
| Host / Port | 0.0.0.0:5000 |
| Package | Version | Purpose |
|---|---|---|
Flask |
3.0.0 | Web framework |
firebase-admin |
6.4.0 | Server-side Firestore & Firebase Auth |
pyrebase4 |
4.7.1 | Client-side Firebase operations |
Flask-SQLAlchemy |
3.1.1 | ORM (configured, Firestore is primary DB) |
Flask-Mail |
0.9.1 | OTP email delivery |
python-dotenv |
1.0.0 | .env configuration loading |
xendit |
0.1.3 | Xendit payment gateway SDK |
requests |
2.29.0 | HTTP calls to Xendit API |
reportlab |
4.0.4 | PDF receipt and document generation |
python-calendar |
1.0.1 | Calendar utilities for HRM payroll |
setuptools |
68.0.0 | Build tools |
| Role | Dashboard URL | Description |
|---|---|---|
user |
/user/dashboard |
Citizen β applies for permits, pays fees |
municipal / municipal_admin |
/municipal/dashboard |
Municipal DENR office staff |
regional / regional_admin |
/regional/profile |
Regional DENR office staff |
national / national_admin |
/national/dashboard |
National DENR headquarters |
super-admin / superadmin |
/superadmin/inventory |
System super-administrator |
Role-based access control is enforced server-side on every route via the @role_required(...) decorator in firebase_auth_middleware.py. Unauthenticated requests redirect to login; wrong-role requests redirect to the user's own dashboard.
- Firebase Authentication (via Pyrebase4) for login; server Flask session set via
/api/set-session - Email OTP verification on registration β 6-digit code with 10-minute expiry
- Role-based access control enforced on every route with
@role_required - Disabled account detection before rendering any page
- Cache-control headers (
no-store) on all protected pages to prevent back-button access - Environment variable isolation for all secrets (
.env+firebase-credentials.json)
| Domain | Application Types |
|---|---|
| Environment | Environmental Compliance Certificate (ECC), Waste Management, Water Use, Hazardous Materials, CCO, PCL, Permit to Operate (Air), PICCS, Water Disposal, Hazardous Waste Generator |
| Fisheries | Aquafarm, Fish Transport, Fish Dealer, Processing, Harvest |
| Forest | Tree-Cutting, Timber, Reforestation, Nursery, Non-Timber Forest Products, Tree Planting |
| Livestock | Animal Transport, Meat Transport, Slaughterhouse, Poultry Farm, Animal Health |
| Wildlife | Wildlife Ownership, Transport, Collection, Wildlife Farm |
| General Permits | Export, Operation, Import, Wildlife Trade, Local Transport, Harvest |
Applications follow a staged approval pipeline across all government levels:
User submits (pending)
βββΊ Municipal Admin reviews β "to review"
βββΊ Regional Admin approves β "approved" (regional)
βββΊ National Admin gives final approval β "nationalStatus: approved"
- Farm Visit Services: Initial visit, compliance, disease, soil, general visit
- Fertilizer Services: Input usage, chemical registration, emergency pest control, fertilizer/pesticide recommendations
- Financial Services: Subsidy, grant, loan, crop insurance, startup support
- Compensation: Typhoon disaster / pest damage compensation requests
- Seminars & Training: GAP training, pest/disease management, safe pesticide handling, nursery/propagation, regulatory compliance orientation
- Creates Xendit invoices for permit and license application fees
- Webhook receiver automatically updates Firestore transaction status on payment confirmation
- PDF receipt generation via ReportLab (downloadable)
- Transaction history visible at every role level (scoped to municipality / region / national)
- Payment statistics (total deposits, paid / pending / failed) on all dashboards
Available at municipal level and above:
- Company, Department & Designation management
- Employee records (hire date, designation, department, contact info)
- Attendance tracking and office shift scheduling
- Leave request management (file, approve, reject)
- Payroll computation and payslip generation
- Holiday calendar management
- Chart of Accounts (COA) templates and individual account entries per municipality
- Entities (offices, banks, organizational units)
- Deposit categories β linked to COA codes and revenue types
- Expense categories β organized by office and fund type
- Accounting dashboard with financial summary statistics
- Payment deposit recording and reconciliation
- Stock tracking per municipality/region/national level
- Stock history and movement reporting
- User-facing stock list view
- Official DENR-branded print styling (
denr-print.css) with DENR green header - Government document formatting with signature sections, security watermarks, and barcode-style reference numbers
- ReportLab-based PDF export for receipts and official documents
- Print preview page (
denr-print-preview.html)
- Comprehensive action logging: login events, CRUD operations, account creation/disablement
- Logs stored in
system_logs(municipal-scoped) andregional_system_logs(region-scoped) Firestore collections - Device type detection (mobile / tablet / desktop) from User-Agent
- 180-day TTL retention with automatic cleanup
- Accessible at municipal, regional, and super-admin levels with appropriate scope filtering
- Complete
models/ph_locations.pymapping all Philippine provinces to their municipalities - Used in dropdowns throughout the system for location-based filtering and scoping
TLPH/
βββ app.py # Main Flask application entry point
βββ config.py # App configuration (session, mail, Firebase)
βββ firebase_config.py # Firebase Admin + Pyrebase initialization
βββ firebase_auth_middleware.py # Role-based access control decorator
β
βββ transaction_storage.py # Payment transactions & finance records (Firestore)
βββ deposit_storage.py # Municipal deposit/revenue categories
βββ expense_storage.py # Municipal expense categories
βββ coa_storage.py # Chart of Accounts templates and account entries
βββ entities_storage.py # Municipal entities (offices, banks, units)
βββ system_logs_storage.py # Audit/activity logs with TTL management
β
βββ routes/
β βββ main_routes.py # Auth, home, national dashboard
β βββ api_routes.py # REST API (OTP, register, login, applications)
β βββ municipal_routes.py # Municipal admin UI (HRM, accounting, operations)
β βββ regional_routes.py # Regional admin UI
β βββ national_routes.py # National admin UI
β βββ superadmin_routes.py # Super-admin UI
β βββ municipal_api_logs.py # Municipal data API (transactions, payroll, COAβ¦)
β βββ payments_routes.py # Xendit invoice creation, webhook, PDF receipt
β βββ permits_routes.py # General permit applications (user)
β βββ environment_routes.py # Environmental clearance applications
β βββ fisheries_routes.py # Fisheries license applications
β βββ forest_routes.py # Forest resource license applications
β βββ livestock_routes.py # Livestock license applications
β βββ wildlife_routes.py # Wildlife license applications
β βββ farm_routes.py # Farm visit service requests
β βββ service_routes.py # General services (fertilizer, financial, compensation)
β βββ seminar_routes.py # Seminar/training registrations
β
βββ models/
β βββ __init__.py
β βββ ph_locations.py # Full Philippine province-to-municipality mapping
β
βββ templates/
β βββ home.html, login.html, signup.html
β βββ create-municipal-admin.html
β βββ create_regional_account.html
β βββ payment-form.html, payment-success.html, payment-failed.html
β βββ denr-print-preview.html
β βββ account-disabled.html, auth_check.html, approval_status.html
β βββ user/ # Citizen portal (dashboard, profile, applications, permits, services)
β βββ municipal/ # Municipal admin (HRM, accounting, operations, logs)
β βββ regional/ # Regional admin (scoped dashboards, HR, accounting)
β βββ national/ # National admin (operations, HRM, logistics)
β βββ super-admin/ # Super-admin (global management, finance, regions)
β
βββ static/
β βββ css/ # Stylesheets (auth, dashboard, denr-print, regional, seminarβ¦)
β βββ js/ # JavaScript files
β βββ images/ # Image assets
β βββ uploads/ # User-uploaded files
β
βββ requirements.txt
βββ firebase-credentials.json # Firebase service account key (not committed)
βββ .env # Environment variables (not committed)
Python 3.8+
pip
Firebase project (Firestore + Authentication + Storage)
Xendit account
Gmail account with App Password enabled
-
Clone the repository
git clone https://github.com/alqzdave/TLPH.git cd TLPH -
Create and activate a virtual environment
python -m venv .venv .venv\Scripts\activate # Windows source .venv/bin/activate # macOS/Linux
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables β create a
.envfile in the root directory:SECRET_KEY=your-secret-key MAIL_USERNAME=your-gmail@gmail.com MAIL_PASSWORD=your-app-password FIREBASE_API_KEY=your-firebase-api-key FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com FIREBASE_DATABASE_URL=https://your-project.firebaseio.com FIREBASE_PROJECT_ID=your-project-id FIREBASE_STORAGE_BUCKET=your-project.appspot.com FIREBASE_MESSAGING_SENDER_ID=your-sender-id FIREBASE_APP_ID=your-app-id XENDIT_API_KEY=your-xendit-api-key XENDIT_PUBLIC_KEY=your-xendit-public-key
-
Place Firebase credentials
- Download your service account key from the Firebase Console
- Save it as
firebase-credentials.jsonin the root directory
-
Run the application
# Always use the virtual environment Python .venv\Scripts\python.exe app.py
Note: Using
.venv\Scripts\python.exeensures all dependencies from the virtual environment are available.py app.pyorpython app.pymay fail with import errors if the system Python is picked up instead. -
Open the application
http://localhost:5000
The application uses Gmail SMTP for OTP verification emails. To configure:
- Enable 2-Factor Authentication on your Gmail account
- Generate an App Password (Google Account β Security β App Passwords)
- Add to
.env:MAIL_USERNAME=your-email@gmail.com MAIL_PASSWORD=your-app-password
| Category | Base Path | Key Endpoints |
|---|---|---|
| Auth | /api |
POST /api/send-otp, POST /api/verify-otp, POST /api/register, POST /api/login, POST /api/logout |
| Session | /api |
POST /api/set-session |
| Applications | /api |
CRUD for permit applications, service requests |
| Payments | /api/payments |
POST /create-invoice, POST /webhook, GET /status/<id>, GET /history, POST /generate-receipt |
| Municipal Data | /api/municipal |
Transactions, deposits, expenses, COA, entities, employees, payroll, leave, system logs |
- Firebase Authentication with secure token management
- Server-side role enforcement (
@role_required) on every protected route - Email OTP with 10-minute expiry for registration verification
- All secrets isolated in
.env(never hardcoded) - Cache-control
no-storeheaders prevent cached access after logout - Disabled account detection at every page load
- Input validation at system boundaries (API routes and form handlers)
- HTTPS-ready for production deployment
.venv\Scripts\python.exe app.py
# Runs on http://localhost:5000 with debug mode enabled- Set
debug=Falseinapp.py - Configure all production environment variables in
.env - Use a production WSGI server (e.g., Gunicorn or Waitress)
- Set up HTTPS with SSL/TLS certificates
- Switch Firebase and Xendit to their production configurations
- Enable Firestore indexes as documented in REGIONAL_SYSTEM_LOGS_OPERATIONS.md
| Problem | Solution |
|---|---|
| Port 5000 already in use | netstat -ano | findstr :5000 then taskkill /PID <id> /F |
| Firebase connection error | Verify .env credentials and confirm firebase-credentials.json is in the root |
| Missing module / ImportError | Run pip install -r requirements.txt inside the virtual environment |
| Email OTP not sending | Confirm Gmail App Password is correct and 2FA is enabled on the account |
| Payment integration issues | Verify Xendit API keys and check whether test or production keys are configured |
| File upload errors | Check Firebase Storage permissions and storage bucket config in .env |
| Firestore permission denied | Verify Firestore security rules allow the operation for the authenticated user's role |
TLPH/
βββ app.py
βββ config.py
βββ firebase_config.py
βββ firebase_auth_middleware.py
βββ transaction_storage.py
βββ deposit_storage.py
βββ expense_storage.py
βββ coa_storage.py
βββ entities_storage.py
βββ system_logs_storage.py
βββ requirements.txt
βββ .env # (not committed)
βββ firebase-credentials.json # (not committed)
β
βββ routes/ # All Flask blueprints
βββ models/ # ph_locations.py
βββ templates/ # Jinja2 HTML templates per role
βββ static/ # CSS, JS, images, uploads
| Name | Role | GitHub | |
|---|---|---|---|
| Mark Dave Alquiza | Team Lead | markdavemarasiganalquiza@gmail.com | @alqzdave |
| Aerone John Grefalda | Frontend Developer | grefaldaaeronejohn01@gmail.com | @Aerone01 |
| John Cedric Acapulco | Frontend Developer | acapulcojohncedric66@gmail.com | @Cheezzyy1 |
| Jhon Carlo Jimenez | Backend Developer | jimenez.jhoncarlo@minsu.edu.ph | @kly-njz |
| John Mark Pagaduan | Frontend Developer | pagaduanjohnmark29@gmail.com | @johnmark009 |
| Huriecane Ivan Ganio | Q/A, Developer | hurieganio@gmail.com | @Huriecane |
Special thanks to the DENR TLPH Team for their support and guidance throughout the development of this project.
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Contribution guidelines:
- Follow the existing code style and blueprint structure
- Write descriptive commit messages
- Test changes at all affected role levels
- Update relevant documentation files as needed
- Ensure Firebase and Xendit integrations are properly tested before submitting
- Firebase Setup Guide
- Firebase Setup Instructions
- Firebase Transactions Setup
- Xendit Payment Integration
- Payment System Overview
- DENR Print System
- Regional System Logs Operations
- Companies Schema
- Departments Schema
- Designations & Employees Schema
- Issue Tracker: Open an issue on GitHub
- Lead Developer: Mark Dave Alquiza β markdavemarasiganalquiza@gmail.com
- Repository: https://github.com/alqzdave/TLPH
- Organization: DENR TLPH Team
When reporting bugs please include: a description of the issue, steps to reproduce, expected vs. actual behavior, screenshots if applicable, and your browser/OS.
- Mobile application (iOS / Android)
- SMS notifications
- Advanced analytics dashboard
- Automated scheduled report generation
- Multi-language support (Filipino / English)
- Offline mode capability
- Data export (CSV / Excel)
- Enhanced search and filtering across all modules
This project is licensed under the MIT License β see the LICENSE file for details.
- Flask Documentation
- Firebase Documentation
- Xendit API Documentation
- Python-dotenv Documentation
- ReportLab Documentation
- DENR (Department of Environment and Natural Resources) - Project sponsor and stakeholder
- Firebase - Backend infrastructure and authentication
- Xendit - Payment gateway integration
- Flask Community - Web framework and ecosystem
- All contributors and team members who made this project possible
- v1.0 - Initial release with core features
- User authentication and authorization
- License and permit management
- Payment integration
- Inventory tracking
- Transaction management
Made with β€οΈ by the DENR TLPH Development Team
For more information or to contribute, visit our GitHub Repository