Microinsurance Products

Install Required Libraries

You’ll need the following libraries to proceed with the project:

bashCopy codepip install flask flask-sqlalchemy flask-login flask-wtf
  • Flask: A micro web framework for building the web application.
  • Flask-SQLAlchemy: For database management.
  • Flask-Login: For user authentication.
  • Flask-WTF: For form handling.

Step 2: Define Database Models

We need to define several models for this system:

  1. User: Stores user information and account credentials.
  2. MicroinsuranceProduct: Represents a microinsurance product, such as health or life insurance.
  3. Policy: Represents the user’s insurance policy for a particular product.
  4. Claim: Tracks the claims submitted by users for their policies.

models.py

pythonCopy codefrom flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    policies = db.relationship('Policy', backref='holder', lazy=True)
    claims = db.relationship('Claim', backref='claimant', lazy=True)

    def __repr__(self):
        return f'<User {self.username}>'

class MicroinsuranceProduct(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), nullable=False)
    description = db.Column(db.String(255), nullable=False)
    premium = db.Column(db.Float, nullable=False)
    coverage = db.Column(db.Float, nullable=False)  # Coverage amount
    policies = db.relationship('Policy', backref='product', lazy=True)

    def __repr__(self):
        return f'<MicroinsuranceProduct {self.name}>'

class Policy(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    product_id = db.Column(db.Integer, db.ForeignKey('microinsurance_product.id'), nullable=False)
    start_date = db.Column(db.DateTime, default=datetime.utcnow)
    end_date = db.Column(db.DateTime)
    active = db.Column(db.Boolean, default=True)  # Whether the policy is active
    claims = db.relationship('Claim', backref='policy', lazy=True)

    def __repr__(self):
        return f'<Policy {self.id} for user {self.user_id}>'

class Claim(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    policy_id = db.Column(db.Integer, db.ForeignKey('policy.id'), nullable=False)
    amount = db.Column(db.Float, nullable=False)
    description = db.Column(db.String(255), nullable=False)
    status = db.Column(db.String(50), default='Pending')  # Pending, Approved, Denied
    date_filed = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return f'<Claim {self.id} for policy {self.policy_id}>'

Step 3: Flask Application Setup

Now, let’s build the main Flask application. We’ll have several routes, including:

  • User Registration: To register new users.
  • Login: To authenticate users.
  • Product Catalog: To view available microinsurance products.
  • Buy Insurance: To buy an insurance policy for a specific product.
  • File a Claim: To submit a claim for a purchased policy.
  • View Claims: To view the status of filed claims.

app.py

pythonCopy codefrom flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from models import db, User, MicroinsuranceProduct, Policy, Claim

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///microinsurance.db'
db.init_app(app)

login_manager = LoginManager(app)
login_manager.login_view = 'login'

# User loader for Flask-Login
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# Routes
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        password_hash = generate_password_hash(password)

        new_user = User(username=username, email=email, password_hash=password_hash)
        db.session.add(new_user)
        db.session.commit()

        flash('Account created successfully! You can now log in.', 'success')
        return redirect(url_for('login'))

    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user = User.query.filter_by(email=email).first()

        if user and check_password_hash(user.password_hash, password):
            login_user(user)
            return redirect(url_for('dashboard'))

        flash('Login failed. Check your email or password.', 'danger')

    return render_template('login.html')

@app.route('/dashboard')
@login_required
def dashboard():
    products = MicroinsuranceProduct.query.all()
    return render_template('dashboard.html', products=products)

@app.route('/product/<int:product_id>', methods=['GET', 'POST'])
@login_required
def product(product_id):
    product = MicroinsuranceProduct.query.get_or_404(product_id)
    
    if request.method == 'POST':
        # Buy insurance policy
        policy = Policy(user_id=current_user.id, product_id=product.id)
        db.session.add(policy)
        db.session.commit()

        flash(f'You have successfully purchased the {product.name} insurance!', 'success')
        return redirect(url_for('dashboard'))

    return render_template('product.html', product=product)

@app.route('/claim/<int:policy_id>', methods=['GET', 'POST'])
@login_required
def claim(policy_id):
    policy = Policy.query.get_or_404(policy_id)

    if request.method == 'POST':
        claim_amount = float(request.form['amount'])
        description = request.form['description']

        claim = Claim(policy_id=policy.id, amount=claim_amount, description=description)
        db.session.add(claim)
        db.session.commit()

        flash('Claim submitted successfully!', 'success')
        return redirect(url_for('dashboard'))

    return render_template('claim.html', policy=policy)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

Step 4: Create Frontend Templates

templates/index.html

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Microinsurance</title>
</head>
<body>
    <h1>Welcome to Microinsurance</h1>
    <a href="{{ url_for('login') }}">Login</a> |
    <a href="{{ url_for('register') }}">Register</a>
</body>
</html>

templates/register.html

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
</head>
<body>
    <h1>Create an Account</h1>
    <form method="POST">
        <label for="username">Username:</label>
        <input type="text" name="username" required><br><br>

        <label for="email">Email:</label>
        <input type="email" name="email" required><br><br>

        <label for="password">Password:</label>
        <input type="password" name="password" required><br><br>

        <button type="submit">Register</button>
    </form>
</body>
</html>

templates/dashboard.html

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome, {{

4o mini


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *