Example #1
0
def main():
    leden = Es.by_name('leden')
    lut = {}
    id2name = {}
    for m in Es.users():
        if not m.name:
            continue
        lut[str(m.name)] = set()
        id2name[m._id] = str(m.name)
    max_q = Es.date_to_year(Es.now()) * 4
    for q in range(1, max_q + 1):
        start, end = Es.quarter_to_range(q)
        for m in leden.get_rrelated(_from=start, until=end, how=None,
                                    deref_who=False, deref_with=False,
                                    deref_how=False):
            lut[id2name[m['who']]].add(q)
    for i, name in enumerate(sorted(six.itervalues(id2name))):
        if i % 20 == 0:
            print()
            print('%20s %s' % (
                'year',
                ' '.join([str(((q - 1) / 4) + 1).ljust(7)
                          for q in range(1, max_q + 1, 4)])
            ))
            print('%20s %s' % (
                'quarter',
                ' '.join([str(((q - 1) % 4) + 1)
                          for q in range(1, max_q + 1)])
            ))
        print('%-20s %s' % (
            name,
            ' '.join(['*' if q in lut[name] else ' '
                      for q in range(1, max_q + 1)])
        ))
Example #2
0
def main():
    leden = Es.by_name('leden')
    lut = {}
    id2name = {}
    for m in Es.users():
        if not m.name:
            continue
        lut[str(m.name)] = set()
        id2name[m._id] = str(m.name)
    max_q = Es.date_to_year(Es.now()) * 4
    for q in range(1, max_q + 1):
        start, end = Es.quarter_to_range(q)
        for m in leden.get_rrelated(_from=start,
                                    until=end,
                                    how=None,
                                    deref_who=False,
                                    deref_with=False,
                                    deref_how=False):
            lut[id2name[m['who']]].add(q)
    for i, name in enumerate(sorted(six.itervalues(id2name))):
        if i % 20 == 0:
            print()
            print('%20s %s' % ('year', ' '.join([
                str(((q - 1) / 4) + 1).ljust(7)
                for q in range(1, max_q + 1, 4)
            ])))
            print('%20s %s' % ('quarter', ' '.join(
                [str(((q - 1) % 4) + 1) for q in range(1, max_q + 1)])))
        print('%-20s %s' % (name, ' '.join(
            ['*' if q in lut[name] else ' ' for q in range(1, max_q + 1)])))
Example #3
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())
Example #5
0
 def add_years_to_relations(rels):
     years_of_year_overrides = [yo[1] for yo in year_overrides.values()]
     until_years = [
         Es.date_to_year(r['until']) for r in rels if r['until'] != DT_MAX
     ]
     max_until = max(
         max(until_years) if until_years else 0,
         max(years_of_year_overrides) if years_of_year_overrides else 0,
         Es.date_to_year(dt_now))
     from_years = [
         Es.date_to_year(r['from']) for r in rels if r['from'] != DT_MIN
     ]
     min_from = min(
         min(from_years) if from_years else Es.date_to_year(dt_now),
         Es.date_to_year(dt_now))
     for rel in rels:
         s = min_from if rel['from'] == DT_MIN \
                 else Es.date_to_year(rel['from'])
         t = max_until if rel['until'] == DT_MAX \
                 else Es.date_to_year(rel['until'])
         years = set(range(s, t + 1))
         for tid in rel.get('tags', ()):
             if tid not in year_overrides:
                 continue
             tp, yr = year_overrides[tid]
             if tp:
                 years.add(yr)
             else:
                 years.remove(yr)
         rel['years'] = years
