예제 #1
0
    def test_update_acl_to_nothing(self):
        self.admin_login()

        group = Group(name='fuga')
        group.save()

        # set ACL object in advance, there are two members in the full parameter
        group.permissions.add(self._aclobj.full)

        params = {
            'object_id':
            str(self._aclobj.id),
            'object_type':
            str(self._aclobj.objtype),
            'acl': [{
                'member_id': str(group.id),
                'member_type': 'group',
                'value': str(ACLType.Nothing.id)
            }],
            'default_permission':
            str(ACLType.Nothing.id),
        }
        resp = self.client.post(reverse('acl:set'), json.dumps(params),
                                'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(group.permissions.count(), 0)
예제 #2
0
def generate_groups(request, num=1):
    for _ in range(num):
        Group.generate_group()
    qs = Group.objects.all()
    new_groups = qs[len(qs) - num:]
    result = '<br>'.join(str(group) for group in new_groups)
    return HttpResponse(result)
예제 #3
0
def new_group(request):
    if request.method == "POST":
        new_group = Group()
        new_group.name = request.POST["group_name"]
        new_group.save()
        return redirect("/all_group")
    return render(request, "new_group.html", {"current_user":get_current_user(request=request)})
예제 #4
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def post(request, lang, group_id):
        group_model = Group()
        group = group_model.get_by_id(group_id)
        form = GroupForm(request.POST)

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                group_model.edit_group(group_id, {
                    'name': form.cleaned_data.get('name'),
                })

                return HttpResponseRedirect(
                    request.META.get('HTTP_REFERER', '/'))

            except:
                pass

        title = group.name

        return TemplateResponse(
            request, 'group.html', {
                'title': title + ' | グループ | FEED App 管理',
                'group': group,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })
예제 #5
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def get(_, lang):
        if lang == 'ja':
            cached_groups = Cache.get('api_groups')
            if cached_groups is None:
                res = GroupSerializer(Group.get_all(), many=True).data
                Cache.set('api_groups', res)
            else:
                res = cached_groups

        elif lang == 'en':
            try:
                cached_groups_en = Cache.get('api_groups_en')
            except:
                cached_groups_en = None

            if cached_groups_en is None:
                res = GroupEnSerializer(Group.get_all(), many=True).data
                Cache.set('api_groups_en', res)
            else:
                res = cached_groups_en

        else:
            return JsonResponse({'message': 'Not Found'}, status=404)

        return JsonResponse(res, safe=False)
예제 #6
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def post(request, lang):

        form = GroupForm(request.POST)
        group_model = Group()

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                group_model.create_group({
                    'name': form.cleaned_data.get('name'),
                })

                return HttpResponseRedirect('/{}/admin/groups'.format(lang))

            except:
                pass

        return TemplateResponse(
            request, 'group_create.html', {
                'title': '新規投稿 | グループ | FEED App 管理',
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })
예제 #7
0
 def post(self, request):
     try:
         new_group = GroupModel(name=request.data.get('name'),
                                admin=request.user)
         new_group.save()
         return Response(new_group.group_id, status=status.HTTP_201_CREATED)
     except Exception as e:
         return Response(status=status.HTTP_400_BAD_REQUEST)
예제 #8
0
    def handle(self, *args, **kwargs):
        Group.objects.all().delete()
        teachers = list(Teacher.objects.all())
        count = kwargs['count']
        for _ in range(count):
            Group.generate_group(teachers)

        self.stdout.write(self.style.SUCCESS(f'Created: {count} groups'))
예제 #9
0
 def test_group_creation(self):
     group = Group(gtype="gpe", gdomain="gen", gsource="man",
                   code="test", abbr="test", title="Test group",
                   description="")
     group.save()
     self.assertEqual(group.pk, 1)
     self.assertEqual(group.group.pk, 1)
     self.assertEqual(DjangoGroup.objects.filter(name="link_1").count(), 1)
예제 #10
0
    def test_new_returns_a_saved_group(self):
        name = "Test Name"
        description = "Test Description"
        user = users.get_current_user()

        returned_group = Group.new(name, description, user)

        result = Group.get_by_id(returned_group.key.id())
        self.assertNotEqual(result, None)
예제 #11
0
 def create_groups( self ):
     wish_sets = sorted( self.cliques(), key=lambda x: len(x) )
     for ws in wish_sets:
         group = Group()
         group.save()
         for w in ws:
             group.persons.add( w.person )
             group.wishes.add( w )
             self._from_graph( w )
         group.save()
예제 #12
0
def do_create(request, recv_data):
    new_group = Group(name=recv_data['name'])
    new_group.save()

    for user in [User.objects.get(id=x) for x in recv_data['users']]:
        user.groups.add(new_group)

    return JsonResponse({
        'msg':
        'Success to create a new Group "%s"' % new_group.name,
    })
예제 #13
0
파일: add_group.py 프로젝트: annalitvin/lms
    def handle(self, *args, **options):
        number_groups = options['number_group']

        try:
            Group.objects.all().delete()
            teachers = list(Teacher.objects.all())
            for _ in range(number_groups):
                Group.generate_group(teachers)
        except Exception as ex:
            raise CommandError(f'Data added fail! {ex}')
        self.stdout.write(self.style.SUCCESS(f'Data added successfully! {number_groups}'))
예제 #14
0
    def handle(self, *args, **kwargs):
        count = kwargs['count']

        try:
            for _ in range(count):
                Group.generate_group()

        except Exception as ex:
            raise CommandError('Generate group failed: "%s"' % ex)

        self.stdout.write(self.style.SUCCESS(f'Successfully generated {count} group(s)'))
예제 #15
0
    def create_group( self ):
        new_group = Group()
        new_group.save()

        for wish in self.nodes:
            wish.is_active = False
            new_group.persons.add( wish.person )
            new_group.wishes.add( wish )
            wish.save()

        new_group.save()
        return new_group
예제 #16
0
    def test_group_by_id(self):
        group = Group(name="test_group", manager=self.manager)
        group.save()
        response = self.client.get(
            f"/api/group/{group.id}/")

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode(), json.dumps(
            group.to_dict()))

        response = self.client.delete(f"/api/group/{group.id}/")
        self.assertEqual(response.status_code, 204)
        self.assertEqual(Group.objects.count(), 0)
