Exemplo n.º 1
0
    def save(self, *args, **kwargs):
        if not (self.full_path is None):
            try:
                from objsys_local.views import set_fields_from_full_path

                set_fields_from_full_path(self)
            except:
                pass
        if not self.id:
            self.obj_created = datetime.utcnow().replace(tzinfo=utc)
        self.obj_last_modified = datetime.utcnow().replace(tzinfo=utc)
        super(UfsObj, self).save(*args, **kwargs)  # Call the "real" save() method.
Exemplo n.º 2
0
def course(request, course_id, template_name='student/course.html'):
    if len(request.user.userprofile.courses.filter(pk=course_id)) > 0:
        course = get_object_or_404(Course, id=course_id)
        documents = Document.objects.filter(course=course).filter(appear_date__lte=datetime.utcnow().replace(tzinfo=utc)).order_by('appear_date')
        return render(request, template_name, {'course': course, 'documents': documents})
    else:
        return HttpResponseRedirect(reverse('main.views.course', kwargs={'course_id': course_id}))
Exemplo n.º 3
0
    def do_step(self):
        print "stepping"
        try:
            # Fetch any outstanding events from the engine process and execute in simulator
            while not self.local_queue.empty():
                action = self.local_queue.get()
                try:
                    self.blueprint.interface.set(action[0], float(action[1]))
                    print "Received action:", action
                except exceptions.ValueError:
                    print "Value '" + str(action[1]) + "' is not convertable to float"

            points = self.blueprint.interface.get_getters()

            self.blueprint.step(stepcount=int(1 / 0.1))

            g = {}
            for point in points:
                if point in BlueprintHandler.getter_blacklist:
                    continue
                g[point] = self.blueprint.interface.get(point)

            for k in g.keys():
                m = Measurement()
                m.bid = self.blueprint.building.buildingID
                m.timestamp = datetime.utcnow().replace(tzinfo=utc)
                m.uuid = k
                m.val = g[k]
                m.save()
        except:
            # print 'error: ', sys.exc_info()
            print "trace: ", traceback.print_exc()
Exemplo n.º 4
0
def add_file(request, course_id, template_name="instructor/addinfo.html", post_add_information_redirect=None):
    course = get_object_or_404(Course, pk=course_id)

    if not course in request.user.userprofile.courses.all():
        return HttpResponseForbidden()

    if request.method == 'POST':
        form1 = MaterialForm(request.POST, request.FILES)
        form2 = DocumentForm(request.POST, request.FILES)
        if form1.is_valid() and form2.is_valid():
            material = form1.save(commit=False)
            file = form2.save(commit=False)
            material.author = request.user
            material.date = datetime.utcnow().replace(tzinfo=utc)
            material.course = course
            material.save()
            file.material = material
            file.save()

            if post_add_information_redirect is None:
                post_add_information_redirect = reverse('instructor.views.course', kwargs={'course_id': course_id})

            return HttpResponseRedirect(post_add_information_redirect)
    else:
        form1 = MaterialForm()
        form2 = DocumentForm()

    return render(request, template_name, {'course': course, 'form1': form1, 'form2': form2})
Exemplo n.º 5
0
def course(request, course_id, template_name='student/course.html'):
    course = get_object_or_404(Course, pk=course_id)
    if course in request.user.userprofile.courses.all():
        materials = Material.objects.filter(course=course).filter(appear_date__lte=datetime.utcnow().replace(tzinfo=utc)).order_by('appear_date')
        videos = Video.objects.filter(material__in=materials)
        infos = Information.objects.filter(material__in=materials)
        documents = Document.objects.filter(material__in=materials)
        return render(request, template_name, {'course': course, 'materials': materials, 'videos': videos, 'infos': infos, 'documents': documents})
    else:
        return HttpResponseRedirect(reverse('main.views.course', kwargs={'course_id': course_id}))
