예제 #1
0
def del_rel(who, _with, how):
    """ Removes a relation given by names.

    For instance: del_rel('giedo', 'leden', None) """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    Es.rcol.remove({'who': who, 'with': _with, 'how': how})
예제 #2
0
파일: shell.py 프로젝트: mrngm/kninfra
def del_rel(who, _with, how):
    """ Removes a relation given by names.

    For instance: del_rel('giedo', 'leden', None) """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    Es.rcol.remove({'who': who,
                    'with': _with,
                    'how': how})
예제 #3
0
파일: shell.py 프로젝트: mrngm/kninfra
def end_rel(who, _with, how, at=None):
    """ Ends a relation given by names.

    For instance: end_rel('giedo', 'leden', None, '2012-04-09') """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    at = str_to_date(at) if at is not None else now()
    Es.rcol.update({'who': who,
                    'with': _with,
                    'how': how,
                    'until': DT_MAX}, {'$set': {'until': at}})
예제 #4
0
파일: shell.py 프로젝트: mrngm/kninfra
def qrel(who=-1, _with=-1, how=-1, _from=None, until=None):
    """ Queries relations """
    if who not in (None, -1):
        who = Es.id_by_name(who)
    if _with not in (None, -1):
        _with = Es.id_by_name(_with)
    if how not in (None, -1):
        how = Es.ecol.find_one({'sofa_suffix': how})['_id']
    if _from not in (None, -1):
        _from = str_to_date(_from)
    if until not in (None, -1):
        until = str_to_date(until)
    return list(Es.query_relations(who, _with, how, _from, until, True,
                                   True, True))
예제 #5
0
def qrel(who=-1, _with=-1, how=-1, _from=None, until=None):
    """ Queries relations """
    if who not in (None, -1):
        who = Es.id_by_name(who)
    if _with not in (None, -1):
        _with = Es.id_by_name(_with)
    if how not in (None, -1):
        how = Es.ecol.find_one({'sofa_suffix': how})['_id']
    if _from not in (None, -1):
        _from = str_to_date(_from)
    if until not in (None, -1):
        until = str_to_date(until)
    return list(
        Es.query_relations(who, _with, how, _from, until, True, True, True))
예제 #6
0
파일: shell.py 프로젝트: mrngm/kninfra
def add_rel(who, _with, how, _from, until):
    """ Adds a relation given by strings.

    For instance: add_rel('giedo', 'bestuur', 'voorzitter', '2004-09-01',
                '2006-09-01') """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    _from = str_to_date(_from) if _from is not None else DT_MIN
    until = str_to_date(until) if until is not None else DT_MAX
    Es.rcol.insert({'who': who,
                    'with': _with,
                    'how': how,
                    'from': _from,
                    'until': until})
예제 #7
0
    def search(self, q, user):
        required_visibility = self.required_visibility(user)
        query_filter = {"path": self.mongo_path_prefix, "effectiveVisibility": {"$in": tuple(required_visibility)}}
        if q.startswith("album:"):
            album = q[len("album:") :]
            query_filter["type"] = "album"
            query_filter = {
                "$and": [
                    query_filter,
                    {
                        "$or": [
                            {"name": {"$regex": re.compile(re.escape(album), re.IGNORECASE)}},
                            {"title": {"$regex": re.compile(re.escape(album), re.IGNORECASE)}},
                        ]
                    },
                ]
            }
        elif q.startswith("tag:"):
            _id = Es.id_by_name(q[len("tag:") :])
            if _id is None:
                return
            query_filter["type"] = {"$ne": "album"}
            query_filter["tags"] = _id
        else:
            # do a full-text search
            for result in db.command(
                "text", "fotos", search=q, filter=query_filter, limit=96  # dividable by 2, 3 and 4
            )["results"]:
                yield entity(result["obj"])
            return

        # search for album or tag
        for o in fcol.find(query_filter).sort("date", -1):
            yield entity(o)
예제 #8
0
    def search(self, q, user):
        required_visibility = self.required_visibility(user)
        query_filter = {'path': self.mongo_path_prefix,
                        'effectiveVisibility': {
                            '$in': tuple(required_visibility)}}
        if q.startswith('album:'):
            album = q[len('album:'):]
            query_filter['type'] = 'album'
            query_filter = {'$and': [
                query_filter,
                {'$or': [
                    {'name': {'$regex': re.compile(re.escape(album),
                                                   re.IGNORECASE)}},
                    {'title': {'$regex': re.compile(re.escape(album),
                                                    re.IGNORECASE)}}
                ]}]}
        elif q.startswith('tag:'):
            _id = Es.id_by_name(q[len('tag:'):])
            if _id is None:
                return
            query_filter['type'] = {'$ne': 'album'}
            query_filter['tags'] = _id
        else:
            # do a full-text search
            query_filter['$text'] = {'$search': q}

        # Don't let non-logged-in users search individual photos, to avoid
        # exposing tags.
        if user is None or not user.is_authenticated():
            query_filter['type'] = 'album'

        # search for album or tag
        for o in fcol.find(query_filter).sort('date', -1):
            yield entity(o)
