def handle_vote()

in kitsune/wiki/views.py [0:0]


def handle_vote(request, document_slug):
    """Handle both helpful/unhelpful votes and unhelpful surveys."""
    if "revision_id" not in request.POST:
        return HttpResponseBadRequest()

    if request.limited:
        survey_response = render_to_string(
            "wiki/includes/survey_form.html",
            {"response_message": _("Thanks for your feedback!")},
            request,
        )
        return HttpResponse(survey_response)

    if vote_id := request.POST.get("vote_id"):
        # Handle survey submission
        vote = get_object_or_404(HelpfulVote, id=smart_int(vote_id))

        # Only save the survey if there's no already one
        if not vote.metadata.filter(key="survey").exists():
            survey = request.POST.copy()
            survey.pop("vote_id")
            survey.pop("revision_id", None)

            # Save the survey in JSON format, ensuring it doesn't exceed 600 chars
            vote.add_metadata("survey", truncated_json_dumps(survey, 600, "comment"))
        survey_response = render_to_string(
            "wiki/includes/survey_form.html",
            {"response_message": _("Thanks for your feedback!")},
            request,
        )
        return HttpResponse(survey_response)

    # Handle helpful/unhelpful voting
    revision = get_object_or_404(Revision, id=smart_int(request.POST["revision_id"]))

    if not revision.is_approved:
        raise PermissionDenied

    if revision.document.category == TEMPLATES_CATEGORY:
        return HttpResponseBadRequest()

    survey_context = {}

    if not revision.has_voted(request):
        ua = request.META.get("HTTP_USER_AGENT", "")[:1000]  # Limit to 1000 characters
        kwargs = {
            "revision": revision,
            "user_agent": ua,
        }

        if request.user.is_authenticated:
            kwargs["creator"] = request.user
        else:
            kwargs["anonymous_id"] = request.anonymous.anonymous_id

        vote = HelpfulVote.objects.create(**kwargs)
        # Save metadata: referrer and search query (if available)
        for name in ["referrer", "query", "source"]:
            val = request.POST.get(name)
            if val:
                vote.add_metadata(name, val)

        survey_context = {
            "vote_id": vote.id,
            "action_url": reverse("wiki.document_vote", args=[document_slug]),
            "revision_id": revision.id,
            "response_message": "",
        }

        if "helpful" in request.POST:
            vote.helpful = True
            vote.save()
            survey_context.update(
                {
                    "survey_type": "helpful",
                    "survey_heading": _('You voted "Yes 👍" Please tell us more'),
                    "survey_options": [
                        {"value": "article-accurate", "text": _("Article is accurate")},
                        {
                            "value": "article-easy-to-understand",
                            "text": _("Article is easy to understand"),
                        },
                        {"value": "article-helpful-visuals", "text": _("The visuals are helpful")},
                        {
                            "value": "article-informative",
                            "text": _("Article provided the information I needed"),
                        },
                        {"value": "other", "text": _("Other")},
                    ],
                }
            )
        else:
            survey_context.update(
                {
                    "survey_type": "unhelpful",
                    "survey_heading": _('You voted "No 👎" Please tell us more'),
                    "survey_options": [
                        {"value": "article-inaccurate", "text": _("Article is inaccurate")},
                        {"value": "article-confusing", "text": _("Article is confusing")},
                        {
                            "value": "article-not-helpful-visuals",
                            "text": _("Missing, unclear, or unhelpful visuals"),
                        },
                        {
                            "value": "article-not-informative",
                            "text": _("Article didn't provide the information I needed"),
                        },
                        {"value": "other", "text": _("Other")},
                    ],
                }
            )

    if request.headers.get("HX-Request") and survey_context:
        survey_html = render_to_string("wiki/includes/survey_form.html", survey_context, request)
        response = HttpResponse(survey_html)
        response["HX-Trigger"] = json.dumps({"closeSurveyWidgets": {"url": request.path}})
        return response
    return HttpResponseRedirect(revision.document.get_absolute_url())