Example #6
0
File: db.py Project: aykevl/kninfra
 def add_years_to_relations(rels):
     years_of_year_overrides = [yo[1] for yo
                                in six.itervalues(year_overrides)]
     until_years = [Es.date_to_year(r['until']) for r in rels
                    if r['until'] != DT_MAX]
     max_until = max(
         max(until_years) if until_years else 0,
         max(years_of_year_overrides) if years_of_year_overrides else 0,
         Es.date_to_year(dt_now)
     )
     from_years = [Es.date_to_year(r['from']) for r in rels
                   if r['from'] != DT_MIN]
     min_from = min(min(from_years) if from_years else
                    Es.date_to_year(dt_now),
                    Es.date_to_year(dt_now))
     for rel in rels:
         s = (min_from if rel['from'] == DT_MIN
              else Es.date_to_year(rel['from']))
         t = (max_until if rel['until'] == DT_MAX
              else Es.date_to_year(rel['until']))
         years = set(range(s, t + 1))
         for tid in rel.get('tags', ()):
             if tid not in year_overrides:
                 continue
             tp, yr = year_overrides[tid]
             if tp:
                 years.add(yr)
             else:
                 if yr not in years:
                     logging.warning('bogus year-override -{} on {}'.format(
                         yr, rel['_id']))
                     continue
                 years.remove(yr)
         rel['years'] = years
Example #7
0
 def add_years_to_relations(rels):
         until_years = [Es.date_to_year(r['until']) for r in rels
                                 if r['until'] != DT_MAX]
         max_until = max(max(until_years) if until_years else 0,
                         Es.date_to_year(dt_now))
         from_years = [Es.date_to_year(r['from']) for r in rels
                                 if r['from'] != DT_MIN]
         min_from = min(min(from_years) if from_years else
                         Es.date_to_year(dt_now),
                         Es.date_to_year(dt_now))
         for rel in rels:
                 s = min_from if rel['from'] == DT_MIN \
                                 else Es.date_to_year(rel['from'])
                 t = max_until if rel['until'] == DT_MAX \
                                 else Es.date_to_year(rel['until'])
                 years = set(range(s, t+1))
                 for tid in rel.get('tags', ()):
                         if tid not in year_overrides:
                                 continue
                         yr, tp = year_overrides[tid]
                         if tp:
                                 years.add(yr)
                         else:
                                 years.remove(yr)
                 rel['years'] = years
Example #8
0
def _brand_detail(request, brand):
    ctx = _entity_detail(request, brand)
    ctx['rels'] = sorted(
        Es.query_relations(how=brand, deref_who=True, deref_with=True),
        key=lambda x: (Es.DT_MIN - Es.relation_until(
            x), Es.entity_humanName(x['with']), Es.entity_humanName(x['who'])))
    for r in ctx['rels']:
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else Es.date_to_year(
            r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    return render(request, 'leden/brand_detail.html', ctx)
Example #9
0
def _entity_detail(request, e):
    def _cmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['with'].humanName),
                unicode(y['with'].humanName))
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        return Es.relation_cmp_from(x,y)
    def _rcmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        r = cmp(unicode(x['who'].humanName),
                unicode(y['who'].humanName))
        if r: return r
        return Es.relation_cmp_from(x,y)
    related = sorted(e.get_related(), cmp=_cmp)
    rrelated = sorted(e.get_rrelated(), cmp=_rcmp)
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                    Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]
    ctx = {'related': related,
           'rrelated': rrelated,
           'now': now(),
           'tags': sorted(tags, Es.entity_cmp_humanName),
           'object': e}
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(cmp=lambda x,y: cmp(unicode(x.humanName),
                        unicode(y.humanName)))
        users = sorted(Es.users(), cmp=Es.entity_cmp_humanName)
        brands = sorted(Es.brands(), cmp=Es.entity_cmp_humanName)
        ctx.update({'users': users,
                'brands': brands,
                'groups': groups,
                'may_add_related': True,
                'may_add_rrelated': True})
    if e.is_tag:
        ctx.update({'tag_bearers': sorted(e.as_tag().get_bearers(),
                        cmp=Es.entity_cmp_humanName)})
    return ctx
