Exemplo n.º 1
0
def api_operation_see(request, profile_id):
    callback = request.GET.get('callback', '')
    req = {}
    request.session['visited'] = True
    try:
        profile = ContentProfile.objects.get(pk = profile_id)
        action = Action(profile = profile, is_seen = True)
        visitor = visitor_utils.get_visitor_from_request(request)
        action.visitor = visitor
        action.save()
        req ['result'] = 'success'
        req ['seen_id'] = action.id
    except Exception, e:
        req ['result'] = 'error'
Exemplo n.º 2
0
 def _get_public_action_details(self, id):
     try:
         action = Action.get_public_action(id)
         return Response(
             {'action': PublicActionSerializer(action, many=False).data})
     except:
         return Response("PUBLIC_ACTION_NOT_FOUND",
                         status=status.HTTP_404_NOT_FOUND)
Exemplo n.º 3
0
 def _get_public_actions(self, request):
     try:
         more = int(request.GET.get("more", 0))
         limit = int(request.GET.get("limit", 10))
     except ValueError:
         more = 0
         limit = 10
     actions = Action.get_public_actions(more, limit)
     return Response(
         {'actions': PublicActionSerializer(actions, many=True).data})
Exemplo n.º 4
0
    def handle(self, *args, **options):
        try:
            sdg = list(SustainableDevelopmentGoal.objects.all())
            principles = list(
                Principle.objects.filter(cooperative=options['coop_id']))
            partners = list(
                Partner.objects.filter(cooperative=options['coop_id']))
            investments = random.sample(range(1, 1000), options['quantity'])
            coop = Cooperative.objects.get(pk=options['coop_id'])

            for n in range(options['quantity']):
                action = Action(date=datetime.date.today(),
                                name=f"Action {n}",
                                description=f"Action {n} description",
                                invested_money=random.choice(investments),
                                cooperative=coop,
                                public=True)
                action.save()
                associated_principles = []
                associated_sdg = []
                if options['associate_multiple_principles']:
                    random.seed()
                    quantity = random.randint(1, principles.__len__() - 1)
                    for i in range(quantity):
                        associated_principles.append(random.choice(principles))
                else:
                    associated_principles.append(random.choice(principles))

                if options['associate_multiple_sdg']:
                    random.seed()
                    quantity = random.randint(1, sdg.__len__() - 1)
                    for i in range(quantity):
                        associated_sdg.append(random.choice(sdg))
                else:
                    associated_sdg.append(random.choice(sdg))

                action.principles.set(associated_principles)
                action.sustainable_development_goals.set(associated_sdg)
                action.save()

                if partners:
                    action.partners_involved.add(random.choice(partners))
                    action.save()

        except Cooperative.DoesNotExist:
            raise CommandError(
                f"Ups! The cooperative with id {options['coop_id']} does not exist"
            )
Exemplo n.º 5
0
def create(request):
    payload = json.loads(str(request.body, 'UTF-8'))
    if request.method != 'POST':
        return HttpResponse("Use POST to create new action", status=405)
    elif 'API_KEY' not in payload:
        return HttpResponse("No key", status=401)
    elif "ACTION" not in payload:
        return HttpResponse("No Action doc", status=401)
    elif not api_key_valid(payload['API_KEY']):
        return HttpResponse("Invalid key", status=403)
    elif not Action.valid_payload(payload["ACTION"]):
        return HttpResponse("Malformed doc", status=400)
    else:
        return JsonResponse(model_to_dict(Action.objects.create(**payload['ACTION'])))