예제 #17
0
def dashboard(request):
    if request.method == 'GET':
        if "create-group" in request.GET:
            name = request.GET.get("name-group", None)
            about = request.GET.get("about-group", None)
            if name is not None and about is not None:
                exist = Group.objects.filter(name=name)
                if exist:
                    message_error = "ese grupo ya existe, por favor, escoja otro nombre"
                    return render(request, 'index.html', locals())
                group = Group(name=name, about=about, owner=request.user)
                group.save()
                return redirect(reverse('account:dashboard'))
        else:
            friend_request = Friendship.objects.filter(Q(status=2) & Q(receiver=request.user))
            users = UserProfile.objects.filter(is_conected=True)
            user = request.user
            return render(request, 'index.html', locals())
    else:
        if "send" in request.POST:
            email = request.POST.get('email', "")
            subject = request.POST.get('subject', "")
            message = request.POST.get('message', "")
            if email and subject and message:
                try:
                    # email = EmailMultiAlternatives(subject, message, '*****@*****.**',
                    # ['*****@*****.**'])
                    # message_html = '<h1>' + message + '</h1>'
                    # email.attach_alternative(message_html, 'text/html')
                    # email.send(False)
                    subject = '[The Wall] ' + subject
                    send_mail(subject, message, '*****@*****.**', ['*****@*****.**'],
                              False, 'rhernandeza', 'seabiskuit32+')
                except BadHeaderError:
                    error = True
                    message_error = 'Se ha encontrado una cabecera invalida'
                    return render(request, 'index.html', locals())
                return render(request, 'index.html', locals())
            else:
                error = True
                message_error = 'Debe de llenar todos los campos'
                return render(request, 'index.html', locals())
        else:  # si "save" in request.POST
            full_name = request.POST.get('name', "")
            email = request.POST.get('email', "")
            user = request.user
            user.first_name = full_name.split(" ")[0]
            user.last_name = " ".join(full_name.split(" ")[1:])
            user.email = email
            user.save()
            return render(request, 'index.html', locals())
