Esempio n. 1
0
    def form_valid(self, form):
        fields = Member.get_fields()
        selected_fields = form.cleaned_data["field_list"]
        header = collections.OrderedDict([(f.field_id, f.name)
                                          for f in fields.values()
                                          if f.field_id in selected_fields])
        data = self.get_data(
            form,
            [(f.field_id, f.getter)
             for f in fields.values() if f.field_id in selected_fields],
        )

        LogEntry.objects.create(
            content_type=None,
            object_id=0,
            user=self.request.user,
            action_type="byro.members.export",
            data={
                "filter":
                form.cleaned_data["member_filter"],
                "format":
                form.cleaned_data["export_format"],
                "fields":
                collections.OrderedDict([
                    (f_id, str(f_name)) for (f_id, f_name) in header.items()
                ]),
            },
        )

        if form.cleaned_data["export_format"].startswith("csv"):
            return self.export_csv(
                header, data, csv_format=form.cleaned_data["export_format"])

        return redirect(self.request.get_full_path())
Esempio n. 2
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     fields = Member.get_fields()
     self.fields["field_list"].choices = [(f.field_id, f.name)
                                          for f in fields.values()]
     self.fields["field_list"].initial = [
         f.field_id for f in fields.values()
         if f.registration_form.get("position", -1) > -1
     ]
Esempio n. 3
0
def test_member_field_reading(member, membership, inactive_member):
    f = Member.get_fields()

    assert '_internal_id' in f
    assert f['_internal_id'].computed
    assert f['_internal_id'].read_only
    assert f['_internal_id'].getter(member) == member.pk

    assert f['member__name'].getter(member) == member.name

    assert f['_internal_active'].getter(member) is True
    assert f['_internal_active'].getter(inactive_member) is False
Esempio n. 4
0
    def save(self):
        profiles = {
            profile.related_model.__name__: profile.related_model()
            for profile in Member._meta.related_objects
            if isinstance(profile, OneToOneRel)
            and profile.name.startswith('profile_')
        }
        member = Member()
        membership = Membership()

        for key, value in self.cleaned_data.items():
            model_name = key.split('__')[0]
            if model_name == 'member':
                obj = member
            elif model_name == 'membership':
                obj = membership
            else:
                obj = profiles[key.split('__')[0]]
            setattr(obj, key.split('__', maxsplit=1)[-1], value)
        member.save()
        member.refresh_from_db()
        membership.member = self.instance = member
        membership.save()
        for profile in profiles.values():
            profile.member = member
            profile.save()
Esempio n. 5
0
    def dispatch(self, request, *args, **kwargs):
        search = request.GET.get("search")
        if not search or len(search) < 2:
            return JsonResponse({"count": 0, "results": []})

        queryset = Member.objects.filter(Member.get_query_for_search(search))
        return JsonResponse({
            "count":
            len(queryset),
            "results": [{
                "id": member.pk,
                "nick": member.profile_profile.nick,
                "name": member.name,
            } for member in queryset],
        })
Esempio n. 6
0
    def get_members_queryset(self, search=None, _filter="active"):
        qs = Member.objects.all()
        if search:
            qs = qs.filter(Member.get_query_for_search(search))

        # Logic:
        #  + Active members have membership with start <= today and (end is null or end >= today)
        active_q = Q(memberships__start__lte=now().date()) & (
            Q(memberships__end__isnull=True)
            | Q(memberships__end__gte=now().date()))
        inactive_q = ~active_q
        if _filter == "all":
            pass
        elif _filter == "inactive":
            qs = qs.filter(inactive_q)
        else:  # Default to 'active'
            qs = qs.filter(active_q)
        return qs.order_by("-id").distinct()
Esempio n. 7
0
def default_csv_form_valid(view, form, dialect='excel'):
    mapping = None
    fields = Member.get_fields()
    encoding = get_encoding(form)

    with form.cleaned_data['upload_file'].open() as fp:
        instream = unicodecsv.DictReader(fp,
                                         dialect=dialect,
                                         encoding=encoding)

        for indict in instream:
            if mapping is None:
                mapping = {}
                for k in indict.keys():
                    for field in fields.values():
                        if str(field.name).strip() == k.strip():
                            mapping[k.strip()] = field
                            break
                    else:
                        messages.error(
                            view.request,
                            _("Couldn't map input column '{}' to field").
                            format(k.strip()),
                        )
                        return redirect(view.request.get_full_path())

            member = Member.objects.create()
            membership_parms = {}
            for k, v in indict.items():
                field = mapping[k.strip()]
                #  FIXME We're special casing the Membership here, but really Field.setter should handle that
                #  (In the case of 'member.memberships.last()' for the getter it should create a new Membership
                #  if no Membership exists.)
                if field.field_id.startswith("membership__"):
                    if v:
                        membership_parms[field.field_id.split('__', 1)[1]] = v
                else:
                    field.setter(member, v)
            member.log(view, '.created')
            member.save()
            create_membership(membership_parms, member)

    return redirect(reverse('office:members.list'))