예제 #9
0
def main():
    now = Es.now()
    for n, r in enumerate(sorted(Es.query_relations(
            _with=Es.id_by_name('leden'), _from=now, until=now,
            deref_who=True),
                key=lambda r: r['from'])): 
        print n+1, r['who'].humanName
예제 #10
0
    def search(self, q, user):
        required_visibility = self.required_visibility(user)
        query_filter = {'path': self.mongo_path_prefix,
                        'effectiveVisibility': {'$in': tuple(required_visibility)}}
        if q.startswith('album:'):
            album = q[len('album:'):]
            query_filter['type'] = 'album'
            query_filter = {'$and': [
                query_filter,
                {'$or': [
                    {'name': {'$regex': re.compile(re.escape(album),
                                                   re.IGNORECASE)}},
                    {'title': {'$regex': re.compile(re.escape(album),
                                                    re.IGNORECASE)}}
                ]}]}
        elif q.startswith('tag:'):
            _id = Es.id_by_name(q[len('tag:'):])
            if _id is None:
                return
            query_filter['type'] = {'$ne': 'album'}
            query_filter['tags'] = _id
        else:
            # do a full-text search
            for result in db.command('text', 'fotos',
                        search=q,
                        filter=query_filter,
                        limit=96, # dividable by 2, 3 and 4
                      )['results']:
                yield entity(result['obj'])
            return

        # search for album or tag
        for o in fcol.find(query_filter).sort('date', -1):
            yield entity(o)
예제 #11
0
def create_year_overrides_for(year):
    """ Creates the year overrides for a certain year """
    parent_tag = Es.id_by_name('!year-overrides')
    Es.ecol.insert({
        'humanNames': [{
            six.u('human'): six.u('Wel jaar {}').format(year)
        }],
        'tags': [parent_tag],
        'types': ['tag'],
        'year-override': {
            'type': True,
            'year': year
        }
    })
    Es.ecol.insert({
        'humanNames': [{
            six.u('human'): six.u('Niet jaar {}').format(year)
        }],
        'tags': [parent_tag],
        'types': ['tag'],
        'year-override': {
            'type': False,
            'year': year
        }
    })
예제 #12
0
def main():
    year_overrides = dict()
    had = set()
    for t in Es.bearers_by_tag_id(Es.id_by_name('!year-overrides'),
                                  _as=Es.Tag):
        year_overrides[(t._data['year-override']['type'],
                        t._data['year-override']['year'])] = t._data['_id']
    for rel in sorted(Es.query_relations(-1, Es.id_by_name('leden'), None,
                                         None, None, True, False, False),
                      cmp=lambda x, y: cmp(x['from'], y['from'])):
        name = str(rel['who'].name)
        if name in had:
            continue
        if ('temp' not in rel['who']._data
                or 'joined' not in rel['who']._data['temp']):
            had.add(name)
            continue
        joined = datetime.datetime.strptime(rel['who']._data['temp']['joined'],
                                            '%Y-%m-%d')
        if joined == rel['from']:
            had.add(name)
            continue
        joined_yr = Es.date_to_year(joined)
        from_yr = Es.date_to_year(rel['from'])
        if joined_yr == from_yr or joined_yr == 0:
            print name, rel['from'].date(), ' -> ', \
                                joined.date()
            rrel = Es.rcol.find({'_id': rel['_id']})[0]
            rrel['from'] = joined
            Es.rcol.save(rrel)
            had.add(name)
            continue
        if joined_yr == from_yr - 1:
            print name, rel['from'].date(), ' -> ', \
                                joined.date()
            rrel = Es.rcol.find({'_id': rel['_id']})[0]
            rrel['from'] = joined
            if not 'tags' in rrel:
                rrel['tags'] = []
            if not year_overrides[(False, joined_yr)] in rrel['tags']:
                rrel['tags'].append(year_overrides[(False, joined_yr)])
            Es.rcol.save(rrel)
            had.add(name)
            continue
        print 'MANUAL REVIEW: ', name, \
                    joined.date(), rel['from'].date()