예제 #18
0
파일: views.py 프로젝트: rudra012/fms
    def post(self, request, format=None):
        serializer = serializers.GroupCreateUpdateSerializer(data=request.data)
        if serializer.is_valid():
            group_instance = Group()
            for instance_field in self.instance_fields:
                group_instance.__setattr__(instance_field,
                                           serializer.data.get(instance_field))

            group_instance.i_by = request.user.id
            group_instance.u_by = request.user.id
            group_instance.save()
            return_arr = {
                "code": 200,
                "success": True,
                "messages": "valid",
                "Group": {
                    'id': group_instance.id or "",
                    'group_name': group_instance.group_name or "",
                    'company_id': group_instance.company_id or "",
                }
            }
            return HttpResponse(json.dumps(return_arr),
                                status=return_arr['code'])

        return_arr = {
            "code": 602,
            "success": False,
            "messages": "Error in Posting data"
        }
        return HttpResponse(json.dumps(return_arr), status=return_arr['code'])
예제 #19
0
    def test_group_members_delete(self):
        group = Group(name="test_group", manager=self.manager)
        group.save()

        user = User.objects.create_user(
            "test-receiver", "1234", email="", salt="", role=User.Role.Coder)

        coder = Coder(user=user, group=group)
        coder.save()

        response = self.client.delete(
            f"/api/group/{group.id}/members/{user.id}/")
        self.assertEqual(response.status_code, 204)

        coder = Coder.objects.get(user=user)
        self.assertEqual(coder.group, None)

        response = self.client.delete(f"/api/group/{group.id}/members/100/")
        self.assertEqual(response.status_code, 400)

        response = self.client.post(
            f"/api/group/{group.id}/members/{user.id}/", {})
        self.assertEqual(response.status_code, 405)

        group = Group(name="test_group2", manager=self.manager2)
        group.save()

        response = self.client.delete(
            f"/api/group/{group.id}/members/{user.id}/")
        self.assertEqual(response.status_code, 400)
예제 #20
0
    def test_group_members_get(self):
        group = Group(name="test_group", manager=self.manager)
        group.save()

        user = User.objects.create_user(
            "test-receiver", "1234", email="", salt="", role=User.Role.Coder)

        coder = Coder(user=user, group=group)
        coder.save()

        response = self.client.get(f"/api/group/{group.pk}/members/")
        self.assertEqual(response.status_code, 200)

        response = self.client.post(f"/api/group/{group.pk}/members/", {})
        self.assertEqual(response.status_code, 405)

        group = Group(name="test2_group", manager=self.manager2)
        group.save()

        response = self.client.get(f"/api/group/{group.pk}/members/")
        self.assertEqual(response.status_code, 400)

        self.client.logout()
        self.client.login(username="******", password="******")

        response = self.client.get(f"/api/group/{group.pk}/members/")
        self.assertEqual(response.status_code, 400)
예제 #21
0
def create(request):
	groupTitle = request.data.get("title")
	groupDescr = request.data.get("descr")
	invatedUsers = request.data.get("users")
	for i in invatedUsers:
		user = User.objects.filter(name=i)
		if(len(user)==1):
			a=Group(title=groupTitle,descr=groupDescr)
			a.save()
			a.Users.add(user)
			#user.Groups.add()
			return Response({"status": True})
		else:
			return Response({"status": False})
예제 #22
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def post(request, lang, category_id):
        category_model = Category()
        category = category_model.get_by_id(category_id)
        groups = Group.get_all()
        category_count = category.video_set.all().count()
        category_count_en = category.videoen_set.all().count()

        try:
            if category_count == 0 and category_count_en == 0:
                category_model.delete_category(category_id)
                return HttpResponseRedirect(
                    '/{}/admin/categories'.format(lang))

        except:
            pass

        title = category.name_ja

        return TemplateResponse(
            request, 'category.html', {
                'title': title + ' | カテゴリー | FEED App 管理',
                'category': category,
                'groups': groups,
                'form_data': {},
                'error_messages': {
                    'delete': ['invalid']
                },
                'lang': lang,
            })
