Example #1
0
def edit_post(request, pk):
    post = Post.objects.get(pk=pk)

    if post.approved or request.user != post.author:
        return redirect('/board/')

    tags = Tag.objects.all()
    role = get_role(request.user)
    posttags = post.tags.split(",")
    menu_type = 'general'

    form = PostForm(instance=post)
    if request.method == 'POST':
        form = PostForm(instance=post, data=request.POST, files=request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            if role == "coordinator" or role == "admin":
                post.status = 1
            else:
                post.status = 3
            post.save()

            short_title = (post.title[:25] +
                           '..') if len(post.title) > 25 else post.title
            details = (post.content[:100] +
                       '..') if len(post.content) > 100 else post.content
            description = u'Board updated - {}'.format(short_title)

            notification = create_notification_from(post)
            notification.type = 4
            notification.creator = request.user
            notification.description = description
            notification.details = details
            notification.save()

            coordinators_ids = (ConsultantProfile.objects.prefetch_related(
                'consultant').get_coordinator_by_market(
                    post.market).is_active().values_list('consultant__id',
                                                         flat=True))

            bulk_receiver_creation(notification, coordinators_ids)

            if role == "coordinator" or role == "admin":
                messages.success(request, 'Post successfully edited.')
            else:
                messages.success(
                    request,
                    'Post successfully edited. An administrator will review it shortly.'
                )

            return redirect('board:board')
        else:
            messages.error(
                request,
                'There was a problem editing the post. Please correct the errors and try again.'
            )

    edit = True

    return render(request, 'board/create.html', locals())
Example #2
0
def notify_aps(request, registration_id):
    registration = Registration.objects.prefetch_related('costumer').filter(pk=registration_id).first()
    if not registration:
        return JsonResponse({'registration': 'not found'}, status=404)

    users_ids = get_user_model().objects.filter(
        programprofile__programs_base__in=registration.prospect_programs.values_list('program_base_id', flat=True)
    ).values_list('id', flat=True)

    description = u'New Lead'
    details = u'New Lead {}'.format(
        registration.costumer.get_full_name()
    )

    if len(users_ids) > 0:
        notification = create_notification_from(registration)
        notification.creator = request.user
        notification.description = description
        notification.details = details
        notification.type = 7
        notification.save()

        bulk_receiver_creation(notification, users_ids)

    return JsonResponse({}, status=200)
Example #3
0
def payment_create(request):
    request_data = json.loads(request.body)
    registration_id = request_data.get('registration_id', '')
    statementApproved = request_data.get('statementApproved', '')

    registration = Registration.objects.filter(pk=registration_id).first()
    if not registration:
        return JsonResponse({}, status=400)

    payments_amount = RegistrationPayment.objects.filter(
        registration=registration).count()
    # if payments_amount > 7:
    #     return JsonResponse({}, status=400)

    if statementApproved:
        payment = RegistrationPayment.objects.create(registration=registration,
                                                     notification_send=True)
        student = registration.costumer
        notification = create_notification_from(registration)
        notification.type = 15
        notification.creator = request.user
        notification.description = 'Payment applied to ' + student + ' account.'
        notification.details = 'Please verify the statement in the students profile.'
        notification.save()

        coordinators_ids = (
            ConsultantProfile.objects.prefetch_related('consultant').filter(
                consultant=registration.consultant).is_active().values_list(
                    'consultant__id', flat=True))

        bulk_receiver_creation(notification, coordinators_ids)

        for user_id in coordinators_ids:
            consultant = get_user_model().objects.filter(pk=user_id).get()

        mail_context = {
            'common_name':
            consultant.person.first_name + ' ' + consultant.person.last_name,
            'student': student
        }
        email_consultant = consultant.person.email

        subject = 'New notification in your ACS profile'
        send_mail_wrapper(subject,
                          'notifications/emails/new_notification.html',
                          mail_context, [email_consultant])
    else:
        payment = RegistrationPayment.objects.create(registration=registration)

    response = {
        'id': payment.pk,
        'deposit_amount': payment.deposit_amount,
        'deposit_date': payment.deposit_date,
        'details': payment.details,
    }

    return JsonResponse(response, status=200)
Example #4
0
def create_post(request):
    role = get_role(request.user)

    tags = Tag.objects.all()
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            market = get_user_market_or_main_market(request.user)

            post = form.save(commit=False)
            post.author = request.user
            post.market = market
            if role == "coordinator" or role == "admin":
                post.status = 1

            post.save()

            short_title = (post.title[:25] +
                           '..') if len(post.title) > 25 else post.title
            details = (post.content[:100] +
                       '..') if len(post.content) > 100 else post.content
            description = u'New board created - {}'.format(short_title)

            notification = create_notification_from(post)
            notification.type = 3
            notification.creator = request.user
            notification.description = description
            notification.details = details
            notification.save()

            coordinators_ids = (
                ConsultantProfile.objects.prefetch_related('consultant').
                get_coordinator_by_market(market).is_active().values_list(
                    'consultant__id', flat=True))

            bulk_receiver_creation(notification, coordinators_ids)

            if role == "coordinator" or role == "admin":
                messages.success(request, 'Post successfully created.')
            else:
                messages.success(
                    request,
                    'Post successfully created. An administrator will review it shortly.'
                )
            return redirect('/board/')
        else:
            messages.error(
                request,
                'There was a problem creating the post. Please correct the errors and try again.'
            )

    if role == 'corporate':
        menu_type = 'general'

    return render(request, 'board/create.html', locals())
Example #5
0
def new_visas_start(context):
    details = u"The visa process has been accepted for {} registration".format(
        context['registration'].costumer.get_full_name())
    description = u"New visas process"

    notification = create_notification_from(context['registration'])
    notification.type = 6
    notification.creator = context['creator']
    notification.description = description
    notification.details = details
    notification.save()

    bulk_receiver_creation(notification, context['receiver_ids'])
Example #6
0
def review(request):
    request_l = json.loads(request.body)
    pk = request_l.get('id', 0)

    preprogram = PreProgram.objects.filter(pk=pk).get()

    if preprogram.first_review:
        keys = [
            'type', 'degree', 'city', 'age',
            'financeComment', 'financeContact', 'comment', 'general',
            'year', 'semester', 'term',
        ]

        for key in keys:
            field_review, created = FieldReview.objects.get_or_create(key=key, preprogram=preprogram)
            if created:
                if not field_review.review:
                    review_m = Review.objects.create(preprogram=preprogram)
                    field_review.review = review_m
                field_review.save()

        requirements = PreRequirement.objects.filter(preprogram=preprogram, review__isnull=True)
        for requirement in requirements:
            requirement.review = Review.objects.create(preprogram=preprogram)
            requirement.save()

    preprogram.review = True
    preprogram.first_review = False
    preprogram.save()

    notification = create_notification_from(preprogram)
    notification.creator = request.user
    notification.description = u'New program review'
    notification.details = u'New review for program: {}'.format(preprogram.name)
    notification.type = 1
    notification.save()

    users = get_user_model().objects.filter(
        groups__name='corporate admin',
    ).distinct()

    receiver = []
    for user in users:
        notification_receiver = NotificationReceiver()
        notification_receiver.receiver = user
        notification_receiver.notification = notification
        receiver.append(notification_receiver)

    NotificationReceiver.objects.bulk_create(receiver)

    return JsonResponse({}, status=200)
Example #7
0
def reimbursements_review(request):
    request_data = json.loads(request.body)

    pk = request_data.get('id', 0)

    reimbursement = Reimbursement.objects.prefetch_related('items').filter(
        pk=pk).first()
    if not reimbursement:
        return JsonResponse({}, status=400)

    items = reimbursement.items.all()

    validator = Validator()

    reimbursement_form = ReimbursementStrictForm({
        'account_id':
        reimbursement.account_id,
        'location':
        reimbursement.location,
        'spending_justification':
        reimbursement.spending_justification,
        'date_from':
        reimbursement.date_from,
        'date_to':
        reimbursement.date_to,
    })

    if not reimbursement_form.is_valid():
        validator.errors.errors = get_form_errors(reimbursement_form, {})

    if len(items) == 0:
        validator.errors.add('no_field_errors', 'Must be at least one item')
    else:
        item_errors = []
        for item in items:
            item_form = ItemStrictForm(item.as_dict())
            errors = {'id': item.pk}

            if not item_form.is_valid():
                errors = get_form_errors(item_form, errors)

            if not item.attachment:
                errors['file'] = ['File required.']

            if len(errors) > 1:
                item_errors.append(errors)

        if len(item_errors) > 0:
            validator.errors.errors['items'] = item_errors

    if validator.has_errors():
        return JsonResponse(validator.get_errors(), status=400)

    main_currency = Currency.objects.filter(main=True).first()

    for item in reimbursement.items.all():
        if item.currency != main_currency:
            exchange = ExchangeRate.objects.filter(
                start_date__lte=item.date,
                end_date__gte=item.date,
                target=item.currency).first()

            exchange_rate = exchange.rate if exchange else Decimal('0.00')
            item.exchange_rate = exchange_rate
            item.total = (item.amount * exchange_rate).quantize(
                Decimal("0.01"), decimal.ROUND_HALF_DOWN)

        else:
            item.exchange_rate = Decimal('1.00')
            item.total = item.amount

        item.save()

    reimbursement.reject_reason = ''
    reimbursement.date_sent = dt.now()
    reimbursement.status = 3
    reimbursement.save()

    notification = create_notification_from(reimbursement)
    notification.creator = request.user
    notification.description = u'New reimbursement to review'
    notification.details = u'New reimbursement from {}'.format(
        request.user.person.get_full_name())
    notification.type = 12
    notification.save()

    user_ids = get_user_model().objects.filter(
        Q(groups__name="corporate admin")
        | Q(groups__name="finances")).values_list('id', flat=True)

    bulk_receiver_creation(notification, user_ids)

    return JsonResponse({})
Example #8
0
def reimbursements_status_update(request):
    role = get_role(request.user)

    if role not in ['corporate', 'finance']:
        return JsonResponse({}, status=400)

    request_data = json.loads(request.body)

    pk = request_data.get('id', 0)
    need_exchange = to_boolean(request_data.get('need_exchange', '0'))

    reimbursement = Reimbursement.objects.prefetch_related('items').filter(
        pk=pk).first()
    if not reimbursement:
        return JsonResponse({}, status=400)

    if ('status' not in request_data
            or (request_data['status'] == 2 and 'reason' not in request_data)
            or request_data['status'] not in [1, 2]):
        return JsonResponse({}, status=400)

    if request_data['status'] == 1 and need_exchange:
        validator = Validator()

        item_errors = []
        for item in reimbursement.items.all():
            errors = {'id': item.pk}

            if item.exchange_rate <= Decimal(0):
                errors['exchange_rate'] = ['Must be greater than zero.']

            if len(errors) > 1:
                item_errors.append(errors)

        if len(item_errors) > 0:
            validator.errors.errors['items'] = item_errors

        if validator.has_errors():
            return JsonResponse(validator.get_errors(), status=400)

    notification = create_notification_from(reimbursement)
    notification.creator = request.user

    if request_data['status'] == 2:
        notification.type = 13
        notification.description = u'Reimbursement rejected'
        notification.details = u'Rejected reason: {}'.format(
            request_data['reason'])

        reimbursement.status = 2
        reimbursement.reject_reason = request_data['reason']
    else:
        notification.type = 14
        notification.description = u'Reimbursement approved'
        notification.details = u'Reimbursement has been approved'

        reimbursement.status = 1
        reimbursement.date_approved = dt.now()

    reimbursement.save()

    notification.save()

    notification_receiver = NotificationReceiver()
    notification_receiver.receiver_id = reimbursement.creator_id
    notification_receiver.notification = notification
    notification_receiver.save()

    return JsonResponse({})
Example #9
0
def review(request):
    request_data = request.POST

    pre_program_pk = request_data.get('id', '')
    attachments = json.loads(request_data.get('attachments', '[]'))
    contacts = json.loads(request_data.get('contacts', '[]'))
    pre_activities_input = json.loads(request_data.get('activities', '[]'))

    pre_program = PreProgram.objects.select_related('program_base').get(pk=pre_program_pk)
    program_base = pre_program.program_base
    user_prepregram = pre_program.user.person.email
    notification = create_notification_from(program_base)
    notification.type = 2
    # notification.description = u'Finished review - {}'.format(
    #     program_base.name
    # )
    notification.description = u'Profile reviewed'
    notification.creator = request.user
    notification.details = ''

    if len(attachments) > 0:
        for a in attachments:
            new_name = a['name']
            pre_attachment = PreAttachment.objects.get(pk=a['id'])

            if pre_attachment.name == new_name:
                continue

            notification.details += u"{} to {}\r\n".format(pre_attachment.name, new_name)

            pre_attachment.name = new_name
            pre_attachment.save()

    if notification.details:
        notification.details = u'The following files were renamed in the revision:\r\n\r\n' + notification.details

    fields = FieldReview.objects.filter(preprogram_id=pre_program_pk).select_related('review')

    pre_program_to_program = PreProgramToProgramBase(pre_program, program_base)
    for field in fields:
        if field.review and field.review.get_status() == 1 and hasattr(pre_program_to_program, field.key):
            getattr(pre_program_to_program, field.key)()
            field.review_id = None
            field.save()
        elif field.review and field.review.get_status() == 0 and hasattr(pre_program_to_program, field.key):
            pre_program.show_errors = True

    pre_program.user = request.user
    pre_program.review = False

    # region attachments
    pre_attachments = PreAttachment.objects.select_related('category').prefetch_related(
        'attachment', 'review',
    ).filter(
        preprogram_id=pre_program_pk
    )

    attachment_url = ['application (online)']
    must_be_unique = ['logo', 'featured image']

    for pre_attachment in pre_attachments:
        unique = False
        if pre_attachment.review:
            status = pre_attachment.review.get_status()
            if status == 1:
                if pre_attachment.deleted_at:
                    pre_attachment.attachment.delete()
                    pre_attachment.review.delete()
                else:
                    program_id = None
                    attachment = pre_attachment.attachment if pre_attachment.attachment else Attachment()

                    if pre_attachment.file:
                        new_file = ContentFile(pre_attachment.file.read())
                        new_file.name = os.path.basename(pre_attachment.file.name)
                        attachment.file = new_file

                    attachment.url = pre_attachment.url
                    attachment.name = pre_attachment.name
                    attachment.active = pre_attachment.active
                    attachment.category = pre_attachment.category
                    attachment.program_base_id = program_base.pk

                    for a in attachments:
                        if a['id'] == pre_attachment.pk and 'market' in a:
                            program_id = a['market']
                            continue

                    if program_id:
                        attachment.program_id = program_id

                    attachment.save()

                    if pre_attachment.category.name.lower() in must_be_unique:
                        unique = True

                    pre_attachment.attachment = attachment
                    pre_attachment.review = None
                    pre_attachment.save()

            elif status == 0:
                pre_program.show_errors = True
        else:
            attachment = pre_attachment.attachment

            if pre_attachment.name != attachment.name:
                attachment.name = pre_attachment.name
                attachment.save()

        if unique:
            Attachment.objects.filter(
                Q(program__program_base_id=program_base.pk) | Q(program_base_id=program_base.pk)
            ).filter(category_id=pre_attachment.category.pk).exclude(pk=pre_attachment.attachment.pk).delete()
    # endregion

    # region requirements
    pre_requirements = PreRequirement.objects.filter(
        preprogram_id=pre_program_pk
    ).select_related('requirement', 'review')
    for pre_requirement in pre_requirements:
        if pre_requirement.review and pre_requirement.review.get_status() == 1:
            if pre_requirement.deleted_at:
                pre_requirement.review.delete()
                pre_requirement.requirement.delete()
            else:
                requirement = pre_requirement.requirement if pre_requirement.requirement else Requirement()
                requirement.name = pre_requirement.name
                requirement.active = pre_requirement.active
                requirement.program_id = None
                requirement.program_base_id = program_base.pk
                requirement.save()

                pre_requirement.review = None
                pre_requirement.requirement = requirement
                pre_requirement.save()
        elif pre_requirement.review and pre_requirement.review.get_status() == 0:
            pre_program.show_errors = True
    # endregion

    # region photos
    pre_photos = PrePhoto.objects.filter(preprogram_id=pre_program.pk).select_related('photo', 'review')
    for pre_photo in pre_photos:
        if pre_photo.review and pre_photo.review.get_status() == 1:
            if pre_photo.deleted_at:
                pre_photo.review.delete()
                pre_photo.photo.delete()
            else:
                new_file = ContentFile(pre_photo.file.read())
                new_file.name = os.path.basename(pre_photo.file.name)

                photo = pre_photo.photo if pre_photo.photo else Photo()
                photo.file = new_file
                photo.program_id = None
                photo.program_base_id = program_base.pk
                photo.save()

                pre_photo.review_id = None
                pre_photo.photo = photo
                pre_photo.save()

        elif pre_photo.review and pre_photo.review.get_status() == 0:
            pre_photo.deleted_at = None
            pre_photo.save()

            pre_program.show_errors = True
    # endregion

    # region websites
    pre_websites = PreWebsite.objects.filter(preprogram_id=pre_program.pk).select_related('website', 'review')
    for pre_website in pre_websites:
        if pre_website.review and pre_website.review.get_status() == 1:
            if pre_website.deleted_at:
                pre_website.review.delete()
                pre_website.website.delete()
            else:
                website = pre_website.website if pre_website.website else Website()
                website.name = pre_website.name
                website.category = pre_website.category
                website.url = pre_website.url
                website.program_id = None
                website.program_base_id = program_base.pk
                website.save()

                pre_website.review_id = None
                pre_website.website = website
                pre_website.save()
        elif pre_website.review and pre_website.review.get_status() == 0:
            if pre_website.deleted_at:
                pre_website.deleted_at = None
                pre_website.save()

            pre_program.show_errors = True
    # endregion

    # region Contact
    contact_change = False
    pre_contacts = PreContact.objects.filter(preprogram_id=pre_program.pk).select_related('contact', 'review')
    for pre_contact in pre_contacts:
        if pre_contact.review and pre_contact.review.get_status() == 1:
            if pre_contact.deleted_at:
                if pre_contact.contact_id:
                    pre_contact.contact.delete()
                    contact_change = True

                pre_contact.delete()
            else:
                program_id = None
                contact = pre_contact.contact if pre_contact.contact else Contact()
                contact.program_base_id = program_base.pk

                for c in contacts:
                    if c['id'] == pre_contact.pk and 'market' in c:
                        program_id = c['market']
                        continue

                if program_id:
                    contact.program_id = program_id

                contact.name = pre_contact.name
                contact.email = pre_contact.email
                contact.position = pre_contact.position
                contact.address = pre_contact.address
                contact.phone = pre_contact.phone
                contact.category = pre_contact.category
                contact.other = pre_contact.other
                contact.active = pre_contact.active
                contact.save()

                pre_contact.program_id = program_id
                pre_contact.review_id = None
                pre_contact.contact = contact
                pre_contact.save()

                contact_change = True
        elif pre_contact.review and pre_contact.review.get_status() == 0:
            pre_program.show_errors = True
    # endregion

    # region Activities
    pre_activities = PreProgramActivitySet.objects.prefetch_related(
        'program_base_activity'
    ).select_related(
        'review'
    ).filter(
        preprogram_id=pre_program.pk
    )
    for pre_activity in pre_activities:
        if pre_activity.review and pre_activity.review.get_status() == 1:
            activity_input = None
            activity_id = pre_activity.activity_id

            for pre_activity_input in pre_activities_input:
                if pre_activity_input['id'] == pre_activity.pk:
                    activity_input = pre_activity_input
                    break

            if not activity_id:
                activity = Activity()

                if activity_input:
                    activity.name = pre_activity.name = activity_input['name']
                else:
                    activity.name = pre_activity.name

                if not activity.name:
                    continue

                activity.save()

                pre_activity.activity_id = activity_id = activity.pk

            if pre_activity.program_base_activity:
                program_base_activity = pre_activity.program_base_activity
            else:
                program_base_activity = ProgramBaseActivitySet()
                program_base_activity.programbase = program_base
                program_base_activity.activity_id = activity_id

            if activity_input:
                program_base_activity.is_active = pre_activity.is_active = activity_input['is_active']
                program_base_activity.extra_cost = pre_activity.extra_cost = activity_input['extra_cost']
            else:
                program_base_activity.is_active = pre_activity.is_active
                program_base_activity.extra_cost = pre_activity.extra_cost

            program_base_activity.save()

            if not pre_activity.program_base_activity_id:
                pre_activity.program_base_activity = program_base_activity

            pre_activity.review_id = None
            pre_activity.save()
        elif pre_contact.review and pre_contact.review.get_status() == 0:
            pre_program.show_errors = True
    # endregion

    Review.objects.filter(preprogram_id=pre_program.pk).filter(
        Q(description__isnull=True) | Q(description='')
    ).delete()

    FieldReview.objects.filter(preprogram_id=pre_program.pk).filter(
        Q(review__description__isnull=True) | Q(review__description='')
    ).delete()

    if notification.details == '':
        # notification.details = u'Excellent, no field has been declined'
        notification.details = u'Your profile has been reviewed by an Ad Astra team member.'

    program_base.date_updates(contact_change, commit=False)
    program_base.save()

    pre_program.save()

    notification.save()

    notify_programs(pre_program, notification)

    mail_context = {
        'detail': 'Your profile has been reviewed by an Ad Astra team member.',
    }
    subject = 'Profile reviewed'
    send_mail_wrapper(
        subject,
        'notifications/emails/new_notification_program_publish.html',
        mail_context,
        [user_prepregram]
    )

    return JsonResponse({}, status=200)