Example #10
0
def _brand_detail(request, brand):
    ctx = _entity_detail(request, brand)
    ctx['rels'] = sorted(Es.query_relations(how=brand, deref_who=True,
                                            deref_with=True),
                         key=lambda x: (Es.DT_MIN - Es.relation_until(x),
                                        Es.entity_humanName(x['with']),
                                        Es.entity_humanName(x['who'])))
    for r in ctx['rels']:
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                           Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    return render(request, 'leden/brand_detail.html', ctx)
Example #11
0
def _brand_detail(request, brand):
    ctx = _entity_detail(request, brand)
    def _cmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['with'].humanName),
                unicode(y['with'].humanName))
        if r: return r
        r = cmp(unicode(x['who'].humanName),
                unicode(y['who'].humanName))
        if r: return r
        return Es.relation_cmp_from(x,y)
    ctx['rels'] = sorted(Es.query_relations(how=brand, deref_who=True,
                deref_with=True), cmp=_cmp)
    for r in ctx['rels']:
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                    Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    return render_to_response('leden/brand_detail.html', ctx,
            context_instance=RequestContext(request))
Example #12
0
def _brand_detail(request, brand):
    ctx = _entity_detail(request, brand)
    def _cmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['with'].humanName),
                unicode(y['with'].humanName))
        if r: return r
        r = cmp(unicode(x['who'].humanName),
                unicode(y['who'].humanName))
        if r: return r
        return Es.relation_cmp_from(x,y)
    ctx['rels'] = sorted(Es.query_relations(how=brand, deref_who=True,
                deref_with=True), cmp=_cmp)
    for r in ctx['rels']:
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                    Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    return render_to_response('leden/brand_detail.html', ctx,
            context_instance=RequestContext(request))
Example #13
0
def _brand_detail(request, brand):
    ctx = _entity_detail(request, brand)

    def _cmp(x, y):
        r = Es.relation_cmp_until(y, x)
        if r:
            return r
        r = cmp(unicode(x["with"].humanName), unicode(y["with"].humanName))
        if r:
            return r
        r = cmp(unicode(x["who"].humanName), unicode(y["who"].humanName))
        if r:
            return r
        return Es.relation_cmp_from(x, y)

    ctx["rels"] = sorted(Es.query_relations(how=brand, deref_who=True, deref_with=True), cmp=_cmp)
    for r in ctx["rels"]:
        r["id"] = r["_id"]
        r["until_year"] = None if r["until"] is None else Es.date_to_year(r["until"])
        r["virtual"] = Es.relation_is_virtual(r)
    return render_to_response("leden/brand_detail.html", ctx, context_instance=RequestContext(request))
Example #14
0
 def add_years_to_relations(rels):
     years_of_year_overrides = [
         yo[1] for yo in six.itervalues(year_overrides)
     ]
     until_years = [
         Es.date_to_year(r['until']) for r in rels if r['until'] != DT_MAX
     ]
     max_until = max(
         max(until_years) if until_years else 0,
         max(years_of_year_overrides) if years_of_year_overrides else 0,
         Es.date_to_year(dt_now))
     from_years = [
         Es.date_to_year(r['from']) for r in rels if r['from'] != DT_MIN
     ]
     min_from = min(
         min(from_years) if from_years else Es.date_to_year(dt_now),
         Es.date_to_year(dt_now))
     for rel in rels:
         s = (min_from
              if rel['from'] == DT_MIN else Es.date_to_year(rel['from']))
         t = (max_until
              if rel['until'] == DT_MAX else Es.date_to_year(rel['until']))
         years = set(range(s, t + 1))
         for tid in rel.get('tags', ()):
             if tid not in year_overrides:
                 continue
             tp, yr = year_overrides[tid]
             if tp:
                 years.add(yr)
             else:
                 if yr not in years:
                     logging.warning('bogus year-override -{} on {}'.format(
                         yr, rel['_id']))
                     continue
                 years.remove(yr)
         rel['years'] = years
