kasownik/web/webapp/commands.py

79 lines
2.2 KiB
Python

import pprint
import click
from flask import g
from flask.cli import AppGroup
from webapp import models, db
import directory
import logic
group = AppGroup(__name__)
@group.command()
@click.option('-n', '--dry-run', is_flag=True, help='Don\'t apply any changes.')
def ldapsync(dry_run):
"""Synchronizes LDAP groups state."""
members = [m.get_status() for m in models.Member.get_members(True)]
g.ldap = directory.connect()
diff = directory.get_ldap_group_diff(members)
if diff is None:
return
changes = {'fatty': {}, 'starving': {}}
changes['fatty']['add'] = diff['fatty_to_add']
changes['fatty']['remove'] = diff['fatty_to_remove']
changes['starving']['add'] = diff['starving_to_add']
changes['starving']['remove'] = diff['starving_to_remove']
click.echo('Applying %d changes:' % sum([len(n) for n in diff.values()]))
for k, v in changes.items():
changelist = ['+%s' % n for n in v['add']] + ['-%s' % n for n in v['remove']]
if changelist:
click.echo('\t%s: %s' % (k, ', '.join(changelist)))
click.echo()
if dry_run:
click.echo('Exiting, just a dry run.')
return
directory.update_member_groups(g.ldap, changes)
click.echo('Done.')
@group.command()
@click.option('-n', '--dry-run', is_flag=True, help='Don\'t commit changes.')
def automatch(dry_run):
"""Matches transfers to membership months."""
transfers_unmatched = logic.get_unmatched_transfers()
matched, unmatched = logic.try_automatch(transfers_unmatched)
for transfer in matched:
mts = transfer.member_transfers
member = mts[0].member
if not dry_run:
member.get_status(force_refresh=True)
months = ', '.join('%d-%d' % (mt.year, mt.month) for mt in mts)
click.echo("Matched transfer {} for {:.2f}PLN to member {} for month {}".format(
transfer.id, transfer.amount/100, member.username, months))
if dry_run:
click.echo("Dry run, not commiting.")
return
db.session.commit()
if matched:
click.echo("Done, %d matched, %d left" % (len(matched), len(unmatched)))
@group.command()
def syncdb():
"""Initializes database."""
db.create_all()
click.echo('Done.')