예제 #23
0
 def setUp(self):
     self.group1 = Group(gtype="gpe", gdomain="gen", gsource="man",
                   code="test1", abbr="test1", title="Test group 1",
                   description="")
     self.group1.save()
     self.group2 = Group(gtype="gpe", gdomain="gen", gsource="man",
                   code="test2", abbr="test2", title="Test group 2",
                   description="")
     self.group2.save()
     self.start = datetime.datetime.now(timezone.get_default_timezone())\
          - datetime.timedelta(days=30)
     self.end = self.start + datetime.timedelta(days=300)
     self.people1 = list(get_user_model().objects.all())
     self.people2 = list(get_user_model().objects.filter(pk__lte=2))
     self.people3 = list(get_user_model().objects.filter(pk__gt=2))
     self.people4 = list(get_user_model().objects.filter(pk=2))
def save_new_fund(name, icon, is_shared, owner, shared_group):
    """Function for safe save FundCategories and SharedFunds
    Args:
        name(str): name of category.
        icon(str): name of icon.
        is_shared(bool): if FundCategories is shared to some group True, else False.
        owner(UserProfile): transaction owner.
        shared_group(int): group to which the category is bound.
    Returns:
        True if success, False else
    """
    new_fund = FundCategories(name=name,
                              icon=icon,
                              is_shared=is_shared,
                              owner=owner)
    try:
        with transaction.atomic():
            new_fund.save()
            if is_shared:
                group = Group.get_group_by_id(shared_group)
                shared_fund = SharedFunds(group=group, fund=new_fund)
                shared_fund.save()
    except IntegrityError:
        return False
    return True
예제 #25
0
def show_spending_group(request):
    """Handling request for creating of spending categories list in group.
        Args:
            request (HttpRequest): Limitation data.
        Returns:
            HttpResponse object.
    """

    user = request.user
    users_group = []
    icon_if_none = AWS_S3_URL + STANDARD_SPENDINGS_FOLDER + ICON_FILE_NAME
    if user:
        for group in Group.filter_groups_by_user_id(user):
            for shared_category in SharedSpendingCategories.objects.filter(
                    group=group.id):
                if shared_category.spending_categories.is_active:
                    icon = \
                        SpendingCategories.objects.get(
                            id=shared_category.spending_categories.id).icon  # pylint: disable=line-too-long
                    url = AwsService.get_image_url(
                        icon) if icon else icon_if_none
                    users_group.append({
                        'id_cat':
                        shared_category.spending_categories.id,
                        'name_cat':
                        shared_category.spending_categories.name,
                        'id_group':
                        group.id,
                        'name_group':
                        group.name,
                        'url':
                        url
                    })
        return JsonResponse(users_group, status=200, safe=False)
    return JsonResponse({}, status=400)
예제 #26
0
def show_fund_by_group(request):
    """Handling request for creating of spending categories list in group.
        Args:
            request (HttpRequest): Limitation data.
        Returns:
            HttpResponse object.
    """

    user = request.user
    users_group = []
    icon_if_none = AWS_S3_URL + STANDARD_FUNDS_FOLDER + ICON_FILE_NAME
    if user:
        for group in Group.filter_groups_by_user_id(user):
            for shared_fund in SharedFunds.objects.filter(group=group.id):
                if not FinancialGoal.has_goals(fund_id=shared_fund.fund.id) \
                    and shared_fund.fund.is_active:
                    icon = FundCategories.objects.get(
                        id=shared_fund.fund.id).icon
                    url = AwsService.get_image_url(
                        icon) if icon else icon_if_none
                    users_group.append({
                        'id_fund': shared_fund.fund.id,
                        'name_fund': shared_fund.fund.name,
                        'id_group': group.id,
                        'url': url
                    })
        return JsonResponse(users_group, status=200, safe=False)
    return JsonResponse({}, status=400)