def main():
    year_overrides = dict()
    had = set()
    for t in Es.bearers_by_tag_id(
            Es.id_by_name('!year-overrides'),
            _as=Es.Tag):
        year_overrides[(t._data['year-override']['type'],
                        t._data['year-override']['year'])] = t._data['_id']
    for rel in sorted(Es.query_relations(-1, Es.id_by_name('leden'), None,
                                         None, None, True, False, False),
                      key=lambda x: x['from']):
        name = str(rel['who'].name)
        if name in had:
            continue
        if ('temp' not in rel['who']._data or
                'joined' not in rel['who']._data['temp']):
            had.add(name)
            continue
        joined = datetime.datetime.strptime(
            rel['who']._data['temp']['joined'], '%Y-%m-%d')
        if joined == rel['from']:
            had.add(name)
            continue
        joined_yr = Es.date_to_year(joined)
        from_yr = Es.date_to_year(rel['from'])
        if joined_yr == from_yr or joined_yr == 0:
            print(name, rel['from'].date(), ' -> ',
                  joined.date())
            rrel = Es.rcol.find({'_id': rel['_id']})[0]
            rrel['from'] = joined
            Es.rcol.save(rrel)
            had.add(name)
            continue
        if joined_yr == from_yr - 1:
            print(name, rel['from'].date(), ' -> ',
                  joined.date())
            rrel = Es.rcol.find({'_id': rel['_id']})[0]
            rrel['from'] = joined
            if 'tags' not in rrel:
                rrel['tags'] = []
            if not year_overrides[(False, joined_yr)] in rrel['tags']:
                rrel['tags'].append(year_overrides[(False, joined_yr)])
            Es.rcol.save(rrel)
            had.add(name)
            continue
        print('MANUAL REVIEW: ', name, joined.date(), rel['from'].date())
예제 #14
0
def end_rel(who, _with, how, at=None):
    """ Ends a relation given by names.

    For instance: end_rel('giedo', 'leden', None, '2012-04-09') """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    at = str_to_date(at) if at is not None else now()
    Es.rcol.update({
        'who': who,
        'with': _with,
        'how': how,
        'until': DT_MAX
    }, {'$set': {
        'until': at
    }})
예제 #15
0
def main():
    now = Es.now()
    for n, r in enumerate(
            sorted(Es.query_relations(_with=Es.id_by_name('leden'),
                                      _from=now,
                                      until=now,
                                      deref_who=True),
                   key=lambda r: r['from'])):
        print(n + 1, r['who'].humanName)
예제 #16
0
파일: fin.py 프로젝트: Blackeel/kninfra
def get_account_entities_of(user):
    """returns the entities whose accounts the user may inspect:
    for the moment the user itself and all the committees it belongs to"""
    comms_id = Es.id_by_name("comms")
    result = [user]
    for group in user.cached_groups:
        if group.has_tag(comms_id):
            result.append(group)
    return result
예제 #17
0
def add_rel(who, _with, how, _from, until):
    """ Adds a relation given by strings.

    For instance: add_rel('giedo', 'bestuur', 'voorzitter', '2004-09-01',
                '2006-09-01') """
    who = Es.id_by_name(who)
    _with = Es.id_by_name(_with)
    how = (Es.ecol.find_one({'sofa_suffix': how})['_id']
           if how is not None else None)
    _from = str_to_date(_from) if _from is not None else DT_MIN
    until = str_to_date(until) if until is not None else DT_MAX
    Es.rcol.insert({
        'who': who,
        'with': _with,
        'how': how,
        'from': _from,
        'until': until
    })
예제 #18
0
파일: fin.py 프로젝트: aykevl/kninfra
def get_account_entities_of(user):
    """returns the entities whose accounts the user may inspect:
    for the moment the user itself and all the committees it belongs to"""
    comms_id = Es.id_by_name("comms")
    result = [user]
    for group in user.cached_groups:
        if group.has_tag(comms_id):
            result.append(group)
    return result
예제 #19
0
def create_extern(humanName, email, name=None):
    Es.ecol.insert({
        'names': [name] if name else [],
        'humanNames': [{'human': humanName}],
        'types': ['user'],
        'tags': [Es.id_by_name('externen')],
        'is_active': False,
        'has_unix_user': False,
        'email': email,
    })
예제 #20
0
def load_year_overrides():
    print 'loading year-overrides ...'
    year_overrides = {}
    for t in Es.bearers_by_tag_id(Es.id_by_name('!year-overrides'), _as=Es.Tag):
        year_overrides[(t._data['year-override']['type'],
                        t._data['year-override']['year'])] = t._id
    assert year_overrides
    years = frozenset([t[1] for t in year_overrides.keys()])
    min_year, max_year = min(years), max(years)
    return years, year_overrides, min_year, max_year
