|
| 1 | +from django.db import transaction |
| 2 | +from django.db.models import Count, Prefetch, Q, QuerySet |
| 3 | + |
| 4 | +from rest_framework.exceptions import ValidationError |
| 5 | + |
| 6 | +from partner_programs.models import PartnerProgram, PartnerProgramProject |
| 7 | +from partner_programs.serializers import ProgramProjectFilterRequestSerializer |
| 8 | +from partner_programs.utils import filter_program_projects_by_field_name |
| 9 | +from projects.models import Project |
| 10 | +from project_rates.models import Criteria, ProjectExpertAssignment, ProjectScore |
| 11 | +from project_rates.serializers import ProjectScoreCreateSerializer |
| 12 | +from users.models import Expert |
| 13 | +from vacancy.mapping import ProjectRatedParams, MessageTypeEnum |
| 14 | +from vacancy.tasks import send_email |
| 15 | + |
| 16 | + |
| 17 | +class MaxProjectRatesReached(Exception): |
| 18 | + def __init__(self, max_project_rates: int): |
| 19 | + self.max_project_rates = max_project_rates |
| 20 | + super().__init__("max project rates reached for this program") |
| 21 | + |
| 22 | + |
| 23 | +def get_rate_program(program_id: int) -> PartnerProgram: |
| 24 | + return PartnerProgram.objects.get(pk=program_id) |
| 25 | + |
| 26 | + |
| 27 | +def extract_project_rate_filters(method: str, data) -> dict: |
| 28 | + """ |
| 29 | + Accept filters from JSON body to mirror /partner_programs/<id>/projects/filter/: |
| 30 | + {"filters": {"case": ["Кейс 1"]}} |
| 31 | + """ |
| 32 | + if method != "POST": |
| 33 | + return {} |
| 34 | + |
| 35 | + body_filters = data.get("filters") if isinstance(data, dict) else {} |
| 36 | + return body_filters if isinstance(body_filters, dict) else {} |
| 37 | + |
| 38 | + |
| 39 | +def get_projects_for_rate_queryset( |
| 40 | + *, |
| 41 | + program: PartnerProgram, |
| 42 | + user, |
| 43 | + field_filters: dict, |
| 44 | +) -> QuerySet[Project]: |
| 45 | + filters_serializer = ProgramProjectFilterRequestSerializer( |
| 46 | + data={"filters": field_filters} |
| 47 | + ) |
| 48 | + filters_serializer.is_valid(raise_exception=True) |
| 49 | + validated_filters = filters_serializer.validated_data.get("filters", {}) |
| 50 | + |
| 51 | + try: |
| 52 | + program_projects_qs = filter_program_projects_by_field_name( |
| 53 | + program, validated_filters |
| 54 | + ) |
| 55 | + except ValueError as e: |
| 56 | + raise ValidationError({"filters": str(e)}) |
| 57 | + |
| 58 | + project_ids = program_projects_qs.values_list("project_id", flat=True) |
| 59 | + |
| 60 | + scores_prefetch = Prefetch( |
| 61 | + "scores", |
| 62 | + queryset=ProjectScore.objects.filter( |
| 63 | + criteria__partner_program=program |
| 64 | + ).select_related("user"), |
| 65 | + to_attr="_program_scores", |
| 66 | + ) |
| 67 | + |
| 68 | + projects_qs = Project.objects.filter(draft=False, id__in=project_ids) |
| 69 | + if program.is_distributed_evaluation: |
| 70 | + projects_qs = projects_qs.filter( |
| 71 | + expert_assignments__partner_program=program, |
| 72 | + expert_assignments__expert__user=user, |
| 73 | + ) |
| 74 | + |
| 75 | + return ( |
| 76 | + projects_qs |
| 77 | + .annotate( |
| 78 | + rated_count=Count( |
| 79 | + "scores__user", |
| 80 | + filter=Q(scores__criteria__partner_program=program), |
| 81 | + distinct=True, |
| 82 | + ) |
| 83 | + ) |
| 84 | + .prefetch_related(scores_prefetch) |
| 85 | + .distinct() |
| 86 | + ) |
| 87 | + |
| 88 | + |
| 89 | +def submit_project_scores(*, user, project_id: int, data) -> None: |
| 90 | + rating_data, criteria_ids, program = _prepare_project_score_data( |
| 91 | + user=user, |
| 92 | + project_id=project_id, |
| 93 | + data=data, |
| 94 | + ) |
| 95 | + |
| 96 | + serializer = ProjectScoreCreateSerializer( |
| 97 | + data=rating_data, |
| 98 | + criteria_to_get=criteria_ids, |
| 99 | + many=True, |
| 100 | + ) |
| 101 | + serializer.is_valid(raise_exception=True) |
| 102 | + |
| 103 | + scores_qs = ProjectScore.objects.filter( |
| 104 | + project_id=project_id, |
| 105 | + criteria__partner_program=program, |
| 106 | + ) |
| 107 | + user_has_scores = scores_qs.filter(user_id=user.id).exists() |
| 108 | + |
| 109 | + if program.max_project_rates: |
| 110 | + distinct_raters = scores_qs.values("user_id").distinct().count() |
| 111 | + if not user_has_scores and distinct_raters >= program.max_project_rates: |
| 112 | + raise MaxProjectRatesReached(program.max_project_rates) |
| 113 | + |
| 114 | + with transaction.atomic(): |
| 115 | + ProjectScore.objects.bulk_create( |
| 116 | + [ProjectScore(**item) for item in serializer.validated_data], |
| 117 | + update_conflicts=True, |
| 118 | + update_fields=["value"], |
| 119 | + unique_fields=["criteria", "user", "project"], |
| 120 | + ) |
| 121 | + |
| 122 | + project = Project.objects.select_related("leader").get(id=project_id) |
| 123 | + _send_project_rated_email(project=project, program=program) |
| 124 | + |
| 125 | + |
| 126 | +def _prepare_project_score_data(*, user, project_id: int, data) -> tuple[list, list, PartnerProgram]: |
| 127 | + rating_data = [dict(criterion) for criterion in data] |
| 128 | + criteria_ids = [criterion["criterion_id"] for criterion in rating_data] |
| 129 | + |
| 130 | + criteria_qs = Criteria.objects.filter(id__in=criteria_ids).select_related( |
| 131 | + "partner_program" |
| 132 | + ) |
| 133 | + partner_program_ids = ( |
| 134 | + criteria_qs.values_list("partner_program_id", flat=True).distinct() |
| 135 | + ) |
| 136 | + if not criteria_qs.exists(): |
| 137 | + raise ValueError("Criteria not found") |
| 138 | + if partner_program_ids.count() != 1: |
| 139 | + raise ValueError("All criteria must belong to the same program") |
| 140 | + |
| 141 | + program = criteria_qs.first().partner_program |
| 142 | + Expert.objects.get(user__id=user.id, programs=program) |
| 143 | + |
| 144 | + for criterion in rating_data: |
| 145 | + criterion["user"] = user.id |
| 146 | + criterion["project"] = project_id |
| 147 | + criterion["criteria"] = criterion.pop("criterion_id") |
| 148 | + |
| 149 | + if not PartnerProgramProject.objects.filter( |
| 150 | + partner_program=program, |
| 151 | + project_id=project_id, |
| 152 | + ).exists(): |
| 153 | + raise ValueError("Project is not linked to the program") |
| 154 | + |
| 155 | + if program.is_distributed_evaluation and not ProjectExpertAssignment.objects.filter( |
| 156 | + partner_program=program, |
| 157 | + project_id=project_id, |
| 158 | + expert__user_id=user.id, |
| 159 | + ).exists(): |
| 160 | + raise ValueError("you are not assigned to rate this project") |
| 161 | + |
| 162 | + return rating_data, criteria_ids, program |
| 163 | + |
| 164 | + |
| 165 | +def _send_project_rated_email(*, project: Project, program: PartnerProgram) -> None: |
| 166 | + send_email.delay( |
| 167 | + ProjectRatedParams( |
| 168 | + message_type=MessageTypeEnum.PROJECT_RATED.value, |
| 169 | + user_id=project.leader.id, |
| 170 | + project_name=project.name, |
| 171 | + project_id=project.id, |
| 172 | + schema_id=2, |
| 173 | + program_name=program.name, |
| 174 | + ) |
| 175 | + ) |
0 commit comments