예제 #27
0
def create_new_goal(request):
    """Handling request for creating of new goal category.
    Args:
        request (HttpRequest): request from server which contain
            value, start_date, finish_date, shred_group, name, icon
    Returns:
        HttpResponse object.
    """
    data = json.loads(request.body)
    if not input_fund_registration_validate(data):
        return HttpResponse(status=400)
    if not date_range_validate(data):
        return HttpResponse(status=400)
    user = request.user
    shared_group = data["shared_group"]
    is_shared = False
    if shared_group:
        is_shared = True
        group = Group.get_group_by_id(shared_group)
        if not group:
            return HttpResponse(status=400)
        if not is_user_admin_group(group.id, user):
            return HttpResponse(status=406)
    if save_new_goal(value=Decimal(data["value"]),
                     start_date=data["start_date"],
                     finish_date=data["finish_date"],
                     name=data["name"],
                     icon=data["icon"],
                     is_shared=is_shared,
                     owner=user,
                     shared_group=shared_group):
        return HttpResponse(status=201)
    return HttpResponse(status=409)
예제 #28
0
def group_make(request):
    data = {}
    if request.method == "POST" and request.is_ajax(
    ) and 'name_check' in request.POST:
        name = request.POST['group_name']

        if group_name_validation(name):
            data['fail'] = "Restriction"
        elif group_name_check(name):
            data['fail'] = ""
        else:
            data['success'] = ""

        return HttpResponse(json.dumps(data), content_type="application/json")

    elif request.method == "POST" and request.is_ajax():
        group_name = request.POST['group_name']
        group_info = request.POST['group_info']

        if group_name_validation(group_name):
            data['fail'] = "Restriction"

        elif 'privategroup' in request.POST:
            pg = Private_Group(title=group_name,
                               info=group_info,
                               user=request.user)
            pg.save()
            data['success'] = ""

        elif group_name_check(group_name):
            data['fail'] = ""

        else:
            g = Group(title=group_name, info=group_info, num_member=1)
            g.save()
            m = Membership(user=request.user, group=g, status=0)
            m.save()
            data['success'] = ""

        return HttpResponse(json.dumps(data), content_type="application/json")
    else:
        return render_to_response(
            'group/group_make.html',
            RequestContext(request, {
                'u': request.user,
                'css': 'group_make'
            }))
예제 #29
0
    def test_create_group(self):
        name = "ほげgroup"
        user1 = self._create_user("user1")
        user2 = self._create_user("user2")

        group = Group(name=name)
        group.save()

        user1.groups.add(group)
        user2.groups.add(group)

        group = Group.objects.get(name=name)
        self.assertTrue(isinstance(group, Group))
        self.assertEqual(group.name, name)

        self.assertEqual(user1.groups.count(), 1)
        self.assertEqual(user2.groups.count(), 1)
예제 #30
0
def do_create(request, recv_data):
    new_group = Group(
        name=recv_data["name"],
        parent_group=Group.objects.filter(
            id=recv_data.get("parent_group", 0), is_active=True
        ).first(),
    )
    new_group.save()

    for user in [User.objects.get(id=x) for x in recv_data.get("users", [])]:
        user.groups.add(new_group)

    return JsonResponse(
        {
            "msg": 'Success to create a new Group "%s"' % new_group.name,
        }
    )
예제 #31
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def get(request, lang):

        groups = Group.get_all()

        return TemplateResponse(request, 'groups.html', {
            'title': 'グループ | FEED App 管理',
            'groups': groups,
            'lang': lang,
        })
예제 #32
0
파일: apply_mock.py 프로젝트: matbur/bojamo
def mock_group():
    with open('mock_group.json') as f:
        for mock in json.load(f):
            owner = User.objects.get(pk=mock.pop('owner'))
            name = re.sub('\W', '', mock.pop('name'))[:50]
            try:
                Group(owner=owner, name=name, **mock).save()
            except IntegrityError as err:
                print(err, mock)
예제 #33
0
    def addGroup(self, wishes=[], persons=[]):
        # [-] remove mutable values
        """
            Create a new group
            @param tags: the group tags
            @param persons: the persons belonging to this group
        """
        group = Group()
        group.save()

        for wish in wishes:
            group.wishes.add(wish)

        for person in persons:
            if person is not None:
                group.persons.add(person)

        return group