Example #15
0
def _entity_detail(request, e):
    related = sorted(
        e.get_related(),
        key=lambda x: (Es.DT_MIN - Es.relation_until(
            x), Es.entity_humanName(x['with']), Es.entity_humanName(x['how'])))
    rrelated = sorted(
        e.get_rrelated(),
        key=lambda x: (Es.DT_MIN - Es.relation_until(
            x), Es.entity_humanName(x['how']), Es.entity_humanName(x['who'])))
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None or r['until'] >= now()
                           else Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r['until_year']
        if year is None:
            year = 'this'

        if year not in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r['who'])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {
        'related': related,
        'rrelated': rrelated,
        'year_counts': year_counts,
        'now': now(),
        'tags': sorted(tags, key=Es.entity_humanName),
        'object': e,
        'chiefs': [],
        'pipos': [],
        'reps': []
    }
    for r in rrelated:
        if r['how'] and Es.relation_is_active(r):
            if str(r['how'].name) == '!brand-hoofd':
                r['hidden'] = True
                ctx['chiefs'].append(r)
            if str(r['how'].name) == '!brand-bestuurspipo':
                r['hidden'] = True
                ctx['pipos'].append(r)
            if str(r['how'].name) == '!brand-vertegenwoordiger':
                r['hidden'] = True
                ctx['reps'].append(r)
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(key=Es.entity_humanName)
        users = sorted(Es.users(), key=Es.entity_humanName)
        brands = sorted(Es.brands(), key=Es.entity_humanName)
        ctx.update({
            'users': users,
            'brands': brands,
            'groups': groups,
            'may_add_related': True,
            'may_add_rrelated': True,
            'may_tag': True,
            'may_untag': True
        })
    ctx['may_upload_smoel'] = e.name and request.user.may_upload_smoel_for(e)
    if e.is_tag:
        ctx.update({
            'tag_bearers':
            sorted(e.as_tag().get_bearers(), key=Es.entity_humanName)
        })

    # Check whether entity has a photo
    photo_size = e.photo_size
    if e.photo_size is not None:
        ctx.update({
            'hasPhoto': True,
            'photoWidth': photo_size[0],
            'photoHeight': photo_size[1]
        })
    return ctx
Example #16
0
def _entity_detail(request, e):
    def _cmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['with'].humanName),
                unicode(y['with'].humanName))
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        return Es.relation_cmp_from(x,y)
    def _rcmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        r = cmp(unicode(x['who'].humanName),
                unicode(y['who'].humanName))
        if r: return r
        return Es.relation_cmp_from(x,y)
    related = sorted(e.get_related(), cmp=_cmp)
    rrelated = sorted(e.get_rrelated(), cmp=_rcmp)
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                    Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r['until_year']
        if year is None:
            year = 'this'

        if not year in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r['who'])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {'related': related,
           'rrelated': rrelated,
           'year_counts': year_counts,
           'now': now(),
           'tags': sorted(tags, Es.entity_cmp_humanName),
           'object': e,
           'chiefs': [],
           'pipos': [] }
    for r in rrelated:
        if r['how'] and Es.relation_is_active(r):
            if str(r['how'].name) == '!brand-hoofd':
                r['hidden'] = True
                ctx['chiefs'].append(r)
            if str(r['how'].name) == '!brand-bestuurspipo':
                r['hidden'] = True
                ctx['pipos'].append(r)
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(cmp=lambda x,y: cmp(unicode(x.humanName),
                        unicode(y.humanName)))
        users = sorted(Es.users(), cmp=Es.entity_cmp_humanName)
        brands = sorted(Es.brands(), cmp=Es.entity_cmp_humanName)
        ctx.update({'users': users,
                'brands': brands,
                'groups': groups,
                'may_add_related': True,
                'may_add_rrelated': True})
    if e.is_tag:
        ctx.update({'tag_bearers': sorted(e.as_tag().get_bearers(),
                        cmp=Es.entity_cmp_humanName)})
    return ctx
