~homeworkprod/byceps

ref: 533662eefb314d54b168e5a46bc07c88b5f88be4 byceps/byceps/blueprints/admin/board/views.py -rw-r--r-- 10.1 KiB
533662ee — Jochen Kupperschmidt Use Flask v2.0's `delete`/`get`/`patch`/`post` route shortcuts 2 months ago
                                                                                
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""
byceps.blueprints.admin.board.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from dataclasses import dataclass

from flask import abort, request
from flask_babel import gettext

from ....services.board import board_service
from ....services.board import (
    category_command_service as board_category_command_service,
    category_query_service as board_category_query_service,
    posting_query_service as board_posting_query_service,
    topic_query_service as board_topic_query_service,
)
from ....services.board.transfer.models import Board, Category
from ....services.brand import service as brand_service
from ....util.authorization import register_permission_enum
from ....util.framework.blueprint import create_blueprint
from ....util.framework.flash import flash_error, flash_success
from ....util.framework.templating import templated
from ....util.views import permission_required, redirect_to, respond_no_content

from ...site.board.authorization import BoardPermission

from .authorization import BoardCategoryPermission
from .forms import BoardCreateForm, CategoryCreateForm, CategoryUpdateForm


blueprint = create_blueprint('board_admin', __name__)


register_permission_enum(BoardPermission)
register_permission_enum(BoardCategoryPermission)


@dataclass(frozen=True)
class BoardStats:
    category_count: int
    topic_count: int
    posting_count: int


# -------------------------------------------------------------------- #
# boards


@blueprint.get('/brands/<brand_id>')
@permission_required(BoardCategoryPermission.view)
@templated
def board_index_for_brand(brand_id):
    """List categories for that brand."""
    brand = _get_brand_or_404(brand_id)

    boards = board_service.get_boards_for_brand(brand.id)
    board_ids = [board.id for board in boards]

    stats_by_board_id = {
        board_id: BoardStats(
            board_category_query_service.count_categories_for_board(board_id),
            board_topic_query_service.count_topics_for_board(board_id),
            board_posting_query_service.count_postings_for_board(board_id),
        )
        for board_id in board_ids
    }

    return {
        'boards': boards,
        'brand': brand,
        'stats_by_board_id': stats_by_board_id,
    }


@blueprint.get('/boards/<board_id>')
@permission_required(BoardCategoryPermission.view)
@templated
def board_view(board_id):
    """View the board."""
    board = _get_board_or_404(board_id)

    brand = brand_service.find_brand(board.brand_id)

    categories = board_category_query_service.get_categories(board.id)

    return {
        'board_id': board.id,
        'board_brand_id': board.brand_id,
        'brand': brand,
        'categories': categories,
    }


@blueprint.get('/for_brand/<brand_id>/boards/create')
@permission_required(BoardPermission.create)
@templated
def board_create_form(brand_id, erroneous_form=None):
    """Show form to create a board."""
    brand = _get_brand_or_404(brand_id)

    form = erroneous_form if erroneous_form else BoardCreateForm()

    return {
        'brand': brand,
        'form': form,
    }


@blueprint.post('/for_brand/<brand_id>/boards')
@permission_required(BoardPermission.create)
def board_create(brand_id):
    """Create a board."""
    brand = _get_brand_or_404(brand_id)

    form = BoardCreateForm(request.form)
    if not form.validate():
        return board_create_form(brand.id, form)

    board_id = form.board_id.data.strip().lower()

    board = board_service.create_board(brand.id, board_id)

    flash_success(
        gettext(
            'Board with ID "%(board_id)s" has been created.',
            board_id=board.id,
        )
    )
    return redirect_to('.board_view', board_id=board.id)


# -------------------------------------------------------------------- #
# categories


@blueprint.get('/categories/for_board/<board_id>/create')
@permission_required(BoardCategoryPermission.create)
@templated
def category_create_form(board_id, erroneous_form=None):
    """Show form to create a category."""
    board = _get_board_or_404(board_id)

    brand = brand_service.find_brand(board.brand_id)

    form = erroneous_form if erroneous_form else CategoryCreateForm()

    return {
        'board': board,
        'brand': brand,
        'form': form,
    }


@blueprint.post('/categories/for_board/<board_id>')
@permission_required(BoardCategoryPermission.create)
def category_create(board_id):
    """Create a category."""
    board = _get_board_or_404(board_id)

    form = CategoryCreateForm(request.form)
    if not form.validate():
        return category_create_form(board.id, form)

    slug = form.slug.data.strip().lower()
    title = form.title.data.strip()
    description = form.description.data.strip()

    category = board_category_command_service.create_category(
        board.id, slug, title, description
    )

    flash_success(
        gettext(
            'Category "%(category_title)s" has been created.',
            category_title=category.title,
        )
    )
    return redirect_to('.board_view', board_id=board.id)


