~homeworkprod/byceps

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

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

import dataclasses
from typing import Iterable, Iterator

from flask import abort, request
from flask_babel import gettext

from ....services.board import board_service
from ....services.brand import service as brand_service
from ....services.brand.transfer.models import Brand
from ....services.news import channel_service as news_channel_service
from ....services.party import service as party_service
from ....services.shop.shop import service as shop_service
from ....services.shop.storefront import service as storefront_service
from ....services.site import (
    service as site_service,
    settings_service as site_settings_service,
)
from ....services.site.transfer.models import Site, SiteWithBrand
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

from .authorization import SitePermission
from .forms import CreateForm, UpdateForm


blueprint = create_blueprint('site_admin', __name__)


register_permission_enum(SitePermission)


@blueprint.get('/')
@permission_required(SitePermission.view)
@templated
def index():
    """List all sites."""
    brands = brand_service.get_all_brands()
    brands.sort(key=lambda brand: brand.title)

    sites = site_service.get_all_sites()
    sites = list(_sites_to_sites_with_brand(sites, brands))
    sites.sort(key=lambda site: (site.title, site.party_id))

    parties = party_service.get_all_parties()
    party_titles_by_id = {p.id: p.title for p in parties}

    storefronts_by_site_id = _get_storefronts_by_site_id(sites)

    return {
        'sites': sites,
        'brands': brands,
        'party_titles_by_id': party_titles_by_id,
        'storefronts_by_site_id': storefronts_by_site_id,
    }


@blueprint.get('/for_brand/<brand_id>')
@permission_required(SitePermission.view)
@templated
def index_for_brand(brand_id):
    """List sites for this brand."""
    brand = brand_service.find_brand(brand_id)
    if brand is None:
        abort(404)

    sites = site_service.get_sites_for_brand(brand.id)
    sites = [_site_to_site_with_brand(site, brand) for site in sites]
    sites.sort(key=lambda site: (site.title, site.party_id))

    parties = party_service.get_all_parties()
    party_titles_by_id = {p.id: p.title for p in parties}

    storefronts_by_site_id = _get_storefronts_by_site_id(sites)

    return {
        'sites': sites,
        'brand': brand,
        'party_titles_by_id': party_titles_by_id,
        'storefronts_by_site_id': storefronts_by_site_id,
    }


def _sites_to_sites_with_brand(
    sites: Iterable[Site], brands: Iterable[Brand]
) -> Iterator[SiteWithBrand]:
    brands_by_id = {brand.id: brand for brand in brands}

    for site in sites:
        brand = brands_by_id[site.brand_id]
        yield _site_to_site_with_brand(site, brand)


def _site_to_site_with_brand(site: Site, brand: Brand) -> SiteWithBrand:
    site_tuple = dataclasses.astuple(site)
    brand_tuple = (brand,)

    return SiteWithBrand(*(site_tuple + brand_tuple))


def _get_storefronts_by_site_id(sites):
    storefront_ids = {
        site.storefront_id for site in sites if site.storefront_id is not None
    }
    storefronts = storefront_service.find_storefronts(storefront_ids)
    storefronts_by_id = {
        storefront.id: storefront for storefront in storefronts
    }
    return {
        site.id: storefronts_by_id.get(site.storefront_id) for site in sites
    }


@blueprint.get('/sites/<site_id>')
@permission_required(SitePermission.view)
@templated
def view(site_id):
    """Show a site's settings."""
    site = site_service.find_site(site_id)
    if site is None:
        abort(404)

    brand = brand_service.find_brand(site.brand_id)

    if site.news_channel_id:
        news_channel = news_channel_service.find_channel(site.news_channel_id)
    else:
        news_channel = None

    if site.board_id:
        board = board_service.find_board(site.board_id)
    else:
        board = None

    if site.storefront_id:
        storefront = storefront_service.get_storefront(site.storefront_id)
        shop = shop_service.get_shop(storefront.shop_id)
    else:
        storefront = None
        shop = None

    settings = site_settings_service.get_settings(site.id)

    return {
        'site': site,
        'brand': brand,
        'news_channel': news_channel,
        'board': board,
        'shop': shop,
        'storefront': storefront,
        'settings': settings,
    }