Example #17
0
def _entity_detail(request, e):
    def _cmp(x, y):
        r = Es.relation_cmp_until(y, x)
        if r:
            return r
        r = cmp(unicode(x["with"].humanName), unicode(y["with"].humanName))
        if r:
            return r
        r = cmp(unicode(x["how"].humanName) if x["how"] else None, unicode(y["how"].humanName) if y["how"] else None)
        if r:
            return r
        return Es.relation_cmp_from(x, y)

    def _rcmp(x, y):
        r = Es.relation_cmp_until(y, x)
        if r:
            return r
        r = cmp(unicode(x["how"].humanName) if x["how"] else None, unicode(y["how"].humanName) if y["how"] else None)
        if r:
            return r
        r = cmp(unicode(x["who"].humanName), unicode(y["who"].humanName))
        if r:
            return r
        return Es.relation_cmp_from(x, y)

    related = sorted(e.get_related(), cmp=_cmp)
    rrelated = sorted(e.get_rrelated(), cmp=_rcmp)
    for r in chain(related, rrelated):
        r["may_end"] = Es.user_may_end_relation(request.user, r)
        r["id"] = r["_id"]
        r["until_year"] = None if r["until"] is None or r["until"] >= now() else Es.date_to_year(r["until"])
        r["virtual"] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r["until_year"]
        if year is None:
            year = "this"

        if not year in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r["who"])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {
        "related": related,
        "rrelated": rrelated,
        "year_counts": year_counts,
        "now": now(),
        "tags": sorted(tags, Es.entity_cmp_humanName),
        "object": e,
        "chiefs": [],
        "pipos": [],
        "reps": [],
    }
    for r in rrelated:
        if r["how"] and Es.relation_is_active(r):
            if str(r["how"].name) == "!brand-hoofd":
                r["hidden"] = True
                ctx["chiefs"].append(r)
            if str(r["how"].name) == "!brand-bestuurspipo":
                r["hidden"] = True
                ctx["pipos"].append(r)
            if str(r["how"].name) == "!brand-vertegenwoordiger":
                r["hidden"] = True
                ctx["reps"].append(r)
    # Is request.user allowed to add (r)relations?
    if "secretariaat" in request.user.cached_groups_names and (e.is_group or e.is_user):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(cmp=lambda x, y: cmp(unicode(x.humanName), unicode(y.humanName)))
        users = sorted(Es.users(), cmp=Es.entity_cmp_humanName)
        brands = sorted(Es.brands(), cmp=Es.entity_cmp_humanName)
        ctx.update(
            {
                "users": users,
                "brands": brands,
                "groups": groups,
                "may_add_related": True,
                "may_add_rrelated": True,
                "may_tag": True,
                "may_untag": True,
            }
        )
    ctx["may_upload_smoel"] = e.name and request.user.may_upload_smoel_for(e)
    if e.is_tag:
        ctx.update({"tag_bearers": sorted(e.as_tag().get_bearers(), cmp=Es.entity_cmp_humanName)})

    # Check whether entity has a photo
    photos_path = path.join(settings.SMOELEN_PHOTOS_PATH, str(e.name)) if e.name else None
    if photos_path and default_storage.exists(photos_path + ".jpg"):
        img = Image.open(default_storage.open(photos_path + ".jpg"))
        width, height = img.size
        if default_storage.exists(photos_path + ".orig"):
            # smoel was created using newer strategy. Shrink until it fits the
            # requirements.
            width, height = resize_proportional(
                img.size[0], img.size[1], settings.SMOELEN_WIDTH, settings.SMOELEN_HEIGHT
            )
        elif width > settings.SMOELEN_WIDTH:
            # smoel was created as high-resolution image, probably 600px wide
            width /= 2
            height /= 2
        else:
            # smoel was created as normal image, probably 300px wide
            pass
        ctx.update({"hasPhoto": True, "photoWidth": width, "photoHeight": height})
    return ctx