Esempio n. 8
0
def default_csv_form_valid(view, form, dialect="excel"):
    mapping = None
    fields = Member.get_fields()
    encoding = get_encoding(form)

    with form.cleaned_data["upload_file"].open() as fp:
        instream = unicodecsv.DictReader(fp,
                                         dialect=dialect,
                                         encoding=encoding)

        for indict in instream:
            if mapping is None:
                mapping = {}
                for k in indict.keys():
                    if not k.strip():
                        continue
                    for field in fields.values():
                        if str(field.name).strip() == k.strip():
                            mapping[k.strip()] = field
                            break
                    else:
                        messages.error(
                            view.request,
                            _("Couldn't map input column '{}' to field").
                            format(k.strip()),
                        )
                        return redirect(view.request.get_full_path())

            do_update = False
            have_changes = False
            for verb_name, field in mapping.items():
                if field.field_id == "_internal_id":
                    member = Member.all_objects.filter(
                        pk=indict[verb_name.strip()]).first()
                    if member:
                        do_update = True
                        del indict[verb_name]

            if not do_update:
                member = Member.objects.create()

            membership_parms = {}
            for k, v in indict.items():
                if k.strip() not in mapping:
                    continue
                field = mapping[k.strip()]
                #  FIXME We're special casing the Membership here, but really Field.setter should handle that
                #  (In the case of 'member.memberships.last()' for the getter it should create a new Membership
                #  if no Membership exists.)
                if field.field_id.startswith("membership__"):
                    if v:
                        membership_parms[field.field_id.split("__", 1)[1]] = v
                else:
                    if do_update:
                        old_v = field.getter(member)
                        if old_v != v and not (old_v is None and not v):
                            field.setter(member, v)
                            have_changes = True
                    else:
                        field.setter(member, v)

            if do_update:
                if have_changes:
                    member.log(view, ".updated")
                    member.save()
            else:
                member.log(view, ".created")
                member.save()

                # FIXME Changing membership when do_update is not implemented
                if membership_parms:
                    create_membership(membership_parms, member)

    return redirect(reverse("office:members.list"))
Esempio n. 9
0
def member():
    return Member.create_member(email='*****@*****.**')
Esempio n. 10
0
def default_csv_form_valid(view, form, dialect="excel"):
    mapping = None
    fields = Member.get_fields()
    encoding = get_encoding(form)

    with form.cleaned_data["upload_file"].open() as fp:
        instream = unicodecsv.DictReader(fp,
                                         dialect=dialect,
                                         encoding=encoding)

        for indict in instream:
            if mapping is None:
                mapping = {}
                for k in indict.keys():
                    if not k.strip():
                        continue
                    for field in fields.values():
                        if str(field.name).strip() == k.strip():
                            mapping[k.strip()] = field
                            break
                    else:
                        messages.error(
                            view.request,
                            _("Couldn't map input column '{}' to field").
                            format(k.strip()),
                        )
                        return redirect(view.request.get_full_path())

            do_update = False
            have_changes = False
            create_initial_balance = False
            initial_balance = None
            initial_balance_timestamp = None
            for verb_name, field in mapping.items():
                if field.field_id == "_internal_id":
                    member = Member.all_objects.filter(
                        pk=indict[verb_name.strip()]).first()
                    if member:
                        do_update = True
                        del indict[verb_name]

            if not do_update:
                member = Member.objects.create()

            membership_parms = {}
            for k, v in indict.items():
                if k.strip() not in mapping:
                    continue
                field = mapping[k.strip()]
                #  FIXME We're special casing the Membership here, but really Field.setter should handle that
                #  (In the case of 'member.memberships.last()' for the getter it should create a new Membership
                #  if no Membership exists.)
                if field.field_id.startswith("membership__"):
                    if v:
                        membership_parms[field.field_id.split("__", 1)[1]] = v
                else:
                    if do_update:
                        old_v = field.getter(member)
                        if old_v != v and not (old_v is None and not v):
                            field.setter(member, v)
                            have_changes = True
                    else:
                        if field.field_id == "_internal_balance":
                            if dialect == csv_excel_de:
                                v = v.replace(".", "").replace(",", ".")
                            initial_balance = Decimal(v)
                            if initial_balance != 0:
                                create_initial_balance = True
                        elif field.field_id == "_internal_last_transaction":
                            if v != "" and v is not None:
                                initial_balance_timestamp = dateparser.parse(
                                    v,
                                    languages=[settings.LANGUAGE_CODE, "en"])
                                create_initial_balance = True
                        else:
                            field.setter(member, v)

            if do_update:
                if have_changes:
                    member.log(view, ".updated")
                    member.save()
            else:
                if create_initial_balance and not initial_balance_timestamp:
                    messages.error(
                        view.request,
                        _("Either both or none columns has to be given: '{}' and '{}'"
                          ).format(
                              fields["_internal_balance"].name,
                              fields["_internal_last_transaction"].name,
                          ),
                    )
                    return redirect(view.request.get_full_path())

                member.log(view, ".created")
                member.save()

                # FIXME Changing membership when do_update is not implemented
                if membership_parms:
                    create_membership(membership_parms, member)

                if create_initial_balance:

                    balance_changed = member.adjust_balance(
                        view,
                        "Initial Balance created by CSV Import",
                        initial_balance,
                        SpecialAccounts.fees_receivable,
                        SpecialAccounts.opening_balance,
                        initial_balance_timestamp,
                    )

                    if balance_changed:
                        member.log(view,
                                   ".finance.initial_balance",
                                   balance=member.balance)

    return redirect(reverse("office:members.list"))
Esempio n. 11
0
def test_member_field_writing_sepa_iban(member):
    f = Member.get_fields()

    f['MemberSepa__iban'].setter(member, 'DE491234567890')
    assert member.profile_sepa.iban == 'DE491234567890'
Esempio n. 12
0
def test_member_field_writing(member):
    f = Member.get_fields()

    assert member.name != 'Fnord'
    f['member__name'].setter(member, 'Fnord')
    assert member.name == 'Fnord'
Esempio n. 13
0
def test_member_field_writing_sepa_iban(member):
    f = Member.get_fields()

    f["MemberSepa__iban"].setter(member, "DE491234567890")
    assert member.profile_sepa.iban == "DE491234567890"
Esempio n. 14
0
def test_member_field_writing(member):
    f = Member.get_fields()

    assert member.name != "Fnord"
    f["member__name"].setter(member, "Fnord")
    assert member.name == "Fnord"