Spaces:
Runtime error
Runtime error
Upload 100 files
#1
by harshbhatiyaa - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
Files changed (50)
- DockerfileAdded+19
- alembic.iniAdded+149
- app/__init__.pyAdded+1
- app/__pycache__/__init__.cpython-314.pycAdded
- app/__pycache__/main.cpython-314.pycAdded
- app/core/__init__.pyAdded+1
- app/core/__pycache__/__init__.cpython-314.pycAdded
- app/core/__pycache__/config.cpython-314.pycAdded
- app/core/__pycache__/database.cpython-314.pycAdded
- app/core/__pycache__/security.cpython-314.pycAdded
- app/core/__pycache__/seeding.cpython-314.pycAdded
- app/core/config.pyAdded+20
- app/core/database.pyAdded+29
- app/core/security.pyAdded+35
- app/core/seeding.pyAdded+191
- app/main.pyAdded+81
- app/models/__init__.pyAdded+24
- app/models/__pycache__/__init__.cpython-314.pycAdded
- app/models/__pycache__/alerts.cpython-314.pycAdded
- app/models/__pycache__/base.cpython-314.pycAdded
- app/models/__pycache__/bookings.cpython-314.pycAdded
- app/models/__pycache__/jobs.cpython-314.pycAdded
- app/models/__pycache__/notifications.cpython-314.pycAdded
- app/models/__pycache__/reviews.cpython-314.pycAdded
- app/models/__pycache__/roster.cpython-314.pycAdded
- app/models/__pycache__/users.cpython-314.pycAdded
- app/models/__pycache__/wallet.cpython-314.pycAdded
- app/models/alerts.pyAdded+10
- app/models/base.pyAdded+14
- app/models/bookings.pyAdded+20
- app/models/jobs.pyAdded+17
- app/models/notifications.pyAdded+15
- app/models/reviews.pyAdded+20
- app/models/roster.pyAdded+17
- app/models/users.pyAdded+48
- app/models/wallet.pyAdded+17
- app/repositories/__init__.pyAdded+15
- app/repositories/__pycache__/__init__.cpython-314.pycAdded
- app/repositories/__pycache__/alerts.cpython-314.pycAdded
- app/repositories/__pycache__/bookings.cpython-314.pycAdded
- app/repositories/__pycache__/jobs.cpython-314.pycAdded
- app/repositories/__pycache__/roster.cpython-314.pycAdded
- app/repositories/__pycache__/users.cpython-314.pycAdded
- app/repositories/__pycache__/wallet.cpython-314.pycAdded
- app/repositories/alerts.pyAdded+34
- app/repositories/bookings.pyAdded+63
- app/repositories/jobs.pyAdded+42
- app/repositories/roster.pyAdded+44
- app/repositories/users.pyAdded+94
- app/repositories/wallet.pyAdded+48
12345678910111213141516171819FROM python:3.11-slim
WORKDIR /code
# Install system libraries needed for database driversRUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ && rm -rf /var/lib/apt/lists/*
# Copy requirements and install dependencies in binary mode to avoid compiler blocksCOPY ./requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --upgrade -r /code/requirements.txt --only-binary :all:
# Copy the rest of the application filesCOPY . /code
# Hugging Face Spaces routes internal traffic to port 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149# A generic, single database configuration.
[alembic]# path to migration scripts.# this is typically a path given in POSIX (e.g. forward slashes)# format, relative to the token %(here)s which refers to the location of this# ini filescript_location = %(here)s/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s# Uncomment the line below if you want the files to be prepended with date and time# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file# for all available tokens# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s# Or organize into date-based subdirectories (requires recursive_version_locations = true)# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.# defaults to the current working directory. for multiple paths, the path separator# is defined by "path_separator" below.prepend_sys_path = .
# timezone to use when rendering the date within the migration file# as well as the filename.# If specified, requires the tzdata library which can be installed by adding# `alembic[tz]` to the pip requirements.# string value is passed to ZoneInfo()# leave blank for localtime# timezone =
# max length of characters to apply to the "slug" field# truncate_slug_length = 40
# set to 'true' to run the environment during# the 'revision' command, regardless of autogenerate# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without# a source .py file to be detected as revisions in the# versions/ directory# sourceless = false
# version location specification; This defaults# to <script_location>/versions. When using multiple version# directories, initial revisions must be specified with --version-path.# The path separator used here should be the separator specified by "path_separator"# below.# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file# paths, including version_locations and prepend_sys_path within configparser# files such as alembic.ini.# The default rendered in new alembic.ini files is "os", which uses os.pathsep# to provide os-dependent path splitting.## Note that in order to support legacy alembic.ini files, this default does NOT# take place if path_separator is not present in alembic.ini. If this# option is omitted entirely, fallback logic is as follows:## 1. Parsing of the version_locations option falls back to using the legacy# "version_path_separator" key, which if absent then falls back to the legacy# behavior of splitting on spaces and/or commas.# 2. Parsing of the prepend_sys_path option falls back to the legacy# behavior of splitting on spaces, commas, or colons.## Valid values for path_separator are:## path_separator = :# path_separator = ;# path_separator = space# path_separator = newline## Use os.pathsep. Default configuration used for new projects.path_separator = os
# set to 'true' to search source files recursively# in each "version_locations" directory# new in Alembic version 1.10# recursive_version_locations = false
# the output encoding used when revision files# are written from script.py.mako# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.# other means of configuring database URLs may be customized within the env.py# file.sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]# post_write_hooks defines scripts or Python functions that are run# on newly generated revision scripts. See the documentation for further# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint# hooks = black# black.type = console_scripts# black.entrypoint = black# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module# hooks = ruff# ruff.type = module# ruff.module = ruff# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH# hooks = ruff# ruff.type = exec# ruff.executable = ruff# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained# env.py script only.[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNINGhandlers = consolequalname =
[logger_sqlalchemy]level = WARNINGhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S1# ConstructHire app package1# Core configuration and security1234567891011121314151617181920import osfrom pydantic_settings import BaseSettings
class Settings(BaseSettings): PROJECT_NAME: str = "ConstructHire API" API_V1_STR: str = "/api" # Security config # In production, this must be a secure random hex string read from environment SECRET_KEY: str = os.getenv("SECRET_KEY", "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7") ALGORITHM: str = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7 # 7 days for BCA viva convenience # Database settings DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/constructhire") class Config: case_sensitive = True
settings = Settings()1234567891011121314151617181920212223242526272829import osfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker
# Database URL configuration# For local development, default to SQLite fallback.# For production/staging, it will read PostgreSQL from environment variables.DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./constructhire.db")
# Support SQLite configuration parametersif DATABASE_URL.startswith("sqlite"): engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})else: # Use pool_pre_ping=True to prevent stale connection errors with Supabase/Render engine = create_engine(DATABASE_URL, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db(): """ Database session generator to be used as a FastAPI dependency. Yields a database session and ensures it is closed after the request is finished. """ db = SessionLocal() try: yield db finally: db.close()1234567891011121314151617181920212223242526272829303132333435import bcryptfrom datetime import datetime, timedeltafrom typing import Any, Unionfrom jose import jwtfrom backend.app.core.config import settings
def verify_password(plain_password: str, hashed_password: str) -> bool: """Verify if a plain text password matches its hashed bcrypt value.""" if not hashed_password: return False try: return bcrypt.checkpw( plain_password.encode("utf-8"), hashed_password.encode("utf-8") ) except Exception: return False
def get_password_hash(password: str) -> str: """Generate a secure bcrypt hash of a plain text password.""" # Generate salt and hash the password salt = bcrypt.gensalt() hashed = bcrypt.hashpw(password.encode("utf-8"), salt) return hashed.decode("utf-8")
def create_access_token(subject: Union[str, Any], expires_delta: timedelta = None) -> str: """Generate a JWT access token for a subject (usually user phone).""" if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = {"exp": expire, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191from sqlalchemy.orm import Sessionfrom backend.app.models.users import User, WorkerProfile, CustomerProfilefrom backend.app.models.jobs import Jobfrom backend.app.models.bookings import Bookingfrom backend.app.models.wallet import WalletTransactionfrom backend.app.models.roster import RosterWorkerfrom backend.app.models.alerts import AdminAlertfrom backend.app.core.security import get_password_hash
def seed_db(db: Session): """Pre-populates the database with initial viva seed data if empty.""" # Check if DB is already seeded if db.query(User).first() is not None: print("Database already seeded.") return False
print("Seeding database...") # 1. Create Default Admin admin = User( name="Chandan Admin", phone="9999999999", role="admin", password_hash=get_password_hash("admin123") ) db.add(admin) # 2. Create Default Customer customer = User( name="Harsh", phone="9876543210", role="customer", password_hash=get_password_hash("pass123") ) db.add(customer) db.flush() cust_profile = CustomerProfile(user_id=customer.id, wallet_balance=8200) db.add(cust_profile) # 3. Create Default Mediator mediator = User( name="Rafiq Thekedar", phone="9876599999", role="mediator", password_hash=get_password_hash("pass123") ) db.add(mediator) db.flush() med_cust_profile = CustomerProfile(user_id=mediator.id, wallet_balance=5000) db.add(med_cust_profile) # 4. Create Seed Workers workers_data = [ ("Ramesh Kumar", "9876500001", "Mason", 650, 4.8, 126, 97, 67, 34, True, True), ("Imran Ali", "9876500002", "Electrician", 800, 4.7, 88, 95, 35, 45, True, True), ("Sita Devi", "9876500003", "Painter", 700, 4.9, 112, 99, 58, 72, True, True), ("Babulal Meena", "9876500004", "Helper", 500, 4.4, 46, 91, 26, 67, True, False), ("Karan Singh", "9876500005", "Carpenter", 750, 4.6, 73, 92, 74, 58, False, True), ("Mohan Lal", "9876500006", "Plumber", 720, 4.5, 65, 93, 46, 28, True, True), ] workers = [] for name, phone, skill, rate, rating, completed, completion, x, y, online, verified in workers_data: user = User( name=name, phone=phone, role="worker", password_hash=get_password_hash("pass123") ) db.add(user) db.flush() # Calculate distance import math dist = round(math.sqrt((x - 50)**2 + (y - 50)**2) / 15, 1) or 1.2 prof = WorkerProfile( user_id=user.id, skill=skill, rate=rate, rating=rating, distance=dist, online=online, verified=verified, completed_jobs=completed, completion_rate=completion, map_x=x, map_y=y ) db.add(prof) workers.append(user) db.flush() # 5. Create Seed Jobs jobs_data = [ ("Mason", "Mansarovar, Jaipur", 1300, "POSTED", "Boundary wall repair and cement finishing."), ("Painter", "Vaishali Nagar", 2800, "ACCEPTED", "Two rooms wall putty and primer."), ("Electrician", "Malviya Nagar", 900, "IN_PROGRESS", "Switch board repair and fan installation."), ] jobs = [] for skill, loc, budget, status, desc in jobs_data: job = Job( customer_id=customer.id, skill_required=skill, location=loc, budget=budget, description=desc, status=status ) db.add(job) jobs.append(job) db.flush() # 6. Create Seed Bookings bookings_data = [ ("B-2401", "Boundary wall repair", workers[0].id, 1300, "ACCEPTED", jobs[0].id), ("B-2402", "Switch board repair", workers[1].id, 900, "IN_PROGRESS", jobs[2].id), ] for code, title, worker_id, amount, status, job_id in bookings_data: booking = Booking( code=code, customer_id=customer.id, worker_id=worker_id, amount=amount, status=status, job_id=job_id ) db.add(booking) db.flush() # 7. Create Seed Wallet Transactions tx_data = [ ("Wallet top-up via UPI", 5000, "credit"), ("Escrow hold for B-2401", -1300, "hold"), ("Escrow hold for B-2402", -900, "hold"), ("Refund from cancelled booking", 600, "credit"), ] for label, amount, tx_type in tx_data: tx = WalletTransaction( user_id=customer.id, label=label, amount=amount, type=tx_type ) db.add(tx) # 8. Create Seed Roster Workers roster_data = [ ("Rafiq", "Helper", "IVR only", "Available", 1200), ("Sunita", "Painter", "Verified", "On job", 820), ("Dinesh", "Mason", "Verified", "Available", 1440), ] for name, skill, phone_status, status, commission in roster_data: roster_worker = RosterWorker( mediator_id=mediator.id, name=name, skill=skill, phone_status=phone_status, status=status, commission=commission ) db.add(roster_worker) # 9. Create Seed Admin Alerts alerts_data = [ ("Dispute", "B-2397 quality issue pending admin review", "red"), ("Fraud", "Duplicate Aadhaar hash detected for two accounts", "orange"), ("IVR", "23 non-smartphone workers received daily job alerts", "gray"), ] for type_, text, severity in alerts_data: alert = AdminAlert( type=type_, text=text, severity=severity, status="active" ) db.add(alert) db.commit() print("Database seeded successfully!") return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import osfrom fastapi import FastAPI, Depends, APIRouterfrom fastapi.middleware.cors import CORSMiddlewarefrom sqlalchemy.orm import Session
from backend.app.core.config import settingsfrom backend.app.core.database import SessionLocal, engine, get_dbfrom backend.app.core.seeding import seed_dbfrom backend.app.models.base import Base
# Import Routersfrom backend.app.routers import ( auth_router, workers_router, jobs_router, bookings_router, wallet_router, roster_router, admin_router)
# Initialize database tables# This is a safe fallback; in production migrations are preferred,# but for the BCA viva, ensuring tables exist automatically is a lifesaver.Base.metadata.create_all(bind=engine)
# Trigger Database Seeding on startupdb = SessionLocal()try: seed_db(db)finally: db.close()
app = FastAPI( title=settings.PROJECT_NAME, description="ConstructHire location-aware labor marketplace backend", version="1.0.0", docs_url="/docs", redoc_url="/redoc")
# CORS configuration# Allow local Vite dev server and production netlify deploymentsapp.add_middleware( CORSMiddleware, allow_origins=["*"], # For BCA viva simplicity; in strict prod specify origins allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Register API Routersapi_router = APIRouter(prefix="/api")api_router.include_router(auth_router)api_router.include_router(workers_router)api_router.include_router(jobs_router)api_router.include_router(bookings_router)api_router.include_router(wallet_router)api_router.include_router(roster_router)api_router.include_router(admin_router)
app.include_router(api_router)
@app.get("/")def read_root(): """Root endpoint to check backend status.""" return { "status": "online", "service": settings.PROJECT_NAME, "docs": "/docs", "api_prefix": settings.API_V1_STR }
@app.post("/api/admin/reset-db")def reset_database(db: Session = Depends(get_db)): """Convenience endpoint to clear and re-seed the database with demo values.""" # Drop all tables and recreate them Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) seed_db(db) return {"message": "Database successfully reset and re-seeded."}123456789101112131415161718192021222324from backend.app.models.base import Base, BaseDBModelfrom backend.app.models.users import User, WorkerProfile, CustomerProfilefrom backend.app.models.jobs import Jobfrom backend.app.models.bookings import Bookingfrom backend.app.models.wallet import WalletTransactionfrom backend.app.models.reviews import Reviewfrom backend.app.models.notifications import Notificationfrom backend.app.models.roster import RosterWorkerfrom backend.app.models.alerts import AdminAlert
__all__ = [ "Base", "BaseDBModel", "User", "WorkerProfile", "CustomerProfile", "Job", "Booking", "WalletTransaction", "Review", "Notification", "RosterWorker", "AdminAlert",]12345678910from sqlalchemy import Column, Stringfrom backend.app.models.base import BaseDBModel
class AdminAlert(BaseDBModel): __tablename__ = "admin_alerts" type = Column(String, nullable=False, index=True) # Dispute, Fraud, IVR text = Column(String, nullable=False) severity = Column(String, nullable=False) # red, orange, gray status = Column(String, nullable=False, default="active", index=True) # active, resolved1234567891011121314import uuidfrom datetime import datetimefrom sqlalchemy import Column, DateTimefrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import declarative_base
Base = declarative_base()
class BaseDBModel(Base): __abstract__ = True id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True, nullable=False) created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)1234567891011121314151617181920from sqlalchemy import Column, String, Integer, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class Booking(BaseDBModel): __tablename__ = "bookings" code = Column(String, unique=True, index=True, nullable=False) # e.g. B-2401 job_id = Column(UUID(as_uuid=True), ForeignKey("jobs.id", ondelete="SET NULL"), nullable=True) customer_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) worker_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) amount = Column(Integer, nullable=False) status = Column(String, nullable=False, default="ACCEPTED", index=True) # ACCEPTED, IN_PROGRESS, COMPLETED, RATED, DISPUTED # Relationships job = relationship("Job", back_populates="bookings") customer = relationship("User", foreign_keys=[customer_id]) worker = relationship("User", foreign_keys=[worker_id]) reviews = relationship("Review", back_populates="booking", cascade="all, delete-orphan")1234567891011121314151617from sqlalchemy import Column, String, Integer, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class Job(BaseDBModel): __tablename__ = "jobs" customer_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) skill_required = Column(String, index=True, nullable=False) location = Column(String, nullable=False) budget = Column(Integer, nullable=False) description = Column(String, nullable=False) status = Column(String, nullable=False, default="POSTED", index=True) # POSTED, ACCEPTED, IN_PROGRESS, COMPLETED, CANCELLED # Relationships bookings = relationship("Booking", back_populates="job", cascade="all, delete-orphan")123456789101112131415from sqlalchemy import Column, String, Boolean, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class Notification(BaseDBModel): __tablename__ = "notifications" user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) title = Column(String, nullable=False) message = Column(String, nullable=False) read = Column(Boolean, nullable=False, default=False, index=True) # Relationships user = relationship("User", back_populates="notifications")1234567891011121314151617181920from sqlalchemy import Column, String, Integer, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class Review(BaseDBModel): __tablename__ = "reviews" booking_id = Column(UUID(as_uuid=True), ForeignKey("bookings.id", ondelete="CASCADE"), index=True, nullable=False) reviewer_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) reviewee_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) rating = Column(Integer, nullable=False) # 1 to 5 comment = Column(String, nullable=True) # Relationships booking = relationship("Booking", back_populates="reviews") reviewer = relationship("User", foreign_keys=[reviewer_id]) reviewee = relationship("User", foreign_keys=[reviewee_id])class Review_Table_Init: pass1234567891011121314151617from sqlalchemy import Column, String, Integer, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class RosterWorker(BaseDBModel): __tablename__ = "roster_workers" mediator_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) name = Column(String, nullable=False) skill = Column(String, nullable=False) phone_status = Column(String, nullable=False) # e.g. "IVR only", "Verified" status = Column(String, nullable=False) # e.g. "Available", "On job" commission = Column(Integer, nullable=False, default=0) # Relationships mediator = relationship("User", back_populates="roster_workers")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748from sqlalchemy import Column, String, Integer, Float, Boolean, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class User(BaseDBModel): __tablename__ = "users" name = Column(String, nullable=False) phone = Column(String, unique=True, index=True, nullable=False) role = Column(String, index=True, nullable=False) # admin, customer, worker, mediator password_hash = Column(String, nullable=True) # can be null for demo OTP bypass city = Column(String, nullable=False, default="Jaipur") is_active = Column(Boolean, nullable=False, default=True) # Relationships worker_profile = relationship("WorkerProfile", back_populates="user", uselist=False, cascade="all, delete-orphan") customer_profile = relationship("CustomerProfile", back_populates="user", uselist=False, cascade="all, delete-orphan") notifications = relationship("Notification", back_populates="user", cascade="all, delete-orphan") wallet_transactions = relationship("WalletTransaction", back_populates="user", cascade="all, delete-orphan") roster_workers = relationship("RosterWorker", back_populates="mediator", cascade="all, delete-orphan")
class WorkerProfile(BaseDBModel): __tablename__ = "worker_profiles" user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), unique=True, index=True, nullable=False) skill = Column(String, index=True, nullable=False) # Mason, Electrician, Painter, etc. rate = Column(Integer, nullable=False) # Daily wage in INR rating = Column(Float, nullable=False, default=4.5) distance = Column(Float, nullable=False, default=1.5) # Simulated distance in km online = Column(Boolean, nullable=False, default=True) verified = Column(Boolean, nullable=False, default=False) # Aadhaar verified completed_jobs = Column(Integer, nullable=False, default=0) completion_rate = Column(Integer, nullable=False, default=90) # percentage map_x = Column(Integer, nullable=False, default=50) # Coordinate x on simulated map map_y = Column(Integer, nullable=False, default=50) # Coordinate y on simulated map # Relationships user = relationship("User", back_populates="worker_profile")
class CustomerProfile(BaseDBModel): __tablename__ = "customer_profiles" user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), unique=True, index=True, nullable=False) wallet_balance = Column(Integer, nullable=False, default=8200) # Relationships user = relationship("User", back_populates="customer_profile")1234567891011121314151617from sqlalchemy import Column, String, Integer, ForeignKeyfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import relationshipfrom backend.app.models.base import BaseDBModel
class WalletTransaction(BaseDBModel): __tablename__ = "wallet_transactions" user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False) booking_id = Column(UUID(as_uuid=True), ForeignKey("bookings.id", ondelete="SET NULL"), nullable=True) label = Column(String, nullable=False) # e.g. "Wallet top-up via UPI", "Escrow hold for B-2401" amount = Column(Integer, nullable=False) # positive for credits/refunds, negative for debits/holds type = Column(String, nullable=False, index=True) # credit, hold, release, refund # Relationships user = relationship("User", back_populates="wallet_transactions") booking = relationship("Booking")123456789101112131415from backend.app.repositories.users import UserRepositoryfrom backend.app.repositories.jobs import JobRepositoryfrom backend.app.repositories.bookings import BookingRepositoryfrom backend.app.repositories.wallet import WalletRepositoryfrom backend.app.repositories.roster import RosterRepositoryfrom backend.app.repositories.alerts import AlertRepository
__all__ = [ "UserRepository", "JobRepository", "BookingRepository", "WalletRepository", "RosterRepository", "AlertRepository",]12345678910111213141516171819202122232425262728293031323334import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.alerts import AdminAlert
class AlertRepository: def __init__(self, db: Session): self.db = db
def create(self, type_: str, text: str, severity: str = "gray") -> AdminAlert: alert = AdminAlert( type=type_, text=text, severity=severity, status="active" ) self.db.add(alert) self.db.commit() self.db.refresh(alert) return alert
def get_active(self) -> List[AdminAlert]: return self.db.query(AdminAlert).filter(AdminAlert.status == "active").order_by(AdminAlert.created_at.asc()).all()
def get_by_id(self, alert_id: uuid.UUID) -> Optional[AdminAlert]: return self.db.query(AdminAlert).filter(AdminAlert.id == alert_id).first()
def resolve(self, alert_id: uuid.UUID) -> Optional[AdminAlert]: alert = self.get_by_id(alert_id) if alert: alert.status = "resolved" self.db.commit() self.db.refresh(alert) return alert123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.bookings import Bookingfrom backend.app.models.reviews import Review
class BookingRepository: def __init__(self, db: Session): self.db = db
def get_by_id(self, booking_id: uuid.UUID) -> Optional[Booking]: return self.db.query(Booking).filter(Booking.id == booking_id).first()
def get_by_code(self, code: str) -> Optional[Booking]: return self.db.query(Booking).filter(Booking.code == code).first()
def create(self, customer_id: uuid.UUID, worker_id: uuid.UUID, amount: int, job_id: Optional[uuid.UUID] = None) -> Booking: # Generate code (B-24XX) count = self.db.query(Booking).count() code = f"B-{2401 + count}" booking = Booking( code=code, customer_id=customer_id, worker_id=worker_id, job_id=job_id, amount=amount, status="ACCEPTED" ) self.db.add(booking) self.db.commit() self.db.refresh(booking) return booking
def get_by_customer(self, customer_id: uuid.UUID) -> List[Booking]: return self.db.query(Booking).filter(Booking.customer_id == customer_id).order_by(Booking.created_at.desc()).all()
def get_by_worker(self, worker_id: uuid.UUID) -> List[Booking]: return self.db.query(Booking).filter(Booking.worker_id == worker_id).order_by(Booking.created_at.desc()).all()
def get_all(self) -> List[Booking]: return self.db.query(Booking).order_by(Booking.created_at.desc()).all()
def update_status(self, booking_id: uuid.UUID, status: str) -> Optional[Booking]: booking = self.get_by_id(booking_id) if booking: booking.status = status self.db.commit() self.db.refresh(booking) return booking
def add_review(self, booking_id: uuid.UUID, reviewer_id: uuid.UUID, reviewee_id: uuid.UUID, rating: int, comment: Optional[str] = None) -> Review: review = Review( booking_id=booking_id, reviewer_id=reviewer_id, reviewee_id=reviewee_id, rating=rating, comment=comment ) self.db.add(review) self.db.commit() self.db.refresh(review) return review123456789101112131415161718192021222324252627282930313233343536373839404142import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.jobs import Job
class JobRepository: def __init__(self, db: Session): self.db = db
def create(self, customer_id: uuid.UUID, skill_required: str, location: str, budget: int, description: str) -> Job: job = Job( customer_id=customer_id, skill_required=skill_required, location=location, budget=budget, description=description, status="POSTED" ) self.db.add(job) self.db.commit() self.db.refresh(job) return job
def get_by_id(self, job_id: uuid.UUID) -> Optional[Job]: return self.db.query(Job).filter(Job.id == job_id).first()
def get_all(self, skill: Optional[str] = None) -> List[Job]: query = self.db.query(Job) if skill and skill != "All": query = query.filter(Job.skill_required == skill) return query.order_by(Job.created_at.desc()).all()
def get_by_customer(self, customer_id: uuid.UUID) -> List[Job]: return self.db.query(Job).filter(Job.customer_id == customer_id).order_by(Job.created_at.desc()).all()
def update_status(self, job_id: uuid.UUID, status: str) -> Optional[Job]: job = self.get_by_id(job_id) if job: job.status = status self.db.commit() self.db.refresh(job) return job1234567891011121314151617181920212223242526272829303132333435363738394041424344import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.roster import RosterWorker
class RosterRepository: def __init__(self, db: Session): self.db = db
def create(self, mediator_id: uuid.UUID, name: str, skill: str, phone_status: str = "IVR only", status: str = "Available", commission: int = 0) -> RosterWorker: worker = RosterWorker( mediator_id=mediator_id, name=name, skill=skill, phone_status=phone_status, status=status, commission=commission ) self.db.add(worker) self.db.commit() self.db.refresh(worker) return worker
def get_by_mediator(self, mediator_id: uuid.UUID) -> List[RosterWorker]: return self.db.query(RosterWorker).filter(RosterWorker.mediator_id == mediator_id).order_by(RosterWorker.created_at.desc()).all()
def get_by_id(self, worker_id: uuid.UUID) -> Optional[RosterWorker]: return self.db.query(RosterWorker).filter(RosterWorker.id == worker_id).first()
def update_status(self, worker_id: uuid.UUID, status: str) -> Optional[RosterWorker]: worker = self.get_by_id(worker_id) if worker: worker.status = status self.db.commit() self.db.refresh(worker) return worker
def add_commission(self, worker_id: uuid.UUID, amount: int) -> Optional[RosterWorker]: worker = self.get_by_id(worker_id) if worker: worker.commission += amount self.db.commit() self.db.refresh(worker) return worker12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.users import User, WorkerProfile, CustomerProfile
class UserRepository: def __init__(self, db: Session): self.db = db
def get_by_id(self, user_id: uuid.UUID) -> Optional[User]: return self.db.query(User).filter(User.id == user_id).first()
def get_by_phone(self, phone: str) -> Optional[User]: return self.db.query(User).filter(User.phone == phone).first()
def create_customer(self, name: str, phone: str, city: str = "Jaipur") -> User: user = User(name=name, phone=phone, role="customer", city=city) self.db.add(user) self.db.flush() # get user id customer_profile = CustomerProfile(user_id=user.id, wallet_balance=8200) self.db.add(customer_profile) self.db.commit() self.db.refresh(user) return user
def create_worker( self, name: str, phone: str, skill: str, rate: int, city: str = "Jaipur", map_x: int = 50, map_y: int = 50 ) -> User: user = User(name=name, phone=phone, role="worker", city=city) self.db.add(user) self.db.flush() # Calculate simulated distance from customer (center 50, 50) import math dist = round(math.sqrt((map_x - 50)**2 + (map_y - 50)**2) / 15, 1) or 1.2 worker_profile = WorkerProfile( user_id=user.id, skill=skill, rate=rate, distance=dist, map_x=map_x, map_y=map_y ) self.db.add(worker_profile) self.db.commit() self.db.refresh(user) return user
def get_all_users(self) -> List[User]: return self.db.query(User).all()
def get_all_workers( self, skill: Optional[str] = None, radius: Optional[float] = None, online_only: bool = False ) -> List[User]: query = self.db.query(User).join(WorkerProfile).filter(User.role == "worker") if skill and skill != "All": query = query.filter(WorkerProfile.skill == skill) if online_only: query = query.filter(WorkerProfile.online == True) if radius: query = query.filter(WorkerProfile.distance <= radius) return query.all()
def update_user_status(self, user_id: uuid.UUID, is_active: bool) -> Optional[User]: user = self.get_by_id(user_id) if user: user.is_active = is_active self.db.commit() self.db.refresh(user) return user
def delete_user(self, user_id: uuid.UUID) -> bool: user = self.get_by_id(user_id) if user: self.db.delete(user) self.db.commit() return True return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import uuidfrom typing import List, Optionalfrom sqlalchemy.orm import Sessionfrom backend.app.models.wallet import WalletTransactionfrom backend.app.models.users import CustomerProfile, User
class WalletRepository: def __init__(self, db: Session): self.db = db
def get_customer_profile(self, user_id: uuid.UUID) -> Optional[CustomerProfile]: return self.db.query(CustomerProfile).filter(CustomerProfile.user_id == user_id).first()
def update_balance(self, user_id: uuid.UUID, amount_change: int) -> int: """Update customer wallet balance and return the new balance.""" profile = self.get_customer_profile(user_id) if not profile: # Create a customer profile dynamically if it doesn't exist profile = CustomerProfile(user_id=user_id, wallet_balance=0) self.db.add(profile) self.db.flush() profile.wallet_balance += amount_change self.db.commit() return profile.wallet_balance
def add_transaction( self, user_id: uuid.UUID, label: str, amount: int, type_: str, booking_id: Optional[uuid.UUID] = None ) -> WalletTransaction: tx = WalletTransaction( user_id=user_id, booking_id=booking_id, label=label, amount=amount, type=type_ ) self.db.add(tx) self.db.commit() self.db.refresh(tx) return tx
def get_user_transactions(self, user_id: uuid.UUID) -> List[WalletTransaction]: return self.db.query(WalletTransaction).filter(WalletTransaction.user_id == user_id).order_by(WalletTransaction.created_at.desc()).all()DockerfileAdded+19
alembic.iniAdded+149
app/__init__.pyAdded+1
app/__pycache__/__init__.cpython-314.pycAdded
app/__pycache__/main.cpython-314.pycAdded
app/core/__init__.pyAdded+1
app/core/__pycache__/__init__.cpython-314.pycAdded
app/core/__pycache__/config.cpython-314.pycAdded
app/core/__pycache__/database.cpython-314.pycAdded
app/core/__pycache__/security.cpython-314.pycAdded
app/core/__pycache__/seeding.cpython-314.pycAdded
app/core/config.pyAdded+20
app/core/database.pyAdded+29
app/core/security.pyAdded+35
app/core/seeding.pyAdded+191
app/main.pyAdded+81
app/models/__init__.pyAdded+24
app/models/__pycache__/__init__.cpython-314.pycAdded
app/models/__pycache__/alerts.cpython-314.pycAdded
app/models/__pycache__/base.cpython-314.pycAdded
app/models/__pycache__/bookings.cpython-314.pycAdded
app/models/__pycache__/jobs.cpython-314.pycAdded
app/models/__pycache__/notifications.cpython-314.pycAdded
app/models/__pycache__/reviews.cpython-314.pycAdded
app/models/__pycache__/roster.cpython-314.pycAdded
app/models/__pycache__/users.cpython-314.pycAdded
app/models/__pycache__/wallet.cpython-314.pycAdded
app/models/alerts.pyAdded+10
app/models/base.pyAdded+14
app/models/bookings.pyAdded+20
app/models/jobs.pyAdded+17
app/models/notifications.pyAdded+15
app/models/reviews.pyAdded+20
app/models/roster.pyAdded+17
app/models/users.pyAdded+48
app/models/wallet.pyAdded+17
app/repositories/__init__.pyAdded+15
app/repositories/__pycache__/__init__.cpython-314.pycAdded
app/repositories/__pycache__/alerts.cpython-314.pycAdded
app/repositories/__pycache__/bookings.cpython-314.pycAdded
app/repositories/__pycache__/jobs.cpython-314.pycAdded
app/repositories/__pycache__/roster.cpython-314.pycAdded
app/repositories/__pycache__/users.cpython-314.pycAdded
app/repositories/__pycache__/wallet.cpython-314.pycAdded
app/repositories/alerts.pyAdded+34
app/repositories/bookings.pyAdded+63
app/repositories/jobs.pyAdded+42
app/repositories/roster.pyAdded+44
app/repositories/users.pyAdded+94
app/repositories/wallet.pyAdded+48