@blueprint.get('/categories/<uuid:category_id>/update')
@permission_required(BoardCategoryPermission.update)
@templated
def category_update_form(category_id, erroneous_form=None):
    """Show form to update the category."""
    category = _get_category_or_404(category_id)

    board = board_service.find_board(category.board_id)
    brand = brand_service.find_brand(board.brand_id)

    form = (
        erroneous_form if erroneous_form else CategoryUpdateForm(obj=category)
    )

    return {
        'category': category,
        'brand': brand,
        'form': form,
    }


@blueprint.post('/categories/<uuid:category_id>')
@permission_required(BoardCategoryPermission.update)
def category_update(category_id):
    """Update the category."""
    category = _get_category_or_404(category_id)

    form = CategoryUpdateForm(request.form)
    if not form.validate():
        return category_update_form(category_id, form)

    slug = form.slug.data
    title = form.title.data
    description = form.description.data

    category = board_category_command_service.update_category(
        category.id, slug, title, description
    )

    flash_success(
        gettext(
            'Category "%(category_title)s" has been updated.',
            category_title=category.title,
        )
    )
    return redirect_to('.board_view', board_id=category.board_id)


@blueprint.post('/categories/<uuid:category_id>/flags/hidden')
@permission_required(BoardCategoryPermission.update)
@respond_no_content
def category_hide(category_id):
    """Hide the category."""
    category = _get_category_or_404(category_id)

    board_category_command_service.hide_category(category.id)

    flash_success(
        gettext(
            'Category "%(category_title)s" has been hidden.',
            category_title=category.title,
        )
    )


@blueprint.delete('/categories/<uuid:category_id>/flags/hidden')
@permission_required(BoardCategoryPermission.update)
@respond_no_content
def category_unhide(category_id):
    """Un-hide the category."""
    category = _get_category_or_404(category_id)

    board_category_command_service.unhide_category(category.id)

    flash_success(
        gettext(
            'Category "%(category_title)s" has been made visible.',
            category_title=category.title,
        )
    )


@blueprint.post('/categories/<uuid:category_id>/up')
@permission_required(BoardCategoryPermission.update)
@respond_no_content
def category_move_up(category_id):
    """Move the category upwards by one position."""
    category = _get_category_or_404(category_id)

    try:
        board_category_command_service.move_category_up(category.id)
    except ValueError:
        flash_error(
            gettext(
                'Category "%(category_title)s" is already at the top.',
                category_title=category.title,
            )
        )
    else:
        flash_success(
            gettext(
                'Category "%(category_title)s" has been moved upwards by one position.',
                category_title=category.title,
            )
        )


@blueprint.post('/categories/<uuid:category_id>/down')
@permission_required(BoardCategoryPermission.update)
@respond_no_content
def category_move_down(category_id):
    """Move the category downwards by one position."""
    category = _get_category_or_404(category_id)

    try:
        board_category_command_service.move_category_down(category.id)
    except ValueError:
        flash_error(
            gettext(
                'Category "%(category_title)s" is already at the bottom.',
                category_title=category.title,
            )
        )
    else:
        flash_success(
            gettext(
                'Category "%(category_title)s" has been moved downwards by one position.',
                category_title=category.title,
            )
        )


@blueprint.delete('/categories/<uuid:category_id>')
@permission_required(BoardCategoryPermission.create)
@respond_no_content
def category_delete(category_id):
    """Delete a category."""
    category = _get_category_or_404(category_id)

    try:
        board_category_command_service.delete_category(category.id)
    except Exception:
        flash_error(
            gettext(
                'Category "%(category_title)s" could not be deleted.',
                category_title=category.title,
            )
        )
    else:
        flash_success(
            gettext(
                'Category "%(category_title)s" has been deleted.',
                category_title=category.title,
            )
        )


# -------------------------------------------------------------------- #
# helpers


def _get_brand_or_404(brand_id):
    brand = brand_service.find_brand(brand_id)

    if brand is None:
        abort(404)

    return brand


def _get_board_or_404(board_id) -> Board:
    board = board_service.find_board(board_id)

    if board is None:
        abort(404)

    return board


def _get_category_or_404(category_id) -> Category:
    category = board_category_query_service.find_category_by_id(category_id)

    if category is None:
        abort(404)

    return category