import uuid from datetime import datetime, timezone from sqlalchemy import DateTime, func from sqlalchemy.ext.asyncio import AsyncSession from sqlmodel import Field, SQLModel, select def _now() -> datetime: return datetime.now(timezone.utc) class HiringCosts(SQLModel, table=True): __tablename__ = "hiring_costs" id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) job_post_id: uuid.UUID | None = Field(default=None, foreign_key="job_posts.id") # Source attribution (REQ-ANL-09): spend tagged to a channel feeds the # cost-per-application column of source performance; untagged spend only # ever feeds cost-per-hire. source_channel_id: int | None = Field(default=None, foreign_key="source_channels.id") cost_type: str = Field(default="other") amount: float = Field(default=0.0) currency: str = Field(default="USD") incurred_at: datetime = Field(default_factory=_now, sa_type=DateTime(timezone=True)) description: str | None = Field(default=None) created_by: uuid.UUID = Field(foreign_key="users.id") created_at: datetime = Field(default_factory=_now, sa_type=DateTime(timezone=True)) updated_at: datetime = Field(default_factory=_now, sa_type=DateTime(timezone=True)) @staticmethod def _as_uuid(record_id) -> uuid.UUID | None: if record_id in (None, ""): return None try: return uuid.UUID(str(record_id)) except ValueError: return None @classmethod async def get_by_id(cls, session: AsyncSession, record_id): uid = cls._as_uuid(record_id) if uid is None: return None result = await session.execute(select(cls).where(cls.id == uid)) return result.scalars().first() @classmethod async def fetch_costs( cls, session: AsyncSession, *, job_post_id=None, from_date=None, to_date=None, top: int | None = None, skip: int = 0, ): statement = select(cls) if job_post_id is not None: uid = cls._as_uuid(job_post_id) if uid is not None: statement = statement.where(cls.job_post_id == uid) if from_date is not None: statement = statement.where(cls.incurred_at >= from_date) if to_date is not None: statement = statement.where(cls.incurred_at < to_date) count_statement = select(func.count()).select_from(statement.subquery()) total = (await session.execute(count_statement)).scalar_one() statement = statement.order_by(cls.incurred_at.desc()) if skip: statement = statement.offset(skip) if top is not None: statement = statement.limit(top) result = await session.execute(statement) return list(result.scalars().all()), total @classmethod async def insert_cost(cls, session: AsyncSession, fields: dict): row = cls(**fields) session.add(row) await session.commit() return await cls.get_by_id(session, row.id) @classmethod def scoped_to_job(cls, statement, department=None, recruiter_id=None): if not department and not recruiter_id: return statement from job.job_post.models import JobPosts statement = statement.outerjoin(JobPosts, cls.job_post_id == JobPosts.id) if department: statement = statement.where(JobPosts.department == department) rid = cls._as_uuid(recruiter_id) if rid is not None: statement = statement.where(JobPosts.has_recruiter(rid)) return statement @classmethod async def sum_amount(cls, session: AsyncSession, *, from_date=None, to_date=None, department=None, recruiter_id=None): statement = select(func.coalesce(func.sum(cls.amount), 0.0)) if from_date is not None: statement = statement.where(cls.incurred_at >= from_date) if to_date is not None: statement = statement.where(cls.incurred_at < to_date) statement = cls.scoped_to_job(statement, department, recruiter_id) result = await session.execute(statement) return float(result.scalar_one() or 0.0) @classmethod async def sum_by_source_channel( cls, session: AsyncSession, *, from_date=None, to_date=None, department=None, recruiter_id=None, ): statement = select( cls.source_channel_id, func.coalesce(func.sum(cls.amount), 0.0), ).where(cls.source_channel_id.is_not(None)) if from_date is not None: statement = statement.where(cls.incurred_at >= from_date) if to_date is not None: statement = statement.where(cls.incurred_at < to_date) statement = cls.scoped_to_job(statement, department, recruiter_id) statement = statement.group_by(cls.source_channel_id) result = await session.execute(statement) return {channel_id: float(total or 0.0) for channel_id, total in result.all()} import users.models as _users_models # noqa: E402, F401