Пример #1
0
def organization_vote(request, pk, action):
    if not FeatureFlag.objects.filter(flag="enable_org_approval",
                                      is_enabled=True).exists():
        raise PermissionDenied

    try:
        org = Organization.objects.get(pk=pk,
                                       status=Organization.STATUS.pending)
    except Organization.DoesNotExist:
        pass
    else:
        if action == "r":
            org.rejection_message = unquote(
                request.GET.get("rejection-message", ""))
            org.status = Organization.STATUS.rejected

            if org.rejection_message:
                org.save()
                utils.send_email(
                    template="org_rejected",
                    context=Context({
                        "representative": org.legal_representative_name,
                        "name": org.name,
                        "rejection_message": org.rejection_message,
                    }),
                    subject="Cerere de inscriere respinsa",
                    to=org.email,
                )
            else:
                messages.error(request,
                               _("You must write a rejection message."))
        elif action == "a":
            try:
                org.status = Organization.STATUS.accepted
                org.save()
            except IntegrityError as exc:
                if 'duplicate key value violates unique constraint "accounts_user_email_key"' in str(
                        exc):
                    messages.error(
                        request,
                        _("An organization with the same email address is already registered."
                          ))

            current_site = get_current_site(request)
            protocol = "https" if request.is_secure() else "http"
            utils.send_email(
                template="org_approved",
                context=Context({
                    "representative":
                    org.legal_representative_name,
                    "name":
                    org.name,
                    "reset_url":
                    f"{protocol}://{current_site.domain}{reverse('password_reset')}",
                }),
                subject="Cerere de inscriere aprobata",
                to=org.email,
            )
    finally:
        return redirect("ngo-detail", pk=pk)
Пример #2
0
    def get_success_message(self, cleaned_data):
        authorized_groups = [ADMIN_GROUP_NAME, DSU_GROUP_NAME, FFC_GROUP_NAME]

        for user in User.objects.filter(groups__name__in=authorized_groups):
            cleaned_data["base_path"] = f"{self.request.scheme}://{self.request.META['HTTP_HOST']}"
            utils.send_email(
                template="mail/new_ngo.html", context=cleaned_data, subject="[RO HELP] ONG nou", to=user.email
            )

        return super().get_success_message(cleaned_data)
Пример #3
0
    def get_success_message(self, cleaned_data):
        ngo = self._get_ngo()
        need = self.get_object()
        base_path = f"{self.request.scheme}://{self.request.META['HTTP_HOST']}"

        for user in ngo.users.all():
            utils.send_email(
                template="mail/new_helper.html",
                context={"helper": cleaned_data, "need": need, "ngo": ngo, "base_path": base_path},
                subject="[RO HELP] Mesaj nou pentru {} ".format(need.title.replace("\n", ""))[:50],
                to=user.email,
            )

        return super().get_success_message(cleaned_data)
Пример #4
0
def send_confirm_email_to_committee(request, candidate, to_email):
    current_site = get_current_site(request)
    protocol = "https" if request.is_secure() else "http"

    confirmation_link_path = reverse("candidate-detail", args=(candidate.pk, ))
    confirmation_link = f"{protocol}://{current_site.domain}{confirmation_link_path}"

    utils.send_email(
        template="confirmation",
        context=Context({
            "candidate": candidate.name,
            "status": Candidate.STATUS[candidate.status],
            "confirmation_link": confirmation_link,
        }),
        subject=f"[VOTONG] Confirmare candidat: {candidate.name}",
        to=to_email,
    )
Пример #5
0
def candidate_vote(request, pk):
    if not FeatureFlag.objects.filter(flag="enable_candidate_voting",
                                      is_enabled=True).exists():
        raise PermissionDenied

    try:
        candidate = Candidate.objects.get(
            pk=pk,
            org__status=Organization.STATUS.accepted,
            status=Candidate.STATUS.accepted,
            is_proposed=True)
        vote = CandidateVote.objects.create(user=request.user,
                                            candidate=candidate)
    except Exception:
        raise PermissionDenied

    if settings.VOTE_AUDIT_EMAIL:
        current_site = get_current_site(request)
        protocol = "https" if request.is_secure() else "http"
        utils.send_email(
            template="vote_audit",
            context=Context({
                "org":
                vote.user.orgs.first().name,
                "candidate":
                vote.candidate.name,
                "timestamp":
                vote.created.isoformat(),
                "org_link":
                f"{protocol}://{current_site.domain}{vote.user.orgs.first().get_absolute_url()}",
                "candidate_link":
                f"{protocol}://{current_site.domain}{vote.candidate.get_absolute_url()}",
            }),
            subject=f"[VOTONG] Vot candidat: {vote.candidate.name}",
            to=settings.VOTE_AUDIT_EMAIL,
        )

    return redirect("candidate-detail", pk=pk)
