coffeebot 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coffeebot/__init__.py +20 -0
- coffeebot/auth.py +75 -0
- coffeebot/config/__init__.py +18 -0
- coffeebot/config/default.json +45 -0
- coffeebot/config/settings.py +240 -0
- coffeebot/db/__init__.py +18 -0
- coffeebot/db/init_DB.sql +29 -0
- coffeebot/db/migration.py +130 -0
- coffeebot/db/statistics.py +149 -0
- coffeebot/db/users.py +390 -0
- coffeebot/gui/__init__.py +18 -0
- coffeebot/gui/icons/enjoy_gif.gif +0 -0
- coffeebot/gui/icons/icon_add_user.svg +107 -0
- coffeebot/gui/icons/icon_back.svg +93 -0
- coffeebot/gui/icons/icon_back_dark.svg +93 -0
- coffeebot/gui/icons/icon_bill.svg +88 -0
- coffeebot/gui/icons/icon_bill_dark.svg +88 -0
- coffeebot/gui/icons/icon_checkmark.svg +72 -0
- coffeebot/gui/icons/icon_chevron_down.svg +71 -0
- coffeebot/gui/icons/icon_chevron_up.svg +71 -0
- coffeebot/gui/icons/icon_collapse.svg +85 -0
- coffeebot/gui/icons/icon_edit.svg +87 -0
- coffeebot/gui/icons/icon_edit_user.svg +109 -0
- coffeebot/gui/icons/icon_expand.svg +77 -0
- coffeebot/gui/icons/icon_hide.svg +84 -0
- coffeebot/gui/icons/icon_home.svg +91 -0
- coffeebot/gui/icons/icon_left_arrow.svg +102 -0
- coffeebot/gui/icons/icon_left_arrow_light.svg +4 -0
- coffeebot/gui/icons/icon_locked.svg +86 -0
- coffeebot/gui/icons/icon_open.svg +80 -0
- coffeebot/gui/icons/icon_price.svg +121 -0
- coffeebot/gui/icons/icon_right_arrow.svg +122 -0
- coffeebot/gui/icons/icon_right_arrow_light.svg +43 -0
- coffeebot/gui/icons/icon_save.svg +114 -0
- coffeebot/gui/icons/icon_settings.svg +80 -0
- coffeebot/gui/icons/icon_show.svg +81 -0
- coffeebot/gui/icons/icon_trash.svg +86 -0
- coffeebot/gui/icons/icon_unlocked.svg +87 -0
- coffeebot/gui/icons/icon_update.svg +94 -0
- coffeebot/gui/icons/icon_user.svg +96 -0
- coffeebot/gui/icons/icon_user_dark.svg +96 -0
- coffeebot/gui/main_window.py +650 -0
- coffeebot/gui/main_window.ui +2646 -0
- coffeebot/gui/widgets/__init__.py +23 -0
- coffeebot/gui/widgets/custom_widgets.py +302 -0
- coffeebot/gui/widgets/edit_info_widget.ui +157 -0
- coffeebot/gui/widgets/edit_user_widget.ui +399 -0
- coffeebot/gui/widgets/login_widget.ui +285 -0
- coffeebot/gui/widgets/reset_challenge_widget.ui +311 -0
- coffeebot/gui/widgets/settings_widget.py +728 -0
- coffeebot/gui/widgets/settings_widget.ui +2055 -0
- coffeebot/gui/widgets/user_management.py +180 -0
- coffeebot/gui/widgets/user_widget.ui +211 -0
- coffeebot/gui/widgets/widget_styles.qss +592 -0
- coffeebot/ressources/icons/icon.svg +114 -0
- coffeebot/startup.py +116 -0
- coffeebot/system/__init__.py +18 -0
- coffeebot/system/credential_store.py +48 -0
- coffeebot/system/migration.py +96 -0
- coffeebot/system/shortcut_manager.py +139 -0
- coffeebot/system/systemd_manager.py +245 -0
- coffeebot/system/webdav_manager.py +308 -0
- coffeebot/update/__init__.py +18 -0
- coffeebot/update/update_check.py +122 -0
- coffeebot/update/update_manager.py +83 -0
- coffeebot-1.0.0.dist-info/METADATA +109 -0
- coffeebot-1.0.0.dist-info/RECORD +69 -0
- coffeebot-1.0.0.dist-info/WHEEL +4 -0
- coffeebot-1.0.0.dist-info/entry_points.txt +8 -0
coffeebot/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""
|
|
2
|
+
################################################################################
|
|
3
|
+
|
|
4
|
+
CoffeeBot: Open Source coffee and beverage billing bookkeeping system.
|
|
5
|
+
|
|
6
|
+
################################################################################
|
|
7
|
+
Copyright (C) 2026 Mavinum
|
|
8
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
9
|
+
See LICENSE in the project root.
|
|
10
|
+
|
|
11
|
+
This program is free software: you can redistribute it and/or modify
|
|
12
|
+
it under the terms of the GNU General Public License as published by
|
|
13
|
+
the Free Software Foundation, version 3 only.
|
|
14
|
+
|
|
15
|
+
This program is distributed in the hope that it will be useful,
|
|
16
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
17
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
18
|
+
for more details.
|
|
19
|
+
################################################################################
|
|
20
|
+
"""
|
coffeebot/auth.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""
|
|
2
|
+
################################################################################
|
|
3
|
+
|
|
4
|
+
Authentication utilities for CoffeeBot.
|
|
5
|
+
|
|
6
|
+
This module provides a thin wrapper around the `bcrypt` library to
|
|
7
|
+
store and verify a master password. The hash is stored in the application
|
|
8
|
+
settings via the `Settings` class.
|
|
9
|
+
################################################################################
|
|
10
|
+
Copyright (C) 2026 Mavinum
|
|
11
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
12
|
+
See LICENSE in the project root.
|
|
13
|
+
|
|
14
|
+
This program is free software: you can redistribute it and/or modify
|
|
15
|
+
it under the terms of the GNU General Public License as published by
|
|
16
|
+
the Free Software Foundation, version 3 only.
|
|
17
|
+
|
|
18
|
+
This program is distributed in the hope that it will be useful,
|
|
19
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
20
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
21
|
+
for more details.
|
|
22
|
+
################################################################################
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import bcrypt
|
|
28
|
+
|
|
29
|
+
from coffeebot.config.settings import Settings
|
|
30
|
+
|
|
31
|
+
_MASTER_HASH_KEY = "master_pwd_hash"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# region Public API
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def set_master_password(password: str) -> None:
|
|
38
|
+
"""
|
|
39
|
+
Hash ``password`` with bcrypt and store the hash.
|
|
40
|
+
|
|
41
|
+
The hash string produced by `bcrypt.hashpw` already contains the
|
|
42
|
+
salt, so it is enough to presist the resulting bytes.
|
|
43
|
+
"""
|
|
44
|
+
if not password:
|
|
45
|
+
msg = "Password must not be empty"
|
|
46
|
+
raise ValueError(msg)
|
|
47
|
+
|
|
48
|
+
# bcrypt requires bytes
|
|
49
|
+
pw_bytes = password.encode("utf-8")
|
|
50
|
+
# Generate a salt and hash the password
|
|
51
|
+
hashed = bcrypt.hashpw(pw_bytes, bcrypt.gensalt())
|
|
52
|
+
# Store the hash as a UTF-8 string
|
|
53
|
+
Settings.get_instance().set(_MASTER_HASH_KEY, hashed.decode("utf-8"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def verify_password(password: str) -> bool:
|
|
57
|
+
"""
|
|
58
|
+
Return ``True`` if ``password`` matches the stored master password.
|
|
59
|
+
|
|
60
|
+
If no password has been set yet, return ``False``.
|
|
61
|
+
"""
|
|
62
|
+
stored_hash = Settings.get_instance().get(_MASTER_HASH_KEY, None)
|
|
63
|
+
if stored_hash is None:
|
|
64
|
+
return False
|
|
65
|
+
try:
|
|
66
|
+
return bcrypt.checkpw(password.encode("utf-8"), str(stored_hash).encode("utf-8"))
|
|
67
|
+
except (ValueError, TypeError):
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# end region
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# Export the function on module level
|
|
75
|
+
__all__ = ["set_master_password", "verify_password"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CoffeeBot configuration package.
|
|
3
|
+
|
|
4
|
+
################################################################################
|
|
5
|
+
Copyright (C) 2026 Mavinum
|
|
6
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
7
|
+
See LICENSE in the project root.
|
|
8
|
+
|
|
9
|
+
This program is free software: you can redistribute it and/or modify
|
|
10
|
+
it under the terms of the GNU General Public License as published by
|
|
11
|
+
the Free Software Foundation, version 3 only.
|
|
12
|
+
|
|
13
|
+
This program is distributed in the hope that it will be useful,
|
|
14
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
15
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
16
|
+
for more details.
|
|
17
|
+
################################################################################
|
|
18
|
+
"""
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"welcome": "I am the Coffee Bot \u2615 and very happy to welcome you to our coffee community! \u0001f973",
|
|
3
|
+
"cat_1_price": 0.40,
|
|
4
|
+
"cat_2_price": 0.80,
|
|
5
|
+
"cat_3_price": 1.00,
|
|
6
|
+
"cat_1_items": [
|
|
7
|
+
"Milk",
|
|
8
|
+
"Water",
|
|
9
|
+
"Expresso"
|
|
10
|
+
],
|
|
11
|
+
"cat_2_items": [
|
|
12
|
+
"Doppio",
|
|
13
|
+
"Cappuccino"
|
|
14
|
+
],
|
|
15
|
+
"cat_3_items": [
|
|
16
|
+
"Coke",
|
|
17
|
+
"Juice",
|
|
18
|
+
"Lemonade"
|
|
19
|
+
],
|
|
20
|
+
"logo_file": "logo.png",
|
|
21
|
+
"db_file": "user_data.db",
|
|
22
|
+
"info_text": "<b>Hello, I am your Coffeebot, and here to help you keep track of your coffee and drinks payments :)</b>\nTo sign up for the beverage list, just press the \"+\" button in the side bar on the left.",
|
|
23
|
+
"challenge_goal": 100,
|
|
24
|
+
"challenge_current": 0,
|
|
25
|
+
"tracked_categories": {
|
|
26
|
+
"cat_1": true,
|
|
27
|
+
"cat_2": false,
|
|
28
|
+
"cat_3": false
|
|
29
|
+
},
|
|
30
|
+
"challenge_rewards": [
|
|
31
|
+
"One Espresso for free",
|
|
32
|
+
"One Softdrink for free",
|
|
33
|
+
"Cleaning the Coffee Machine"
|
|
34
|
+
],
|
|
35
|
+
"selected_reward": "One Expresso for free",
|
|
36
|
+
"bot_startup": false,
|
|
37
|
+
"auto_check_update": true,
|
|
38
|
+
"webdav_enabled": false,
|
|
39
|
+
"auto_backup_enabled": false,
|
|
40
|
+
"auto_restart": false,
|
|
41
|
+
"restart_timeout": 10,
|
|
42
|
+
"lock_timeout": 20,
|
|
43
|
+
"backup_interval": 24,
|
|
44
|
+
"log_level": "INFO"
|
|
45
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Settings management and organization.
|
|
3
|
+
|
|
4
|
+
App wide settings store that behaves like a dict and is backed by JSON
|
|
5
|
+
files. The first call to configure_app creates a shared instance that the rest
|
|
6
|
+
of the application can reuse.
|
|
7
|
+
################################################################################
|
|
8
|
+
Copyright (C) 2026 Mavinum
|
|
9
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
10
|
+
See LICENSE in the project root.
|
|
11
|
+
|
|
12
|
+
This program is free software: you can redistribute it and/or modify
|
|
13
|
+
it under the terms of the GNU General Public License as published by
|
|
14
|
+
the Free Software Foundation, version 3 only.
|
|
15
|
+
|
|
16
|
+
This program is distributed in the hope that it will be useful,
|
|
17
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
18
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
19
|
+
for more details.
|
|
20
|
+
################################################################################
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import contextlib
|
|
26
|
+
import json
|
|
27
|
+
from importlib import metadata
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import TYPE_CHECKING, Any
|
|
30
|
+
|
|
31
|
+
from filelock import FileLock, Timeout
|
|
32
|
+
from platformdirs import PlatformDirs
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from collections.abc import ItemsView, Iterable, Iterator
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
type JSONPrimitive = str | int | float | bool | None
|
|
39
|
+
type JSONValue = JSONPrimitive | list["JSONPrimitive"] | dict[str, "JSONPrimitive"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Settings:
|
|
43
|
+
"""Platform-independent storage for app and user settings."""
|
|
44
|
+
|
|
45
|
+
_instance: Settings | None = None
|
|
46
|
+
app_name = ""
|
|
47
|
+
vendor = ""
|
|
48
|
+
version = ""
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def get_instance(cls) -> Settings:
|
|
52
|
+
"""Return the shared application settings instance."""
|
|
53
|
+
if cls._instance is None:
|
|
54
|
+
msg = "Settings have not been configured yet. Call configure_app() first."
|
|
55
|
+
raise RuntimeError(msg)
|
|
56
|
+
return cls._instance
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def configure_app( # noqa: PLR0913
|
|
60
|
+
cls,
|
|
61
|
+
app_name: str,
|
|
62
|
+
vendor: str,
|
|
63
|
+
*,
|
|
64
|
+
config_dir: str | Path | None = None,
|
|
65
|
+
default_path: str | Path | None = None,
|
|
66
|
+
config_filename: str = "config.json",
|
|
67
|
+
lock_timeout: int = 5,
|
|
68
|
+
) -> Settings:
|
|
69
|
+
"""Configure a shared settings instance for the application."""
|
|
70
|
+
cls.app_name = app_name
|
|
71
|
+
cls.vendor = vendor
|
|
72
|
+
cls.version = metadata.version(app_name)
|
|
73
|
+
cls.dirs = PlatformDirs(app_name, vendor)
|
|
74
|
+
|
|
75
|
+
resolved_config_dir = Path(config_dir) if config_dir is not None else Path(cls.dirs.user_config_path)
|
|
76
|
+
resolved_config_dir.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
|
|
78
|
+
resolved_default_path = (
|
|
79
|
+
Path(default_path) if default_path is not None else Path(__file__).with_name("default.json")
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if cls._instance is None:
|
|
83
|
+
cls._instance = cls(resolved_config_dir / config_filename, resolved_default_path, lock_timeout=lock_timeout)
|
|
84
|
+
else:
|
|
85
|
+
cls._instance.path = resolved_config_dir / config_filename
|
|
86
|
+
cls._instance.path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
cls._instance.default_path = resolved_default_path
|
|
88
|
+
cls._instance.lock = FileLock(str(cls._instance.path) + ".lock")
|
|
89
|
+
cls._instance.lock_timeout = lock_timeout
|
|
90
|
+
cls._instance.load()
|
|
91
|
+
|
|
92
|
+
return cls._instance
|
|
93
|
+
|
|
94
|
+
def __init__(self, path: str | Path, default_path: str | Path | None = None, lock_timeout: int = 5):
|
|
95
|
+
self.path = Path(path)
|
|
96
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
self.default_path = Path(default_path) if default_path is not None else None
|
|
98
|
+
self.lock = FileLock(str(self.path) + ".lock")
|
|
99
|
+
self.lock_timeout = lock_timeout
|
|
100
|
+
self._defaults: dict[str, JSONValue] = {}
|
|
101
|
+
self._data: dict[str, JSONValue] = {}
|
|
102
|
+
self.load()
|
|
103
|
+
|
|
104
|
+
def load(self) -> bool:
|
|
105
|
+
"""Load settings from disk and merge them with defaults."""
|
|
106
|
+
defaults = self._load_json(self.default_path) if self.default_path is not None else {}
|
|
107
|
+
self._defaults = defaults
|
|
108
|
+
data_dir = self.dirs.user_data_path
|
|
109
|
+
log_dir = self.dirs.user_log_path
|
|
110
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
112
|
+
self._defaults["data_dir"] = str(data_dir)
|
|
113
|
+
self._defaults["log_dir"] = str(log_dir)
|
|
114
|
+
|
|
115
|
+
try:
|
|
116
|
+
self.lock.acquire(timeout=self.lock_timeout)
|
|
117
|
+
try:
|
|
118
|
+
if not self.path.exists():
|
|
119
|
+
self._data = dict(defaults)
|
|
120
|
+
self.save()
|
|
121
|
+
return False
|
|
122
|
+
|
|
123
|
+
user_config = self._load_json(self.path)
|
|
124
|
+
self._data = dict(defaults)
|
|
125
|
+
self._data.update(user_config)
|
|
126
|
+
finally:
|
|
127
|
+
with contextlib.suppress(Exception):
|
|
128
|
+
self.lock.release()
|
|
129
|
+
except Timeout:
|
|
130
|
+
try:
|
|
131
|
+
user_config = self._load_json(self.path)
|
|
132
|
+
self._data = dict(defaults)
|
|
133
|
+
self._data.update(user_config)
|
|
134
|
+
except (PermissionError, json.JSONDecodeError):
|
|
135
|
+
self._data = dict(defaults)
|
|
136
|
+
return False
|
|
137
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
138
|
+
self._data = dict(defaults)
|
|
139
|
+
self.save()
|
|
140
|
+
return False
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
def save(self) -> None:
|
|
144
|
+
"""Persist current settings to disk atomically."""
|
|
145
|
+
self._write_json(self._data)
|
|
146
|
+
|
|
147
|
+
def get(self, key: str, default: JSONValue | None = None) -> JSONValue | None:
|
|
148
|
+
"""Return a stored setting value or a fallback default."""
|
|
149
|
+
return self._data.get(key, default)
|
|
150
|
+
|
|
151
|
+
def set(self, key: str, value: JSONValue) -> None:
|
|
152
|
+
"""Store a setting value and persist it to disk."""
|
|
153
|
+
self._data[key] = value
|
|
154
|
+
self.save()
|
|
155
|
+
|
|
156
|
+
def remove(self, key: str) -> None:
|
|
157
|
+
"""Remove a stored setting entry if it exists."""
|
|
158
|
+
if key in self._data:
|
|
159
|
+
del self._data[key]
|
|
160
|
+
self.save()
|
|
161
|
+
|
|
162
|
+
def update(self, values: dict[str, JSONValue]) -> None:
|
|
163
|
+
"""Update multiple settings values and persist them to disk."""
|
|
164
|
+
self._data.update(values)
|
|
165
|
+
self.save()
|
|
166
|
+
|
|
167
|
+
def set_defaults(self, defaults: dict[str, Any]) -> None:
|
|
168
|
+
"""Set default values from a dict and refresh the live data."""
|
|
169
|
+
self._defaults = dict(defaults)
|
|
170
|
+
merged = dict(self._defaults)
|
|
171
|
+
merged.update(self._data)
|
|
172
|
+
self._data = merged
|
|
173
|
+
self.save()
|
|
174
|
+
|
|
175
|
+
def as_dict(self) -> dict[str, JSONValue]:
|
|
176
|
+
"""Return a shallow copy of the current settings."""
|
|
177
|
+
return dict(self._data)
|
|
178
|
+
|
|
179
|
+
def __getitem__(self, key: str) -> JSONValue:
|
|
180
|
+
"""Return a setting value using mapping syntax."""
|
|
181
|
+
return self._data[key]
|
|
182
|
+
|
|
183
|
+
def __setitem__(self, key: str, value: JSONValue) -> None:
|
|
184
|
+
"""Store a setting value using mapping syntax."""
|
|
185
|
+
self.set(key, value)
|
|
186
|
+
|
|
187
|
+
def __contains__(self, key: object) -> bool:
|
|
188
|
+
"""Return whether a key exists in the current settings."""
|
|
189
|
+
return key in self._data
|
|
190
|
+
|
|
191
|
+
def __iter__(self) -> Iterator[str]:
|
|
192
|
+
"""Iterate over the current setting keys."""
|
|
193
|
+
return iter(self._data)
|
|
194
|
+
|
|
195
|
+
def __len__(self) -> int:
|
|
196
|
+
"""Return the number of currently stored settings."""
|
|
197
|
+
return len(self._data)
|
|
198
|
+
|
|
199
|
+
def items(self) -> ItemsView[str, JSONValue]:
|
|
200
|
+
"""Return the current settings as key/value items."""
|
|
201
|
+
return self._data.items()
|
|
202
|
+
|
|
203
|
+
def keys(self) -> Iterable[str]:
|
|
204
|
+
"""Return the current setting keys."""
|
|
205
|
+
return self._data.keys()
|
|
206
|
+
|
|
207
|
+
def values(self) -> Iterable[JSONValue]:
|
|
208
|
+
"""Return the current setting values."""
|
|
209
|
+
return self._data.values()
|
|
210
|
+
|
|
211
|
+
def _write_json(self, data: dict[str, JSONValue], path: Path | None = None) -> None:
|
|
212
|
+
"""Write dict data to json file."""
|
|
213
|
+
target = path or self.path
|
|
214
|
+
temp_path = target.with_suffix(target.suffix + ".tmp")
|
|
215
|
+
try:
|
|
216
|
+
self.lock.acquire(timeout=self.lock_timeout)
|
|
217
|
+
try:
|
|
218
|
+
with temp_path.open("w", encoding="utf-8") as f:
|
|
219
|
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
|
220
|
+
Path.replace(temp_path, target)
|
|
221
|
+
finally:
|
|
222
|
+
with contextlib.suppress(Exception):
|
|
223
|
+
self.lock.release()
|
|
224
|
+
except Timeout:
|
|
225
|
+
with contextlib.suppress(Exception):
|
|
226
|
+
with temp_path.open("w", encoding="utf-8") as f:
|
|
227
|
+
json.dump(data, f, indent=4, ensure_ascii=False)
|
|
228
|
+
Path.replace(temp_path, target)
|
|
229
|
+
finally:
|
|
230
|
+
if temp_path.exists():
|
|
231
|
+
with contextlib.suppress(Exception):
|
|
232
|
+
temp_path.unlink()
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def _load_json(path: Path | None) -> dict[str, JSONValue]:
|
|
236
|
+
"""Return dict form json file."""
|
|
237
|
+
if path is None or not path.exists():
|
|
238
|
+
return {}
|
|
239
|
+
with path.open("r", encoding="utf-8") as f:
|
|
240
|
+
return json.load(f)
|
coffeebot/db/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CoffeeBot database package.
|
|
3
|
+
|
|
4
|
+
################################################################################
|
|
5
|
+
Copyright (C) 2026 Mavinum
|
|
6
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
7
|
+
See LICENSE in the project root.
|
|
8
|
+
|
|
9
|
+
This program is free software: you can redistribute it and/or modify
|
|
10
|
+
it under the terms of the GNU General Public License as published by
|
|
11
|
+
the Free Software Foundation, version 3 only.
|
|
12
|
+
|
|
13
|
+
This program is distributed in the hope that it will be useful,
|
|
14
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
15
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
16
|
+
for more details.
|
|
17
|
+
################################################################################
|
|
18
|
+
"""
|
coffeebot/db/init_DB.sql
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BEGIN;
|
|
2
|
+
CREATE TABLE IF NOT EXISTS users(
|
|
3
|
+
id INTEGER PRIMARY KEY,
|
|
4
|
+
forename TEXT,
|
|
5
|
+
surename TEXT,
|
|
6
|
+
workgroup TEXT,
|
|
7
|
+
email TEXT,
|
|
8
|
+
telegram_id INT,
|
|
9
|
+
balance REAL
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
CREATE TABLE IF NOT EXISTS user_stats(
|
|
13
|
+
process_id INTEGER PRIMARY KEY,
|
|
14
|
+
timestamp TEXT NOT NULL,
|
|
15
|
+
category TEXT NOT NULL,
|
|
16
|
+
price REAL NOT NULL
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
CREATE TABLE IF NOT EXISTS bookkeeping(
|
|
20
|
+
transaction_id INTEGER PRIMARY KEY,
|
|
21
|
+
timestamp TEXT NOT NULL,
|
|
22
|
+
balance_old TEXT,
|
|
23
|
+
balance_new REAL NOT NULL,
|
|
24
|
+
deposit REAL NOT NULL,
|
|
25
|
+
user_id INTEGER NOT NULL,
|
|
26
|
+
FOREIGN KEY(user_id) REFERENCES users(id)
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
COMMIT;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
################################################################################
|
|
3
|
+
|
|
4
|
+
DB Migration module to handle schema updates.
|
|
5
|
+
|
|
6
|
+
################################################################################
|
|
7
|
+
Copyright (C) 2026 Mavinum
|
|
8
|
+
SPDX-License-Identifier: GPL-3.0-only
|
|
9
|
+
See LICENSE in the project root.
|
|
10
|
+
|
|
11
|
+
This program is free software: you can redistribute it and/or modify
|
|
12
|
+
it under the terms of the GNU General Public License as published by
|
|
13
|
+
the Free Software Foundation, version 3 only.
|
|
14
|
+
|
|
15
|
+
This program is distributed in the hope that it will be useful,
|
|
16
|
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
17
|
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE
|
|
18
|
+
for more details.
|
|
19
|
+
################################################################################
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import sqlite3
|
|
25
|
+
|
|
26
|
+
from loguru import logger
|
|
27
|
+
|
|
28
|
+
# Schema versions
|
|
29
|
+
# 0: Legacy (coffee_users table)
|
|
30
|
+
# 1: Initial structured release (users, user_stats, bookkeeping, meta)
|
|
31
|
+
CURRENT_VERSION = 1
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def migrate_legacy_to_v1(conn: sqlite3.Connection) -> None:
|
|
35
|
+
"""Migrates the old coffee_users structure to the new version."""
|
|
36
|
+
cursor = conn.cursor()
|
|
37
|
+
|
|
38
|
+
# Check for legacy table
|
|
39
|
+
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='coffee_users'")
|
|
40
|
+
if not cursor.fetchone():
|
|
41
|
+
return
|
|
42
|
+
|
|
43
|
+
logger.info("Legacy database detected. Migrating to V1...")
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
# Update table name
|
|
47
|
+
cursor.execute("ALTER TABLE coffee_users RENAME TO users")
|
|
48
|
+
|
|
49
|
+
# Update columns
|
|
50
|
+
cursor.execute("ALTER TABLE users RENAME COLUMN chair TO workgroup")
|
|
51
|
+
|
|
52
|
+
cursor.execute("ALTER TABLE users ADD COLUMN telegram_id INTEGER")
|
|
53
|
+
|
|
54
|
+
cursor.execute("UPDATE users SET telegram_id = CAST(telegram_username AS INTEGER)")
|
|
55
|
+
|
|
56
|
+
# Remove the old column
|
|
57
|
+
try:
|
|
58
|
+
cursor.execute("ALTER TABLE users DROP COLUMN telegram_username")
|
|
59
|
+
except sqlite3.OperationalError:
|
|
60
|
+
logger.warning("Could not drop column 'telegram_username'. Your SQLite version might be too old.")
|
|
61
|
+
|
|
62
|
+
# Create missing tables
|
|
63
|
+
cursor.execute("""
|
|
64
|
+
CREATE TABLE IF NOT EXISTS user_stats (
|
|
65
|
+
process_id INTEGER PRIMARY KEY,
|
|
66
|
+
timestamp TEXT NOT NULL,
|
|
67
|
+
category TEXT NOT NULL,
|
|
68
|
+
price REAL NOT NULL
|
|
69
|
+
)
|
|
70
|
+
""")
|
|
71
|
+
cursor.execute("""
|
|
72
|
+
CREATE TABLE IF NOT EXISTS bookkeeping (
|
|
73
|
+
transaction_id INTEGER PRIMARY KEY,
|
|
74
|
+
timestamp TEXT NOT NULL,
|
|
75
|
+
balance_old TEXT,
|
|
76
|
+
balance_new REAL NOT NULL,
|
|
77
|
+
deposit REAL NOT NULL,
|
|
78
|
+
user_id INTEGER NOT NULL,
|
|
79
|
+
FOREIGN KEY(user_id) REFERENCES users(id)
|
|
80
|
+
)
|
|
81
|
+
""")
|
|
82
|
+
|
|
83
|
+
conn.commit()
|
|
84
|
+
logger.info("Migration to V1 successful.")
|
|
85
|
+
except sqlite3.Error as e:
|
|
86
|
+
conn.rollback()
|
|
87
|
+
logger.error(f"Migration failed: {e}")
|
|
88
|
+
raise
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def init_meta_table(conn: sqlite3.Connection) -> None:
|
|
92
|
+
"""Initialize the version tracking table."""
|
|
93
|
+
cursor = conn.cursor()
|
|
94
|
+
cursor.execute("""
|
|
95
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
96
|
+
key TEXT PRIMARY KEY,
|
|
97
|
+
value TEXT
|
|
98
|
+
)
|
|
99
|
+
""")
|
|
100
|
+
conn.commit()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_schema_version(conn: sqlite3.Connection) -> int:
|
|
104
|
+
"""Retrieve the current schema version from the meta table."""
|
|
105
|
+
cursor = conn.cursor()
|
|
106
|
+
cursor.execute("SELECT value FROM meta WHERE key='schema_version'")
|
|
107
|
+
row = cursor.fetchone()
|
|
108
|
+
return int(row[0]) if row else 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def set_schema_version(conn: sqlite3.Connection, version: int) -> None:
|
|
112
|
+
"""Set the schema version in the meta table."""
|
|
113
|
+
cursor = conn.cursor()
|
|
114
|
+
cursor.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('schema_version', ?)", (str(version),))
|
|
115
|
+
conn.commit()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def apply_migrations(conn: sqlite3.Connection) -> None:
|
|
119
|
+
"""Entry point to apply all pending migrations."""
|
|
120
|
+
init_meta_table(conn)
|
|
121
|
+
|
|
122
|
+
schema_version = get_schema_version(conn)
|
|
123
|
+
logger.debug(f"Current DB schema version: {schema_version}")
|
|
124
|
+
|
|
125
|
+
if schema_version < CURRENT_VERSION:
|
|
126
|
+
# Version 0 (Legacy) -> 1
|
|
127
|
+
migrate_legacy_to_v1(conn)
|
|
128
|
+
set_schema_version(conn, CURRENT_VERSION)
|
|
129
|
+
|
|
130
|
+
logger.debug(f"DB schema is up to date (Version {CURRENT_VERSION})")
|