예제 #34
0
    def addGroup(self, wishes=[], persons=[]):
        # [-] remove mutable values
        """
            Create a new group
            @param tags: the group tags
            @param persons: the persons belonging to this group
        """
        group = Group()
        group.save()

        for wish in wishes:
            group.wishes.add(wish)

        for person in persons:
            if person is not None:
                group.persons.add(person)

        return group
예제 #35
0
def create_spending_history_individual(user, start_date, finish_date,
                                       utc_difference):
    """Creating array of data for individual spending history.
        Args:
            user (UserProfile): user.
            start_date (date): The beginning of statistic period
            finish_date (date): The end of statistic period
            utc_difference(int): difference between user's time and UTC
        Returns:
            Array of data for individual spending history statistic.
    """

    history_individual = []
    for entry in SpendingCategories.filter_by_user(user):
        history_individual_entry = []
        for item in SpendingHistory.filter_by_user_date_spending(
                user, start_date, finish_date, entry):
            history_individual_entry.append({
                'value':
                float(item.value),
                'date': (item.date + timedelta(hours=utc_difference)).date(),
                'fund':
                item.fund.name,
                'Delete':
                item.id
            })
        if history_individual_entry:
            history_individual.append({
                'spending': entry.name,
                'history': history_individual_entry
            })
    for group in groups_for_user(user):
        if is_user_member_group(group, user):
            for entry in SharedSpendingCategories.filter_by_group(group=group):
                history_individual_entry = []
                for item in SpendingHistory.filter_by_user_date_spending(
                        user, start_date, finish_date,
                        spending_categories=entry):
                    history_individual_entry.append({
                        'value':
                        float(item.value),
                        'date':
                        (item.date + timedelta(hours=utc_difference)).date(),
                        'fund':
                        item.fund.name,
                        'Delete':
                        item.id
                    })
                if history_individual_entry:
                    history_individual.append({
                        'spending':
                        entry.name + ' / ' + Group.get_group_by_id(group).name,
                        'history':
                        history_individual_entry
                    })
    return history_individual
예제 #36
0
class CategoryForm(forms.Form):
    name_ja = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    name_en = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    image = forms.CharField(required=True, error_messages=ERROR_MESSAGES)
    order = forms.IntegerField(required=True, error_messages=ERROR_MESSAGES)
    group = forms.ChoiceField(required=False,
                              widget=forms.Select,
                              choices=lambda: [(v.id, v.id)
                                               for v in Group.get_all()],
                              error_messages=ERROR_MESSAGES)
예제 #37
0
파일: views.py 프로젝트: ShinjiroMoriya/cms
    def post(request, lang, category_id):

        category_model = Category()
        category = category_model.get_by_id(category_id)
        groups = Group.get_all()
        form = CategoryForm(request.POST)

        if category is None:
            return HttpResponseRedirect('/{}/admin/categories'.format(lang))

        if form.errors:
            messages.add_message(request, messages.INFO,
                                 dict(form.errors.items()))

        if form.is_valid():
            try:
                category_model.edit_category(
                    category_id, {
                        'name_ja': form.cleaned_data.get('name_ja'),
                        'name_en': form.cleaned_data.get('name_en'),
                        'image': form.cleaned_data.get('image'),
                        'order': form.cleaned_data.get('order'),
                        'group': Group.get_by_id(
                            form.cleaned_data.get('group')),
                    })

                return HttpResponseRedirect(
                    '/{}/admin/categories'.format(lang))

            except:
                pass

        title = category.name_ja

        return TemplateResponse(
            request, 'category.html', {
                'title': title + ' | カテゴリー | FEED App 管理',
                'category': category,
                'groups': groups,
                'form_data': form.cleaned_data,
                'error_messages': get_error_message(request),
                'lang': lang,
            })
