~homeworkprod/byceps

ref: 867978381e58811d3878ce9aa2bf68873ed80caa byceps/byceps/services/brand/service.py -rw-r--r-- 2.1 KiB
86797838 — Jochen Kupperschmidt Implement functionality to update a brand 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
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 update_brand(
    brand_id: BrandID, title: str, *, image_filename: Optional[str] = None
) -> Brand:
    """Update a brand."""
    brand = _get_db_brand(brand_id)

    brand.title = title
    brand.image_filename = image_filename

    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 = _get_db_brand(brand_id)

    if brand is None:
        return None

    return _db_entity_to_brand(brand)


def _get_db_brand(brand_id: BrandID) -> DbBrand:
    """Return the brand with that ID."""
    return DbBrand.query.get(brand_id)


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,
        brand.image_filename,
        image_url_path,
    )