diff --git a/sources/AUTHORS b/sources/AUTHORS index f104070..89a2af3 100644 --- a/sources/AUTHORS +++ b/sources/AUTHORS @@ -1,2 +1,2 @@ -The project has been started by Alexis Métaireau and Frédéric Sureau. Friends are +The project has been started by Alexis Métaireau and Frédéric Sureau. Friends are helping since that in the persons of Arnaud Bos and Quentin Roy. diff --git a/sources/LICENSE b/sources/LICENSE index a668284..ecc7977 100644 --- a/sources/LICENSE +++ b/sources/LICENSE @@ -19,7 +19,7 @@ that the following conditions are met: promote products derived from this software without specific prior written permission. -* If you meet the authors of this software in person and you want to +* If you meet the authors of this software in person and you want to pay them a beer, you're encouraged to do so. Please, do. If you have homebrewed beer, this works as well (may even be better). diff --git a/sources/budget/default_settings.py b/sources/budget/default_settings.py index 111abf2..d5a9a9b 100644 --- a/sources/budget/default_settings.py +++ b/sources/budget/default_settings.py @@ -3,9 +3,4 @@ SQLALCHEMY_DATABASE_URI = 'sqlite:///budget.db' SQLACHEMY_ECHO = DEBUG SECRET_KEY = "tralala" -DEFAULT_MAIL_SENDER = ("Budget manager", "budget@notmyidea.org") - -try: - from settings import * -except ImportError: - pass +MAIL_DEFAULT_SENDER = ("Budget manager", "budget@notmyidea.org") diff --git a/sources/budget/forms.py b/sources/budget/forms.py index 2dde57d..7d6eb51 100644 --- a/sources/budget/forms.py +++ b/sources/budget/forms.py @@ -152,27 +152,35 @@ class BillForm(Form): class MemberForm(Form): name = TextField(_("Name"), validators=[Required()]) + weight = CommaDecimalField(_("Weight"), default=1) submit = SubmitField(_("Add")) - def __init__(self, project, *args, **kwargs): + def __init__(self, project, edit=False, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.project = project + self.edit = edit def validate_name(form, field): if field.data == form.name.default: raise ValidationError(_("User name incorrect")) - if Person.query.filter(Person.name == field.data)\ - .filter(Person.project == form.project)\ - .filter(Person.activated == True).all(): + if (not form.edit and Person.query.filter( + Person.name == field.data, + Person.project == form.project, + Person.activated == True).all()): raise ValidationError(_("This project already have this member")) def save(self, project, person): # if the user is already bound to the project, just reactivate him person.name = self.name.data person.project = project + person.weight = self.weight.data return person + def fill(self, member): + self.name.data = member.name + self.weight.data = member.weight + class InviteForm(Form): emails = TextAreaField(_("People to notify")) diff --git a/sources/budget/manage.py b/sources/budget/manage.py new file mode 100755 index 0000000..e0b25a7 --- /dev/null +++ b/sources/budget/manage.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +from flask.ext.script import Manager +from flask.ext.migrate import Migrate, MigrateCommand + +from run import app +from models import db + +migrate = Migrate(app, db) + +manager = Manager(app) +manager.add_command('db', MigrateCommand) + + +if __name__ == '__main__': + manager.run() diff --git a/sources/budget/merged_settings.py b/sources/budget/merged_settings.py new file mode 100644 index 0000000..f6b1f81 --- /dev/null +++ b/sources/budget/merged_settings.py @@ -0,0 +1,10 @@ +""" +Merges default settings with user-defined settings +""" + +from default_settings import * + +try: + from settings import * +except ImportError: + pass diff --git a/sources/budget/migrations/README b/sources/budget/migrations/README new file mode 100755 index 0000000..98e4f9c --- /dev/null +++ b/sources/budget/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/sources/budget/migrations/alembic.ini b/sources/budget/migrations/alembic.ini new file mode 100644 index 0000000..f8ed480 --- /dev/null +++ b/sources/budget/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/sources/budget/migrations/env.py b/sources/budget/migrations/env.py new file mode 100755 index 0000000..cef89d2 --- /dev/null +++ b/sources/budget/migrations/env.py @@ -0,0 +1,85 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import engine_from_config, pool +from logging.config import fileConfig +import logging + +# This is the Alembic Config object, which provides access to the values within +# the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. This line sets up loggers +# basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# Add your model's MetaData object here for 'autogenerate' support from myapp +# import mymodel target_metadata = mymodel.Base.metadata. +from flask import current_app +config.set_main_option('sqlalchemy.url', + current_app.config.get('SQLALCHEMY_DATABASE_URI')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# Other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # This callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema. + # reference: http://alembic.readthedocs.org/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + engine = engine_from_config(config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure(connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/sources/budget/migrations/script.py.mako b/sources/budget/migrations/script.py.mako new file mode 100755 index 0000000..9570201 --- /dev/null +++ b/sources/budget/migrations/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision} +Create Date: ${create_date} + +""" + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/sources/budget/migrations/versions/26d6a218c329_.py b/sources/budget/migrations/versions/26d6a218c329_.py new file mode 100644 index 0000000..859b9af --- /dev/null +++ b/sources/budget/migrations/versions/26d6a218c329_.py @@ -0,0 +1,26 @@ +"""Add Person.weight column + +Revision ID: 26d6a218c329 +Revises: b9a10d5d63ce +Create Date: 2016-06-15 09:22:04.069447 + +""" + +# revision identifiers, used by Alembic. +revision = '26d6a218c329' +down_revision = 'b9a10d5d63ce' + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.add_column('person', sa.Column('weight', sa.Float(), nullable=True)) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_column('person', 'weight') + ### end Alembic commands ### diff --git a/sources/budget/migrations/versions/b9a10d5d63ce_.py b/sources/budget/migrations/versions/b9a10d5d63ce_.py new file mode 100644 index 0000000..92bb446 --- /dev/null +++ b/sources/budget/migrations/versions/b9a10d5d63ce_.py @@ -0,0 +1,68 @@ +"""Initial migration + +Revision ID: b9a10d5d63ce +Revises: None +Create Date: 2016-05-21 23:21:21.605076 + +""" + +# revision identifiers, used by Alembic. +revision = 'b9a10d5d63ce' +down_revision = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('project', + sa.Column('id', sa.String(length=64), nullable=False), + sa.Column('name', sa.UnicodeText(), nullable=True), + sa.Column('password', sa.String(length=128), nullable=True), + sa.Column('contact_email', sa.String(length=128), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('archive', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('project_id', sa.String(length=64), nullable=True), + sa.Column('name', sa.UnicodeText(), nullable=True), + sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('person', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('project_id', sa.String(length=64), nullable=True), + sa.Column('name', sa.UnicodeText(), nullable=True), + sa.Column('activated', sa.Boolean(), nullable=True), + sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('bill', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('payer_id', sa.Integer(), nullable=True), + sa.Column('amount', sa.Float(), nullable=True), + sa.Column('date', sa.Date(), nullable=True), + sa.Column('what', sa.UnicodeText(), nullable=True), + sa.Column('archive', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['archive'], ['archive.id'], ), + sa.ForeignKeyConstraint(['payer_id'], ['person.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('billowers', + sa.Column('bill_id', sa.Integer(), nullable=True), + sa.Column('person_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['bill_id'], ['bill.id'], ), + sa.ForeignKeyConstraint(['person_id'], ['person.id'], ) + ) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_table('billowers') + op.drop_table('bill') + op.drop_table('person') + op.drop_table('archive') + op.drop_table('project') + ### end Alembic commands ### diff --git a/sources/budget/migrations/versions/f629c8ef4ab0_initialize_all_members_weights_to_1.py b/sources/budget/migrations/versions/f629c8ef4ab0_initialize_all_members_weights_to_1.py new file mode 100644 index 0000000..5542146 --- /dev/null +++ b/sources/budget/migrations/versions/f629c8ef4ab0_initialize_all_members_weights_to_1.py @@ -0,0 +1,39 @@ +"""Initialize all members weights to 1 + +Revision ID: f629c8ef4ab0 +Revises: 26d6a218c329 +Create Date: 2016-06-15 09:40:30.400862 + +""" + +# revision identifiers, used by Alembic. +revision = 'f629c8ef4ab0' +down_revision = '26d6a218c329' + +from alembic import op +import sqlalchemy as sa + +# Snapshot of the person table +person_helper = sa.Table( + 'person', sa.MetaData(), + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('project_id', sa.String(length=64), nullable=True), + sa.Column('name', sa.UnicodeText(), nullable=True), + sa.Column('activated', sa.Boolean(), nullable=True), + sa.Column('weight', sa.Float(), nullable=True), + sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), + sa.PrimaryKeyConstraint('id') +) + + +def upgrade(): + op.execute( + person_helper.update() + .where(person_helper.c.weight == None) + .values(weight=1) + ) + + +def downgrade(): + # Downgrade path is not possible, because information has been lost. + pass diff --git a/sources/budget/models.py b/sources/budget/models.py index 27bd80b..852b3e1 100644 --- a/sources/budget/models.py +++ b/sources/budget/models.py @@ -40,8 +40,9 @@ class Project(db.Model): bills = Bill.query.filter(Bill.owers.contains(person)) for bill in bills.all(): if person != bill.payer: - should_pay[person] += bill.pay_each() - should_receive[bill.payer] += bill.pay_each() + share = bill.pay_each() * person.weight + should_pay[person] += share + should_receive[bill.payer] += share for person in self.members: balance = should_receive[person] - should_pay[person] @@ -49,6 +50,10 @@ class Project(db.Model): return balances + @property + def uses_weights(self): + return len([i for i in self.members if i.weight != 1]) > 0 + def get_transactions_to_settle_bill(self): """Return a list of transactions that could be made to settle the bill""" #cache value for better performance @@ -62,7 +67,7 @@ class Project(db.Model): debts.append({"person": person, "balance": -balance[person.id]}) # Try and find exact matches for credit in credits: - match = self.exactmatch(credit["balance"], debts) + match = self.exactmatch(round(credit["balance"], 2), debts) if match: for m in match: transactions.append({"ower": m["person"], "receiver": credit["person"], "amount": m["balance"]}) @@ -152,13 +157,14 @@ class Person(db.Model): query_class = PersonQuery - _to_serialize = ("id", "name", "activated") + _to_serialize = ("id", "name", "weight", "activated") id = db.Column(db.Integer, primary_key=True) project_id = db.Column(db.String(64), db.ForeignKey("project.id")) bills = db.relationship("Bill", backref="payer") name = db.Column(db.UnicodeText) + weight = db.Column(db.Float, default=1) activated = db.Column(db.Boolean, default=True) def has_bills(self): @@ -217,9 +223,10 @@ class Bill(db.Model): archive = db.Column(db.Integer, db.ForeignKey("archive.id")) def pay_each(self): - """Compute what each person has to pay""" + """Compute what each share has to pay""" if self.owers: - return self.amount / len(self.owers) + # FIXME: SQL might dot that more efficiently + return self.amount / sum(i.weight for i in self.owers) else: return 0 diff --git a/sources/budget/requirements.txt b/sources/budget/requirements.txt index 87d8966..d49767e 100644 --- a/sources/budget/requirements.txt +++ b/sources/budget/requirements.txt @@ -1,7 +1,8 @@ flask>=0.9 flask-wtf==0.8 flask-sqlalchemy -flask-mail +flask-mail>=0.8 +Flask-Migrate==1.8.0 flask-babel flask-rest jinja2==2.6 diff --git a/sources/budget/run.py b/sources/budget/run.py index dace736..a7ce25e 100644 --- a/sources/budget/run.py +++ b/sources/budget/run.py @@ -1,22 +1,56 @@ +import os +import warnings + from flask import Flask, g, request, session from flask.ext.babel import Babel +from flask.ext.migrate import Migrate, upgrade from raven.contrib.flask import Sentry from web import main, db, mail from api import api -from utils import ReverseProxied +from utils import PrefixedWSGI +from utils import minimal_round + app = Flask(__name__) -app.config.from_object("default_settings") -app.wsgi_app = ReverseProxied(app.wsgi_app, app.config['APPLICATION_ROOT']) + + +def configure(): + """ A way to (re)configure the app, specially reset the settings + """ + config_obj = os.environ.get('FLASK_SETTINGS_MODULE', 'merged_settings') + app.config.from_object(config_obj) + app.wsgi_app = PrefixedWSGI(app) + + # Deprecations + if 'DEFAULT_MAIL_SENDER' in app.config: + # Since flask-mail 0.8 + warnings.warn( + "DEFAULT_MAIL_SENDER is deprecated in favor of MAIL_DEFAULT_SENDER" + +" and will be removed in further version", + UserWarning + ) + if not 'MAIL_DEFAULT_SENDER' in app.config: + app.config['MAIL_DEFAULT_SENDER'] = DEFAULT_MAIL_SENDER + +configure() app.register_blueprint(main) app.register_blueprint(api) +# custom jinja2 filters +app.jinja_env.filters['minimal_round'] = minimal_round + # db db.init_app(app) db.app = app -db.create_all() + +# db migrations +migrate = Migrate(app, db) + +# auto-execute migrations on runtime +with app.app_context(): + upgrade() # mail mail.init_app(app) diff --git a/sources/budget/static/css/main.css b/sources/budget/static/css/main.css index 3274241..f3fe8a0 100644 --- a/sources/budget/static/css/main.css +++ b/sources/budget/static/css/main.css @@ -176,11 +176,16 @@ tr.payer_line .balance-name{ color: red; } +.edit button, .edit button:hover { + background: url('../images/edit.png') left no-repeat; + +} + .reactivate button, .reactivate button:hover { background: url('../images/reactivate.png') left no-repeat; color: white; } - + #bill-form > fieldset { margin-top: 10px; } @@ -189,6 +194,18 @@ tr.payer_line .balance-name{ position: absolute; } +.light { + opacity: 0.3; +} + +.extra-info { + display: none; +} + +tr:hover .extra-info { + display: inline; +} + .modal-body { max-height:455px; } @@ -208,4 +225,3 @@ tr.payer_line .balance-name{ .row-fluid > .offset3{margin-left:25.5%;} .row-fluid > .offset2{margin-left:17%;} .row-fluid > .offset1{margin-left:8.5%;} - diff --git a/sources/budget/templates/authenticate.html b/sources/budget/templates/authenticate.html index dc62a70..98914d0 100644 --- a/sources/budget/templates/authenticate.html +++ b/sources/budget/templates/authenticate.html @@ -3,7 +3,7 @@
{{ _("The project you are trying to access do not exist, do you want +
{{ _("The project you are trying to access do not exist, do you want to") }} {{ _("create it") }}{{ _("?") }}
{% endif %} diff --git a/sources/budget/templates/edit_member.html b/sources/budget/templates/edit_member.html new file mode 100644 index 0000000..5f097f9 --- /dev/null +++ b/sources/budget/templates/edit_member.html @@ -0,0 +1,17 @@ +{% extends "layout.html" %} + +{% block js %} + $('#cancel-form').click(function(){location.href={{ url_for(".list_bills") }};}); +{% endblock %} + + +{% block top_menu %} +{{ _("Back to the list") }} +{% endblock %} + +{% block content %} + + +{% endblock %} diff --git a/sources/budget/templates/forms.html b/sources/budget/templates/forms.html index 2904e0d..07e5b3d 100644 --- a/sources/budget/templates/forms.html +++ b/sources/budget/templates/forms.html @@ -76,12 +76,12 @@