def save_new_group(name, icon, owner):
    """Function for safe save FundCategories and SharedFunds
    Args:
        name(str): name of group.
        icon(str): name of icon.
        owner(UserProfile): transaction owner.
    Returns:
        True if success, False else
    """
    new_group = Group(name=name, icon=icon, owner=owner)
    try:
        with transaction.atomic():
            new_group.save()
            new_users_in_group = UsersInGroups(group=new_group,
                                               user=owner,
                                               is_admin=True)
            new_users_in_group.save()
    except IntegrityError:
        return False
    return True
예제 #39
0
    def get_structures(self):
        """
        Get structures info from structures xml

        """
        self.log(logging.INFO, "Getting structures")
        self.get_parameters("BEE_STRUCTURES")
        # TODO: Check params consistency
        self.structures = {}
        self.grouplinks = {}
        for division in self.xml['BEE_STRUCTURES'].\
                findall('./DONNEES/DIVISIONS/DIVISION'):
            grp = Group(gtype='div', gdomain='loc', gsource='imp')
            grp.code = division.get('CODE_STRUCTURE')
            grp.abbr = grp.code
            grp.title = grp.code
            grp.description = self._gtb(division,
                                        "LIBELLE_LONG", grp.code)
            self.grouplinks[grp.code] = []
            for mef in division.findall('MEFS_APPARTENANCE/MEF_APPARTENANCE'):
                mef = self._gtb(mef, "CODE_MEF", "")
                self.grouplinks[grp.code].append(self.mefs[mef])
            grp.school = self.school
            # SEE: school RNE/REF ?
            self.structures[grp.code] = grp
        self.log(logging.INFO, "Getting structures : DONE", commit=True)
        return self.structures
예제 #40
0
파일: views.py 프로젝트: yeomii/bacchusDB
def group_make(request):
	data = {}
	if request.method == "POST" and request.is_ajax() and 'name_check' in request.POST:
		name = request.POST['group_name']

		if group_name_validation(name):
			data['fail'] = "Restriction"
		elif group_name_check(name):
			data['fail'] = ""
		else:
		 	data['success'] = ""

		return HttpResponse(json.dumps(data), content_type="application/json")

	elif request.method == "POST" and request.is_ajax():
		group_name = request.POST['group_name']
		group_info = request.POST['group_info']
		
		if group_name_validation(group_name):
			data['fail'] = "Restriction"
		
		elif 'privategroup' in request.POST:
		 	pg = Private_Group(title=group_name, info=group_info, user=request.user)
		 	pg.save()
		 	data['success'] = ""	

		elif group_name_check(group_name):
			data['fail'] = ""

		else:
			g = Group(title=group_name, info=group_info, num_member=1)
			g.save()
			m = Membership(user=request.user, group=g, status=0)
			m.save()
			data['success'] = ""

		return HttpResponse(json.dumps(data), content_type="application/json")
	else:
		return render_to_response('group/group_make.html', RequestContext(request, {'u': request.user, 'css':'group_make'}))
예제 #41
0
    def get_matieres(self):
        """
        Get matieres from nomenclatures xml

        """
        self.log(logging.INFO, "Getting matieres")
        self.matieres = {}
        self.grouplinks = {}
        for mat in self.xml['BEE_NOMENCLATURES'].\
                findall('./DONNEES/MATIERES/MATIERE'):
            matiere = Group(gtype='mat', gdomain='gen', gsource='imp')
            matiere.code = mat.get('CODE_MATIERE')
            matiere.abbr = self._gtb(mat, "CODE_GESTION", "")
            matiere.title = self._gtb(mat, "LIBELLE_COURT", "")
            matiere.description = self._gtb(mat, "LIBELLE_EDITION",
                                            matiere.title)
            mef = self._gtb(mat, "MEF_RATTACHEMENT", None)
            if mef is not None:
                self.grouplinks[matiere.code] = self.mefs[mef]
            self.matieres[matiere.code] = matiere
            self.log(logging.DEBUG, "Found matiere %s %s" % \
                     (matiere.code, matiere.title))
        self.log(logging.INFO, "Getting matieres : DONE", commit=True)
        return self.matieres
예제 #42
0
def create_group(creator, category='H'):
    group_name = create_group_name(creator)
    group = Group(name=group_name, creator=creator, type=category)
    group.save()
    return group_name