@blueprint.get('/sites/create/for_brand/<brand_id>')
@permission_required(SitePermission.create)
@templated
def create_form(brand_id, erroneous_form=None):
    """Show form to create a site."""
    brand = _get_brand_or_404(brand_id)

    form = erroneous_form if erroneous_form else CreateForm()
    _fill_in_common_form_choices(form, brand.id)

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


@blueprint.post('/sites/for_brand/<brand_id>')
@permission_required(SitePermission.create)
def create(brand_id):
    """Create a site."""
    brand = _get_brand_or_404(brand_id)

    form = CreateForm(request.form)
    _fill_in_common_form_choices(form, brand.id)

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

    site_id = form.id.data.strip().lower()
    title = form.title.data.strip()
    server_name = form.server_name.data.strip()
    party_id = form.party_id.data
    enabled = form.enabled.data
    user_account_creation_enabled = form.user_account_creation_enabled.data
    login_enabled = form.login_enabled.data
    news_channel_id = form.news_channel_id.data.strip() or None
    board_id = form.board_id.data.strip() or None
    storefront_id = form.storefront_id.data.strip() or None

    if party_id:
        party = party_service.find_party(party_id)
        if not party:
            flash_error(
                gettext(
                    'Party ID "%(party_id)s" is unknown.',
                    party_id=party_id,
                )
            )
            return create_form(brand_id, form)
    else:
        party_id = None

    site = site_service.create_site(
        site_id,
        title,
        server_name,
        brand.id,
        enabled=enabled,
        user_account_creation_enabled=user_account_creation_enabled,
        login_enabled=login_enabled,
        party_id=party_id,
        board_id=board_id,
        news_channel_id=news_channel_id,
        storefront_id=storefront_id,
    )

    flash_success(
        gettext('Site "%(title)s" has been created.', title=site.title)
    )

    return redirect_to('.view', site_id=site.id)


@blueprint.get('/sites/<site_id>/update')
@permission_required(SitePermission.update)
@templated
def update_form(site_id, erroneous_form=None):
    """Show form to update the site."""
    site = _get_site_or_404(site_id)

    form = erroneous_form if erroneous_form else UpdateForm(obj=site)
    form.set_brand_choices()
    _fill_in_common_form_choices(form, site.brand_id)

    return {
        'site': site,
        'form': form,
    }


@blueprint.post('/sites/<site_id>')
@permission_required(SitePermission.update)
def update(site_id):
    """Update the site."""
    site = _get_site_or_404(site_id)

    form = UpdateForm(request.form)
    form.set_brand_choices()
    _fill_in_common_form_choices(form, site.brand_id)

    if not form.validate():
        return update_form(site.id, form)

    title = form.title.data.strip()
    server_name = form.server_name.data.strip()
    brand_id = form.brand_id.data
    party_id = form.party_id.data
    enabled = form.enabled.data
    user_account_creation_enabled = form.user_account_creation_enabled.data
    login_enabled = form.login_enabled.data
    news_channel_id = form.news_channel_id.data.strip() or None
    board_id = form.board_id.data.strip() or None
    storefront_id = form.storefront_id.data.strip() or None
    archived = form.archived.data

    if party_id:
        party = party_service.find_party(party_id)
        if not party:
            flash_error(
                gettext(
                    'Party ID "%(party_id)s" is unknown.',
                    party_id=party_id,
                )
            )
            return update_form(site.id, form)
    else:
        party_id = None

    try:
        site = site_service.update_site(
            site.id,
            title,
            server_name,
            brand_id,
            party_id,
            enabled,
            user_account_creation_enabled,
            login_enabled,
            news_channel_id,
            board_id,
            storefront_id,
            archived,
        )
    except site_service.UnknownSiteId:
        abort(404, f'Unknown site ID "{site_id}".')

    flash_success(
        gettext('Site "%(title)s" has been updated.', title=site.title)
    )

    return redirect_to('.view', site_id=site.id)


def _fill_in_common_form_choices(form, brand_id):
    form.set_party_choices(brand_id)
    form.set_board_choices(brand_id)
    form.set_news_channel_choices(brand_id)
    form.set_storefront_choices()


def _get_site_or_404(site_id):
    site = site_service.find_site(site_id)

    if site is None:
        abort(404)

    return site


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

    if brand is None:
        abort(404)

    return brand