예제 #21
0
def create_brand(name, humanName):
    Es.ecol.insert({
        'humanNames': [{
            'human': humanName
        }],
        'names': ['!brand-' + name],
        'sofa_suffix': name,
        'tags': [Es.id_by_name('!sofa-brand')],
        'types': ['brand']
    })
예제 #22
0
def load_year_overrides():
    print('loading year-overrides ...')
    year_overrides = {}
    for t in Es.bearers_by_tag_id(Es.id_by_name('!year-overrides'),
                                  _as=Es.Tag):
        year_overrides[(t._data['year-override']['type'],
                        t._data['year-override']['year'])] = t._id
    assert year_overrides
    years = frozenset([t[1] for t in year_overrides.keys()])
    min_year, max_year = min(years), max(years)
    return years, year_overrides, min_year, max_year
예제 #23
0
def create_extern(humanName, email, name=None):
    Es.ecol.insert({
        'names': [name] if name else [],
        'humanNames': [{
            'human': humanName
        }],
        'types': ['user'],
        'tags': [Es.id_by_name('externen')],
        'is_active': False,
        'has_unix_user': False,
        'email': email,
    })
예제 #24
0
def create_year_overrides_for(year):
    """ Creates the year overrides for a certain year """
    parent_tag = Es.id_by_name('!year-overrides')
    Es.ecol.insert({
        'humanNames': [{six.u('human'): six.u('Wel jaar {}').format(year)}],
        'tags': [parent_tag],
        'types': ['tag'],
        'year-override': {'type': True, 'year': year}})
    Es.ecol.insert({
        'humanNames': [{six.u('human'): six.u('Niet jaar {}').format(year)}],
        'tags': [parent_tag],
        'types': ['tag'],
        'year-override': {'type': False, 'year': year}})
예제 #25
0
def _group_detail(request, group):
    ctx = _entity_detail(request, group)
    isFreeToJoin = group.has_tag(Es.id_by_name("!free-to-join", True))
    rel_id = None
    if isFreeToJoin:
        dt = now()
        rel = list(Es.query_relations(request.user, group, None, dt, dt, False, False, False))
        assert len(rel) <= 1
        for r in rel:
            rel_id = r["_id"]
    ctx.update(
        {"isFreeToJoin": group.has_tag(Es.by_name("!free-to-join")), "request": request, "relation_with_group": rel_id}
    )
    return render_to_response("leden/group_detail.html", ctx, context_instance=RequestContext(request))
예제 #26
0
def main():
    # Fetch year overrides
    print 'loading year overrides ...'
    year_overrides = {}
    for t in Es.bearers_by_tag_id(Es.id_by_name('!year-overrides'), _as=Es.Tag):
        year_overrides[(t._data['year-override']['type'],
                        t._data['year-override']['year'])] = t._id
    assert year_overrides
    years = [t[1] for t in year_overrides.keys()]
    min_year, max_year = min(years), max(years)
    leden_id = Es.id_by_name('leden')
    print 'checking ...'
    for year in xrange(min_year+1, max_year+1):
        start_of_year = Es.year_to_range(year)[0]
        informal_start = start_of_year - datetime.timedelta(3*365/12)
        for rel in Es.rcol.find({'with': leden_id,
                                 'from': {'$gt': informal_start,
                                          '$lt': start_of_year}}):
            if year_overrides[(False, year-1)] in rel.get('tags', ()):
                continue
            if 'tags' not in rel:
                rel['tags'] = []
            rel['tags'].append(year_overrides[(False, year-1)])
            print Es.by_id(rel['who']).name, year
예제 #27
0
def _group_detail(request, group):
    ctx = _entity_detail(request, group)
    isFreeToJoin = group.has_tag(Es.id_by_name('!free-to-join', True))
    rel_id = None
    if isFreeToJoin:
        dt = now()
        rel = list(Es.query_relations(request.user, group, None,
                                      dt, dt, False, False, False))
        assert len(rel) <= 1
        for r in rel:
            rel_id = r['_id']
    ctx.update({'isFreeToJoin': group.has_tag(Es.by_name('!free-to-join')),
                'request': request,
                'relation_with_group': rel_id})
    return render(request, 'leden/group_detail.html', ctx)
