def post(self, request, **kwargs):
        company = self.get_object()
        user_mesage = request.POST.get('message')

        subject = 'Delete company message.'

        body = render_to_string(
            'entrepreneur/emails/delete_object_message.html',
            {
                'title': subject,
                'company': company,
                'user': request.user.get_full_name,
                'message': user_mesage,
            },
        )

        # Send email to the registered email Address
        # of the platform administrators.
        send_email(
            subject=subject,
            body=body,
            mail_to=settings.ADMIN_EMAILS,
        )

        return HttpResponse('success')
Exemplo n.º 2
0
    def form_valid(self, form):
        # Create membership object.
        membership = form.save(commit=False)
        membership.building = self.get_object()
        membership.is_active = True
        membership.save()

        messages.success(self.request, _('Membersía creada exitosamente.'))

        # Send notification email about new membership
        # to the user.
        subject = _('Se ha creado una nueva membresía en una copropiedad '
                    ' para usted.')

        body = render_to_string(
            'buildings/administrative/roles/membership_email.html',
            {
                'title': subject,
                'from': self.request.user,
                'membership': membership,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[membership.user.email],
        )

        return redirect(
            'buildings:memberships_list',
            self.get_object().id,
        )
    def get(self, request, **kwargs):
        user = request.user
        subject = _('Active su cuenta')

        body = render_to_string(
            'accounts/signup/verify_email.html',
            {
                'title': subject,
                'user': user,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[user.email],
        )

        user.sent_verification_emails += 1
        user.save()

        messages.success(
            self.request,
            _('Gracias por registrarse.Hemos enviado un '
              'correo electrónico para verificar su cuenta.'),
        )

        return redirect('home')
    def form_valid(self, form):
        user = form.save()
        user.is_active = True
        user.save()

        subject = _('Active su cuenta')

        body = render_to_string(
            'accounts/signup/verify_email.html',
            {
                'title': subject,
                'user': user,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[user.email],
        )

        messages.success(
            self.request,
            _('Gracias por registrarse.Hemos enviado un '
              'correo electrónico para verificar su cuenta.'),
        )

        return super().form_valid(form)
Exemplo n.º 5
0
    def form_valid(self, form):
        # Update membership object.
        membership = form.save()

        messages.success(
            self.request,
            _('Membresía actualizada exitosamente.'),
        )

        # Send email to user about his membership update.
        subject = _('Su membresía ha sido editada')

        body = render_to_string(
            'buildings/administrative/roles/membership_email.html',
            {
                'title': subject,
                'from': self.request.user,
                'membership': membership,
                'update': True,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[membership.user.email],
        )

        return super().form_valid(form)
Exemplo n.º 6
0
    def form_valid(self, form):
        subject = form.cleaned_data['subject']
        phone = form.cleaned_data['phone']
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        message = form.cleaned_data['message']

        # Create email body with the information provided
        # by the users.
        body = render_to_string(
            'corporative/emails/user_message.html',
            {
                'title': subject,
                'phone': phone,
                'name': name,
                'email': email,
                'message': message,
                'base_url': settings.BASE_URL,
            },
        )

        # Send email to the registered email Address
        # of the platform administrators.
        send_email(
            subject=subject,
            body=body,
            mail_to=settings.ADMIN_EMAILS,
        )

        return redirect('contact_form_success')
Exemplo n.º 7
0
    def form_valid(self, form):
        company = self.get_object()

        company_score = CompanyScore.objects.create(
            user=self.request.user,
            company=company,
            score=form.cleaned_data['score'],
            comment=form.cleaned_data['comment'],
        )

        for membership in company.administratormembership_set.filter(
                status=ACTIVE_MEMBERSHIP, ):
            subject = '{} has been scored by an user.'.format(company)
            # Create platform notification.
            UserNotification.objects.create(
                notification_type=NEW_COMPANY_SCORE,
                noty_to=membership.admin.user,
                venture_to=company,
                description=subject,
            )

            if membership.admin.new_company_scores_notifications:
                body = render_to_string(
                    'account/emails/new_company_score.html',
                    {
                        'title': subject,
                        'user_to': membership.admin.user,
                        'company_score': company_score,
                        'base_url': settings.BASE_URL,
                    },
                )

                send_email(
                    subject=subject,
                    body=body,
                    mail_to=[membership.admin.user.email],
                )

        if company.get_votes_quantity == 1:
            message = '1 user has scored {}.'.format(company.name)
        else:
            message = '{0} user have scored {1}.'.format(
                company.get_votes_quantity,
                company.name,
            )

        return JsonResponse({
            'new_score':
            company.get_score,
            'message':
            message,
            'score_line':
            render_to_string(
                'entrepreneur/company_score_line.html',
                {
                    'company_score': company_score,
                },
            )
        })
Exemplo n.º 8
0
    def form_valid(self, form):
        # Save legal item.
        legal_item = form.save()

        # Notify users field. If the value is True, all
        # platform users will be notified about the change.
        notify_users = form.cleaned_data['notify_users']

        if notify_users:
            # Update the date in which the legal item was updated.
            legal_item.updated_at = timezone.now()

            # Notify all users about the new legal item update.
            for user in User.objects.all():
                if legal_item.slug == 'privacy-policy':
                    user.accepted_privacy_policy = False
                    notification_type = UPDATED_PRIVACY_POLICY
                    description = 'Our privacy policy has been updated.'

                elif legal_item.slug == 'user-agreement':
                    user.accepted_terms = False
                    notification_type = UPDATED_TERMS
                    description = 'Our user agreement has been updated.'

                user.save()

                # Create notification about legal item update for all
                # registered users.
                UserNotification.objects.create(
                    notification_type=notification_type,
                    noty_to=user,
                    description=description,
                )

                # Create email to notify all users about legal item update.
                body = render_to_string(
                    'corporative/emails/legal_item_update.html',
                    {
                        'title': description,
                        'user_to': user,
                        'notification_type': notification_type,
                        'base_url': settings.BASE_URL,
                    },
                )

                # Send email.
                send_email(
                    subject=description,
                    body=body,
                    mail_to=[user.email],
                )

        legal_item.save()

        messages.success(self.request,
                         _('legal item has been successfully updated.'))

        return super().form_valid(form)
    def post(self, request, **kwargs):
        company = self.get_object()

        transfer_form = TransferCompany(
            request.POST,
            instance=company,
        )

        if transfer_form.is_valid():
            owner_membership = AdministratorMembership.objects.get(
                venture=company, admin=request.user.professionalprofile)

            # Change role for old owner.
            owner_membership.role = QJANE_ADMIN
            owner_membership.save()

            new_owner = transfer_form.cleaned_data['owner']
            new_owner_membership = AdministratorMembership.objects.get(
                venture=company, admin=new_owner)

            # Set role for new owner.
            new_owner_membership.role = OWNER
            new_owner_membership.save()

            # Change company owner.
            company.owner = new_owner
            company.save()

            subject = _('New role in {}'.format(company))

            # Create platform notification.
            notification = UserNotification.objects.create(
                notification_type=TRANSFERED_COMPANY,
                venture_from=company,
                noty_to=new_owner_membership.admin.user,
                description=subject,
                created_by=owner_membership.admin,
            )

            body = render_to_string(
                'entrepreneur/emails/company_transfer.html',
                {
                    'title': subject,
                    'notification': notification,
                    'base_url': settings.BASE_URL,
                },
            )

            send_email(
                subject=subject,
                body=body,
                mail_to=[new_owner_membership.admin.user.email],
            )

            return HttpResponse('success')

        return HttpResponse('fail')
Exemplo n.º 10
0
def test_send_email(mocker, email_logs, faker):
    from app.tasks import mailext
    return_val = {'id': faker.isbn13()}
    send_mock = mocker.patch.object(mailext,
                                    'send_email',
                                    return_value=return_val)
    email = EmailLog.select().first()
    send_email(email.id)
    assert send_mock.called == 1
    assert EmailLog[email.id].status == EmailLog.SEND_MAILGUN
    assert EmailLog[email.id].email_id == return_val['id']
Exemplo n.º 11
0
def new_applicants_notifications():
    for job_offer in JobOffer.objects.filter(status=JOB_STATUS_ACTIVE):
        applicants_record = job_offer.applicants_record
        current_applicants = job_offer.applicant_set.count()

        new_applicants = current_applicants - applicants_record

        if new_applicants:
            # admins_m = admin memberships
            admins_m = job_offer.venture.administratormembership_set.filter(
                status=ACTIVE_MEMBERSHIP, )

            for admin_m in admins_m:
                # Send email notification.
                if admin_m.admin.new_applicants_notifications:
                    subject = '{0} new applicants to your job offer.'.format(
                        new_applicants, )

                    body = render_to_string(
                        'entrepreneur/emails/new_applicants.html',
                        {
                            'title': subject,
                            'job_offer': job_offer,
                            'new_applicants': new_applicants,
                            'base_url': settings.BASE_URL,
                        },
                    )

                    send_email(
                        subject=subject,
                        body=body,
                        mail_to=[admin_m.admin.user.email],
                    )

                description = 'New applicants for "{}".'.format(job_offer, )

                # Create platform notification.
                UserNotification.objects.create(
                    notification_type=NEW_APPLICANTS,
                    noty_to=admin_m.admin.user,
                    job_offer=job_offer,
                    venture_from=job_offer.venture,
                    description=description,
                )

                logger.info(
                    'Created notifications for %s',
                    admin_m.admin.user.email,
                )

        job_offer.applicants_record = current_applicants
        job_offer.save()
    def post(self, request, **kwargs):
        email = request.POST.get('email')

        # Send notification email about new membership
        # to the user.
        subject = _('Invitación para crear cuenta.')

        body = render_to_string(
            'accounts/signup/email_invitation.html',
            {
                'title': subject,
                'from': self.request.user,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[email],
        )

        return HttpResponse("success")
Exemplo n.º 13
0
    def delete(self, request, *args, **kwargs):
        messages.success(self.request, _('Membresía eliminada exitosamente.'))

        # Send email to user about his membership delete.
        subject = _('Su membresía ha sido eliminada')

        body = render_to_string(
            'buildings/administrative/roles/membership_email.html',
            {
                'title': subject,
                'from': self.request.user,
                'membership': self.get_object(),
                'delete': True,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[self.get_object().user.email],
        )

        return super().delete(request, *args, **kwargs)
Exemplo n.º 14
0
    def post(self, *args, **kwargs):
        # Get formset post data.
        owner_update_formset = ConfirmOwnerUpdateFormSet(
            self.request.POST,
            prefix='owner_update',
            queryset=UnitDataUpdate.objects.filter(
                unit__building=self.get_object(),
            ),
        )

        for form in owner_update_formset:
            if form.is_valid():
                unit_data_object = form.save(commit=False)

                # Get request value. If True, an email
                # will be sent to the unit registered owners.
                update = form.cleaned_data['update']

                if update and unit_data_object.unit.owner_has_email:
                    # Owners update form must be available.
                    unit_data_object.enable_owners_update = True
                    unit_data_object.owners_update_activated_at = timezone.now()

                    # Generate random string to add security to the
                    # owners update link.
                    key = get_random_string(length=30)
                    # This key is used to decrypt the generated url
                    # to activate the update owners data form.
                    unit_data_object.owners_update_key = key
                    unit_data_object.save()

                    unit = unit_data_object.unit

                    # Filter owners by email value. Only send
                    # email if owners have a registered email.
                    for owner in unit.owner_set.exclude(
                        email__isnull=True,
                    ).exclude(email__exact=''):
                        # Send email.
                        subject = _('Actualizacón de datos de propietarios')

                        update_url = reverse(
                            'buildings:owners_update_form',
                            args=[
                                unit_data_object.id,
                                unit_data_object.owners_data_key,
                            ],
                        )

                        body = render_to_string(
                            'buildings/administrative/data_update/update_email.html', {
                                'title': subject,
                                'owners_update': True,
                                'unit_data_object': unit_data_object,
                                'update_url': update_url,
                                'base_url': settings.BASE_URL,
                            },
                        )

                        send_email(
                            subject=subject,
                            body=body,
                            mail_to=[owner.email],
                        )

        messages.success(
            self.request,
            _('Se ha solicitado la actualización de datos a'
              ' los propietarios con correo electrónico registrado.')
        )

        return redirect(
            'buildings:data_update_view',
            self.get_object().id,
        )
Exemplo n.º 15
0
    def post(self, *args, **kwargs):
        resident_update_formset = ConfirmResidentUpdateFormSet(
            self.request.POST,
            prefix='resident_update',
            queryset=UnitDataUpdate.objects.filter(
                unit__building=self.get_object(),
            ),
        )

        for form in resident_update_formset:
            if form.is_valid():
                unit_data_object = form.save(commit=False)

                # Get update request value. If True, an email
                # will be sent to the unit registered residents.
                update = form.cleaned_data['update']

                if update and unit_data_object.unit.residents_have_email:
                    # Leaseholder update form must be available.
                    unit_data_object.enable_residents_update = True
                    unit_data_object.residents_update_activated_at = timezone.now()

                    # Activate each item for update.
                    unit_data_object.residents_update = True
                    unit_data_object.visitors_update = True
                    unit_data_object.vehicles_update = True
                    unit_data_object.domestic_workers_update = True
                    unit_data_object.pets_update = True

                    # Generate random string to add security to the
                    # residents update link.
                    key = get_random_string(length=30)
                    # This key is used to decrypt the generated url
                    # to activate the update residents data form.
                    unit_data_object.residents_update_key = key
                    unit_data_object.save()

                    unit = unit_data_object.unit

                    # Create email content.
                    subject = _('Actualizacón de datos de residentes')

                    update_url = reverse(
                        'buildings:residents_update_form',
                        args=[
                            unit_data_object.id,
                            unit_data_object.residents_data_key,
                        ],
                    )

                    # Create email content.
                    body = render_to_string(
                        'buildings/administrative/data_update/update_email.html', {
                            'title': subject,
                            'residents_update': True,
                            'unit_data_object': unit_data_object,
                            'update_url': update_url,
                            'base_url': settings.BASE_URL,
                        },
                    )

                    # Filter residents by email value. Only send
                    # email if residents have a registered email.
                    # First, we are seeking for owners that are
                    # residents of the unit.
                    for resident_owner in unit.owner_set.filter(
                        is_resident=True,
                        email__isnull=False,
                    ).exclude(email__exact=''):
                        # Send email.
                        send_email(
                            subject=subject,
                            body=body,
                            mail_to=[resident_owner.email],
                        )

                    # Filter leaseholders by email value. Only send
                    # email if residents have a registered email.
                    # We're seeking for leaseholders in this forloop.
                    for leaseholder in unit.leaseholder_set.filter(
                        email__isnull=False,
                    ).exclude(email__exact=''):
                        # Send email.
                        send_email(
                            subject=subject,
                            body=body,
                            mail_to=[leaseholder.email],
                        )

        messages.success(
            self.request,
            _('Se ha solicitado la actualización de datos a'
              ' los residentes con correo electrónico registrado.')
        )

        return redirect(
            'buildings:data_update_view',
            self.get_object().id,
        )
    def form_valid(self, form):
        company = self.get_object()

        if company.is_inactive:
            raise Http404

        job_offer = form.save(commit=False)
        slug = slugify(job_offer.title)

        if JobOffer.objects.filter(slug=slug):
            random_string = get_random_string(length=6)
            slug = '{0}-{1}'.format(
                slug,
                random_string.lower(),
            )

        job_offer.venture = company
        job_offer.slug = slug
        job_offer.save()

        job_offer.industry_categories = form.cleaned_data[
            'industry_categories']
        job_offer.save()

        # Create potential applicants notifications.
        potential_applicants = ProfessionalProfile.objects.filter(
            industry_categories__in=job_offer.industry_categories.all(),
        ).distinct().exclude(id__in=company.get_active_administrator_ids)

        if job_offer.country:
            potential_applicants = potential_applicants.filter(
                user__country=job_offer.country, )

        if job_offer.city:
            potential_applicants = potential_applicants.filter(
                user__city=job_offer.city, )

        description = 'New job offer that may interest you published by {}.'.format(
            company, )

        for profile in potential_applicants.all():
            UserNotification.objects.create(
                notification_type=NEW_JOB_OFFER,
                noty_to=profile.user,
                venture_from=company,
                job_offer=job_offer,
                description=description,
                created_by=self.request.user.professionalprofile,
            )

            if profile.email_jobs_notifications:
                subject = description

                body = render_to_string(
                    'account/emails/potenitial_job_offer.html',
                    {
                        'title': subject,
                        'profile': profile,
                        'job_offer': job_offer,
                        'base_url': settings.BASE_URL,
                    },
                )

                send_email(
                    subject=subject,
                    body=body,
                    mail_to=[profile.user.email],
                )

        return HttpResponseRedirect(
            reverse(
                'entrepreneur:job_offers_list',
                args=[self.get_object().slug],
            ))
Exemplo n.º 17
0
def new_received_messages():
    """
    Peridoic task that runs all Mondays, Wednesdays and Fridays at 7:00 am.
    This tasks checks if users have new private messages and creates a
    notification to inform them about new messages.
    """
    for professionalprofile in ProfessionalProfile.objects.filter(
            has_new_messages=True,
            email_messages_notifications=True,
    ):
        # Get new messages
        new_messages = UserMessage.objects.filter(
            user_to=professionalprofile.user,
            unread=True,
        )

        messages_dict = {}

        for new_message in new_messages:
            if new_message.company_from:
                # Creating key to group messages from companies
                # to display them in the email detail. The used
                # format is c_company_id.
                key = 'c_{}'.format(new_message.company_from.id)

                if key in messages_dict:
                    messages_dict[key]['messages'].append(new_message)
                else:
                    contact_dict = {
                        'name': new_message.company_from.name,
                        'messages': [new_message],
                    }

                    messages_dict[key] = contact_dict
            else:
                # Creating key to group messages from users
                # to display them in the email detail. The used
                # format is u_user_id.
                key = 'u_{}'.format(new_message.user_from.id)

                if key in messages_dict:
                    messages_dict[key]['messages'].append(new_message)
                else:
                    contact_dict = {
                        'name': new_message.user_from.get_full_name,
                        'messages': [new_message],
                    }

                    messages_dict[key] = contact_dict

        subject = 'You have {0} new messages in your inbox'.format(
            new_messages.count(), )

        body = render_to_string(
            'account/emails/new_messages.html',
            {
                'title': subject,
                'to_user': True,
                'receiver': professionalprofile.user,
                'messages_dict': messages_dict,
                'base_url': settings.BASE_URL,
            },
        )

        send_email(
            subject=subject,
            body=body,
            mail_to=[professionalprofile.user.email],
        )

        professionalprofile.has_new_messages = False
        professionalprofile.save()

    for company in Venture.objects.filter(has_new_messages=True, ):
        # Get new messages
        new_messages = UserMessage.objects.filter(
            company_to=company,
            unread=True,
        )

        messages_dict = {}

        for new_message in new_messages:
            # Creating key to group messages from users
            # to display them in the email detail. The used
            # format is u_user_id.
            key = 'u_{}'.format(new_message.user_from.id)

            if key in messages_dict:
                messages_dict[key]['messages'].append(new_message)
            else:
                contact_dict = {
                    'name': new_message.user_from.get_full_name,
                    'messages': [new_message],
                }

                messages_dict[key] = contact_dict

        description = '{0} has {1} new messages'.format(
            company,
            new_messages.count(),
        )

        # Create new message notification for company administrators.
        for membership in company.administratormembership_set.filter(
                status=ACTIVE_MEMBERSHIP,
                role__in=(OWNER, QJANE_ADMIN),
        ):
            user = membership.admin.user

            if user.professionalprofile.new_company_messages_notifications:
                subject = description

                body = render_to_string(
                    'account/emails/new_messages.html',
                    {
                        'title': subject,
                        'company_to': company,
                        'receiver': user,
                        'messages_dict': messages_dict,
                        'base_url': settings.BASE_URL,
                    },
                )

                send_email(
                    subject=subject,
                    body=body,
                    mail_to=[user.email],
                )

        company.has_new_messages = False
        company.save()