~homeworkprod/byceps

ref: 533662eefb314d54b168e5a46bc07c88b5f88be4 byceps/byceps/blueprints/admin/user_badge/views.py -rw-r--r-- 7.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
"""
byceps.blueprints.admin.user_badge.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

from flask import abort, g, request
from flask_babel import gettext

from ....services.brand import service as brand_service
from ....services.user import service as user_service
from ....services.user_badge import awarding_service, badge_service
from ....signals import user_badge as user_badge_signals
from ....util.authorization import register_permission_enum
from ....util.framework.blueprint import create_blueprint
from ....util.framework.flash import flash_success
from ....util.framework.templating import templated
from ....util.views import permission_required, redirect_to

from .authorization import UserBadgePermission
from .forms import AwardForm, CreateForm, UpdateForm


blueprint = create_blueprint('user_badge_admin', __name__)


register_permission_enum(UserBadgePermission)


# -------------------------------------------------------------------- #
# badges


@blueprint.get('/badges')
@permission_required(UserBadgePermission.view)
@templated
def index():
    """List all badges."""
    all_badges = badge_service.get_all_badges()

    brands = brand_service.get_all_brands()
    brands_by_id = {brand.id: brand for brand in brands}

    def _find_brand(brand_id):
        if brand_id is None:
            return None

        return brands_by_id[brand_id]

    awarding_counts_by_badge_id = awarding_service.count_awardings()

    badges = [
        {
            'id': badge.id,
            'slug': badge.slug,
            'label': badge.label,
            'image_url_path': badge.image_url_path,
            'brand': _find_brand(badge.brand_id),
            'featured': badge.featured,
            'awarding_count': awarding_counts_by_badge_id[badge.id],
        }
        for badge in all_badges
    ]

    return {
        'badges': badges,
    }


@blueprint.get('/badges/<uuid:badge_id>')
@permission_required(UserBadgePermission.view)
@templated
def view(badge_id):
    """Show badge details."""
    badge = _get_badge_or_404(badge_id)

    if badge.brand_id:
        brand = brand_service.find_brand(badge.brand_id)
    else:
        brand = None

    awardings = awarding_service.get_awardings_of_badge(badge.id)
    recipient_ids = [awarding.user_id for awarding in awardings]
    recipients = user_service.find_users(recipient_ids, include_avatars=True)
    recipients = list(sorted(recipients, key=lambda r: r.screen_name or ''))

    return {
        'badge': badge,
        'brand': brand,
        'recipients': recipients,
    }


@blueprint.get('/create')
@permission_required(UserBadgePermission.create)
@templated
def create_form(erroneous_form=None):
    """Show form to create a user badge."""
    form = erroneous_form if erroneous_form else CreateForm()
    _set_brand_ids_on_form(form)

    return {
        'form': form,
    }


@blueprint.post('/badges')
@permission_required(UserBadgePermission.create)
def create():
    """Create a user badge."""
    form = CreateForm(request.form)
    _set_brand_ids_on_form(form)

    if not form.validate():
        return create_form(form)

    slug = form.slug.data.strip()
    label = form.label.data.strip()
    description = form.description.data.strip()
    image_filename = form.image_filename.data.strip()
    brand_id = form.brand_id.data
    featured = form.featured.data

    if brand_id:
        brand = brand_service.find_brand(brand_id)
        brand_id = brand.id
    else:
        brand_id = None

    badge = badge_service.create_badge(
        slug,
        label,
        image_filename,
        description=description,
        brand_id=brand_id,
        featured=featured,
    )

    flash_success(
        gettext(
            'Badge "%(badge_label)s" has been created.',
            badge_label=badge.label,
        )
    )
    return redirect_to('.index')


@blueprint.get('/badges/<uuid:badge_id>/update')
@permission_required(UserBadgePermission.update)
@templated
def update_form(badge_id, erroneous_form=None):
    """Show form to update a badge."""
    badge = _get_badge_or_404(badge_id)

    form = erroneous_form if erroneous_form else UpdateForm(obj=badge)
    _set_brand_ids_on_form(form)

    return {
        'badge': badge,
        'form': form,
    }


@blueprint.post('/badges/<uuid:badge_id>')
@permission_required(UserBadgePermission.update)
def update(badge_id):
    """Update a badge."""
    badge = _get_badge_or_404(badge_id)

    form = UpdateForm(request.form)
    _set_brand_ids_on_form(form)
    if not form.validate():
        return update_form(badge.id, form)

    slug = form.slug.data.strip()
    label = form.label.data.strip()
    description = form.description.data.strip()
    image_filename = form.image_filename.data.strip()
    brand_id = form.brand_id.data
    featured = form.featured.data

    badge = badge_service.update_badge(
        badge.id, slug, label, description, image_filename, brand_id, featured
    )

    flash_success(
        gettext(
            'Badge "%(badge_label)s" has been updated.',
            badge_label=badge.label,
        )
    )
    return redirect_to('.view', badge_id=badge_id)


def _set_brand_ids_on_form(form):
    brands = brand_service.get_all_brands()
    form.set_brand_choices(brands)


# -------------------------------------------------------------------- #
# awarding


@blueprint.get('/awardings/to/<uuid:user_id>')
@permission_required(UserBadgePermission.award)
@templated
def award_form(user_id, erroneous_form=None):
    """Show form to award a badge to a user."""
    user = user_service.find_user(user_id)
    if not user:
        abort(404)

    form = erroneous_form if erroneous_form else AwardForm(user_id=user.id)
    _set_badge_ids_on_form(form)

    return {
        'form': form,
        'user': user,
    }


@blueprint.post('/awardings/to/<uuid:user_id>')
@permission_required(UserBadgePermission.award)
def award(user_id):
    """Award a badge to a user."""
    form = AwardForm(request.form)
    _set_badge_ids_on_form(form)

    if not form.validate():
        return award_form(user_id, form)

    badge_id = form.badge_id.data

    user = user_service.find_user(user_id)
    if not user:
        abort(401, 'Unknown user ID')

    badge = badge_service.find_badge(badge_id)
    if not badge:
        abort(401, 'Unknown badge ID')

    initiator_id = g.user.id

    _, event = awarding_service.award_badge_to_user(
        badge_id, user_id, initiator_id=initiator_id
    )

    flash_success(
        gettext(
            'Badge "%(badge_label)s" has been awarded to %(screen_name)s.',
            badge_label=badge.label,
            screen_name=user.screen_name,
        )
    )

    user_badge_signals.user_badge_awarded.send(None, event=event)

    return redirect_to('user_admin.view', user_id=user.id)


def _set_badge_ids_on_form(form):
    badges = badge_service.get_all_badges()
    form.set_badge_choices(badges)


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


def _get_badge_or_404(badge_id):
    badge = badge_service.find_badge(badge_id)

    if badge is None:
        abort(404)

    return badge