Пример #6
0
    def vote(self, request, queryset):
        activate(request.LANGUAGE_CODE)
        if request.POST.get("post") == "yes":
            authorized_groups = [
                ADMIN_GROUP_NAME, DSU_GROUP_NAME, FFC_GROUP_NAME
            ]
            user = request.user
            base_path = f"{request.scheme}://{request.META['HTTP_HOST']}"
            user_groups = user.groups.values_list("name", flat=True)
            entity = list(set(authorized_groups).intersection(user_groups))[0]

            for ngo_request in queryset:
                vote = RegisterNGORequestVote.objects.create(
                    user=user,
                    ngo_request=ngo_request,
                    entity=entity,
                    vote=request.POST.get("vote"),
                    motivation=request.POST.get("motivation"),
                )

                notify_groups = list(set(authorized_groups) - set(user_groups))
                e = 0
                for group in Group.objects.filter(name__in=notify_groups):
                    for user in group.user_set.all():
                        e += utils.send_email(
                            template="mail/new_vote.html",
                            context={
                                "vote": vote,
                                "user": user,
                                "base_path": base_path
                            },
                            subject=
                            f"[RO HELP] {entity} a votat pentru {ngo_request.name}",
                            to=user.email,
                        )
                self.message_user(
                    request,
                    _("Vote succesfully registered. {} email{} sent to others admins"
                      .format(e, pluralize(e, str(_("s"))))),
                    level=messages.INFO,
                )
        else:
            context = dict(
                title=f"Vot ONG",
                opts=self.model._meta,
                queryset=queryset,
                form=RegisterNGORequestVoteForm,
                action_checkbox_name=helpers.ACTION_CHECKBOX_NAME,
            )
            return render(request, "admin/vote_motivation.html", context)
Пример #7
0
def organization_vote(request, pk, action):
    if not FeatureFlag.objects.filter(flag="enable_org_approval", is_enabled=True).exists():
        raise PermissionDenied

    try:
        org = Organization.objects.get(pk=pk, status=Organization.STATUS.pending)
    except Organization.DoesNotExist:
        pass
    else:
        if action == "r":
            org.status = Organization.STATUS.rejected
            org.save()
            utils.send_email(
                template="org_rejected",
                context=Context({"representative": org.legal_representative_name, "name": org.name,}),
                subject="Cerere de inscriere respinsa",
                to=org.email,
            )
        elif action == "a":
            org.status = Organization.STATUS.accepted
            org.save()
            current_site = get_current_site(request)
            protocol = "https" if request.is_secure() else "http"
            utils.send_email(
                template="org_approved",
                context=Context(
                    {
                        "representative": org.legal_representative_name,
                        "name": org.name,
                        "reset_url": f"{protocol}://{current_site.domain}{reverse('password_reset')}",
                    }
                ),
                subject="Cerere de inscriere aprobata",
                to=org.email,
            )
    finally:
        return redirect("ngo-detail", pk=pk)