예제 #43
0
def create_home_group(creator, home_id):
    group = Group(name=home_id, creator=creator, type='H')
    group.save()
예제 #44
0
    def test_group_composition(self):
        group = Group(gtype="gpe", gdomain="gen", gsource="man",
                      code="test", abbr="test", title="Test group",
                      description="")
        group.save()
        start = datetime.datetime.now(timezone.get_default_timezone())\
             - datetime.timedelta(days=30)
        end = start + datetime.timedelta(days=300)
        people = list(get_user_model().objects.all())
        group.new_main_composition(people, start, end)
        self.assertEqual(group.get_people_by_date(
            start + datetime.timedelta(days=3)).count(), 4)
        self.assertEqual(group.get_people_by_date(
            start - datetime.timedelta(days=3)).count(), 0)
        self.assertEqual(group.get_people_by_date(
            start + datetime.timedelta(days=350)).count(), 0)
        self.assertEqual(DjangoGroup.objects.get(name="link_1").\
                         person_set.count(), 4)

        # Testing group main composition updates
        group.update_main_composition(people,
                                      start + datetime.timedelta(days=15),
                                      start + datetime.timedelta(days=200))

        people = list(get_user_model().objects.all().filter(pk__gt=1))
        group.update_main_composition(people,
                                      start + datetime.timedelta(days=20),
                                      start + datetime.timedelta(days=180))
        self.assertEqual(group.get_people_by_date(
            start + datetime.timedelta(days=10)).count(), 4)
        self.assertEqual(group.get_people_by_date(
            start + datetime.timedelta(days=17)).count(), 4)
        self.assertEqual(group.get_people_by_date(
            start + datetime.timedelta(days=23)).count(), 2)
        self.assertEqual(DjangoGroup.objects.get(name="link_1").\
                         person_set.count(), 2)
예제 #45
0
class GroupTestCompositionOperations(TestCase):

    fixtures = ['people1.json']

    def setUp(self):
        self.group1 = Group(gtype="gpe", gdomain="gen", gsource="man",
                      code="test1", abbr="test1", title="Test group 1",
                      description="")
        self.group1.save()
        self.group2 = Group(gtype="gpe", gdomain="gen", gsource="man",
                      code="test2", abbr="test2", title="Test group 2",
                      description="")
        self.group2.save()
        self.start = datetime.datetime.now(timezone.get_default_timezone())\
             - datetime.timedelta(days=30)
        self.end = self.start + datetime.timedelta(days=300)
        self.people1 = list(get_user_model().objects.all())
        self.people2 = list(get_user_model().objects.filter(pk__lte=2))
        self.people3 = list(get_user_model().objects.filter(pk__gt=2))
        self.people4 = list(get_user_model().objects.filter(pk=2))

    def test_group_composition_operations(self):
        self.group1.new_main_composition(self.people1, self.start, self.end)
        self.group1.update_current_composition(people=self.people4,
                                               operation="-",
                                               datestart=self.start)
        self.assertEqual(self.group1.get_people_by_date().count(), 3)

        self.group2.new_main_composition(self.people2, self.start, self.end)
        self.assertEqual(self.group2.get_people_by_date().count(), 3)
        self.group2.update_current_composition(people=self.people3,
                                               operation="U",
                                               datestart=self.start)
        self.assertEqual(self.group2.get_people_by_date().count(), 4)
        self.group2.update_current_composition(people=self.people3,
                                               operation="U",
                                               datestart=self.start)
        self.group2.update_current_composition(group=self.group1,
                                               operation="I",
                                               datestart=self.start)
        self.assertEqual(self.group2.get_people_by_date().count(), 3)
예제 #46
0
 def test_create_adds_to_datastore(self):
     group = GroupInteractor.create(self.GROUP_TITLE, self.admin_user, self.GROUP_DESCRIPTION)
     self.assertEqual(Group.get_by_id(group.key.id()), group)
예제 #47
0
 def _put_group(self, title="Test Title", description="Test Description", active=True, group_user=None):
     if group_user is None:
         group_user = users.get_current_user()
     entity = Group.new(name=title, description=description, active=active, user=group_user)
     entity.put()
     return entity