예제 #28
0
파일: views.py 프로젝트: Jille/kninfra
def _group_detail(request, group):
    ctx = _entity_detail(request, group)
    isFreeToJoin = group.has_tag(Es.id_by_name('!free-to-join', True))
    rel_id = None
    if isFreeToJoin:
        dt = now()
        rel = list(Es.query_relations(request.user, group, None,
                                        dt, dt, False, False, False))
        assert len(rel) <= 1
        for r in rel:
            rel_id = r['_id']
    ctx.update({'isFreeToJoin': group.has_tag(Es.by_name('!free-to-join')),
        'request': request,
        'relation_with_group': rel_id})
    return render_to_response('leden/group_detail.html', ctx,
            context_instance=RequestContext(request))
예제 #29
0
def _generate_member_count():
    events = []
    for rel in Es.query_relations(_with=Es.id_by_name('leden'), how=None):
        events.append((max(rel['from'], Es.DT_MIN), True))
        if rel['until'] != Es.DT_MAX:
            events.append((rel['until'], False))
    N = 0
    old_days = -1
    old_N = None
    ret = []
    for when, what in sorted(events, key=lambda x: x[0]):
        N += 1 if what else -1
        days = (when - Es.DT_MIN).days
        if old_days != days:
            if old_N:
                ret.append([old_days, old_N])
            old_days = days
            old_N = N
    ret.append([days, N])
    ret = [(1 + days / 365.242, N) for days, N in ret]
    return ret
예제 #30
0
파일: graphs.py 프로젝트: yorickvP/kninfra
def _generate_member_count():
    events = []
    for rel in Es.query_relations(_with=Es.id_by_name('leden'), how=None):
        events.append((max(rel['from'], Es.DT_MIN), True))
        if rel['until'] != Es.DT_MAX:
            events.append((rel['until'], False))
    N = 0
    old_days = -1
    old_N = None
    ret = []
    for when, what in sorted(events, key=lambda x: x[0]):
        N += 1 if what else -1
        days = (when - Es.DT_MIN).days
        if old_days != days:
            if old_N:
                ret.append([old_days, old_N])
            old_days = days
            old_N = N
    ret.append([days, N])
    ret = [(1 + days2 / 365.242, N2) for days2, N2 in ret]
    return ret
예제 #31
0
def secr_add_user(request):
    if "secretariaat" not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == "POST":
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User(
                {
                    "types": ["user"],
                    "names": [fd["username"]],
                    "humanNames": [{"human": fd["first_name"] + " " + fd["last_name"]}],
                    "person": {
                        "titles": [],
                        "nick": fd["first_name"],
                        "given": None,
                        "family": fd["last_name"],
                        "gender": fd["gender"],
                        "dateOfBirth": date_to_dt(fd["dateOfBirth"]),
                    },
                    "emailAddresses": [{"email": fd["email"], "from": DT_MIN, "until": DT_MAX}],
                    "addresses": [
                        {
                            "street": fd["addr_street"],
                            "number": fd["addr_number"],
                            "zip": fd["addr_zip"],
                            "city": fd["addr_city"],
                            "from": DT_MIN,
                            "until": DT_MAX,
                        }
                    ],
                    "telephones": [{"number": fd["telephone"], "from": DT_MIN, "until": DT_MAX}],
                    "studies": [
                        {
                            "institute": _id(fd["study_inst"]),
                            "study": _id(fd["study"]),
                            "from": DT_MIN,
                            "until": DT_MAX,
                            "number": fd["study_number"],
                        }
                    ],
                    "is_active": True,
                    "password": None,
                }
            )
            logging.info("Added user %s" % fd["username"])
            u.save()
            # Then, add the relations.
            groups = ["leden"]
            groups.append({"m": "mannen", "v": "vrouwen"}.get(fd["gender"]))
            if fd["incasso"]:
                groups.append("incasso")
            else:
                groups.append("geen-incasso")
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group, use_cache=True), _from=date_to_dt(fd["dateJoined"]))
            for l in fd["addToList"]:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True), _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {"user": u, "password": pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {"u": u})
            Es.notify_informacie("adduser", request.user, entity=u._id)
            return HttpResponseRedirect(reverse("user-by-name", args=(fd["username"],)))
    else:
        form = AddUserForm()
    return render_to_response("leden/secr_add_user.html", {"form": form}, context_instance=RequestContext(request))
예제 #32
0
파일: entities.py 프로젝트: aykevl/kninfra
def may_set_owner(user, owner):
    if is_superuser(owner):
        return True
    comms = Es.id_by_name('comms', use_cache=True)
    allowTag = Es.id_by_name('!can-organize-official-events', use_cache=True)
    return owner.has_tag(comms) or owner.has_tag(allowTag)
