linkedin2/utils/clients.py

177 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import joinedload
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from model.database import Client, AppliedJob, Job
async def get_filtered_jobs(db: AsyncSession, user_job_titles, minimum_annual_salary, salary_currency,
user_location_type, user_locations, user_levels, user_job_types): #
# Строим фильтры для каждого из параметров пользователя
filters = []
# Фильтрация по job_title (примерное совпадение)
if user_job_titles:
title_filters = [Job.job_title.ilike(f"%{title}%") for title in user_job_titles]
filters.append(or_(*title_filters))
# Фильтрация по minimum_annual_salary (если указано)
if minimum_annual_salary is not None:
filters.append(Job.minimum_annual_salary >= minimum_annual_salary)
# Фильтрация по salary_currency (если указано)
if salary_currency is not None:
filters.append(Job.salary_currency == salary_currency)
# Фильтрация по location_type (если указано)
if user_location_type:
filters.append(Job.location_type == user_location_type)
# Фильтрация по location (разделяем по каждому городу)
if user_locations:
location_filters = [Job.location.ilike(location) for location in user_locations]
filters.append(or_(*location_filters))
# Фильтрация по job_level (если указаны)
if user_levels:
filters.append(Job.job_level.in_(user_levels))
# Фильтрация по job_type (если указаны)
if user_job_types:
filters.append(Job.job_type.in_(user_job_types))
# Выполняем запрос с применением всех фильтров
query = select(Job).filter(*filters)
# Выполняем асинхронный запрос
result = await db.execute(query)
# Получаем все результаты
jobs = result.scalars().all()
return jobs
async def upsert_client(db: AsyncSession, user_id: str, user_login: str, user_nicename: str, user_email: str, phone: str, json_data: str):
# Проверяем, существует ли клиент с таким логином или email
async with db.begin():
result = await db.execute(
select(Client).filter((Client.id == user_id))# | (Client.user_email == user_email))
)
client = result.scalars().first() # Получаем первый результат или None
if client:
# Если клиент существует, обновляем его данные
client.user_nicename = user_login
client.phone = phone
client.json_data = json_data
# Можно добавить другие поля для обновления
try:
await db.commit() # Применяем изменения в базе данных
await db.refresh(client) # Обновляем объект в Python
return client
except IntegrityError:
await db.rollback() # В случае ошибки откатываем изменения
raise
else:
# Если клиента нет, создаем нового
new_client = Client(
user_login=user_login,
user_nicename=user_nicename,
user_email=user_email,
json_data=json_data,
)
db.add(new_client)
try:
await db.commit() # Сохраняем нового клиента в базе данных
await db.refresh(new_client) # Обновляем объект в Python
return new_client
except IntegrityError:
await db.rollback() # В случае ошибки откатываем изменения
raise
async def del_jobs(db: AsyncSession, user_id: str):
jobs = await db.execute(
select(AppliedJob).where(
AppliedJob.client_id == user_id,
or_(AppliedJob.status == "Scheduled", AppliedJob.status.is_(None))
)
)
jobs = jobs.scalars().all()
for job in jobs:
await db.delete(job)
await db.commit()
async def add_jobs(db: AsyncSession, user_id: str):
# Фильтруем вакансии по переданным параметрам
query = select(Job).filter(Job.active == 3)
result = await db.execute(query)
jobs = result.scalars().all() # Получаем список вакансий
if not jobs:
return {"message": "Нет вакансий по данному фильтру"}
# Создаём записи в AppliedJob
applied_jobs = [
AppliedJob(client_id=user_id, job_id=job.job_id)
for job in jobs
]
db.add_all(applied_jobs) # Добавляем в сессию
await db.commit() # Фиксируем изменения
return {"message": f"{len(applied_jobs)} вакансий добавлено в AppliedJob"}
async def get_applied_jobs(db, client_id: int):
query = (
select(AppliedJob)
.options(joinedload(AppliedJob.job)) # Подгружаем данные о вакансии
.where(AppliedJob.client_id == client_id)
)
result = await db.execute(query)
applied_jobs = result.scalars().all()
if not applied_jobs:
return {"message": "Нет откликов на вакансии"}
jobs_list = []
for applied in applied_jobs:
job = applied.job # Получаем объект Job из отношения AppliedJob.job
jobs_list.append({
"id": job.job_id,
"title": job.job_title,
"company": job.job_company,
"postedDate": job.date_posted,
"location": job.location,
"jobType": job.job_type,
"salary": f"${job.minimum_annual_salary}K" if job.minimum_annual_salary else "Not specified",
"level": job.job_level,
"status": applied.status if applied.status else "Scheduled",
"requiredSkills": "",
"aboutJob": job.about,
"jobLink": job.link
})
print(jobs_list)
return jobs_list