aboutsummaryrefslogtreecommitdiffstats
path: root/pysite/views/staff/tables/table.py
blob: f47d7793763bce01628b0d0e102402de52998a9d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from math import ceil

from flask import request
from werkzeug.exceptions import BadRequest, NotFound

from pysite.base_route import RouteView
from pysite.constants import TABLE_MANAGER_ROLES
from pysite.decorators import require_roles
from pysite.mixins import DBMixin
from pysite.tables import TABLES


class TableView(RouteView, DBMixin):
    path = "/tables/<table>/<page>"
    name = "tables.table"

    @require_roles(*TABLE_MANAGER_ROLES)
    def get(self, table, page):
        search = request.args.get("search")
        search_key = request.args.get("search-key")

        pages = page
        obj = TABLES.get(table)

        if not obj:
            return NotFound()

        if search:
            new_search = f"(?i){search}"  # Case-insensitive search
            search_key = search_key or obj.primary_key

            query = self.db.query(table).filter(lambda d: d[search_key].match(new_search))
        else:
            query = self.db.query(table)

        if page != "all":
            try:
                page = int(page)
            except ValueError:
                # Not an integer
                return BadRequest()

            count = self.db.run(query.count(), coerce=int)
            pages = max(ceil(count / 10), 1)  # Pages if we have 10 documents per page, always at least one

            if page < 1 or page > pages:
                # If the page is too small or too big, well, that's an error
                return BadRequest()

            documents = self.db.run(  # Get only the documents for this page
                query.skip((page - 1) * 10).limit(10),
                coerce=list
            )
        else:
            documents = self.db.run(query, coerce=list)

        documents = [dict(sorted(d.items())) for d in documents]

        return self.render(
            "staff/tables/table.html",
            table=table, documents=documents, table_obj=obj,
            page=page, pages=pages, search=search, search_key=search_key
        )