예제 #33
0
파일: shell.py 프로젝트: aykevl/kninfra
def create_brand(suffix, name):
    Es.ecol.insert({'humanNames': [{'human': name}],
                    'names': [],
                    'sofa_suffix': suffix,
                    'tags': [Es.id_by_name('!sofa-brand')],
                    'types': ['brand']})
예제 #34
0
파일: views.py 프로젝트: Blackeel/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{
                    'human':
                    fd['first_name'] + ' ' + fd['last_name']
                }],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(fd['dateOfBirth'])
                },
                'email':
                fd['email'],
                'address': {
                    'street': fd['addr_street'],
                    'number': fd['addr_number'],
                    'zip': fd['addr_zip'],
                    'city': fd['addr_city']
                },
                'telephone':
                fd['telephone'],
                'studies': [{
                    'institute': _id(fd['study_inst']),
                    'study': _id(fd['study']),
                    'from': DT_MIN,
                    'until': DT_MAX,
                    'number': fd['study_number']
                }],
                'is_active':
                True,
                'password':
                None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u,
                                Es.id_by_name(group, use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u,
                                Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.html", u, {
                'user': u,
                'password': pwd
            })
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.html", u, {'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(
                reverse('user-by-name', args=(fd['username'], )))
    else:
        form = AddUserForm()
    return render(request, 'leden/secr_add_user.html', {'form': form})
예제 #35
0
파일: shell.py 프로젝트: mrngm/kninfra
def create_brand(name, humanName):
    Es.ecol.insert({'humanNames': [{'human': humanName}],
                    'names': ['!brand-'+name],
                    'sofa_suffix': name,
                    'tags': [Es.id_by_name('!sofa-brand')],
                    'types': ['brand']})
예제 #36
0
def main():
    parser = argparse.ArgumentParser(description="Prepare for the next year")
    parser.add_argument('--apply',
                        action='store_true',
                        help=('Apply the changes.  By default the changes '
                              'are only displayed'))
    args = parser.parse_args()

    # Fetch year overrides
    while True:
        years, year_overrides, min_year, max_year = load_year_overrides()
        assert len(years) == max_year - min_year + 1  # year-override missing?
        current_year = Es.date_to_year(datetime.datetime.now())
        if current_year == max_year:
            print(' adding year-overrides for year', current_year + 1)
            if args.apply:
                create_year_overrides_for(current_year + 1)
            continue
        break

    today = datetime.datetime.today()
    max_year = today.year - Es.DT_MIN.year + 1

    # Fetch ids of all current members
    leden_id = Es.id_by_name('leden')

    print('If you became a member after june,'
          ' you should be in the next year ...')
    for year in range(min_year + 1, max_year):
        start_of_year = Es.year_to_range(year)[0]
        informal_start = start_of_year - datetime.timedelta(3 * 365 / 12)
        for rel in Es.rcol.find({
                'with': leden_id,
                'from': {
                    '$gt': informal_start,
                    '$lt': start_of_year
                }
        }):
            if year_overrides[(False, year - 1)] in rel.get('tags', ()):
                continue
            if 'tags' not in rel:
                rel['tags'] = []
            rel['tags'].append(year_overrides[(False, year - 1)])
            print(' ', Es.by_id(rel['who']).name, '-' + str(year - 1))
            if args.apply:
                Es.rcol.save(rel)

    print('Any relation that starts near the change of year, should start')
    print('exactly on the change of year ...')
    for year in range(min_year + 1, max_year):
        start_of_year = Es.year_to_range(year)[0]
        window = datetime.timedelta(1, 12 * 60 * 60)
        for rel in Es.rcol.find({
                'from': {
                    '$gt': start_of_year - window,
                    '$lt': start_of_year + window
                }
        }):
            if rel['from'] == start_of_year:
                continue
            how = Es.by_id(rel['how'])
            print(' {} {} (as {}): {} -> {}'.format(
                six.text_type(Es.by_id(rel['who'])),
                str(Es.by_id(rel['with'])),
                how._data['sofa_suffix'] if how else 'member', rel['from'],
                start_of_year))
            if args.apply:
                rel['from'] = start_of_year
                Es.rcol.save(rel)

    print('Any relation that ends near the change of year, should end')
    print('exactly on the change of year ...')
    for year in range(min_year + 1, max_year):
        start_of_year = Es.year_to_range(year)[0]
        end_of_year = Es.year_to_range(year)[0] - datetime.timedelta(0, 1)
        window = datetime.timedelta(1, 12 * 60 * 60)
        for rel in Es.rcol.find({
                'until': {
                    '$gt': start_of_year - window,
                    '$lt': start_of_year + window
                }
        }):
            if rel['until'] == end_of_year:
                continue
            how = Es.by_id(rel['how'])
            print(' {} {} (as {}): {} -> {}'.format(
                six.text_type(Es.by_id(rel['who'])),
                str(Es.by_id(rel['with'])),
                how._data['sofa_suffix'] if how else 'member', rel['until'],
                end_of_year))
            if args.apply:
                rel['until'] = end_of_year
                Es.rcol.save(rel)

    print('End eerstejaars relations from previous year ...')
    ej = Es.by_name('eerstejaars')
    members = Es.rcol.find({'with': ej._data['_id'], 'until': Es.DT_MAX})
    for r in sorted(members, key=lambda r: r['from']):
        member = Es.by_id(r['who'])
        if r['from'] >= datetime.datetime(today.year, 7, 1):
            continue  # Only just became a member, don't remove.
        until = datetime.datetime(today.year, 8, 31, 23, 59, 59)
        print(' {:25} from {:26} until None -> {}'.format(
            member.humanName, str(r['from']), str(until)))
        if args.apply:
            r['until'] = until
            Es.rcol.save(r)
