server.py 59.5 KB
Newer Older
1
2
3
4
#!/usr/bin/env python3
import locale
locale.setlocale(locale.LC_TIME, "de_DE.utf8")

Robin Sonnabend's avatar
Robin Sonnabend committed
5
from flask import Flask, g, current_app, request, session, flash, redirect, url_for, abort, render_template, Response, send_file as flask_send_file, Markup
6
from werkzeug.utils import secure_filename
7
8
9
10
from flask_script import Manager, prompt
from flask_migrate import Migrate, MigrateCommand
#from flask_socketio import SocketIO
from celery import Celery
Robin Sonnabend's avatar
Robin Sonnabend committed
11
from sqlalchemy import or_, and_
12
13
14
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
Robin Sonnabend's avatar
Robin Sonnabend committed
15
import atexit
Robin Sonnabend's avatar
Robin Sonnabend committed
16
from io import StringIO, BytesIO
17
import os
Robin Sonnabend's avatar
Robin Sonnabend committed
18
from datetime import datetime
Robin Sonnabend's avatar
Robin Sonnabend committed
19
import math
20
import mimetypes
21
22

import config
Robin Sonnabend's avatar
Robin Sonnabend committed
23
from shared import db, date_filter, datetime_filter, date_filter_long, date_filter_short, time_filter, time_filter_short, user_manager, security_manager, current_user, check_login, login_required, group_required, class_filter, needs_date_test, todostate_name_filter, code_filter, indent_tab_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
24
from utils import is_past, mail_manager, url_manager, get_first_unused_int, set_etherpad_text, get_etherpad_text, split_terms, optional_int_arg, fancy_join
Robin Sonnabend's avatar
Robin Sonnabend committed
25
from decorators import db_lookup, require_public_view_right, require_private_view_right, require_modify_right, require_admin_right
Robin Sonnabend's avatar
Robin Sonnabend committed
26
from models.database import ProtocolType, Protocol, DefaultTOP, TOP, LocalTOP, Document, Todo, Decision, MeetingReminder, Error, TodoMail, DecisionDocument, TodoState, Meta, DefaultMeta, DecisionCategory, Like
Robin Sonnabend's avatar
Robin Sonnabend committed
27
from views.forms import LoginForm, ProtocolTypeForm, DefaultTopForm, MeetingReminderForm, NewProtocolForm, DocumentUploadForm, KnownProtocolSourceUploadForm, NewProtocolSourceUploadForm, generate_protocol_form, TopForm, LocalTopForm, SearchForm, DecisionSearchForm, ProtocolSearchForm, TodoSearchForm, NewProtocolFileUploadForm, NewTodoForm, TodoForm, TodoMailForm, DefaultMetaForm, MetaForm, MergeTodosForm, DecisionCategoryForm, DocumentEditForm
28
from views.tables import ProtocolsTable, ProtocolTypesTable, ProtocolTypeTable, DefaultTOPsTable, MeetingRemindersTable, ErrorsTable, TodosTable, DocumentsTable, DecisionsTable, TodoTable, ErrorTable, TodoMailsTable, DefaultMetasTable, DecisionCategoriesTable
29
from legacy import import_old_todos, import_old_protocols, import_old_todomails
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)

def make_celery(app, config):
    celery = Celery(app.import_name, broker=config.CELERY_BROKER_URL)
    celery.conf.update(app.config)
    return celery
celery = make_celery(app, config)

#def make_socketio(app, config):
#    socketio = SocketIO(app)
#    return socketio
#socketio = make_socketio(app, config)

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.jinja_env.filters["datify"] = date_filter
app.jinja_env.filters["datetimify"] = datetime_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
53
app.jinja_env.filters["timify"] = time_filter
54
app.jinja_env.filters["timify_short"] = time_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
55
app.jinja_env.filters["datify_short"] = date_filter_short
Robin Sonnabend's avatar
Robin Sonnabend committed
56
app.jinja_env.filters["datify_long"] = date_filter_long
57
app.jinja_env.filters["url_complete"] = url_manager.complete
58
app.jinja_env.filters["class"] = class_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
59
60
app.jinja_env.filters["todo_get_name"] = todostate_name_filter
app.jinja_env.filters["code"] = code_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
61
app.jinja_env.filters["indent_tab"] = indent_tab_filter
Robin Sonnabend's avatar
Robin Sonnabend committed
62
app.jinja_env.filters["fancy_join"] = fancy_join
63
app.jinja_env.tests["auth_valid"] = security_manager.check_user
Robin Sonnabend's avatar
Robin Sonnabend committed
64
app.jinja_env.tests["needs_date"] = needs_date_test
65
66
67

import tasks

68
69
app.jinja_env.globals.update(check_login=check_login)
app.jinja_env.globals.update(current_user=current_user)
Robin Sonnabend's avatar
Robin Sonnabend committed
70
app.jinja_env.globals.update(zip=zip)
Robin Sonnabend's avatar
Robin Sonnabend committed
71
72
73
app.jinja_env.globals.update(min=min)
app.jinja_env.globals.update(max=max)
app.jinja_env.globals.update(dir=dir)
Robin Sonnabend's avatar
Robin Sonnabend committed
74
app.jinja_env.globals.update(now=datetime.now)
75

76
77
# blueprints here

78
79
@manager.command
def import_legacy():
80
    """Import the old todos and protocols from an sql dump"""
81
    filename = prompt("SQL-file")
82
    #filename = "legacy.sql"