Exemplo n.º 6
0
 def post(self, request):
     serializer = self.serializer_class(data=request.DATA)
     if serializer.is_valid():
         token, created = Token.objects.get_or_create(user=serializer.object['user'])
         if not created:
             token.created = datetime.utcnow()
             token.save()
         return Response({'token': token.key},
                         status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 7
0
    def make_test(self, files):
        context = {
            'config': self.config,
            'when': datetime.utcnow(),
            'request': {
                'method': self.request.method,
                'path': self.request.path,
                'resolved': resolve(self.request.path),
            },
            'response': {
                'status_code': self.response.status_code,
                'headers': [v for k, v in self.response._headers.items()
                            if v[0] not in ('Last-Modified', 'Expires', 'Location')]
            },
            'setup': [],
        }

        if self.config.is_post and self.config.has_get_params:
            context['request']['data'] = dict(self.request.POST)
            # include the QS.
            context['request']['path'] = self.request.get_full_path()
        elif self.config.is_post:
            context['request']['data'] = dict(self.request.POST)
        elif self.config.is_get:
            context['request']['data'] = dict(self.request.GET)

        # Do anything necessary for authenticating users.
        if self.config.is_authenticated:
            context['request']['user'] = self.request.user

        user_for_test = generate_user_for_setup(config=self.config,
                                                context=context)
        context['setup'].append(user_for_test)

        tests_to_run = {
            'status_code': generate_status_code_test,
            'reverse': generate_url_reverse_test,
            'headers': generate_response_headers_test,
            'content_parsed': generate_content_parsing_test,
            'context_data': generate_context_data_test,
        }
        tests_context = {}
        for k, v in tests_to_run.items():
            generated_test = v(config=self.config, request=self.request,
                               response=self.response, context=context)
            if generated_test is not None:
                tests_context[k] = generated_test
        context['tests'] = tests_context
        finalised = TEST_TEMPLATE(context=context)
        last = files.tree[-1]
        assert last.file.endswith('test_{}.py'.format(self.config.magic_number()))
        with open(last.file, 'w+') as f:
            f.write(finalised)
        return last, finalised
Exemplo n.º 8
0
 def authenticate_credentials(self, key):
     try:
         token = self.model.objects.get(key=key)
     except self.model.DoesNotExist:
         raise exceptions.AuthenticationFailed('Invalid token')
     if not token.user.is_active:
         raise exceptions.AuthenticationFailed('User inactive or deleted')
     utc_now = datetime.utcnow().replace(tzinfo=pytz.utc)
     if token.created < utc_now - timedelta(days=settings.MAX_TOKEN_AGE_DAYS):
         raise exceptions.AuthenticationFailed('Token has expired')
     return token.user, tokens
Exemplo n.º 9
0
def crud_bitfund_link(request, project_key, action):
    project = get_object_or_404(Project, key=project_key)
    bitfund = get_object_or_404(Project, id=BITFUND_OWN_PROJECT_ID)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    template_data['giving_to_bitfund'] = project.checkProjectLinkedToBitFund()

    if action == 'donate' :
        initial_data = {'linked_project': bitfund}
        template_data['crud_linked_project_add_form'] = AddLinkedProjectForm(project.id, initial=initial_data)
        template_data['giving_to_bitfund'] = True
        template_data['crud_linked_project_action'] = 'add'
        project.is_refused_to_give_to_bitfund = False
        project.save()
    elif action == 'refuse' :
        project.is_refused_to_give_to_bitfund = True
        project.save()

        return redirect('bitfund.project.views.crud_linked_project', project_key=project_key)


    if project.maintainer_id == request.user.id :
        template_data['project_edit_access'] = True
    else :
        template_data['project_edit_access'] = False

    template_data['refused_to_give_to_bitfund'] = project.is_refused_to_give_to_bitfund

    projects_i_depend_on = (Project_Dependencies.objects
                            .filter(depender_project=project.id)
                            .order_by('sort_order')
                            .prefetch_related('dependee_project')
    )
    template_data['projects_i_depend_on'] = []
    template_data['projects_i_depend_on_count'] = projects_i_depend_on.count()
    for project_i_depend_on in projects_i_depend_on:
        if project_i_depend_on.dependee_project.is_public :
            template_data['projects_i_depend_on'].append({'id': project_i_depend_on.dependee_project.id,
                                                          'key': project_i_depend_on.dependee_project.key,
                                                          'title': project_i_depend_on.dependee_project.title,
                                                          'logo': project_i_depend_on.dependee_project.logo,
                                                          'brief': (project_i_depend_on.brief or ''),
                                                          'amount_sum': project_i_depend_on.redonation_amount,
                                                          'amount_percent': project_i_depend_on.redonation_percent,
                                                          })

    return render_to_response('project/linked_projects/ajax-i_depend_on_projects_list.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 10
0
def budget_edit(request, project_key):
    project = get_object_or_404(Project, key=project_key)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    #BUDGET, pledges, redonations, other sources, donut charts radiants
    template_data['budget'] = _prepare_project_budget_template_data(request, project)

    if request.method == 'POST' :
        template_data['project_form'] = EditProjectForm(data=request.POST, instance=project)
        all_valid = True

        if not template_data['project_form'].is_valid() :
            all_valid = False

        template_data['project_needs'] = []

        project_needs = ProjectNeed.objects.filter(project=project.id).order_by('sort_order')
        for need in project_needs:
            need_template_data = _prepare_need_item_template_data(request, project, need)
            need_template_data['crud_form'] = ProjectNeedForm(request.POST, instance=need, prefix='need-'+str(need.id))
            if not need_template_data['crud_form'].is_valid() :
                all_valid = False

            template_data['project_needs'].append(need_template_data)

        if all_valid :
            template_data['project_form'].save()
            for need_template_data in template_data['project_needs'] :
                if need_template_data['crud_form'].cleaned_data['drop_need'] :
                    need_template_data['crud_form'].instance.delete()
                else :
                    need_template_data['crud_form'].save()

            return redirect('bitfund.project.views.budget_edit', project_key=project.key)
    else :
        template_data['project_form'] = EditProjectForm(instance=project)

        #NEEDS
        template_data['project_needs'] = []
        project_needs = ProjectNeed.objects.filter(project=project.id).order_by('sort_order')
        for need in project_needs :
            need_template_data = _prepare_need_item_template_data(request, project, need)
            need_template_data['crud_form'] = ProjectNeedForm(instance=need, prefix='need-'+str(need.id))
            template_data['project_needs'].append(need_template_data)

    return render_to_response('project/budget/budget_edit.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 11
0
def conference_registration(request):
    if request.method == 'GET' and request.GET:
        form = ConferenceRegistrationForm(request.GET)
        if form.is_valid():
            balance = request.user.balance
            now = datetime.utcnow().replace(tzinfo=utc)
            pay_until = now + timedelta(days=7)
            ids = []
            prefix = ConferenceRegistrationForm.prefix
            for name, count in form.cleaned_data.items():
                if count and name.startswith(prefix):
                    price_id = int(name[len(prefix):])
                    price = get_object_or_404(Price, id=price_id)
                    for i in range(count):
                        tp = TimePeriod(start=now, end=pay_until)
                        tp.save()
                        p = Payment(
                            balance=balance,
                            short_description=price.title,
                            time_to_pay=tp,
                            amount=price.value
                        )
                        p.save()
                        ids.append(p.id)
            formset = PaymentsConfirmFormSet(
                queryset=Payment.objects.filter(id__in=ids))
            for f in formset:
                f.fields['summary'].queryset = Summary.objects.filter(payment__isnull=True, owner=request.user)
            return render(request, 'conferences/conference/register_confirm.html', {
                'formset': formset
            })
        return render(request, 'conferences/conference/register.html', {
            'form': form
        })
    elif request.method == 'POST':
        formset = PaymentsConfirmFormSet(request.POST)
        for f in formset:
            f.fields['summary'].queryset = Summary.objects.filter(payment__isnull=True, owner=request.user)
        if formset.is_valid():
            formset.save()
            return redirect('account')
        return render(request, 'conferences/conference/register_confirm.html', {
            'formset': formset
        })
    else:
        form = ConferenceRegistrationForm()
        return render(request, 'conferences/conference/register.html', {
            'form': form
        })
Exemplo n.º 12
0
def feedback(request):
    if request.method == "POST":
        form = FeedbackForm(request.POST)
        if form.is_valid():
            fb = form.save(commit=False)
            fb.date = datetime.utcnow().replace(tzinfo=utc)
            fb.save()
            messages.success(request, 'Спасибо за ваш отзыв!')
            return redirect('main.views.index')
    else:
        form = FeedbackForm()

    return render(request, 'main/feedback.html', {
        'form': form,
    })
Exemplo n.º 13
0
def add_course(request, template_name='instructor/addcourse.html', add_course_form=AddCourseForm,
               post_course_new_redirect=None):
    if request.method == 'POST':
        form = add_course_form(request.POST, request.FILES)
        if form.is_valid():
            course = form.save(commit=False)
            course.author = request.user
            course.date = datetime.utcnow().replace(tzinfo=utc)
            course.approved = False
            course.save()
            request.user.userprofile.courses.add(course) # # # # #
            if post_course_new_redirect is None:
                post_course_new_redirect = reverse('instructor.views.course', kwargs={'course_id': course.id})
            return HttpResponseRedirect(post_course_new_redirect)
    else:
        form = add_course_form()
    return render(request, template_name, {'form': form})
Exemplo n.º 14
0
def add_need(request, project_key):
    project = get_object_or_404(Project, key=project_key)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    need = ProjectNeed()
    need.project = project
    need.is_public = False
    need.save()

    template_data['need'] = _prepare_need_item_template_data(request, project, need)
    template_data['need']['crud_form'] = ProjectNeedForm(instance=need, prefix='need-'+str(need.id))

    return render_to_response('project/budget/ajax-crud_need_form.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 15
0
def requests(request):
    user = request.user
    contextDic = {}
    request_list = []
    u = datetime.utcnow()
    u = u.replace(tzinfo=pytz.utc)
    userRequests = Request.objects.filter(menteeId=user.id, dateTime__gte=u).order_by('dateTime')
    for reqObj in userRequests:
        obj = {}
        obj['mentorId'] = reqObj.mentorId
        obj['mentorName'] = User.objects.get(id=reqObj.mentorId_id).get_full_name()
        obj['picture'] = User.objects.get(id=reqObj.mentorId_id).user_profile.picture

        obj['dateTime'] = reqObj.dateTime.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(user.user_profile.timezone))
        obj["is_approved"] = reqObj.is_approved
        obj["callType"] = reqObj.callType
        obj["is_rescheduled"] = reqObj.is_rescheduled
        obj["duration"] = reqObj.duration
        obj["requestDate"] = reqObj.requestDate
        request_list.append(obj)
    contextDic['userRequests'] = request_list
    print request_list
    return render_to_response('mentee/requests.html', contextDic, RequestContext(request))
Exemplo n.º 16
0
def crud_pledge_need(request, project_key, need_id, action=None):
    if not request.user.is_authenticated() :
        if request.is_ajax() :
            return HttpResponseBadRequest()
        else :
            return redirect('bitfund.core.login')

    project = get_object_or_404(Project, key=project_key)
    need = get_object_or_404(ProjectNeed, id=need_id)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    if request.method == 'POST' :
        if action == 'pledge' :
            pledge_need_form = PledgeProjectNeedForm(request.POST, prefix='need-'+str(need.id))
            if pledge_need_form.is_valid() :
                with transaction.commit_on_success():
                    cleaned_pledge_type = pledge_need_form.cleaned_data['pledge_type']
                    cleaned_pledge_amount = pledge_need_form.cleaned_data['pledge_amount']

                    if cleaned_pledge_type == DONATION_TYPES_CHOICES.onetime :
                        transaction = DonationTransaction()
                        transaction.populatePledgeTransaction(project=project, user=request.user, need=need,
                                                              pledge_amount=cleaned_pledge_amount)
                        transaction.save()
                        transaction.createRedonationTransactions()
                    else :
                        pledge_subscription = (DonationSubscription.objects
                                               .filter(user=request.user)
                                               .filter(project=project)
                                               .select_related())

                        if pledge_subscription.count() == 1 :
                            pledge_subscription = pledge_subscription[0]
                            pledge_subscription_need = (DonationSubscriptionNeeds.objects
                                                        .filter(donation_subscription=pledge_subscription)
                                                        .filter(need=need))
                            if pledge_subscription_need.count() == 1 :
                                pledge_subscription_need = pledge_subscription_need[0]

                                pledge_subscription.cancelPendingTransactions(pledge_subscription_need)

                                pledge_subscription_need.amount = cleaned_pledge_amount
                                pledge_subscription_need.save()
                            else :
                                pledge_subscription_need = DonationSubscriptionNeeds()
                                pledge_subscription_need.donation_subscription = pledge_subscription
                                pledge_subscription_need.need = need
                                pledge_subscription_need.amount = cleaned_pledge_amount
                                pledge_subscription_need.save()

                        else :
                            pledge_subscription = DonationSubscription()
                            pledge_subscription.user = request.user
                            pledge_subscription.project = project
                            pledge_subscription.save()

                            pledge_subscription_need = DonationSubscriptionNeeds()
                            pledge_subscription_need.donation_subscription = pledge_subscription
                            pledge_subscription_need.need = need
                            pledge_subscription_need.amount = cleaned_pledge_amount
                            pledge_subscription_need.save()

                        transaction = DonationTransaction()
                        transaction.populatePledgeTransaction(project=project, user=request.user, need=need,
                                                              pledge_amount=cleaned_pledge_amount,
                                                              donation_subscription=pledge_subscription)
                        transaction.transaction_status = DONATION_TRANSACTION_STATUSES_CHOICES.pending
                        transaction.save()
                        transaction.createRedonationTransactions()

                        return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id)
            else :
                template_data['need'] = _prepare_need_item_template_data(request, project, need, pledge_need_form)

            if not request.is_ajax() :
                if not request.user_has_bank_card_attached :
                    request.session[SESSION_PARAM_RETURN_TO_PROJECT] = project.key
                    return redirect('bitfund.pledger.attach_card')
                else :
                    return redirect('bitfund.project.budget', project_key=project.key)

        elif action == 'switch_monthly' :
            pledge_need_form = PledgeProjectNeedForm(request.POST, prefix='need-'+str(need.id))
            if pledge_need_form.is_valid() :
                with transaction.commit_on_success():
                    pledge_subscription = (DonationSubscription.objects
                                           .filter(user=request.user)
                                           .filter(project=project)
                                           .select_related())
                    if pledge_subscription.count() == 1 :
                        pledge_subscription = pledge_subscription[0]
                    else :
                        pledge_subscription = DonationSubscription()
                        pledge_subscription.user = request.user
                        pledge_subscription.project = project
                        pledge_subscription.save()


                    pledge_subscription_need = (DonationSubscriptionNeeds.objects
                                                .filter(donation_subscription=pledge_subscription)
                                                .filter(need=need))
                    if pledge_subscription_need.count() == 0 :
                        cleaned_pledge_amount = pledge_need_form.cleaned_data['pledge_amount']
                        pledge_subscription_need = DonationSubscriptionNeeds()
                        pledge_subscription_need.donation_subscription = pledge_subscription
                        pledge_subscription_need.need = need
                        pledge_subscription_need.amount = cleaned_pledge_amount
                        pledge_subscription_need.save()

                return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id)

            else :
                template_data['need'] = _prepare_need_item_template_data(request, project, need, pledge_need_form)

        elif action == 'drop_subscription' :
            existing_subscription = (DonationSubscription.objects
                                     .filter(user=request.user, project=project)
                                     .select_related())

            if existing_subscription.count() == 1 :
                with transaction.commit_on_success():
                    existing_subscription = existing_subscription[0]
                    existing_subscription_need = (DonationSubscriptionNeeds.objects
                                                  .filter(donation_subscription=existing_subscription,
                                                          need=need))
                    if existing_subscription_need.count() == 1 :
                        existing_subscription_need = existing_subscription_need[0]
                        existing_subscription.cancelPendingTransactions(existing_subscription_need)

                        existing_subscription_need.delete()

                    other_subscriptions_count = (DonationSubscriptionNeeds.objects
                                                 .filter(donation_subscription_id=existing_subscription.id)
                                                 .count())
                    if other_subscriptions_count == 0 :
                        existing_subscription.delete()

            return redirect('bitfund.project.views.crud_pledge_need', project_key=project.key, need_id=need.id)

    if 'need' not in template_data:
        template_data['need'] = _prepare_need_item_template_data(request, project, need)

    template_data['budget'] = _prepare_project_budget_template_data(request, project)

    return render_to_response('project/budget/ajax-pledge_need_form.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 17
0
def crud_linked_project(request, project_key, linked_project_key=None, action=None):
    project = get_object_or_404(Project, key=project_key)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    if request.method == 'POST':
        if action == 'add' :
            linked_project_add_form = AddLinkedProjectForm(project.id, request.POST)
            if linked_project_add_form.is_valid():
                project_dependency = Project_Dependencies()
                project_dependency.depender_project = project
                project_dependency.dependee_project = linked_project_add_form.cleaned_data['linked_project']
                project_dependency.redonation_amount = (linked_project_add_form.cleaned_data['redonation_amount'] or None)
                project_dependency.redonation_percent = (linked_project_add_form.cleaned_data['redonation_percent'] or None)
                project_dependency.brief = (linked_project_add_form.cleaned_data['brief'] or None)
                project_dependency.save()

                return redirect('bitfund.project.views.crud_linked_project', project_key=project_key)
            else :
                template_data['crud_linked_project_add_form'] = linked_project_add_form
        elif action == 'edit' :
            linked_project = get_object_or_404(Project, key=linked_project_key)
            template_data['linked_project'] = linked_project
            linked_project_edit_form = EditLinkedProjectForm(project.id, linked_project.id, request.POST)
            if linked_project_edit_form.is_valid():
                project_dependency = (Project_Dependencies.objects.get(dependee_project_id=linked_project.id,
                                                                       depender_project_id=project.id))
                project_dependency.redonation_amount = Decimal(
                    (linked_project_edit_form.cleaned_data['redonation_amount'] or 0))
                project_dependency.redonation_percent = Decimal(
                    (linked_project_edit_form.cleaned_data['redonation_percent'] or 0))
                project_dependency.brief = (linked_project_edit_form.cleaned_data['brief'] or None)
                project_dependency.save()

                return redirect('bitfund.project.views.crud_linked_project', project_key=project_key)
            else :
                template_data['crud_linked_project_edit_form'] = linked_project_edit_form

    elif action == 'add' :
        template_data['crud_linked_project_add_form'] = AddLinkedProjectForm(project.id)
    elif linked_project_key is not None :
        linked_project = get_object_or_404(Project, key=linked_project_key)

        if action == 'drop' :
            (Project_Dependencies.objects.filter(dependee_project_id=linked_project.id)
             .filter(depender_project__id=project.id).delete())
        elif action == 'edit':
            linked_project_dependency = (Project_Dependencies.objects.get(dependee_project_id=linked_project.id,
                                                                          depender_project_id=project.id))
            template_data['linked_project'] = linked_project
            form_data = {'linked_project': linked_project,
                         'redonation_percent' : linked_project_dependency.redonation_percent,
                         'redonation_amount' : linked_project_dependency.redonation_amount,
                         'brief' : linked_project_dependency.brief,
                         }
            template_data['crud_linked_project_edit_form'] = EditLinkedProjectForm(project.id, linked_project.id, initial=form_data)

    if project.maintainer_id == request.user.id :
        template_data['project_edit_access'] = True
    else :
        template_data['project_edit_access'] = False

    template_data['giving_to_bitfund'] = project.checkProjectLinkedToBitFund()
    template_data['refused_to_give_to_bitfund'] = project.is_refused_to_give_to_bitfund

    projects_i_depend_on = (Project_Dependencies.objects
                            .filter(depender_project=project.id)
                            .order_by('sort_order')
                            .prefetch_related('dependee_project')
    )
    template_data['projects_i_depend_on'] = []
    template_data['projects_i_depend_on_count'] = projects_i_depend_on.count()
    for project_i_depend_on in projects_i_depend_on:
        if project_i_depend_on.dependee_project.is_public :
            template_data['projects_i_depend_on'].append({'id': project_i_depend_on.dependee_project.id,
                                                          'key': project_i_depend_on.dependee_project.key,
                                                          'title': project_i_depend_on.dependee_project.title,
                                                          'logo': project_i_depend_on.dependee_project.logo,
                                                          'brief': (project_i_depend_on.brief or ''),
                                                          'amount_sum': project_i_depend_on.redonation_amount,
                                                          'amount_percent': project_i_depend_on.redonation_percent,
                                                          })

    template_data['crud_linked_project_action'] = action

    return render_to_response('project/linked_projects/ajax-i_depend_on_projects_list.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 18
0
def crud_pledge_empty_project(request, project_key, action=None):

    if not request.user.is_authenticated() :
        if request.is_ajax() :
            return HttpResponseBadRequest()
        else :
            return redirect('bitfund.core.login')

    project = get_object_or_404(Project, key=project_key)

    template_data = {'project': project,
                     'request': request,
                     'today': datetime.utcnow().replace(tzinfo=utc).today(),
                     'site_currency_sign': SITE_CURRENCY_SIGN,
                     }

    template_data['project_edit_access'] = False
    if request.user.id == project.maintainer_id :
        template_data['project_edit_access'] = True


    if request.method == 'POST' :
        if action == 'pledge' :
            pledge_empty_project_form = PledgeNoBudgetProjectForm(request.POST)
            if pledge_empty_project_form.is_valid() :
                with transaction.commit_on_success():
                    cleaned_pledge_type = pledge_empty_project_form.cleaned_data['pledge_type']
                    cleaned_pledge_amount = pledge_empty_project_form.cleaned_data['pledge_amount']

                    if cleaned_pledge_type == DONATION_TYPES_CHOICES.onetime:
                        transaction = DonationTransaction()
                        transaction.populatePledgeTransaction(project=project, user=request.user,
                                                              pledge_amount=cleaned_pledge_amount)
                        transaction.save()
                        transaction.createRedonationTransactions()
                    else:
                        pledge_subscription = (DonationSubscription.objects
                                               .filter(user=request.user)
                                               .filter(project=project)
                                               .select_related())

                        if pledge_subscription.count() == 1:
                            pledge_subscription = pledge_subscription[0]
                            pledge_subscription.cancelPendingTransactions()
                            pledge_subscription.amount = cleaned_pledge_amount
                            pledge_subscription.save()
                        else:
                            pledge_subscription = DonationSubscription()
                            pledge_subscription.user = request.user
                            pledge_subscription.project = project
                            pledge_subscription.amount = cleaned_pledge_amount
                            pledge_subscription.save()

                        transaction = DonationTransaction()
                        transaction.populatePledgeTransaction(project=project, user=request.user,
                                                              pledge_amount=cleaned_pledge_amount,
                                                              donation_subscription=pledge_subscription)
                        transaction.transaction_status = DONATION_TRANSACTION_STATUSES_CHOICES.pending
                        transaction.save()
                        transaction.createRedonationTransactions()

                        return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key)
            else :
                template_data['empty_project'] = _prepare_empty_project_template_data(request, project, pledge_empty_project_form)

            if not request.is_ajax() :
                #@TODO card presence check (along with the payment integration itself)
                if not request.user.is_card_attached :
                    request.session[SESSION_PARAM_RETURN_TO_PROJECT] = project.key
                    return redirect('bitfund.pledger.attach_card')
                else :
                    return redirect('bitfund.project.budget', project_key=project.key)

        elif action == 'switch_monthly' :
            pledge_empty_project_form = PledgeNoBudgetProjectForm(request.POST)
            if pledge_empty_project_form.is_valid() :
                with transaction.commit_on_success():
                    cleaned_pledge_amount = pledge_empty_project_form.cleaned_data['pledge_amount']

                    pledge_subscription = (DonationSubscription.objects
                                           .filter(user=request.user)
                                           .filter(project=project)
                                           .select_related())
                    if pledge_subscription.count() == 1 :
                        pledge_subscription = pledge_subscription[0]
                    else :
                        pledge_subscription = DonationSubscription()
                        pledge_subscription.user = request.user
                        pledge_subscription.project = project


                    pledge_subscription.amount = cleaned_pledge_amount
                    pledge_subscription.save()

                    return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key)
            else :
                template_data['empty_project'] = _prepare_empty_project_template_data(request, project, pledge_empty_project_form)

        elif action == 'drop_subscription' :
            existing_subscription = (DonationSubscription.objects
                                     .filter(user=request.user, project=project)
                                     .select_related())

            if existing_subscription.count() == 1 :
                with transaction.commit_on_success():
                    existing_subscription = existing_subscription[0]
                    existing_subscription.cancelPendingTransactions()

                    subscription_needs_count = (DonationSubscriptionNeeds.objects
                                                .filter(donation_subscription_id=existing_subscription.id)
                                                .count())
                    if subscription_needs_count == 0 :
                        existing_subscription.delete()
                    else :
                        existing_subscription.amount = 0
                        existing_subscription.save()

            return redirect('bitfund.project.views.crud_pledge_empty_project', project_key=project.key)

    template_data['empty_project'] = _prepare_empty_project_template_data(request, project)
    template_data['budget'] = _prepare_project_budget_template_data(request, project)

    return render_to_response('project/budget/ajax-pledge_empty_project_form.djhtm', template_data, context_instance=RequestContext(request))
Exemplo n.º 19
0
 def _match_datetime_around_now(cls, actual, reason):
     actual_time = datetime.strptime(actual.split('.')[0], '%Y-%m-%dT%H:%M:%S')
     now = datetime.utcnow()
     difference = now - actual_time
     if abs(difference.total_seconds()) > 60:
         cls._raise_not_matching(actual, 'utc time string within 60 seconds of now', reason)
Exemplo n.º 20
0
def linked_projects(request, project_key):
    project = get_object_or_404(Project, key=project_key)

    template_data = {
        'project': project,
        'request': request,
        'today': datetime.utcnow().replace(tzinfo=utc).today(),
        'site_currency_sign': SITE_CURRENCY_SIGN,
    }

    projects_depending_on_me = (Project_Dependencies.objects.filter(
        dependee_project=project.id).order_by('sort_order').prefetch_related(
            'depender_project'))

    if project.maintainer_id == request.user.id:
        template_data['project_edit_access'] = True
    else:
        template_data['project_edit_access'] = False

    template_data['giving_to_bitfund'] = project.checkProjectLinkedToBitFund()
    template_data[
        'refused_to_give_to_bitfund'] = project.is_refused_to_give_to_bitfund

    template_data['projects_depending_on_me'] = []
    template_data[
        'projects_depending_on_me_count'] = projects_depending_on_me.count()
    for project_depending_on_me in projects_depending_on_me:
        template_data['projects_depending_on_me'].append({
            'id':
            project_depending_on_me.depender_project.id,
            'key':
            project_depending_on_me.depender_project.key,
            'title':
            project_depending_on_me.depender_project.title,
            'logo':
            project_depending_on_me.depender_project.logo,
            'brief':
            project_depending_on_me.brief,
            'amount_sum':
            project_depending_on_me.redonation_amount,
            'amount_percent':
            project_depending_on_me.redonation_percent,
        })

    projects_i_depend_on = (Project_Dependencies.objects.filter(
        depender_project=project.id).order_by('sort_order').prefetch_related(
            'dependee_project'))
    template_data['projects_i_depend_on'] = []
    template_data['projects_i_depend_on_count'] = projects_i_depend_on.count()
    for project_i_depend_on in projects_i_depend_on:
        template_data['projects_i_depend_on'].append({
            'id':
            project_i_depend_on.dependee_project.id,
            'key':
            project_i_depend_on.dependee_project.key,
            'title':
            project_i_depend_on.dependee_project.title,
            'logo':
            project_i_depend_on.dependee_project.logo,
            'brief':
            project_i_depend_on.brief,
            'amount_sum':
            project_i_depend_on.redonation_amount,
            'amount_percent':
            project_i_depend_on.redonation_percent,
        })

    return render_to_response('project/linked_projects/linked_projects.djhtm',
                              template_data,
                              context_instance=RequestContext(request))
Exemplo n.º 21
0
def budget(request, project_key):
    project = get_object_or_404(Project, key=project_key)

    template_data = {
        'project': project,
        'request': request,
        'today': datetime.utcnow().replace(tzinfo=utc).today(),
        'site_currency_sign': SITE_CURRENCY_SIGN,
    }

    #GENERAL PROJECT INFO
    if project.maintainer_id == request.user.id:
        template_data['project_edit_access'] = True
        template_data['create_goal_form'] = CreateProjectGoalForm()
    else:
        template_data['project_edit_access'] = False

    #BUDGET, pledges, redonations, other sources, donut charts radiants
    template_data['budget'] = _prepare_project_budget_template_data(
        request, project)

    #NEEDS
    template_data['project_needs'] = []
    # template_data['project_needs_radiants'] = []
    project_needs = ProjectNeed.objects.filter(project=project.id).filter(
        is_public=True).order_by('sort_order')
    for need in project_needs:
        template_data['project_needs'].append(
            _prepare_need_item_template_data(request, project, need))

    template_data['empty_project'] = _prepare_empty_project_template_data(
        request, project)

    #template_data['maintainer_status_text'] = PROJECT_USER_STATUS_CHOICES.get_maintainer_status_choices_display(project.maintainer_status)

    #GOALS

    if template_data['project_edit_access']:
        project_published_goals = (ProjectGoal.objects.filter(
            project_id=project.id).filter(
                is_public=True).order_by('sort_order'))
        template_data['project_published_goals'] = []
        template_data[
            'project_published_goals_count'] = project_published_goals.count()
        if template_data['project_published_goals'] > 0:
            for goal in project_published_goals:
                template_data['project_published_goals'].append(
                    _prepare_goal_item_template_data(request, project, goal))

        project_unpublished_goals = (ProjectGoal.objects.filter(
            project_id=project.id).filter(
                is_public=False).order_by('sort_order'))
        template_data['project_unpublished_goals'] = []
        template_data[
            'project_unpublished_goals_count'] = project_unpublished_goals.count(
            )
        if template_data['project_unpublished_goals'] > 0:
            for goal in project_unpublished_goals:
                template_data['project_unpublished_goals'].append(
                    _prepare_goal_item_template_data(request, project, goal))
    else:
        project_goals = (ProjectGoal.objects.filter(
            project_id=project.id).filter(is_public=True).filter(
                date_starting__lt=now()).order_by('sort_order'))
        template_data['project_public_goals'] = []
        template_data['project_public_goals_count'] = project_goals.count()
        if template_data['project_public_goals_count'] > 0:
            for goal in project_goals:
                template_data['project_public_goals'].append(
                    _prepare_goal_item_template_data(request, project, goal))

    if request.user.is_authenticated():
        report = (ProjectReport.objects.filter(project_id=project.id).filter(
            reporter_id=request.user.id))
        if report.count() > 0:
            template_data['project_report'] = report[0]
        else:
            template_data['project_report'] = False
        vote = (ProjectMaintainerVote.objects.filter(
            project_id=project.id).filter(user_id=request.user.id))
        if vote.count() > 0:
            template_data['maintainer_vote'] = vote[0]
        else:
            template_data['maintainer_vote'] = False
    else:
        template_data['maintainer_vote'] = False
        template_data['project_report'] = False

    return render_to_response('project/budget/budget.djhtm',
                              template_data,
                              context_instance=RequestContext(request))
Exemplo n.º 22
0
 def subscribed_today(self, obj):
     #return obj.created_at.date() == datetime.today().date()
     return obj.created_at.date() == datetime.utcnow().date()
Exemplo n.º 23
0
 def _match_datetime_around_now(cls, actual, reason):
     actual_time = datetime.strptime(actual.split('.')[0], '%Y-%m-%dT%H:%M:%S')
     now = datetime.utcnow()
     difference = now - actual_time
     if abs(difference.total_seconds()) > 60:
         cls._raise_not_matching(actual, 'utc time string within 60 seconds of now', reason)
Exemplo n.º 24
0
 def generate_token(self):
     payload = {
         'email': self.email,
         'iat': datetime.utcnow(),
     }
     return jwt.encode(payload, settings.SECRET_KEY)