Exemplo n.º 6
0
    def list(self, request):
        cooperative_id = request.user.cooperative_id
        empty_response = {'period': [], 'actions': [], 'all_periods': []}

        all_periods_data = Period.objects.filter(cooperative=cooperative_id)
        all_periods_serializer = PeriodSerializer(all_periods_data, many=True)
        if not all_periods_serializer.data:
            return Response(empty_response)

        period_id = request.query_params.get('periodId', None)
        if period_id is not None:
            period_data = next((period
                                for period in all_periods_serializer.data
                                if period['id'] == int(period_id)), None)
        else:
            period_data = get_current_period(all_periods_serializer.data)

        if not period_data:
            return Response(empty_response)

        action_data = Action.get_current_actions(
            cooperative_id, period_data['date_from'],
            period_data['date_to']).order_by('date')
        action_serializer = ActionSerializer(action_data, many=True)

        actions = []
        [[
            actions.append({
                **action, 'principle_name_key':
                action_principle['name_key'],
                'principle':
                action_principle['id']
            }) for action_principle in action['principles']
        ] for action in action_serializer.data]

        total_invested = 0 if len(actions) == 0 else functools.reduce(
            lambda a, b: a + b,
            [action.invested_money for action in list(action_data)])
        totalHoursInvested = 0 if len(actions) == 0 else functools.reduce(
            lambda a, b: a + b,
            [action.invested_hours for action in list(action_data)])
        return Response({
            'period': period_data,
            'actions': actions,
            'all_periods': all_periods_serializer.data,
            'total_invested': total_invested,
            'totalHoursInvested': totalHoursInvested
        })
Exemplo n.º 7
0
    def list(self, request):
        user_id = request.user.id
        cooperative_id = request.user.cooperative_id
        empty_response = {
            'period': [],
            'actions': [],
            'principles': [],
            'charts': {
                'cards_data': [],
                'all_principles_data': [],
                'progress_data': {
                    'investmentProgressData': {},
                    'periodProgressData': {},
                    'actionsProgressData': {}
                },
                'actions_by_partner': [],
                'monthly_investment_by_date': [],
                'monthly_actions_by_principle': []
            },
            'all_periods': []
        }

        all_periods_data = Period.objects.filter(cooperative=cooperative_id)
        all_periods_serializer = PeriodSerializer(all_periods_data, many=True)
        if not all_periods_serializer.data:
            return Response(empty_response)

        period_id = request.query_params.get('periodId', None)
        if period_id is not None:
            period_data = next((period
                                for period in all_periods_serializer.data
                                if period['id'] == int(period_id)), None)
        else:
            period_data = get_current_period(all_periods_serializer.data)

        if not period_data:
            return Response(empty_response)

        date_from = period_data['date_from']
        date_to = period_data['date_to']
        action_data = Action.get_current_actions(cooperative_id, date_from,
                                                 date_to,
                                                 user_id).order_by('date')
        action_serializer = ActionSerializer(action_data, many=True)
        date = datetime.today() if str(datetime.today()) <= date_to and str(
            datetime.today()) >= date_from else date_to
        done_actions_data = Action.get_current_actions(
            cooperative_id, date_from, date, user_id).order_by('date')

        principle_data = Principle.objects.filter(visible=True,
                                                  cooperative=cooperative_id)
        principle_serializer = PrincipleSerializer(principle_data, many=True)

        actions_by_principles_data = Action.objects.filter(
            cooperative=cooperative_id,
            principles__visible=True,
            date__gte=date_from,
            date__lte=date_to,
            partners_involved__in=[user_id]).values('principles').annotate(
                total=Count('principles')).order_by()

        principles = {
            principle['id']: principle['name_key']
            for principle in list(principle_serializer.data)
        }

        charts = {
            'cards_data':
            get_cards_data(action_data, done_actions_data, period_data),
            'all_principles_data':
            get_all_principles_data_for_current_partner(
                actions_by_principles_data, principles),
            'progress_data':
            get_progress_data(action_data, done_actions_data, period_data,
                              request.user),
            'monthly_hours_by_date':
            get_monthly_hours(done_actions_data),
            'monthly_investment_by_date':
            get_monthly_investment_by_principle(done_actions_data, date_from,
                                                principles),
            'monthly_actions_by_principle':
            get_monthly_actions_by_principle(
                done_actions_data, datetime.strptime(date_from, '%Y-%m-%d'),
                principles)
        }

        return Response({
            'period': period_data,
            'actions': action_serializer.data,
            'principles': principle_serializer.data,
            'charts': charts,
            'all_periods': all_periods_serializer.data
        })