Пример #8
0
def confirm(request, order):
    order = PaymentOrder.objects.get(order_id=order)
    ngo = order.ngo
    error_code = 0
    error_type = Request.CONFIRM_ERROR_TYPE_NONE
    clean_response = False
    error_message = ""
    payment_response = PaymentResponse()
    payment_response.payment_order = order
    base_path = f"{request.scheme}://{request.META['HTTP_HOST']}"
    if request.method == "POST":
        """calea catre cheia privata aflata pe serverul dumneavoastra"""
        private_key_path = order.ngo.mobilpay_private_key.url
        """verifica daca exista env_key si data in request"""
        env_key = request.POST.get("env_key")
        env_data = request.POST.get("data")
        """daca env_key si env_data exista, se incepe decriptarea"""
        if env_key is not None and len(
                env_key) > 0 and env_data is not None and len(env_data) > 0:
            try:
                """env_key si data trebuie parsate pentru ca vin din url, se face cu function unquote din urllib
                in cazul in care decriptarea nu este reusita, raspunsul v-a contine o eroare si mesajul acesteia
                """
                obj_pm_request = Request().factory_from_encrypted(
                    unquote(env_key), unquote(env_data), private_key_path)
                """obiectul notify contine metode pentru setarea si citirea proprietatilor"""
                notify = obj_pm_request.get_notify()
                if int(notify.errorCode) == 0:
                    payment_response.action = notify.action
                    """
                    orice action este insotit de un cod de eroare si de un mesaj de eroare. Acestea pot fi citite
                    folosind error_code = obj_pm_req.get_notify().errorCode
                    respectiv error_message = obj_pm_req.get_notify()errorMessage
                    pentru a identifica ID-ul comenzii pentru care primim rezultatul platii folosim
                    order_id = obj_pm_req.get_order_id()
                    """
                    if notify.action == "confirmed":
                        """ 
                        cand action este confirmed avem certitudinea ca banii au plecat din contul posesorului de
                        card si facem update al starii comenzii si livrarea produsului
                        update DB, SET status = "confirmed/captured"
                        """
                        order.success = True
                        order.save()
                        error_message = notify.errorMessage
                        for user in order.ngo.users.all():
                            utils.send_email(
                                template="mail/new_donation.html",
                                context={"base_path": base_path},
                                subject="[RO HELP] Donație inregistrată",
                                to=user.email,
                            )
                        utils.send_email(
                            template="mail/new_payment.html",
                            context={
                                "ngo": ngo,
                                "base_path": base_path
                            },
                            subject="[RO HELP] Plată confirmată",
                            to=order.email,
                        )
                    elif notify.action == "confirmed_pending":
                        """ 
                        cand action este confirmed_pending inseamna ca tranzactia este in curs de verificare
                        antifrauda. Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o
                        noua notificare pentru o actiune de confirmare sau anulare.
                        update DB, SET status = "pending"
                        """
                        error_message = notify.errorMessage
                    elif notify.action == "paid_pending":
                        """
                        cand action este paid_pending inseamna ca tranzactia este in curs de verificare. 
                        Nu facem livrare/expediere. In urma trecerii de aceasta verificare se va primi o noua 
                        notificare pentru o actiune de confirmare sau anulare.
                        update DB, SET status = "pending"
                        """
                        error_message = notify.errorMessage
                    elif notify.action == "paid":
                        """cand action este paid inseamna ca tranzactia este in curs de procesare.
                        Nu facem livrare/expediere. In urma trecerii de aceasta procesare se va primi o noua
                        notificare pentru o actiune de confirmare sau anulare.
                        update DB, SET status = 'open/preauthorized'"""
                        error_message = notify.errorMessage
                    elif notify.action == "canceled":
                        """cand action este canceled inseamna ca tranzactia este anulata. Nu facem livrare/expediere.
                        update DB, SET status = 'canceled'"""
                        error_message = notify.errorMessage
                    elif notify.action == "credit":
                        """
                        cand action este credit inseamna ca banii sunt returnati posesorului de card.
                        Daca s-a facut deja livrare, aceasta trebuie oprita sau facut un reverse.
                        update DB, SET status = 'refunded'
                        """
                        error_message = notify.errorMessage
                    else:
                        error_type = Request.CONFIRM_ERROR_TYPE_PERMANENT
                        error_code = Request.ERROR_CONFIRM_INVALID_ACTION
                        error_message = "mobilpay_refference_action paramaters is invalid"
                else:
                    """  # update DB, SET status = "rejected"""
                    clean_response = True
                    error_message = notify.errorMessage
                    error_type = Request.CONFIRM_ERROR_TYPE_TEMPORARY
                    error_code = notify.errorCode
            except Exception as e:
                clean_response = True
                error_type = Request.CONFIRM_ERROR_TYPE_TEMPORARY
                error_message, error_code = e.args[0], e.args[1]
        else:
            error_type = Request.CONFIRM_ERROR_TYPE_PERMANENT
            error_code = Request.ERROR_CONFIRM_INVALID_POST_PARAMETERS
            error_message = "mobilpay.ro posted invalid parameters"
    else:
        error_type = Request.CONFIRM_ERROR_TYPE_PERMANENT
        error_code = Request.ERROR_CONFIRM_INVALID_POST_METHOD
        error_message = "invalid request method for payment confirmation"
    payment_response.error_code = error_code
    payment_response.error_type = error_type
    payment_response.error_message = error_message
    payment_response.save()
    if clean_response:
        error_code = 0
        error_type = Request.CONFIRM_ERROR_TYPE_NONE
        error_message = ""
    crc = Crc(error_code, error_type, error_message).create_crc()
    return HttpResponse(crc.toprettyxml(indent="\t", encoding="utf-8"),
                        content_type="text/xml")