~homeworkprod/byceps

ref: e8cad0b6c26fa348e85c82b0edc168ea6ccbb6b7 byceps/byceps/services/brand/service.py -rw-r--r-- 1.7 KiB
e8cad0b6 — Jochen Kupperschmidt Add/link breadcrumbs in admin brand views 1 year, 3 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
"""
byceps.services.brand.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import List, Optional

from ...database import db
from ...typing import BrandID

from .models.brand import Brand as DbBrand
from .models.setting import Setting as DbSetting
from .transfer.models import Brand


def create_brand(brand_id: BrandID, title: str) -> Brand:
    """Create a brand."""
    brand = DbBrand(brand_id, title)

    db.session.add(brand)
    db.session.commit()

    return _db_entity_to_brand(brand)


def delete_brand(brand_id: BrandID) -> None:
    """Delete a brand."""
    db.session.query(DbSetting) \
        .filter_by(brand_id=brand_id) \
        .delete()

    db.session.query(DbBrand) \
        .filter_by(id=brand_id) \
        .delete()

    db.session.commit()


def find_brand(brand_id: BrandID) -> Optional[Brand]:
    """Return the brand with that id, or `None` if not found."""
    brand = DbBrand.query.get(brand_id)

    if brand is None:
        return None

    return _db_entity_to_brand(brand)


def get_brands() -> List[Brand]:
    """Return all brands, ordered by title."""
    brands = DbBrand.query \
        .order_by(DbBrand.title) \
        .all()

    return [_db_entity_to_brand(brand) for brand in brands]


def count_brands() -> int:
    """Return the number of brands."""
    return DbBrand.query.count()


def _db_entity_to_brand(brand: DbBrand) -> Brand:
    if brand.image_filename:
        image_url_path = f'/data/global/brand_images/{brand.image_filename}'
    else:
        image_url_path = None

    return Brand(
        brand.id,
        brand.title,
        image_url_path,
    )