예제 #37
0
파일: views.py 프로젝트: mrngm/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            # First, create the entity.
            u = Es.User({
                'types': ['user'],
                'names': [fd['username']],
                'humanNames': [{'human': fd['first_name'] + ' ' +
                                fd['last_name']}],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'dateOfBirth': date_to_dt(
                        fd['dateOfBirth'])
                },
                'emailAddresses': [
                    {'email': fd['email'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'addresses': [
                    {'street': fd['addr_street'],
                     'number': fd['addr_number'],
                     'zip': fd['addr_zip'],
                     'city': fd['addr_city'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'telephones': [
                    {'number': fd['telephone'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'studies': [
                    {'institute': _id(fd['study_inst']),
                     'study': _id(fd['study']),
                     'from': DT_MIN,
                     'until': DT_MAX,
                     'number': fd['study_number']}],
                'is_active': True,
                'password': None
            })
            logging.info("Added user %s" % fd['username'])
            u.save()
            # Then, add the relations.
            groups = ['leden']
            if fd['incasso']:
                groups.append('incasso')
            else:
                groups.append('geen-incasso')
            for group in groups:
                Es.add_relation(u, Es.id_by_name(group,
                                                 use_cache=True),
                                _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True),
                                _from=now())
            # Let giedo synch. to create the e-mail adresses, unix user, etc.
            # TODO use giedo.async() and let giedo send the welcome e-mail
            giedo.sync()
            # Create a new password and send it via e-mail
            pwd = pseudo_randstr()
            u.set_password(pwd)
            giedo.change_password(str(u.name), pwd, pwd)
            render_then_email("leden/set-password.mail.txt", u, {
                'user': u,
                'password': pwd})
            # Send the welcome e-mail
            render_then_email("leden/welcome.mail.txt", u, {
                'u': u})
            Es.notify_informacie('adduser', request.user, entity=u._id)
            return HttpResponseRedirect(reverse('user-by-name',
                                                args=(fd['username'],)))
    else:
        form = AddUserForm()
    return render_to_response('leden/secr_add_user.html',
                              {'form': form},
                              context_instance=RequestContext(request))
예제 #38
0
def main():
    parser = argparse.ArgumentParser(description="Prepare for the next year")
    parser.add_argument('--apply', action='store_true',
                        help=('Apply the changes.  By default the changes '
                              'are only displayed'))
    args = parser.parse_args()

    # Fetch year overrides
    while True:
        years, year_overrides, min_year, max_year = load_year_overrides()
        assert len(years) == max_year - min_year + 1  # year-override missing?
        current_year = Es.date_to_year(datetime.datetime.now())
        if current_year == max_year:
            print(' adding year-overrides for year', current_year + 1)
            if args.apply:
                create_year_overrides_for(current_year + 1)
            continue
        break

    # Fetch ids of all current members
    leden_id = Es.id_by_name('leden')

    print('If you became a member after june,'
          ' you should be in the next year ...')
    for year in range(min_year + 1, max_year + 1):
        start_of_year = Es.year_to_range(year)[0]
        informal_start = start_of_year - datetime.timedelta(3 * 365 / 12)
        for rel in Es.rcol.find({'with': leden_id,
                                 'from': {'$gt': informal_start,
                                          '$lt': start_of_year}}):
            if year_overrides[(False, year - 1)] in rel.get('tags', ()):
                continue
            if 'tags' not in rel:
                rel['tags'] = []
            rel['tags'].append(year_overrides[(False, year - 1)])
            print(' ', Es.by_id(rel['who']).name, '-' + str(year - 1))
            if args.apply:
                Es.rcol.save(rel)

    print('Any relation that starts near the change of year, should start')
    print('exactly on the change of year ...')
    for year in range(min_year + 1, max_year + 1):
        start_of_year = Es.year_to_range(year)[0]
        window = datetime.timedelta(1, 12 * 60 * 60)
        for rel in Es.rcol.find({'from': {'$gt': start_of_year - window,
                                          '$lt': start_of_year + window}}):
            if rel['from'] == start_of_year:
                continue
            how = Es.by_id(rel['how'])
            print(' {} {} (as {}): {} -> {}'.format(
                six.text_type(Es.by_id(rel['who'])),
                str(Es.by_id(rel['with'])),
                how._data['sofa_suffix'] if how else 'member',
                rel['from'], start_of_year
            ))
            if args.apply:
                rel['from'] = start_of_year
                Es.rcol.save(rel)

    print('Any relation that ends near the change of year, should end')
    print('exactly on the change of year ...')
    for year in range(min_year + 1, max_year + 1):
        start_of_year = Es.year_to_range(year)[0]
        end_of_year = Es.year_to_range(year)[0] - datetime.timedelta(0, 1)
        window = datetime.timedelta(1, 12 * 60 * 60)
        for rel in Es.rcol.find({'until': {'$gt': start_of_year - window,
                                           '$lt': start_of_year + window}}):
            if rel['until'] == end_of_year:
                continue
            how = Es.by_id(rel['how'])
            print(' {} {} (as {}): {} -> {}'.format(
                six.text_type(Es.by_id(rel['who'])),
                str(Es.by_id(rel['with'])),
                how._data['sofa_suffix'] if how else 'member',
                rel['until'], end_of_year
            ))
            if args.apply:
                rel['until'] = end_of_year
                Es.rcol.save(rel)
예제 #39
0
파일: views.py 프로젝트: Soyweiser/kninfra
def secr_add_user(request):
    if 'secretariaat' not in request.user.cached_groups_names:
        raise PermissionDenied
    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():
            fd = form.cleaned_data
            nm = find_name_for_user(fd['first_name'],
                        fd['last_name'])
            u = Es.User({
                'types': ['user'],
                'names': [nm],
                'humanNames': [{'human': fd['first_name']+' '+
                             fd['last_name']}],
                'person': {
                    'titles': [],
                    'nick': fd['first_name'],
                    'given': None,
                    'family': fd['last_name'],
                    'gender': fd['sex'],
                    'dateOfBirth': date_to_dt(
                        fd['dateOfBirth'])
                },
                'emailAddresses': [
                    {'email': fd['email'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'addresses': [
                    {'street': fd['addr_street'],
                     'number': fd['addr_number'],
                     'zip': fd['addr_zip'],
                     'city': fd['addr_city'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'telephones': [
                    {'number': fd['telephone'],
                     'from': DT_MIN,
                     'until': DT_MAX}],
                'studies': [
                    {'institute': _id(fd['study_inst']),
                     'study': _id(fd['study']),
                     'from': DT_MIN,
                     'until': DT_MAX,
                     'number': fd['study_number']}],
                'is_active': True,
                'password': None
                })
            logging.info("Added user %s" % nm)
            u.save()
            Es.add_relation(u, Es.id_by_name('leden',
                            use_cache=True),
                    _from=date_to_dt(fd['dateJoined']))
            for l in fd['addToList']:
                Es.add_relation(u, Es.id_by_name(l, use_cache=True),
                    _from=now())
            Es.notify_informacie("%s is ingeschreven als lid." % (
                        u.humanName))
            giedo.sync_async(request)
            request.user.push_message("Gebruiker toegevoegd. "+
                "Let op: hij heeft geen wachtwoord "+
                "en hij moet nog gemaild worden.")
            return HttpResponseRedirect(reverse('user-by-name',
                    args=(nm,)))
    else:
        form = AddUserForm()
    return render_to_response('leden/secr_add_user.html',
            {'form': form},
            context_instance=RequestContext(request))
예제 #40
0
def may_set_owner(user, owner):
    if is_superuser(owner):
        return True
    comms = Es.id_by_name('comms', use_cache=True)
    allowTag = Es.id_by_name('!can-organize-official-events', use_cache=True)
    return owner.has_tag(comms) or owner.has_tag(allowTag)