web / app.py
Bubaa001's picture
Update app.py
fbab0af verified
Raw History Blame Contribute Delete
46.4 kB
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory, g, flash, jsonify from flask_babel import Babel, gettext as _ from flask_mail import Mail, Message import os import json from datetime import datetime from functools import wraps import uuid from werkzeug.utils import secure_filename from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY', 'dev_secret_key') # Application Configuration app.config['BABEL_DEFAULT_LOCALE'] = 'en' app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations' app.config['SCHOOL_NAME'] = "Munishi Secondary School" app.config['SCHOOL_MOTTO'] = "Excellence Through Diligence" app.config['CONTACT_EMAIL'] = "info@munishischool.ac.tz" app.config['CONTACT_PHONE'] = "+255 22 123 4567" app.config['ADDRESS'] = "P.O. Box 1234, Dar es Salaam, Tanzania" app.config['SOCIAL_MEDIA'] = { 'facebook': 'https://facebook.com/munishischool', 'twitter': 'https://twitter.com/munishischool', 'instagram': 'https://instagram.com/munishischool', 'youtube': 'https://youtube.com/munishischool' } app.config['UPLOAD_FOLDER'] = 'static/uploads' app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif', 'pdf'} app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload size # Admin Configuration app.config['ADMIN_USERNAME'] = os.environ.get('ADMIN_USERNAME', 'admin') app.config['ADMIN_PASSWORD'] = os.environ.get('ADMIN_PASSWORD', generate_password_hash('admin123')) app.config['ADMIN_UPLOAD_FOLDER'] = 'static/uploads/admin' app.config['APPLICATIONS_PER_PAGE'] = 10 app.config['ADMIN_SESSION_TIMEOUT'] = 3600 # 1 hour in seconds # Email Configuration app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = 'egliszaratus@gmail.com' app.config['MAIL_PASSWORD'] = 'xwzd nogw tavi qgtg' # Your app password app.config['MAIL_DEFAULT_SENDER'] = 'Munishi Secondary School <egliszaratus@gmail.com>' app.config['ADMIN_EMAIL'] = 'egliszaratus@gmail.com' # Initialize Babel and Mail babel = Babel(app) mail = Mail(app) # Admin Authentication Decorator def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('admin_logged_in'): return redirect(url_for('admin_login', next=request.url)) # Check session timeout last_activity = session.get('admin_last_activity') if last_activity and (datetime.now() - datetime.strptime(last_activity, "%Y-%m-%d %H:%M:%S")).seconds > app.config['ADMIN_SESSION_TIMEOUT']: session.pop('admin_logged_in', None) flash(_('Your session has timed out. Please log in again.'), 'warning') return redirect(url_for('admin_login', next=request.url)) # Update last activity time session['admin_last_activity'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") return f(*args, **kwargs) return decorated_function # Helper Functions def load_data(filename): """Load JSON data from the data directory""" try: with open(f'data/{filename}.json', 'r', encoding='utf-8') as f: data = json.load(f) # Process the data based on type if isinstance(data, list): for item in data: if isinstance(item, dict): # Escape % signs in strings for translation for key in ['title', 'description', 'excerpt']: if key in item and isinstance(item[key], str): item[key] = item[key].replace('%', '%%') # Set default image if missing or file doesn't exist if 'image' in item: image_path = os.path.join('static', 'images', item['image']) if not os.path.exists(image_path): item['image'] = 'default.jpg' return data except FileNotFoundError: app.logger.warning(f"Data file not found: {filename}.json") return None except json.JSONDecodeError: app.logger.error(f"Invalid JSON in file: {filename}.json") return None except Exception as e: app.logger.error(f"Error loading {filename}.json: {str(e)}") return None def save_data(filename, data): """Save data to JSON file""" try: with open(f'data/{filename}.json', 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False) return True except Exception as e: app.logger.error(f"Error saving data: {str(e)}") return False def allowed_file(filename): """Check if a file has an allowed extension""" return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] def format_date(value, format='medium', part=None): """Jinja2 filter for date formatting""" try: if format == 'full': format_str = "%A, %d %B %Y" elif format == 'medium': format_str = "%d %b %Y" else: format_str = format date_obj = datetime.strptime(value, "%Y-%m-%d") formatted = date_obj.strftime(format_str) if part == 'first': return formatted.split()[0] elif part == 'second': parts = formatted.split() return parts[1] if len(parts) > 1 else '' return formatted except Exception as e: app.logger.error(f"Date formatting error: {str(e)}") return value def format_currency(value): """Jinja2 filter for currency formatting""" return f"TZS {value:,.0f}" def send_email(subject, recipients, body, html=None): """Send an email using Flask-Mail""" try: msg = Message( subject=subject, recipients=recipients, body=body, html=html ) mail.send(msg) return True except Exception as e: app.logger.error(f"Error sending email: {str(e)}") return False # Register filters app.jinja_env.filters['format_date'] = format_date app.jinja_env.filters['date'] = format_date app.jinja_env.filters['format_currency'] = format_currency app.jinja_env.filters['currency'] = format_currency # Make helpers and configuration available to all templates @app.context_processor def inject_config(): """Inject configuration and helper functions into all templates""" return { 'school_name': app.config['SCHOOL_NAME'], 'school_motto': app.config['SCHOOL_MOTTO'], 'contact_email': app.config['CONTACT_EMAIL'], 'contact_phone': app.config['CONTACT_PHONE'], 'address': app.config['ADDRESS'], 'social_media': app.config['SOCIAL_MEDIA'], 'now': datetime.now(), 'load_data': load_data } # Language Handling @app.before_request def before_request(): """Set language for the request""" if 'lang' not in session: session['lang'] = request.accept_languages.best_match(['en', 'sw']) g.current_lang = session['lang'] @babel.localeselector def get_locale(): """Get the current locale""" return session.get('lang', 'en') @app.route('/set_lang/<lang>') def set_lang(lang): """Change the application language""" if lang in ['en', 'sw']: session['lang'] = lang return redirect(request.referrer or url_for('home')) # Admin Routes @app.route('/admin/login', methods=['GET', 'POST']) def admin_login(): if session.get('admin_logged_in'): return redirect(url_for('admin_dashboard')) if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') if (username == app.config['ADMIN_USERNAME'] and check_password_hash(app.config['ADMIN_PASSWORD'], password)): session['admin_logged_in'] = True session['admin_last_activity'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") next_url = request.args.get('next') or url_for('admin_dashboard') return redirect(next_url) else: flash(_('Invalid username or password'), 'error') return render_template('admin/login.html') @app.route('/admin/logout') @admin_required def admin_logout(): session.pop('admin_logged_in', None) session.pop('admin_last_activity', None) flash(_('You have been logged out successfully'), 'success') return redirect(url_for('admin_login')) @app.route('/admin/dashboard') @admin_required def admin_dashboard(): applications = load_data('applications') or [] stats = { 'total': len(applications), 'submitted': len([a for a in applications if a.get('status') == 'submitted']), 'reviewed': len([a for a in applications if a.get('status') == 'reviewed']), 'accepted': len([a for a in applications if a.get('status') == 'accepted']), 'rejected': len([a for a in applications if a.get('status') == 'rejected']) } recent_apps = sorted(applications, key=lambda x: x.get('submission_date', ''), reverse=True)[:5] return render_template('admin/dashboard.html', stats=stats, recent_apps=recent_apps) @app.route('/admin/applications') @admin_required def admin_applications(): page = request.args.get('page', 1, type=int) status_filter = request.args.get('status', 'all') search_query = request.args.get('search', '') sort_by = request.args.get('sort', 'submission_date') sort_order = request.args.get('order', 'desc') applications = load_data('applications') or [] # Apply filters if status_filter != 'all': applications = [a for a in applications if a['status'] == status_filter] if search_query: search_query = search_query.lower() applications = [a for a in applications if search_query in a['first_name'].lower() or search_query in a['last_name'].lower() or search_query in a['parent_name'].lower() or search_query in a['id'].lower()] # Sorting reverse_order = sort_order == 'desc' if sort_by in ['first_name', 'last_name', 'submission_date', 'status']: applications.sort(key=lambda x: x.get(sort_by, ''), reverse=reverse_order) # Pagination per_page = app.config['APPLICATIONS_PER_PAGE'] total_pages = max(1, (len(applications) + per_page - 1) // per_page) paginated_apps = applications[(page-1)*per_page : page*per_page] return render_template('admin/applications.html', applications=paginated_apps, current_page=page, total_pages=total_pages, status_filter=status_filter, search_query=search_query, sort_by=sort_by, sort_order=sort_order) @app.route('/admin/application/<application_id>', methods=['GET', 'POST']) @admin_required def admin_application_detail(application_id): # Load all applications all_applications = load_data('applications') or [] # Find the current application current_app = None app_index = -1 for i, app_data in enumerate(all_applications): if app_data['id'] == application_id: current_app = app_data app_index = i break if not current_app: flash(_('Application not found'), 'error') return redirect(url_for('admin_applications')) if request.method == 'POST': # Capture the current status before any changes old_status = current_app.get('status') # Get form data new_status = request.form.get('status') notes = request.form.get('admin_notes', '') if new_status in ['submitted', 'reviewed', 'accepted', 'rejected', 'waitlisted']: # Update application data current_app['status'] = new_status current_app['admin_notes'] = notes current_app['review_date'] = datetime.now().strftime("%Y-%m-%d %H:%M") current_app['reviewed_by'] = session.get('admin_username', 'admin') # Handle file uploads for file_field in ['additional_docs']: file = request.files.get(file_field) if file and allowed_file(file.filename): filename = secure_filename( f"{application_id}_{file_field}_{datetime.now().strftime('%Y%m%d%H%M%S')}{os.path.splitext(file.filename)[1]}" ) upload_dir = os.path.join(app.config['ADMIN_UPLOAD_FOLDER'], 'application_docs') os.makedirs(upload_dir, exist_ok=True) file_path = os.path.join(upload_dir, filename) file.save(file_path) if 'admin_uploads' not in current_app: current_app['admin_uploads'] = [] current_app['admin_uploads'].append({ 'filename': filename, 'original_name': file.filename, 'upload_date': datetime.now().strftime("%Y-%m-%d %H:%M"), 'uploaded_by': session.get('admin_username', 'admin') }) # Update the application in the list if app_index >= 0: all_applications[app_index] = current_app # Save updated data if save_data('applications', all_applications): flash(_('Application updated successfully'), 'success') # Send email notifications if status changed if old_status != new_status: # Send to applicant/parent applicant_email = current_app.get('parent_email') if applicant_email: # Prepare email content based on status if new_status == 'accepted': subject = _("Congratulations! Your Application Has Been Accepted") body = _( f"Dear {current_app['first_name']} {current_app['last_name']},\n\n" "We are pleased to inform you that your application to Munishi Secondary School has been accepted!\n\n" "Congratulations! We look forward to welcoming you to our school community.\n\n" "Next Steps:\n" "1. Please log in to your application portal to review the acceptance letter\n" "2. Complete the enrollment forms by [date]\n" "3. Submit any remaining documents\n\n" "If you have any questions, please contact our admissions office at admissions@munishischool.ac.tz\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) elif new_status == 'rejected': subject = _("Update on Your Application to Munishi Secondary School") body = _( f"Dear {current_app['first_name']} {current_app['last_name']},\n\n" "Thank you for applying to Munishi Secondary School.\n\n" "After careful consideration, we regret to inform you that we are unable to offer you a place at this time.\n\n" "We appreciate your interest in our school and wish you the best in your educational journey.\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) elif new_status == 'waitlisted': subject = _("Update on Your Application to Munishi Secondary School") body = _( f"Dear {current_app['first_name']} {current_app['last_name']},\n\n" "Thank you for applying to Munishi Secondary School.\n\n" "We have received a large number of applications this year. While we are not able to offer you a place at this time, " "your application has been placed on our waitlist. We will contact you if a place becomes available.\n\n" "We appreciate your patience and understanding.\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) elif new_status == 'reviewed': subject = _("Update on Your Application to Munishi Secondary School") body = _( f"Dear {current_app['first_name']} {current_app['last_name']},\n\n" "This email is to inform you that your application to Munishi Secondary School has been reviewed.\n\n" "Our admissions committee has examined your application materials, and we are currently in the final stages " "of our decision-making process.\n\n" "We will notify you as soon as a final decision has been made. Thank you for your patience.\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) else: # submitted (shouldn't happen, but just in case) subject = _("Application Update") body = _( f"Dear {current_app['first_name']} {current_app['last_name']},\n\n" "Your application status has been updated to: Submitted\n\n" "This is usually an initial status when we receive your application. " "We will begin reviewing it shortly.\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) send_email(subject, [applicant_email], body) # Send to admin admin_subject = _("Application Status Updated: {} {}").format( current_app['first_name'], current_app['last_name']) admin_body = _( f"Application ID: {application_id}\n" f"Student: {current_app['first_name']} {current_app['last_name']}\n" f"Parent Email: {current_app.get('parent_email', 'N/A')}\n" f"Status changed from {old_status} to: {new_status}\n\n" "Review the application: {}\n" ).format(url_for('admin_application_detail', application_id=application_id, _external=True)) send_email(admin_subject, [app.config['ADMIN_EMAIL']], admin_body) else: flash(_('Failed to save application update. Please try again.'), 'error') return redirect(url_for('admin_application_detail', application_id=application_id)) # Document fields to display document_fields = [ 'birth_certificate', 'academic_records', 'recommendation_letter', 'photo' ] # Get all uploaded documents documents = [] for field in document_fields: if current_app.get(field): documents.append({ 'name': field.replace('_', ' ').title(), 'filename': current_app[field], 'path': url_for('download_application_file', filename=current_app[field]) }) # Get admin uploaded documents admin_documents = [] for doc in current_app.get('admin_uploads', []): admin_documents.append({ 'name': doc['original_name'], 'uploaded_by': doc['uploaded_by'], 'upload_date': doc['upload_date'], 'path': url_for('download_admin_file', filename=doc['filename']) }) return render_template('admin/application_detail.html', application=current_app, documents=documents, admin_documents=admin_documents) @app.route('/admin/settings', methods=['GET', 'POST']) @admin_required def admin_settings(): if request.method == 'POST': current_password = request.form.get('current_password') new_password = request.form.get('new_password') confirm_password = request.form.get('confirm_password') if not check_password_hash(app.config['ADMIN_PASSWORD'], current_password): flash(_('Current password is incorrect'), 'error') elif new_password != confirm_password: flash(_('New passwords do not match'), 'error') elif len(new_password) < 8: flash(_('Password must be at least 8 characters long'), 'error') else: app.config['ADMIN_PASSWORD'] = generate_password_hash(new_password) flash(_('Password updated successfully'), 'success') return redirect(url_for('admin_settings')) return render_template('admin/settings.html') @app.route('/admin/content') @admin_required def admin_content(): # Get all content types available for management content_types = [ {'name': 'News', 'endpoint': 'news', 'count': len(load_data('news') or [])}, {'name': 'Events', 'endpoint': 'events', 'count': len(load_data('events') or [])}, {'name': 'Faculty', 'endpoint': 'faculty', 'count': len(load_data('faculty') or [])}, {'name': 'Alumni', 'endpoint': 'alumni', 'count': len(load_data('alumni') or [])}, {'name': 'Clubs', 'endpoint': 'clubs', 'count': len(load_data('clubs') or [])} ] return render_template('admin/content.html', content_types=content_types) @app.route('/admin/content/<content_type>', methods=['GET', 'POST']) @admin_required def manage_content(content_type): if content_type not in ['news', 'events', 'faculty', 'alumni', 'clubs']: flash(_('Invalid content type'), 'error') return redirect(url_for('admin_content')) data = load_data(content_type) or [] if request.method == 'POST': # Handle content creation/update action = request.form.get('action') item_id = request.form.get('id') if action == 'delete': # Delete item data = [item for item in data if item.get('id') != item_id] save_data(content_type, data) flash(_('Item deleted successfully'), 'success') return redirect(url_for('manage_content', content_type=content_type)) elif action in ['create', 'update']: # Validate required fields required_fields = { 'news': ['title', 'content', 'date'], 'events': ['title', 'date', 'location'], 'faculty': ['name', 'position', 'department'], 'alumni': ['name', 'graduation_year', 'current_position'], 'clubs': ['name', 'description', 'meeting_schedule'] }.get(content_type, []) form_data = {k: request.form.get(k, '').strip() for k in request.form} if not all(form_data.get(field) for field in required_fields): flash(_('Please fill in all required fields'), 'error') return redirect(url_for('manage_content', content_type=content_type)) # Handle file upload image_file = request.files.get('image') image_filename = None if image_file and allowed_file(image_file.filename): image_filename = secure_filename(f"{content_type}_{datetime.now().strftime('%Y%m%d%H%M%S')}_{image_file.filename}") upload_dir = os.path.join(app.config['ADMIN_UPLOAD_FOLDER'], content_type) os.makedirs(upload_dir, exist_ok=True) image_file.save(os.path.join(upload_dir, image_filename)) if action == 'create': # Create new item new_item = { 'id': str(uuid.uuid4()), 'created_at': datetime.now().strftime("%Y-%m-%d %H:%M"), 'created_by': session.get('admin_username', 'admin'), **form_data } if image_filename: new_item['image'] = image_filename data.append(new_item) flash(_('Item created successfully'), 'success') else: # Update existing item for item in data: if item.get('id') == item_id: item.update({ 'updated_at': datetime.now().strftime("%Y-%m-%d %H:%M"), 'updated_by': session.get('admin_username', 'admin'), **{k: v for k, v in form_data.items() if v} }) if image_filename: item['image'] = image_filename break flash(_('Item updated successfully'), 'success') save_data(content_type, data) return redirect(url_for('manage_content', content_type=content_type)) return render_template('admin/manage_content.html', content_type=content_type, items=data, fields=get_content_fields(content_type)) def get_content_fields(content_type): """Return field configuration for different content types""" fields = { 'news': [ {'name': 'title', 'type': 'text', 'required': True, 'label': _('Title')}, {'name': 'content', 'type': 'textarea', 'required': True, 'label': _('Content')}, {'name': 'excerpt', 'type': 'textarea', 'required': False, 'label': _('Excerpt')}, {'name': 'date', 'type': 'date', 'required': True, 'label': _('Date')}, {'name': 'image', 'type': 'file', 'required': False, 'label': _('Featured Image')}, {'name': 'author', 'type': 'text', 'required': False, 'label': _('Author')}, {'name': 'tags', 'type': 'text', 'required': False, 'label': _('Tags')} ], 'events': [ {'name': 'title', 'type': 'text', 'required': True, 'label': _('Title')}, {'name': 'description', 'type': 'textarea', 'required': True, 'label': _('Description')}, {'name': 'date', 'type': 'date', 'required': True, 'label': _('Date')}, {'name': 'time', 'type': 'text', 'required': False, 'label': _('Time')}, {'name': 'location', 'type': 'text', 'required': True, 'label': _('Location')}, {'name': 'image', 'type': 'file', 'required': False, 'label': _('Featured Image')}, {'name': 'registration_link', 'type': 'url', 'required': False, 'label': _('Registration Link')} ], 'faculty': [ {'name': 'name', 'type': 'text', 'required': True, 'label': _('Name')}, {'name': 'position', 'type': 'text', 'required': True, 'label': _('Position')}, {'name': 'department', 'type': 'text', 'required': True, 'label': _('Department')}, {'name': 'bio', 'type': 'textarea', 'required': False, 'label': _('Biography')}, {'name': 'image', 'type': 'file', 'required': False, 'label': _('Photo')}, {'name': 'email', 'type': 'email', 'required': False, 'label': _('Email')}, {'name': 'phone', 'type': 'tel', 'required': False, 'label': _('Phone')} ] } return fields.get(content_type, []) # Admin API Endpoints @app.route('/admin/api/application/<application_id>/status', methods=['POST']) @admin_required def update_application_status(application_id): applications = load_data('applications') or [] application = next((app for app in applications if app['id'] == application_id), None) if not application: return jsonify({'success': False, 'message': 'Application not found'}), 404 new_status = request.json.get('status') if new_status not in ['submitted', 'reviewed', 'accepted', 'rejected', 'waitlisted']: return jsonify({'success': False, 'message': 'Invalid status'}), 400 # Update application for app in applications: if app['id'] == application_id: old_status = app['status'] app['status'] = new_status app['review_date'] = datetime.now().strftime("%Y-%m-%d %H:%M") app['reviewed_by'] = session.get('admin_username', 'admin') break save_data('applications', applications) # Send email notification if status changed to accepted if new_status == 'accepted' and new_status != old_status: # Send to applicant applicant_email = application.get('parent_email') if applicant_email: subject = _("Your Application to Munishi Secondary School Has Been Accepted!") body = _( f"Dear {application['first_name']} {application['last_name']},\n\n" "We are pleased to inform you that your application to Munishi Secondary School has been accepted!\n\n" "Congratulations! We look forward to welcoming you to our school community.\n\n" "Next Steps:\n" "1. Please log in to your application portal to review the acceptance letter\n" "2. Complete the enrollment forms by [date]\n" "3. Submit any remaining documents\n\n" "If you have any questions, please contact our admissions office at admissions@munishischool.ac.tz\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) send_email(subject, [applicant_email], body) # Send to admin admin_subject = _("Application Accepted: {} {}").format( application['first_name'], application['last_name']) admin_body = _( f"Application ID: {application_id}\n" f"Student: {application['first_name']} {application['last_name']}\n" f"Parent Email: {application.get('parent_email', 'N/A')}\n" f"Status changed to: Accepted\n\n" "Review the application: {}\n" ).format(url_for('admin_application_detail', application_id=application_id, _external=True)) send_email(admin_subject, [app.config['ADMIN_EMAIL']], admin_body) return jsonify({'success': True, 'new_status': new_status}) @app.route('/admin/api/application/<application_id>/notes', methods=['POST']) @admin_required def update_application_notes(application_id): applications = load_data('applications') or [] application = next((app for app in applications if app['id'] == application_id), None) if not application: return jsonify({'success': False, 'message': 'Application not found'}), 404 notes = request.json.get('notes', '') # Update application for app in applications: if app['id'] == application_id: app['admin_notes'] = notes break save_data('applications', applications) return jsonify({'success': True}) # Main Routes @app.route('/') def home(): """Home page route""" news_data = load_data('news') events_data = load_data('events') highlights_data = load_data('highlights') news = news_data[:3] if news_data else [] events = events_data[:3] if events_data else [] highlights = highlights_data[:3] if highlights_data else [] return render_template('home.html', news=news, events=events, highlights=highlights) @app.route('/about') def about(): """About page route""" return render_template('about.html', history=load_data('history') or {}, mission=load_data('mission') or {}, leadership=load_data('leadership') or [], facilities=load_data('facilities') or [], faculty=load_data('faculty') or { 'stats': {'teachers': 0, 'degrees': 0, 'training': 0}, 'department_heads': [] }) @app.route('/academics') def academics(): """Academics page route""" return render_template('academics.html', subjects=load_data('subjects') or [], results=load_data('results') or {}, calendar=load_data('calendar') or []) # Admissions Routes @app.route('/admissions') def admissions(): """Admissions main page""" return render_template('admissions.html', process={ 'steps': load_data('admissions_steps') or [], 'requirements': load_data('admissions_requirements') or [] }, fees=load_data('fee_structure') or [], scholarships=load_data('scholarships') or [], downloads=load_data('admissions_downloads') or []) @app.route('/admissions/apply', methods=['GET', 'POST']) def admissions_apply(): """Admissions application form""" if request.method == 'POST': # Validate required fields required_fields = [ 'first_name', 'last_name', 'birthdate', 'gender', 'parent_name', 'parent_email', 'parent_phone' ] if not all(request.form.get(field) for field in required_fields): flash(_('Please fill in all required fields'), 'error') return redirect(url_for('admissions_apply')) # Create application data student_data = { 'id': str(uuid.uuid4()), 'first_name': request.form.get('first_name'), 'last_name': request.form.get('last_name'), 'birthdate': request.form.get('birthdate'), 'gender': request.form.get('gender'), 'nationality': request.form.get('nationality', ''), 'current_school': request.form.get('current_school', ''), 'applying_grade': request.form.get('applying_grade', ''), 'parent_name': request.form.get('parent_name'), 'parent_email': request.form.get('parent_email'), 'parent_phone': request.form.get('parent_phone'), 'address': request.form.get('address', ''), 'emergency_contact': request.form.get('emergency_contact', ''), 'medical_conditions': request.form.get('medical_conditions', ''), 'previous_schools': request.form.get('previous_schools', ''), 'extracurriculars': request.form.get('extracurriculars', ''), 'why_join': request.form.get('why_join', ''), 'status': 'submitted', 'submission_date': datetime.now().strftime("%Y-%m-%d %H:%M"), } # Handle file uploads uploaded_files = {} for file_field in ['birth_certificate', 'academic_records', 'recommendation_letter', 'photo']: file = request.files.get(file_field) if file and allowed_file(file.filename): filename = secure_filename(f"{student_data['id']}_{file_field}{os.path.splitext(file.filename)[1]}") upload_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'applications') os.makedirs(upload_dir, exist_ok=True) file_path = os.path.join(upload_dir, filename) file.save(file_path) uploaded_files[file_field] = filename # Save application data applications = load_data('applications') or [] full_data = {**student_data, **uploaded_files} applications.append(full_data) save_data('applications', applications) # Send email notifications # To applicant applicant_subject = _("Application Submitted to Munishi Secondary School") applicant_body = _( f"Dear {student_data['first_name']} {student_data['last_name']},\n\n" "Thank you for submitting your application to Munishi Secondary School!\n\n" f"Your application ID is: {student_data['id']}\n" "We will review your application and contact you within 5-7 business days.\n\n" "If you have any questions, please contact our admissions office at admissions@munishischool.ac.tz\n\n" "Sincerely,\n" "The Admissions Committee\n" "Munishi Secondary School" ) send_email(applicant_subject, [student_data['parent_email']], applicant_body) # To admin admin_subject = _("New Application Submitted: {} {}").format( student_data['first_name'], student_data['last_name']) admin_body = _( f"Application ID: {student_data['id']}\n" f"Student: {student_data['first_name']} {student_data['last_name']}\n" f"Applying Grade: {student_data.get('applying_grade', 'N/A')}\n" f"Parent: {student_data['parent_name']}\n" f"Email: {student_data['parent_email']}\n" f"Phone: {student_data['parent_phone']}\n\n" "Review the application: {}\n" ).format(url_for('admin_application_detail', application_id=student_data['id'], _external=True)) send_email(admin_subject, [app.config['ADMIN_EMAIL']], admin_body) flash(_('Application submitted successfully!'), 'success') return redirect(url_for('application_success', application_id=student_data['id'])) return render_template('admissions/apply.html') @app.route('/admissions/success/<application_id>') def application_success(application_id): """Application submission success page""" return render_template('admissions/application_success.html', application_id=application_id) @app.route('/admissions/view/<application_id>') def view_application(application_id): """View submitted application (admin view)""" applications = load_data('applications') or [] application = next((app for app in applications if app['id'] == application_id), None) if not application: return render_template('404.html'), 404 return render_template('admissions/view_application.html', application=application) # Other Routes @app.route('/student-life') def student_life(): """Student life page route""" return render_template('student_life.html', clubs=load_data('clubs') or [], sports={ 'competitive': load_data('sports_competitive') or [], 'recreational': load_data('sports_recreational') or [], 'achievements': load_data('sports_achievements') or [] }, arts={ 'performing': load_data('arts_performing') or [], 'visual': load_data('arts_visual') or [] }, activities=load_data('activities') or [], blogs=load_data('blogs') or []) @app.route('/safeguarding') def safeguarding(): """Safeguarding page route""" return render_template('safeguarding.html', policies=load_data('policies') or []) @app.route('/news') def news(): """News listing page route""" return render_template('news.html', news=load_data('news') or []) @app.route('/news/<slug>') def news_detail(slug): """News detail page route""" news_items = load_data('news') or [] item = next((item for item in news_items if item.get('slug') == slug), None) if not item: return render_template('404.html'), 404 return render_template('news_detail.html', item=item) @app.route('/events') def events(): """Events listing page route""" return render_template('events.html', events=load_data('events') or []) @app.route('/alumni') def alumni(): """Alumni page route""" return render_template('alumni.html', alumni=load_data('alumni') or []) # Add these routes in the "Admin Routes" section @app.route('/download/application/<filename>') @admin_required def download_application_file(filename): """Download an application file uploaded by the applicant""" directory = os.path.join(app.config['UPLOAD_FOLDER'], 'applications') return send_from_directory(directory, filename, as_attachment=True) @app.route('/download/admin/<filename>') @admin_required def download_admin_file(filename): """Download an admin uploaded file for an application""" directory = os.path.join(app.config['ADMIN_UPLOAD_FOLDER'], 'application_docs') return send_from_directory(directory, filename, as_attachment=True) @app.route('/contact', methods=['GET', 'POST']) def contact(): """Contact page route with form handling""" contact_data = load_data('contact') or { 'locations': [], 'departments': [], 'office_hours': {} } if request.method == 'POST': name = request.form.get('name', '').strip() email = request.form.get('email', '').strip() subject = request.form.get('subject', 'No Subject').strip() message = request.form.get('message', '').strip() # Validate form data if not all([name, email, message]): flash(_('Please fill in all required fields'), 'error') return redirect(url_for('contact')) if '@' not in email or '.' not in email: flash(_('Please enter a valid email address'), 'error') return redirect(url_for('contact')) # Process the message (in production: save to DB and send email) print(f"New contact message from {name} ({email}): {message}") # Send email to admin admin_subject = f"New Contact Form Submission: {subject}" admin_body = ( f"Name: {name}\n" f"Email: {email}\n" f"Subject: {subject}\n\n" f"Message:\n{message}" ) send_email(admin_subject, [app.config['ADMIN_EMAIL']], admin_body) flash(_('Your message has been sent successfully!'), 'success') return redirect(url_for('contact_success')) return render_template('contact.html', locations=contact_data.get('locations', []), departments=contact_data.get('departments', []), office_hours=contact_data.get('office_hours', {})) @app.route('/contact/success') def contact_success(): """Contact success page""" return render_template('contact_success.html') @app.route('/downloads/<category>/<filename>') def download_file(category, filename): """File download route""" try: # Secure the filename to prevent directory traversal attacks safe_filename = secure_filename(filename) directory = os.path.join(app.root_path, 'static', 'downloads', category) # Verify file exists before sending if not os.path.exists(os.path.join(directory, safe_filename)): app.logger.error(f"File not found: {category}/{safe_filename}") return render_template('404.html'), 404 return send_from_directory( directory, safe_filename, as_attachment=True, mimetype='application/octet-stream' ) except Exception as e: app.logger.error(f"Download error: {str(e)}") return render_template('500.html'), 500 # Error Handlers @app.errorhandler(404) def page_not_found(e): """404 Error handler""" return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): """500 Error handler""" return render_template('500.html'), 500 if __name__ == '__main__': # Create necessary directories if they don't exist os.makedirs('data', exist_ok=True) os.makedirs('static/downloads/admissions', exist_ok=True) os.makedirs('static/downloads/scholarships', exist_ok=True) os.makedirs('static/uploads/applications', exist_ok=True) os.makedirs(app.config['ADMIN_UPLOAD_FOLDER'], exist_ok=True) # Create admin template files if they don't exist admin_templates = [ 'admin/base.html', 'admin/login.html', 'admin/dashboard.html', 'admin/applications.html', 'admin/application_detail.html', 'admin/settings.html', 'admin/content.html', 'admin/manage_content.html' ] os.makedirs('templates/admin', exist_ok=True) for template in admin_templates: template_path = os.path.join('templates', template) if not os.path.exists(template_path): with open(template_path, 'w') as f: f.write(f"<!-- {template} -->\n") app.run(debug=True, host='0.0.0.0', port=7860)
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory, g, flash, jsonify
from flask_babel import Babel, gettext as _
from flask_mail import Mail, Message
import os
import json
from datetime import datetime
from functools import wraps
import uuid
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'dev_secret_key')
# Application Configuration
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations'
app.config['SCHOOL_NAME'] = "Munishi Secondary School"
app.config['SCHOOL_MOTTO'] = "Excellence Through Diligence"
app.config['CONTACT_EMAIL'] = "info@munishischool.ac.tz"
app.config['CONTACT_PHONE'] = "+255 22 123 4567"
app.config['ADDRESS'] = "P.O. Box 1234, Dar es Salaam, Tanzania"
app.config['SOCIAL_MEDIA'] = {
'facebook': 'https://facebook.com/munishischool',
'twitter': 'https://twitter.com/munishischool',
'instagram': 'https://instagram.com/munishischool',
'youtube': 'https://youtube.com/munishischool'
}
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif', 'pdf'}
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload size
# Admin Configuration
app.config['ADMIN_USERNAME'] = os.environ.get('ADMIN_USERNAME', 'admin')
app.config['ADMIN_PASSWORD'] = os.environ.get('ADMIN_PASSWORD', generate_password_hash('admin123'))
app.config['ADMIN_UPLOAD_FOLDER'] = 'static/uploads/admin'
app.config['APPLICATIONS_PER_PAGE'] = 10
app.config['ADMIN_SESSION_TIMEOUT'] = 3600 # 1 hour in seconds
# Email Configuration
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = 'egliszaratus@gmail.com'
app.config['MAIL_PASSWORD'] = 'xwzd nogw tavi qgtg' # Your app password
app.config['MAIL_DEFAULT_SENDER'] = 'Munishi Secondary School <egliszaratus@gmail.com>'
app.config['ADMIN_EMAIL'] = 'egliszaratus@gmail.com'
# Initialize Babel and Mail
babel = Babel(app)
mail = Mail(app)
# Admin Authentication Decorator
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('admin_logged_in'):
return redirect(url_for('admin_login', next=request.url))
# Check session timeout
last_activity = session.get('admin_last_activity')
if last_activity and (datetime.now() - datetime.strptime(last_activity, "%Y-%m-%d %H:%M:%S")).seconds > app.config['ADMIN_SESSION_TIMEOUT']:
session.pop('admin_logged_in', None)
flash(_('Your session has timed out. Please log in again.'), 'warning')
return redirect(url_for('admin_login', next=request.url))
# Update last activity time
session['admin_last_activity'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return f(*args, **kwargs)
return decorated_function
# Helper Functions
def load_data(filename):
"""Load JSON data from the data directory"""
try:
with open(f'data/{filename}.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# Process the data based on type
if isinstance(data, list):
for item in data:
if isinstance(item, dict):
# Escape % signs in strings for translation
for key in ['title', 'description', 'excerpt']:
if key in item and isinstance(item[key], str):
item[key] = item[key].replace('%', '%%')
# Set default image if missing or file doesn't exist
if 'image' in item:
image_path = os.path.join('static', 'images', item['image'])
if not os.path.exists(image_path):
item['image'] = 'default.jpg'
return data
except FileNotFoundError:
app.logger.warning(f"Data file not found: {filename}.json")
return None
except json.JSONDecodeError:
app.logger.error(f"Invalid JSON in file: {filename}.json")
return None
except Exception as e:
app.logger.error(f"Error loading {filename}.json: {str(e)}")
return None