83
84
    with open(filename, "rb") as sqlfile:
        content = sqlfile.read().decode("utf-8")
85
86
        import_old_todos(content)
        import_old_protocols(content)
87
        import_old_todomails(content)
88

89
90
91
92
@manager.command
def recompile_all():
    for protocol in sorted(Protocol.query.all(), key=lambda p: p.date):
        if protocol.is_done():
93
            print(protocol.get_short_identifier())
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
            tasks.parse_protocol(protocol)

@manager.command
def merge_todos():
    todo_by_id = {}
    todos = Todo.query.all()
    for todo in todos:
        todo_id = todo.get_id()
        if todo_id in todo_by_id:
            todo1, todo2 = todo, todo_by_id[todo_id]
            print(todo1)
            print(todo2)
            if todo2.id > todo1.id:
                todo2, todo1 = todo1, todo2
            for protocol in todo2.protocols:
                if protocol not in todo1.protocols:
                    todo1.protocols.append(protocol)
                todo2.protocols.remove(protocol)
            db.session.delete(todo2)
            db.session.commit()
            todo_by_id[todo_id] = todo1
        else:
            todo_by_id[todo_id] = todo

@manager.command
def runserver():
120
    app.run()
121
122
    make_scheduler()

123
124
125
126
# cause uwsgi currently has a bug
def send_file(file_like, cache_timeout, as_attachment, attachment_filename):
    mimetype, _ = mimetypes.guess_type(attachment_filename)
    response = Response(file_like.read(), mimetype)
127
128
129
130
131
132
133
134
    if as_attachment:
        response.headers["Content-Disposition"] = 'attachment; filename="{}"'.format(attachment_filename)
    content_type = mimetype
    if mimetype.startswith("text/"):
        content_type = "{}; charset=utf-8".format(content_type)
    response.headers["Content-Type"] = content_type
    response.headers["Cache-Control"] = "public, max-age={}".format(cache_timeout)
    response.headers["Connection"] = "close"
135
    return response
136

137
138
@app.route("/")
def index():
Robin Sonnabend's avatar
Robin Sonnabend committed
139
140
141
    user = current_user()
    protocols = [
        protocol for protocol in Protocol.query.all()
142
143
        if protocol.protocoltype.has_public_view_right(user,
            check_networks=False)
Robin Sonnabend's avatar
Robin Sonnabend committed
144
    ]