Example #18
0
def _entity_detail(request, e):
    def _cmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['with'].humanName),
                unicode(y['with'].humanName))
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        return Es.relation_cmp_from(x,y)
    def _rcmp(x,y):
        r = Es.relation_cmp_until(y,x)
        if r: return r
        r = cmp(unicode(x['how'].humanName) if x['how'] else None,
            unicode(y['how'].humanName) if y['how'] else None)
        if r: return r
        r = cmp(unicode(x['who'].humanName),
                unicode(y['who'].humanName))
        if r: return r
        return Es.relation_cmp_from(x,y)
    related = sorted(e.get_related(), cmp=_cmp)
    rrelated = sorted(e.get_rrelated(), cmp=_rcmp)
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None else
                    Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r['until_year']
        if year is None:
            year = 'this'

        if not year in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r['who'])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {'related': related,
           'rrelated': rrelated,
           'year_counts': year_counts,
           'now': now(),
           'tags': sorted(tags, Es.entity_cmp_humanName),
           'object': e,
           'chiefs': [],
           'pipos': [] }
    for r in rrelated:
        if r['how'] and Es.relation_is_active(r):
            if str(r['how'].name) == '!brand-hoofd':
                r['hidden'] = True
                ctx['chiefs'].append(r)
            if str(r['how'].name) == '!brand-bestuurspipo':
                r['hidden'] = True
                ctx['pipos'].append(r)
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(cmp=lambda x,y: cmp(unicode(x.humanName),
                        unicode(y.humanName)))
        users = sorted(Es.users(), cmp=Es.entity_cmp_humanName)
        brands = sorted(Es.brands(), cmp=Es.entity_cmp_humanName)
        ctx.update({'users': users,
                'brands': brands,
                'groups': groups,
                'may_add_related': True,
                'may_add_rrelated': True})
    if e.is_tag:
        ctx.update({'tag_bearers': sorted(e.as_tag().get_bearers(),
                        cmp=Es.entity_cmp_humanName)})
    return ctx