145
    def _protocol_sort_key(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
146
147
148
        if protocol.date is not None:
            return protocol.date
        return datetime.now().date()
Robin Sonnabend's avatar
Robin Sonnabend committed
149
    current_day = datetime.now().date()
150
    open_protocols = sorted(
Robin Sonnabend's avatar
Robin Sonnabend committed
151
152
153
154
155
        [
            protocol for protocol in protocols
            if not protocol.done
            and (protocol.date - current_day).days < config.MAX_INDEX_DAYS
        ],
156
        key=_protocol_sort_key
Robin Sonnabend's avatar
Robin Sonnabend committed
157
158
    )
    finished_protocols = sorted(
159
160
        [
            protocol for protocol in protocols
161
162
163
            if protocol.done and protocol.public
            and (protocol.has_private_view_right(user)
                or protocol.protocoltype.has_public_view_right(user, check_networks=False))
164
        ],
165
166
        key=_protocol_sort_key,
        reverse=True
Robin Sonnabend's avatar
Robin Sonnabend committed
167
    )
168
169
170
171
172
173
174
    protocol = None
    show_private = False
    has_public_view_right = False
    if len(finished_protocols) > 0:
        protocol = finished_protocols[0]
        show_private = protocol.has_private_view_right(user)
        has_public_view_right = protocol.protocoltype.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
175
176
177
    todos = None
    if check_login():
        todos = [
178
            todo for todo in Todo.query.all()
179
            if todo.protocoltype.has_private_view_right(user)
180
            and not todo.is_done()
Robin Sonnabend's avatar
Robin Sonnabend committed
181
        ]
182
183
184
185
186
187
        user_todos = [
            todo for todo in todos
            if user.username.lower() in list(map(str.strip, todo.who.lower().split(",")))
        ]
        if len(user_todos) > 0:
            todos = user_todos
188
189
        def _todo_sort_key(todo):
            protocol = todo.get_first_protocol()
190
            return protocol.date if protocol is not None and protocol.date is not None else datetime.now().date()
191
        todos = sorted(todos, key=_todo_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
192
    todos_table = TodosTable(todos) if todos is not None else None
193
    return render_template("index.html", open_protocols=open_protocols, protocol=protocol, todos=todos, show_private=show_private, has_public_view_right=has_public_view_right)
194

Robin Sonnabend's avatar
Robin Sonnabend committed
195
@app.route("/documentation")
Robin Sonnabend's avatar
Robin Sonnabend committed
196
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
197
def documentation():
Robin Sonnabend's avatar
Robin Sonnabend committed
198
199
200
    todostates = list(TodoState)
    name_to_state = TodoState.get_name_to_state()
    return render_template("documentation.html", todostates=todostates, name_to_state=name_to_state)
Robin Sonnabend's avatar
Robin Sonnabend committed
201

Robin Sonnabend's avatar
Robin Sonnabend committed
202
@app.route("/types/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
203
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
204
205
206
207
208
209
210
211
def list_types():
    is_logged_in = check_login()
    user = current_user()
    types = [
        protocoltype for protocoltype in ProtocolType.query.all()
        if (protocoltype.public_group in user.groups
        or protocoltype.private_group in user.groups
        or protocoltype.is_public)]
212
    types = sorted(types, key=lambda t: t.short_name)
Robin Sonnabend's avatar
Robin Sonnabend committed
213
214
215
216
217
218
219
220
221
222
223
224
    types_table = ProtocolTypesTable(types)
    return render_template("types-list.html", types=types, types_table=types_table)

@app.route("/type/new", methods=["GET", "POST"])
@login_required
def new_type():
    form = ProtocolTypeForm()
    if form.validate_on_submit():
        user = current_user()
        if form.private_group.data not in user.groups:
            flash("Du kannst keinen internen Protokolltypen anlegen, zu dem du selbst keinen Zugang hast.", "alert-error")
        else:
225
226
            protocoltype = ProtocolType()
            form.populate_obj(protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
227
228
229
230
231
232
            db.session.add(protocoltype)
            db.session.commit()
            flash("Der Protokolltyp {} wurde angelegt.".format(protocoltype.name), "alert-success")
        return redirect(request.args.get("next") or url_for("list_types"))
    return render_template("type-new.html", form=form)

Robin Sonnabend's avatar
Robin Sonnabend committed
233
@app.route("/type/edit/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
234
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
235
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
236
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
237
def edit_type(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
238
239
240
241
242
243
244
245
    user = current_user()
    form = ProtocolTypeForm(obj=protocoltype)
    if form.validate_on_submit():
        if form.private_group.data not in user.groups:
            flash("Du kannst keinen internen Protokolltypen anlegen, zu dem du selbst keinen Zugang hast.", "alert-error")
        else:
            form.populate_obj(protocoltype)
            db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
246
            return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
247
248
    return render_template("type-edit.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
249
@app.route("/type/show/<int:protocoltype_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
250
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
251
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
252
@require_private_view_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
253
def show_type(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
254
255
    protocoltype_table = ProtocolTypeTable(protocoltype)
    default_tops_table = DefaultTOPsTable(protocoltype.default_tops, protocoltype)
256
    reminders_table = MeetingRemindersTable(protocoltype.reminders, protocoltype)
Robin Sonnabend's avatar
Robin Sonnabend committed
257
    metas_table = DefaultMetasTable(protocoltype.metas, protocoltype)
258
259
    categories_table = DecisionCategoriesTable(protocoltype.decisioncategories, protocoltype)
    return render_template("type-show.html", protocoltype=protocoltype, protocoltype_table=protocoltype_table, default_tops_table=default_tops_table, metas_table=metas_table, reminders_table=reminders_table, mail_active=config.MAIL_ACTIVE, categories_table=categories_table)
260

Robin Sonnabend's avatar
Robin Sonnabend committed
261
@app.route("/type/delete/<int:protocoltype_id>")
262
@login_required
263
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
264
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
265
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
266
def delete_type(protocoltype):
267
268
269
270
271
272
    name = protocoltype.name
    db.session.delete(protocoltype) 
    db.session.commit()
    flash("Der Protokolltype {} wurde gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_types"))

Robin Sonnabend's avatar
Robin Sonnabend committed
273
@app.route("/type/reminders/new/<int:protocoltype_id>", methods=["GET", "POST"])
274
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
275
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
276
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
277
def new_reminder(protocoltype):
278
279
    form = MeetingReminderForm()
    if form.validate_on_submit():
280
281
        meetingreminder = MeetingReminder(protocoltype_id=protocoltype.id)
        form.populate_obj(meetingreminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
282
        db.session.add(meetingreminder)
283
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
284
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
285
286
    return render_template("reminder-new.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
287
@app.route("/type/reminder/edit/<int:meetingreminder_id>", methods=["GET", "POST"])
288
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
289
@db_lookup(MeetingReminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
290
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
291
292
def edit_reminder(meetingreminder):
    form = MeetingReminderForm(obj=meetingreminder)
293
    if form.validate_on_submit():
Robin Sonnabend's avatar
Robin Sonnabend committed
294
        form.populate_obj(meetingreminder)
295
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
296
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
297
    return render_template("reminder-edit.html", form=form, meetingreminder=meetingreminder)
298

Robin Sonnabend's avatar
Robin Sonnabend committed
299
@app.route("/type/reminder/delete/<int:meetingreminder_id>")
300
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
301
@db_lookup(MeetingReminder)
Robin Sonnabend's avatar
Robin Sonnabend committed
302
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
303
304
305
def delete_reminder(meetingreminder):
    protocoltype = meetingreminder.protocoltype
    db.session.delete(meetingreminder)
306
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
307
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
308

Robin Sonnabend's avatar
Robin Sonnabend committed
309
@app.route("/type/tops/new/<int:protocoltype_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
310
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
311
@db_lookup(ProtocolType)
Robin Sonnabend's avatar
Robin Sonnabend committed
312
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
313
def new_default_top(protocoltype):
Robin Sonnabend's avatar
Robin Sonnabend committed
314
315
    form = DefaultTopForm()
    if form.validate_on_submit():
316
317
        defaulttop = DefaultTOP(protocoltype_id=protocoltype.id)
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
318
        db.session.add(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
319
        db.session.commit()
320
321
322
323
324
325
        for protocol in protocoltype.protocols:
            if not protocol.done:
                localtop = LocalTOP(protocol_id=protocol.id,
                    defaulttop_id=defaultop.id, description="")
                db.session.add(localtop)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
326
        flash("Der Standard-TOP {} wurde für dem Protokolltyp {} hinzugefügt.".format(defaulttop.name, protocoltype.name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
327
328
329
        return redirect(request.args.get("next") or url_for("index"))
    return render_template("default-top-new.html", form=form, protocoltype=protocoltype)

Robin Sonnabend's avatar
Robin Sonnabend committed
330
@app.route("/type/tops/edit/<int:protocoltype_id>/<int:defaulttop_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
331
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
332
@db_lookup(ProtocolType, DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
333
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
334
335
def edit_default_top(protocoltype, defaulttop):
    form = DefaultTopForm(obj=defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
336
    if form.validate_on_submit():
Robin Sonnabend's avatar
Robin Sonnabend committed
337
        form.populate_obj(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
338
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
339
340
        return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=protocoltype.id))
    return render_template("default-top-edit.html", form=form, protocoltype=protocoltype, defaulttop=defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
341

Robin Sonnabend's avatar
Robin Sonnabend committed
342
@app.route("/type/tops/delete/<int:defaulttop_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
343
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
344
@db_lookup(DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
345
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
346
347
def delete_default_top(defaulttop):
    db.session.delete(defaulttop)
Robin Sonnabend's avatar
Robin Sonnabend committed
348
    db.session.commit()
349
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=defaulttop.protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
350

Robin Sonnabend's avatar
Robin Sonnabend committed
351
@app.route("/type/tops/move/<int:defaulttop_id>/<diff>/")
Robin Sonnabend's avatar
Robin Sonnabend committed
352
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
353
@db_lookup(DefaultTOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
354
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
355
def move_default_top(defaulttop, diff):
Robin Sonnabend's avatar
Robin Sonnabend committed
356
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
357
        defaulttop.number += int(diff)
Robin Sonnabend's avatar
Robin Sonnabend committed
358
359
360
        db.session.commit()
    except ValueError:
        flash("Die angegebene Differenz ist keine Zahl.", "alert-error")
Robin Sonnabend's avatar
Robin Sonnabend committed
361
    return redirect(request.args.get("next") or url_for("show_type", protocoltype_id=defaulttop.protocoltype.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
362
363

@app.route("/protocols/list")
364
365
366
def list_protocols():
    is_logged_in = check_login()
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
367
368
369
    protocoltype = None
    protocoltype_id = None
    try:
370
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
371
372
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
373
    state_open = -1
Robin Sonnabend's avatar
Robin Sonnabend committed
374
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
375
        state_open = int(request.args.get("state_open"))
Robin Sonnabend's avatar
Robin Sonnabend committed
376
377
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
378
    search_term = request.args.get("search")
379
    protocoltypes = ProtocolType.get_public_protocoltypes(user, check_networks=False)
Robin Sonnabend's avatar
Robin Sonnabend committed
380
    search_form = ProtocolSearchForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
381
    if protocoltype_id is not None:
382
        search_form.protocoltype_id.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
383
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
384
385
    if state_open is not None:
        search_form.state_open.data = state_open
Robin Sonnabend's avatar
Robin Sonnabend committed
386
387
388
    if search_term is not None:
        search_form.search.data = search_term
    protocol_query = Protocol.query
Robin Sonnabend's avatar
Robin Sonnabend committed
389
390
391
392
393
394
395
396
397
    shall_search = search_term is not None and len(search_term.strip()) > 0
    search_terms = []
    if shall_search:
        search_terms = list(map(str.lower, split_terms(search_term)))
        for term in search_terms:
            protocol_query = protocol_query.filter(or_(
                Protocol.content_public.ilike("%{}%".format(term)),
                Protocol.content_private.ilike("%{}%".format(term))
            ))
398
    protocols = [
Robin Sonnabend's avatar
Robin Sonnabend committed
399
        protocol for protocol in protocol_query.all()
400
        if protocol.protocoltype.has_public_view_right(user, check_networks=False)
401
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
402
403
404
405
406
407
408
409
410
411
412
413
414
    def _matches_search(content):
        content = content.lower()
        for search_term in search_terms:
            if search_term.lower() not in content:
                return False
        return True
    def _matches_search_lazy(content):
        content = content.lower()
        for search_term in search_terms:
            if search_term.lower() in content:
                return True
        return False
    search_results = {} if shall_search else None
Robin Sonnabend's avatar
Robin Sonnabend committed
415
416
417
418
419
    if protocoltype_id is not None and protocoltype_id != -1:
        protocols = [
            protocol for protocol in protocols
            if protocol.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
420
421
    if state_open is not None and state_open != -1:
        protocol_done = bool(state_open)
Robin Sonnabend's avatar
Robin Sonnabend committed
422
423
        protocols = [
            protocol for protocol in protocols
424
            if (protocol.is_done() or False) == protocol_done
Robin Sonnabend's avatar
Robin Sonnabend committed
425
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
426
427
428
429
430
    if shall_search:
        protocols = [
            protocol for protocol in protocols
            if (protocol.protocoltype.has_private_view_right(user)
                and _matches_search(protocol.content_private))
431
            or (protocol.has_public_view_right(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
                and _matches_search(protocol.content_public))
        ]
        for protocol in protocols:
            content = protocol.content_private if protocol.protocoltype.has_private_view_right(user) else protocol.content_public
            lines = content.splitlines()
            matches = [line for line in lines if _matches_search_lazy(line)]
            formatted_lines = []
            for line in matches:
                parts = []
                lower_line = line.lower()
                last_index = 0
                while last_index < len(line):
                    index_candidates = list(filter(lambda t: t[0] != -1, 
                        [(lower_line.find(term, last_index), term) for term in search_terms]))
                    if len(index_candidates) == 0:
                        parts.append((line[last_index:], False))
                        break
                    else:
                        new_index, term = min(index_candidates, key=lambda t: t[0])
                        new_end_index = new_index + len(term)
                        parts.append((line[last_index:new_index], False))
                        parts.append((line[new_index:new_end_index], True))
                        last_index = new_end_index
                formatted_lines.append("".join([
                    "<b>{}</b>".format(text) if matched else text
                    for text, matched in parts
                ]))
459
            search_results[protocol] = " …<br />\n".join(formatted_lines)
Robin Sonnabend's avatar
Robin Sonnabend committed
460
    protocols = sorted(protocols, key=lambda protocol: protocol.date, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
461
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
462
463
    page_length = _get_page_length()
    page_count = int(math.ceil(len(protocols) / page_length))
Robin Sonnabend's avatar
Robin Sonnabend committed
464
465
    if page >= page_count:
        page = 0
Robin Sonnabend's avatar
Robin Sonnabend committed
466
467
    begin_index = page * page_length
    end_index = (page + 1) * page_length
468
    max_page_length_exp = math.ceil(math.log10(len(protocols))) if len(protocols) > 0 else 1
Robin Sonnabend's avatar
Robin Sonnabend committed
469
    protocols = protocols[begin_index:end_index]
Robin Sonnabend's avatar
Robin Sonnabend committed
470
    protocols_table = ProtocolsTable(protocols, search_results=search_results)
Robin Sonnabend's avatar
Robin Sonnabend committed
471
    return render_template("protocols-list.html", protocols=protocols, protocols_table=protocols_table, search_form=search_form, page=page, page_count=page_count, page_diff=config.PAGE_DIFF, protocoltype_id=protocoltype_id, search_term=search_term, state_open=state_open, page_length=page_length, max_page_length_exp=max_page_length_exp)
Robin Sonnabend's avatar
Robin Sonnabend committed
472
473
474
475
476

@app.route("/protocol/new", methods=["GET", "POST"])
@login_required
def new_protocol():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
477
    protocoltypes = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
478
    form = NewProtocolForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
479
    upload_form = NewProtocolSourceUploadForm(protocoltypes)
480
    file_upload_form = NewProtocolFileUploadForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
481
    if form.validate_on_submit():
482
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
483
484
485
        if protocoltype is None or not protocoltype.has_modify_right(user):
            flash("Dir fehlen die nötigen Zugriffsrechte.", "alert-error")
            return redirect(request.args.get("next") or url_for("index"))
486
487
        protocol = Protocol(protocoltype_id=protocoltype.id)
        form.populate_obj(protocol)
488
489
        if form.start_time.data is None:
            protocol.start_time = protocoltype.usual_time
Robin Sonnabend's avatar
Robin Sonnabend committed
490
491
        db.session.add(protocol)
        db.session.commit()
492
        for local_top in protocol.create_localtops():
493
            db.session.add(local_top)
494
495
496
497
        for default_meta in protocoltype.metas:
            if default_meta.prior:
                meta = Meta(protocol_id=protocol.id, name=default_meta.name, internal=default_meta.internal, value=default_meta.value)
                db.session.add(meta)
498
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
499
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
500
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
501
    type_id = request.args.get("protocoltype_id")
Robin Sonnabend's avatar
Robin Sonnabend committed
502
503
    if type_id is not None:
        form.protocoltype.data = type_id
504
505
        upload_form.protocoltype.data = type_id
    return render_template("protocol-new.html", form=form, upload_form=upload_form, file_upload_form=file_upload_form, protocoltypes=protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
506
507

@app.route("/protocol/show/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
508
509
@db_lookup(Protocol)
def show_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
510
511
    user = current_user()
    errors_table = ErrorsTable(protocol.errors)
512
    if not protocol.protocoltype.has_public_view_right(user, check_networks=False): # yes, feature
Robin Sonnabend's avatar
Robin Sonnabend committed
513
        flash("Die fehlen die nötigen Zugriffsrechte.", "alert-error")
514
        return redirect(request.args.get("next") or url_for("login", next=request.url))
Robin Sonnabend's avatar
Robin Sonnabend committed
515
516
    visible_documents = [
        document for document in protocol.documents
517
        if (not document.is_private and document.protocol.has_public_view_right(user))
Robin Sonnabend's avatar
Robin Sonnabend committed
518
519
        or (document.is_private and document.protocol.protocoltype.has_private_view_right(user))
    ]
520
    documents_table = DocumentsTable(visible_documents, protocol)
521
    document_upload_form = DocumentUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
522
    source_upload_form = KnownProtocolSourceUploadForm()
523
524
525
    time_diff = protocol.date - datetime.now().date()
    large_time_diff = not protocol.is_done() and time_diff.days > 0
    return render_template("protocol-show.html", protocol=protocol, errors_table=errors_table, documents_table=documents_table, document_upload_form=document_upload_form, source_upload_form=source_upload_form, time_diff=time_diff, large_time_diff=large_time_diff)
Robin Sonnabend's avatar
Robin Sonnabend committed
526

Robin Sonnabend's avatar
Robin Sonnabend committed
527
528
@app.route("/protocol/delete/<int:protocol_id>")
@login_required
529
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
530
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
531
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
532
def delete_protocol(protocol):
533
    name = protocol.get_short_identifier()
Robin Sonnabend's avatar
Robin Sonnabend committed
534
    protocol.delete_orphan_todos()
Robin Sonnabend's avatar
Robin Sonnabend committed
535
536
537
538
539
    db.session.delete(protocol)
    db.session.commit()
    flash("Protokoll {} ist gelöscht.".format(name), "alert-success")
    return redirect(request.args.get("next") or url_for("list_protocols"))

Robin Sonnabend's avatar
Robin Sonnabend committed
540
@app.route("/protocol/etherpull/<int:protocol_id>")
Robin Sonnabend's avatar
Robin Sonnabend committed
541
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
542
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
543
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
544
def etherpull_protocol(protocol):
545
546
547
    if not config.ETHERPAD_ACTIVE:
        flash("Die Etherpadfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
Robin Sonnabend's avatar
Robin Sonnabend committed
548
    protocol.source = get_etherpad_text(protocol.get_identifier())
Robin Sonnabend's avatar
Robin Sonnabend committed
549
550
551
552
553
    db.session.commit()
    tasks.parse_protocol(protocol)
    flash("Das Protokoll wird kompiliert.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

Robin Sonnabend's avatar
Robin Sonnabend committed
554
555
@app.route("/protocol/upload/known/<int:protocol_id>", methods=["POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
556
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
557
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
558
def upload_source_to_known_protocol(protocol):
559
    form = KnownProtocolSourceUploadForm()
Robin Sonnabend's avatar
Robin Sonnabend committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    if form.validate_on_submit():
        if form.source.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
        else:
            file = form.source.data
            if file.filename == "":
                flash("Es wurde keine Datei ausgewählt.", "alert-error")
            else:
                # todo: Prüfen, ob es Text ist?
                source = file.stream.read().decode("utf-8")
                protocol.source = source
                db.session.commit()
                tasks.parse_protocol(protocol)
                flash("Das Protokoll wird kompiliert.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

@app.route("/protocol/upload/new/", methods=["POST"])
@login_required
def upload_new_protocol():
    user = current_user()
580
    available_types = ProtocolType.get_modifiable_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
581
582
583
584
    form = NewProtocolSourceUploadForm(protocoltypes=available_types)
    if form.validate_on_submit():
        if form.source.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
585
586
587
588
589
590
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        file = form.source.data
        if file.filename == "":
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        source = file.stream.read().decode("utf-8")
591
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
592
593
594
        if protocoltype is None or not protocoltype.has_modify_right(user):
            flash("Invalider Protokolltyp oder keine Rechte.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
595
        protocol = Protocol(protocoltype_id=protocoltype.id, source=source)
596
597
        db.session.add(protocol)
        db.session.commit()
598
599
600
        for local_top in protocol.create_localtops:
            db.session.add(local_top)
        db.session.commit()
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        tasks.parse_protocol(protocol)
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    return redirect(request.args.get("fail") or url_for("new_protocol"))

@app.route("/protocol/upload/new/file/", methods=["POST"])
@login_required
def upload_new_protocol_by_file():
    user = current_user()
    available_types = ProtocolType.get_modifiable_protocoltypes(user)
    form = NewProtocolFileUploadForm(protocoltypes=available_types)
    if form.validate_on_submit():
        if form.file.data is None:
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        file = form.file.data
        if file.filename == "":
            flash("Es wurde keine Datei ausgewählt.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
        filename = secure_filename(file.filename)
620
        protocoltype = ProtocolType.query.filter_by(id=form.protocoltype_id.data).first()
621
622
623
        if protocoltype is None or not protocoltype.has_modify_right(user):
            flash("Invalider Protokolltyp oder keine Rechte.", "alert-error")
            return redirect(request.args.get("fail") or url_for("new_protocol"))
624
        protocol = Protocol(protocoltype_id=protocoltype.id, date=datetime.now().date(), done=True)
625
626
        db.session.add(protocol)
        db.session.commit()
627
628
629
        for local_top in protocol.create_localtops:
            db.session.add(local_top)
        db.session.commit()
630
631
632
        document = Document(protocol_id=protocol.id, name=filename,
            filename="", is_compiled=False)
        form.populate_obj(document)
633
634
635
636
637
638
639
        db.session.add(document)
        db.session.commit()
        internal_filename = "{}-{}-{}".format(protocol.id, document.id, filename)
        document.filename = internal_filename
        file.save(os.path.join(config.DOCUMENTS_PATH, internal_filename))
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
640
641
    return redirect(request.args.get("fail") or url_for("new_protocol"))

Administrator's avatar
Administrator committed
642
643
644
@app.route("/protocol/recompile/<int:protocol_id>")
@login_required
@group_required(config.ADMIN_GROUP)
Robin Sonnabend's avatar
Robin Sonnabend committed
645
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
646
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
647
def recompile_protocol(protocol):
Administrator's avatar
Administrator committed
648
649
    tasks.parse_protocol(protocol)
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
650

Robin Sonnabend's avatar
Robin Sonnabend committed
651
652
@app.route("/protocol/source/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
653
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
654
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
655
def get_protocol_source(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
656
    file_like = BytesIO(protocol.source.encode("utf-8"))
657
    return send_file(file_like, cache_timeout=1, as_attachment=True, attachment_filename="{}.txt".format(protocol.get_short_identifier()))
Robin Sonnabend's avatar
Robin Sonnabend committed
658

Robin Sonnabend's avatar
Robin Sonnabend committed
659
660
@app.route("/protocol/template/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
661
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
662
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
663
def get_protocol_template(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
664
    file_like = BytesIO(protocol.get_template().encode("utf-8"))
665
    return send_file(file_like, cache_timeout=1, as_attachment=True, attachment_filename="{}-template.txt".format(protocol.get_short_identifier()))
Robin Sonnabend's avatar
Robin Sonnabend committed
666

Robin Sonnabend's avatar
Robin Sonnabend committed
667
668
@app.route("/protocol/etherpush/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
669
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
670
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
671
def etherpush_protocol(protocol):
672
673
674
    if not config.ETHERPAD_ACTIVE:
        flash("Die Etherpadfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
675
676
677
    if not protocol.is_done():
        tasks.set_etherpad_content(protocol)
    return redirect(request.args.get("next") or protocol.get_etherpad_link())
Robin Sonnabend's avatar
Robin Sonnabend committed
678

Robin Sonnabend's avatar
Robin Sonnabend committed
679
@app.route("/protocol/update/<int:protocol_id>", methods=["GET", "POST"])
Robin Sonnabend's avatar
Robin Sonnabend committed
680
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
681
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
682
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
683
def update_protocol(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
684
    upload_form = KnownProtocolSourceUploadForm()
685
    edit_form = generate_protocol_form(protocol)(obj=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
686
687
    if edit_form.validate_on_submit():
        edit_form.populate_obj(protocol)
688
689
        for meta in protocol.metas:
            meta.value = getattr(edit_form.metas, meta.name).data
Robin Sonnabend's avatar
Robin Sonnabend committed
690
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
691
        tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
692
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
693
694
    for meta in protocol.metas:
        getattr(edit_form.metas, meta.name).data = meta.value
Robin Sonnabend's avatar
Robin Sonnabend committed
695
    return render_template("protocol-update.html", upload_form=upload_form, edit_form=edit_form, protocol=protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
696

697
698
@app.route("/protocol/publish/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
699
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
700
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
701
def publish_protocol(protocol):
702
703
704
705
    protocol.public = True
    db.session.commit()
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

706
707
@app.route("/prococol/send/<int:protocol_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
708
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
709
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
710
def send_protocol(protocol):
711
712
713
    if not config.MAIL_ACTIVE:
        flash("Die Mailfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
714
715
716
717
    tasks.send_protocol(protocol)
    flash("Das Protokoll wurde versandt.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))

718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
@app.route("/protocol/reminder/<int:protocol_id>")
@login_required
@db_lookup(Protocol)
@require_modify_right()
def send_protocol_reminder(protocol):
    if not config.MAIL_ACTIVE:
        flash("Die Mailfunktion ist nicht aktiviert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
    meetingreminders = MeetingReminder.query.filter_by(protocoltype_id=protocol.protocoltype.id).all()
    if len(meetingreminders) == 0:
        flash("Für diesen Protokolltyp sind keine Einladungsmails konfiguriert.", "alert-error")
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol_id))
    day_difference = (protocol.date - datetime.now().date()).days
    past_reminders = [
        meetingreminder for meetingreminder in meetingreminders
        if meetingreminder.days_before > day_difference
    ]
    if len(past_reminders) == 0:
        flash("Bisher hätte keine Einladungsmail verschickt werden sollen, schicke letzte.", "alert-info")
        past_reminders = meetingreminders
    past_reminders = sorted(past_reminders, key=lambda r: r.days_before)
    choosen_reminder = past_reminders[0]
    tasks.send_reminder(choosen_reminder, protocol)
    flash("Einladungsmail ist versandt.", "alert-success")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
        

Robin Sonnabend's avatar
Robin Sonnabend committed
745
746
@app.route("/protocol/tops/new/<int:protocol_id>", methods=["GET", "POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
747
@db_lookup(Protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
748
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
749
def new_top(protocol):
Robin Sonnabend's avatar
Robin Sonnabend committed
750
751
    form = TopForm()
    if form.validate_on_submit():
752
753
        top = TOP(protocol_id=protocol.id, planned=True)
        form.populate_obj(top)
Robin Sonnabend's avatar
Robin Sonnabend committed
754
755
        db.session.add(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
756
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
757
758
759
760
761
762
763
764
765
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
    else:
        current_numbers = list(map(lambda t: t.number, protocol.tops))
        suggested_number = get_first_unused_int(current_numbers)
        form.number.data = suggested_number
    return render_template("top-new.html", form=form, protocol=protocol)

@app.route("/protocol/top/edit/<int:top_id>", methods=["GET", "POST"])
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
766
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
767
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
768
def edit_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
769
770
771
772
    form = TopForm(obj=top)
    if form.validate_on_submit():
        form.populate_obj(top)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
773
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
774
775
776
777
778
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=top.protocol.id))
    return render_template("top-edit.html", form=form, top=top)

@app.route("/protocol/top/delete/<int:top_id>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
779
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
780
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
781
def delete_top(top):
Robin Sonnabend's avatar
Robin Sonnabend committed
782
    name = top.name
Robin Sonnabend's avatar
Robin Sonnabend committed
783
    protocol = top.protocol
Robin Sonnabend's avatar
Robin Sonnabend committed
784
785
    db.session.delete(top)
    db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
786
    tasks.push_tops_to_calendar(protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
787
    flash("Der TOP {} wurde gelöscht.".format(name), "alert-success")
Robin Sonnabend's avatar
Robin Sonnabend committed
788
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=protocol.id))
Robin Sonnabend's avatar
Robin Sonnabend committed
789
790
791

@app.route("/protocol/top/move/<int:top_id>/<diff>")
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
792
@db_lookup(TOP)
Robin Sonnabend's avatar
Robin Sonnabend committed
793
@require_modify_right()
Robin Sonnabend's avatar
Robin Sonnabend committed
794
def move_top(top, diff):
Robin Sonnabend's avatar
Robin Sonnabend committed
795
796
797
    try:
        top.number += int(diff)
        db.session.commit()
Robin Sonnabend's avatar
Robin Sonnabend committed
798
        tasks.push_tops_to_calendar(top.protocol)
Robin Sonnabend's avatar
Robin Sonnabend committed
799
800
801
802
    except ValueError:
        flash("Die angegebene Differenz ist keine Zahl.", "alert-error")
    return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=top.protocol.id))

803
804
805
806
807
808
809
810
811
812
813
814
@app.route("/protocol/localtop/edit/<int:localtop_id>", methods=["GET", "POST"])
@login_required
@db_lookup(LocalTOP)
@require_modify_right()
def edit_localtop(localtop):
    form = LocalTopForm(obj=localtop)
    if form.validate_on_submit():
        form.populate_obj(localtop)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("show_protocol", protocol_id=localtop.protocol.id))
    return render_template("localtop-edit.html", form=form, localtop=localtop)

Robin Sonnabend's avatar
Robin Sonnabend committed
815
816
817
818
819
820
821
822
823
def _get_page():
    try:
        page = request.args.get("page")
        if page is None:
            return 0
        return int(page)
    except ValueError:
        return 0

Robin Sonnabend's avatar
Robin Sonnabend committed
824
825
826
827
828
829
830
831
832
def _get_page_length():
    try:
        page_length = request.args.get("page_length")
        if page_length is None:
            return config.PAGE_LENGTH
        return int(page_length)
    except ValueError:
        return config.PAGE_LENGTH

833
@app.route("/todos/list")
Robin Sonnabend's avatar
Robin Sonnabend committed
834
@login_required
Robin Sonnabend's avatar
Robin Sonnabend committed
835
836
def list_todos():
    user = current_user()
Robin Sonnabend's avatar
Robin Sonnabend committed
837
838
839
    protocoltype = None
    protocoltype_id = None
    try:
840
        protocoltype_id = int(request.args.get("protocoltype_id"))
Robin Sonnabend's avatar
Robin Sonnabend committed
841
842
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
843
    state_open = -1
Robin Sonnabend's avatar
Robin Sonnabend committed
844
    try:
Robin Sonnabend's avatar
Robin Sonnabend committed
845
        state_open = int(request.args.get("state_open"))
Robin Sonnabend's avatar
Robin Sonnabend committed
846
847
    except (ValueError, TypeError):
        pass
Robin Sonnabend's avatar
Robin Sonnabend committed
848
    search_term = request.args.get("search")
Robin Sonnabend's avatar
Robin Sonnabend committed
849
    protocoltypes = ProtocolType.get_public_protocoltypes(user)
Robin Sonnabend's avatar
Robin Sonnabend committed
850
    search_form = TodoSearchForm(protocoltypes)
Robin Sonnabend's avatar
Robin Sonnabend committed
851
    if protocoltype_id is not None:
852
        search_form.protocoltype_id.data = protocoltype_id
Robin Sonnabend's avatar
Robin Sonnabend committed
853
        protocoltype = ProtocolType.query.filter_by(id=protocoltype_id).first()
Robin Sonnabend's avatar
Robin Sonnabend committed
854
855
    if state_open is not None:
        search_form.state_open.data = state_open
856
857
    if search_term is not None:
        search_form.search.data = search_term
Robin Sonnabend's avatar
Robin Sonnabend committed
858
859
860
861
    todos = [
        todo for todo in Todo.query.all()
        if todo.protocoltype.has_public_view_right(user)
    ]
Robin Sonnabend's avatar
Robin Sonnabend committed
862
    if protocoltype_id is not None and protocoltype_id != -1:
Robin Sonnabend's avatar
Robin Sonnabend committed
863
864
865
866
        todos = [
            todo for todo in todos
            if todo.protocoltype.id == protocoltype_id
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
867
868
    if state_open is not None and state_open != -1:
        todo_done = bool(state_open)
Robin Sonnabend's avatar
Robin Sonnabend committed
869
870
871
872
        todos = [
            todo for todo in todos
            if todo.is_done() == todo_done
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
873
    if search_term is not None and len(search_term.strip()) > 0:
Robin Sonnabend's avatar
Robin Sonnabend committed
874
875
876
        todos = [
            todo for todo in todos
            if search_term.lower() in todo.description.lower()
877
            or search_term.lower() in todo.who.lower()
Robin Sonnabend's avatar
Robin Sonnabend committed
878
        ]
Robin Sonnabend's avatar
Robin Sonnabend committed
879
    def _sort_key(todo):
Administrator's avatar
Administrator committed
880
        return (not todo.is_done(), todo.get_id())
Robin Sonnabend's avatar
Robin Sonnabend committed
881
    todos = sorted(todos, key=_sort_key, reverse=True)
Robin Sonnabend's avatar
Robin Sonnabend committed
882
    page = _get_page()
Robin Sonnabend's avatar
Robin Sonnabend committed
883
884
    page_length = _get_page_length()
    page_count = int(math.ceil(len(todos) / page_length))
Robin Sonnabend's avatar
Robin Sonnabend committed
</