Example #19
0
def _entity_detail(request, e):
    related = sorted(e.get_related(),
                     key=lambda x: (Es.DT_MIN - Es.relation_until(x),
                                    Es.entity_humanName(x['with']),
                                    Es.entity_humanName(x['how'])))
    rrelated = sorted(e.get_rrelated(),
                      key=lambda x: (Es.DT_MIN - Es.relation_until(x),
                                     Es.entity_humanName(x['how']),
                                     Es.entity_humanName(x['who'])))
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None
                           or r['until'] >= now()
                           else Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r['until_year']
        if year is None:
            year = 'this'

        if year not in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r['who'])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {'related': related,
           'rrelated': rrelated,
           'year_counts': year_counts,
           'now': now(),
           'tags': sorted(tags, key=Es.entity_humanName),
           'object': e,
           'chiefs': [],
           'pipos': [],
           'reps': []}
    for r in rrelated:
        if r['how'] and Es.relation_is_active(r):
            if str(r['how'].name) == '!brand-hoofd':
                r['hidden'] = True
                ctx['chiefs'].append(r)
            if str(r['how'].name) == '!brand-bestuurspipo':
                r['hidden'] = True
                ctx['pipos'].append(r)
            if str(r['how'].name) == '!brand-vertegenwoordiger':
                r['hidden'] = True
                ctx['reps'].append(r)
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(key=Es.entity_humanName)
        users = sorted(Es.users(), key=Es.entity_humanName)
        brands = sorted(Es.brands(), key=Es.entity_humanName)
        ctx.update({'users': users,
                    'brands': brands,
                    'groups': groups,
                    'may_add_related': True,
                    'may_add_rrelated': True,
                    'may_tag': True,
                    'may_untag': True})
    ctx['may_upload_smoel'] = e.name and request.user.may_upload_smoel_for(e)
    if e.is_tag:
        ctx.update({'tag_bearers': sorted(e.as_tag().get_bearers(),
                                          key=Es.entity_humanName)})

    # Check whether entity has a photo
    photo_size = e.photo_size
    if e.photo_size is not None:
        ctx.update({
            'hasPhoto': True,
            'photoWidth': photo_size[0],
            'photoHeight': photo_size[1]})
    return ctx
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)
Example #21
0
def _entity_detail(request, e):
    related = sorted(e.get_related(),
                     key=lambda x: (Es.DT_MIN - Es.relation_until(x),
                                    Es.entity_humanName(x['with']),
                                    Es.entity_humanName(x['how'])))
    rrelated = sorted(e.get_rrelated(),
                      key=lambda x: (Es.DT_MIN - Es.relation_until(x),
                                     Es.entity_humanName(x['how']),
                                     Es.entity_humanName(x['who'])))
    for r in chain(related, rrelated):
        r['may_end'] = Es.user_may_end_relation(request.user, r)
        r['id'] = r['_id']
        r['until_year'] = (None if r['until'] is None
                           or r['until'] >= now()
                           else Es.date_to_year(r['until']))
        r['virtual'] = Es.relation_is_virtual(r)
    tags = [t.as_primary_type() for t in e.get_tags()]

    # mapping of year => set of members
    year_sets = {}
    for r in rrelated:
        year = r['until_year']
        if year is None:
            year = 'this'

        if year not in year_sets:
            year_sets[year] = set()
        year_sets[year].add(r['who'])

    year_counts = {}
    for year in year_sets:
        year_counts[year] = len(year_sets[year])

    ctx = {'related': related,
           'rrelated': rrelated,
           'year_counts': year_counts,
           'now': now(),
           'tags': sorted(tags, key=Es.entity_humanName),
           'object': e,
           'chiefs': [],
           'pipos': [],
           'reps': []}
    for r in rrelated:
        if r['how'] and Es.relation_is_active(r):
            if str(r['how'].name) == '!brand-hoofd':
                r['hidden'] = True
                ctx['chiefs'].append(r)
            if str(r['how'].name) == '!brand-bestuurspipo':
                r['hidden'] = True
                ctx['pipos'].append(r)
            if str(r['how'].name) == '!brand-vertegenwoordiger':
                r['hidden'] = True
                ctx['reps'].append(r)
    # Is request.user allowed to add (r)relations?
    if ('secretariaat' in request.user.cached_groups_names
            and (e.is_group or e.is_user)):
        groups = [g for g in Es.groups() if not g.is_virtual]
        groups.sort(key=Es.entity_humanName)
        users = sorted(Es.users(), key=Es.entity_humanName)
        brands = sorted(Es.brands(), key=Es.entity_humanName)
        ctx.update({'users': users,
                    'brands': brands,
                    'groups': groups,
                    'may_add_related': True,
                    'may_add_rrelated': True,
                    'may_tag': True,
                    'may_untag': True})
    ctx['may_upload_smoel'] = e.name and request.user.may_upload_smoel_for(e)
    if e.is_tag:
        ctx.update({'tag_bearers': sorted(e.as_tag().get_bearers(),
                                          key=Es.entity_humanName)})

    # Check whether entity has a photo
    photos_path = (path.join(settings.SMOELEN_PHOTOS_PATH, str(e.name))
                   if e.name else None)
    if photos_path and default_storage.exists(photos_path + '.jpg'):
        img = PIL.Image.open(default_storage.open(photos_path + '.jpg'))
        width, height = img.size
        if default_storage.exists(photos_path + '.orig'):
            # smoel was created using newer strategy. Shrink until it fits the
            # requirements.
            width, height = resize_proportional(img.size[0], img.size[1],
                                                settings.SMOELEN_WIDTH,
                                                settings.SMOELEN_HEIGHT)
        elif width > settings.SMOELEN_WIDTH:
            # smoel was created as high-resolution image, probably 600px wide
            width /= 2
            height /= 2
        else:
            # smoel was created as normal image, probably 300px wide
            pass
        ctx.update({
            'hasPhoto': True,
            'photoWidth': width,
            'photoHeight': height})
    return ctx
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)