sqlite-sh 0.1.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.
sqlite_sh/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
sqlite_sh/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .gui import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
Binary file
sqlite_sh/assets/1.jpg ADDED
Binary file
Binary file
sqlite_sh/assets/2.jpg ADDED
Binary file
sqlite_sh/assets/3.jpg ADDED
Binary file
sqlite_sh/assets/4.jpg ADDED
Binary file
sqlite_sh/assets/5.jpg ADDED
Binary file
sqlite_sh/assets/6.jpg ADDED
Binary file
sqlite_sh/assets/7.jpg ADDED
Binary file
sqlite_sh/assets/8.jpg ADDED
Binary file
sqlite_sh/assets/9.jpg ADDED
Binary file
Binary file
Binary file
Binary file
File without changes
Binary file
sqlite_sh/bootstrap.py ADDED
@@ -0,0 +1,249 @@
1
+ import re
2
+ import shutil
3
+ import sqlite3
4
+ import zipfile
5
+ from datetime import datetime, timedelta
6
+ from pathlib import Path
7
+ from xml.etree import ElementTree as ET
8
+
9
+ from sqlite_sh.config import ASSETS_DIR, DATA_DIR, DB_FILE, PACKAGE_DIR, SCHEMA_FILE
10
+
11
+
12
+ IMPORT_RELATIVE_DIR = (
13
+ Path("Прил_ОЗ_КОД 09.02.07-2-2026")
14
+ / "БУ"
15
+ / "Модуль 1"
16
+ / "Прил_2_ОЗ_КОД 09.02.07-2-2026-М1"
17
+ / "import"
18
+ )
19
+
20
+
21
+ def find_source_dir():
22
+ candidates = [
23
+ PACKAGE_DIR.parent.parent / IMPORT_RELATIVE_DIR,
24
+ Path("/home/adwed/demo-ex") / IMPORT_RELATIVE_DIR,
25
+ Path.cwd().parent / IMPORT_RELATIVE_DIR,
26
+ ]
27
+ for candidate in candidates:
28
+ if candidate.exists():
29
+ return candidate
30
+ return candidates[0]
31
+
32
+
33
+ SOURCE_DIR = find_source_dir()
34
+
35
+ NS = {"a": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
36
+
37
+
38
+ def column_index(cell_ref):
39
+ match = re.match(r"([A-Z]+)", cell_ref or "")
40
+ if not match:
41
+ return 0
42
+ value = 0
43
+ for char in match.group(1):
44
+ value = value * 26 + ord(char) - 64
45
+ return value - 1
46
+
47
+
48
+ def read_shared_strings(archive):
49
+ if "xl/sharedStrings.xml" not in archive.namelist():
50
+ return []
51
+ root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
52
+ values = []
53
+ for item in root.findall("a:si", NS):
54
+ values.append("".join(node.text or "" for node in item.findall(".//a:t", NS)))
55
+ return values
56
+
57
+
58
+ def read_cell(cell, shared_strings):
59
+ cell_type = cell.get("t")
60
+ if cell_type == "inlineStr":
61
+ return "".join(node.text or "" for node in cell.findall(".//a:t", NS))
62
+ value = cell.find("a:v", NS)
63
+ if value is None:
64
+ return None
65
+ raw = value.text
66
+ if cell_type == "s":
67
+ return shared_strings[int(raw)]
68
+ return raw
69
+
70
+
71
+ def read_xlsx_rows(path):
72
+ with zipfile.ZipFile(path) as archive:
73
+ shared_strings = read_shared_strings(archive)
74
+ sheet_name = "xl/worksheets/sheet1.xml"
75
+ root = ET.fromstring(archive.read(sheet_name))
76
+ rows = []
77
+ for row in root.findall(".//a:sheetData/a:row", NS):
78
+ values = []
79
+ last_index = -1
80
+ for cell in row.findall("a:c", NS):
81
+ idx = column_index(cell.get("r", ""))
82
+ while last_index + 1 < idx:
83
+ values.append(None)
84
+ last_index += 1
85
+ values.append(read_cell(cell, shared_strings))
86
+ last_index = idx
87
+ rows.append(values)
88
+ return rows
89
+
90
+
91
+ def clean(value):
92
+ if value is None:
93
+ return ""
94
+ return str(value).replace("\xa0", " ").strip()
95
+
96
+
97
+ def excel_date(value):
98
+ text = clean(value)
99
+ if not text:
100
+ return None
101
+ if re.fullmatch(r"\d+(\.0)?", text):
102
+ serial = int(float(text))
103
+ return (datetime(1899, 12, 30) + timedelta(days=serial)).date().isoformat()
104
+ try:
105
+ return datetime.strptime(text, "%d.%m.%Y").date().isoformat()
106
+ except ValueError:
107
+ print(f"Warning: invalid date value '{text}', saved as NULL")
108
+ return None
109
+
110
+
111
+ def scalar(conn, sql, params=()):
112
+ row = conn.execute(sql, params).fetchone()
113
+ return row[0] if row else None
114
+
115
+
116
+ def get_or_create(conn, table, name):
117
+ name = clean(name)
118
+ conn.execute(f"INSERT OR IGNORE INTO {table}(name) VALUES (?)", (name,))
119
+ return scalar(conn, f"SELECT id FROM {table} WHERE name = ?", (name,))
120
+
121
+
122
+ def copy_assets():
123
+ ASSETS_DIR.mkdir(exist_ok=True)
124
+ for source in SOURCE_DIR.iterdir():
125
+ if source.suffix.lower() in {".png", ".ico", ".jpg", ".jpeg"}:
126
+ shutil.copy2(source, ASSETS_DIR / source.name)
127
+
128
+
129
+ def import_users(conn):
130
+ rows = read_xlsx_rows(SOURCE_DIR / "user_import.xlsx")
131
+ for row in rows[1:]:
132
+ if len(row) < 4 or not clean(row[0]):
133
+ continue
134
+ role_id = get_or_create(conn, "roles", row[0])
135
+ conn.execute(
136
+ "INSERT OR IGNORE INTO users(role_id, full_name, login, password) VALUES (?, ?, ?, ?)",
137
+ (role_id, clean(row[1]), clean(row[2]), clean(row[3])),
138
+ )
139
+
140
+
141
+ def import_products(conn):
142
+ rows = read_xlsx_rows(SOURCE_DIR / "Tovar.xlsx")
143
+ for row in rows[1:]:
144
+ if len(row) < 10 or not clean(row[0]):
145
+ continue
146
+ unit_id = get_or_create(conn, "units", row[2])
147
+ supplier_id = get_or_create(conn, "suppliers", row[4])
148
+ manufacturer_id = get_or_create(conn, "manufacturers", row[5])
149
+ category_id = get_or_create(conn, "categories", row[6])
150
+ conn.execute(
151
+ """
152
+ INSERT OR REPLACE INTO products(
153
+ article, name, unit_id, price, supplier_id, manufacturer_id,
154
+ category_id, discount, stock, description, image_path
155
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
156
+ """,
157
+ (
158
+ clean(row[0]),
159
+ clean(row[1]),
160
+ unit_id,
161
+ float(clean(row[3]) or 0),
162
+ supplier_id,
163
+ manufacturer_id,
164
+ category_id,
165
+ int(float(clean(row[7]) or 0)),
166
+ int(float(clean(row[8]) or 0)),
167
+ clean(row[9]),
168
+ clean(row[10]) if len(row) > 10 and clean(row[10]) else None,
169
+ ),
170
+ )
171
+
172
+
173
+ def import_pickup_points(conn):
174
+ rows = read_xlsx_rows(SOURCE_DIR / "Пункты выдачи_import.xlsx")
175
+ for row in rows:
176
+ if row and clean(row[0]):
177
+ conn.execute("INSERT OR IGNORE INTO pickup_points(address) VALUES (?)", (clean(row[0]),))
178
+
179
+
180
+ def parse_order_items(raw):
181
+ parts = [clean(part) for part in clean(raw).split(",") if clean(part)]
182
+ result = []
183
+ for index in range(0, len(parts), 2):
184
+ if index + 1 >= len(parts):
185
+ break
186
+ result.append((parts[index], int(float(parts[index + 1]))))
187
+ return result
188
+
189
+
190
+ def import_orders(conn):
191
+ rows = read_xlsx_rows(SOURCE_DIR / "Заказ_import.xlsx")
192
+ for row in rows[1:]:
193
+ if len(row) < 8 or not clean(row[0]):
194
+ continue
195
+ order_id = int(float(clean(row[0])))
196
+ pickup_point_id = int(float(clean(row[4]))) if clean(row[4]) else None
197
+ conn.execute(
198
+ """
199
+ INSERT OR REPLACE INTO orders(
200
+ id, order_date, delivery_date, pickup_point_id, client_name, receive_code, status
201
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
202
+ """,
203
+ (
204
+ order_id,
205
+ excel_date(row[2]),
206
+ excel_date(row[3]),
207
+ pickup_point_id,
208
+ clean(row[5]),
209
+ clean(row[6]),
210
+ clean(row[7]),
211
+ ),
212
+ )
213
+ conn.execute("DELETE FROM order_items WHERE order_id = ?", (order_id,))
214
+ for article, quantity in parse_order_items(row[1]):
215
+ product_id = scalar(conn, "SELECT id FROM products WHERE article = ?", (article,))
216
+ if product_id is None:
217
+ print(f"Warning: product article '{article}' not found for order {order_id}")
218
+ continue
219
+ conn.execute(
220
+ "INSERT INTO order_items(order_id, product_id, quantity) VALUES (?, ?, ?)",
221
+ (order_id, product_id, quantity),
222
+ )
223
+
224
+
225
+ def reset_database():
226
+ DATA_DIR.mkdir(exist_ok=True)
227
+ if DB_FILE.exists():
228
+ DB_FILE.unlink()
229
+ with sqlite3.connect(DB_FILE) as conn:
230
+ conn.execute("PRAGMA foreign_keys = ON")
231
+ conn.executescript(SCHEMA_FILE.read_text(encoding="utf-8"))
232
+ import_users(conn)
233
+ import_products(conn)
234
+ import_pickup_points(conn)
235
+ import_orders(conn)
236
+ conn.commit()
237
+
238
+
239
+ def main():
240
+ if not SOURCE_DIR.exists():
241
+ raise SystemExit(f"Source directory not found: {SOURCE_DIR}")
242
+ copy_assets()
243
+ reset_database()
244
+ print(f"Database created: {DB_FILE}")
245
+ print(f"Assets copied: {ASSETS_DIR}")
246
+
247
+
248
+ if __name__ == "__main__":
249
+ main()
sqlite_sh/config.py ADDED
@@ -0,0 +1,23 @@
1
+ import os
2
+ import shutil
3
+ from pathlib import Path
4
+
5
+
6
+ PACKAGE_DIR = Path(__file__).resolve().parent
7
+ ASSETS_DIR = PACKAGE_DIR / "assets"
8
+ DATA_DIR = PACKAGE_DIR / "data"
9
+ SCHEMA_FILE = PACKAGE_DIR / "database.sql"
10
+ SEED_DB_FILE = DATA_DIR / "shop.db"
11
+
12
+ USER_DIR = Path(os.environ.get("SQLITE_SH_HOME", Path.home() / ".sqlite_sh"))
13
+ DB_FILE = USER_DIR / "shop.db"
14
+
15
+
16
+ def ensure_user_database():
17
+ USER_DIR.mkdir(parents=True, exist_ok=True)
18
+ if not DB_FILE.exists() and SEED_DB_FILE.exists():
19
+ shutil.copy2(SEED_DB_FILE, DB_FILE)
20
+ return DB_FILE
21
+
22
+
23
+ ensure_user_database()
File without changes
sqlite_sh/data/shop.db ADDED
Binary file
sqlite_sh/database.sql ADDED
@@ -0,0 +1,87 @@
1
+ PRAGMA foreign_keys = ON;
2
+
3
+ DROP TABLE IF EXISTS order_items;
4
+ DROP TABLE IF EXISTS orders;
5
+ DROP TABLE IF EXISTS products;
6
+ DROP TABLE IF EXISTS pickup_points;
7
+ DROP TABLE IF EXISTS users;
8
+ DROP TABLE IF EXISTS roles;
9
+ DROP TABLE IF EXISTS categories;
10
+ DROP TABLE IF EXISTS manufacturers;
11
+ DROP TABLE IF EXISTS suppliers;
12
+ DROP TABLE IF EXISTS units;
13
+
14
+ CREATE TABLE roles (
15
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
16
+ name TEXT NOT NULL UNIQUE
17
+ );
18
+
19
+ CREATE TABLE users (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ role_id INTEGER NOT NULL REFERENCES roles(id),
22
+ full_name TEXT NOT NULL,
23
+ login TEXT NOT NULL UNIQUE,
24
+ password TEXT NOT NULL
25
+ );
26
+
27
+ CREATE TABLE categories (
28
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
29
+ name TEXT NOT NULL UNIQUE
30
+ );
31
+
32
+ CREATE TABLE manufacturers (
33
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
34
+ name TEXT NOT NULL UNIQUE
35
+ );
36
+
37
+ CREATE TABLE suppliers (
38
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
39
+ name TEXT NOT NULL UNIQUE
40
+ );
41
+
42
+ CREATE TABLE units (
43
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ name TEXT NOT NULL UNIQUE
45
+ );
46
+
47
+ CREATE TABLE products (
48
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
49
+ article TEXT NOT NULL UNIQUE,
50
+ name TEXT NOT NULL,
51
+ unit_id INTEGER NOT NULL REFERENCES units(id),
52
+ price REAL NOT NULL CHECK (price >= 0),
53
+ supplier_id INTEGER NOT NULL REFERENCES suppliers(id),
54
+ manufacturer_id INTEGER NOT NULL REFERENCES manufacturers(id),
55
+ category_id INTEGER NOT NULL REFERENCES categories(id),
56
+ discount INTEGER NOT NULL DEFAULT 0 CHECK (discount >= 0),
57
+ stock INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
58
+ description TEXT NOT NULL DEFAULT '',
59
+ image_path TEXT
60
+ );
61
+
62
+ CREATE TABLE pickup_points (
63
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
64
+ address TEXT NOT NULL UNIQUE
65
+ );
66
+
67
+ CREATE TABLE orders (
68
+ id INTEGER PRIMARY KEY,
69
+ order_date TEXT,
70
+ delivery_date TEXT,
71
+ pickup_point_id INTEGER REFERENCES pickup_points(id),
72
+ client_name TEXT,
73
+ receive_code TEXT,
74
+ status TEXT NOT NULL
75
+ );
76
+
77
+ CREATE TABLE order_items (
78
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
79
+ order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
80
+ product_id INTEGER NOT NULL REFERENCES products(id),
81
+ quantity INTEGER NOT NULL CHECK (quantity > 0),
82
+ UNIQUE(order_id, product_id)
83
+ );
84
+
85
+ CREATE INDEX idx_products_article ON products(article);
86
+ CREATE INDEX idx_products_supplier ON products(supplier_id);
87
+ CREATE INDEX idx_order_items_product ON order_items(product_id);
Binary file
sqlite_sh/diagram.py ADDED
@@ -0,0 +1,37 @@
1
+ import sqlite3
2
+
3
+ from sqlite_sh.config import DB_FILE
4
+
5
+
6
+ def main():
7
+ if not DB_FILE.exists():
8
+ raise SystemExit("База данных не найдена. Сначала выполните: python bootstrap_db.py")
9
+
10
+ with sqlite3.connect(DB_FILE) as conn:
11
+ tables = [
12
+ row[0]
13
+ for row in conn.execute(
14
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
15
+ )
16
+ ]
17
+
18
+ print("erDiagram")
19
+ for table in tables:
20
+ print(f" {table} {{")
21
+ for col in conn.execute(f"PRAGMA table_info({table})"):
22
+ col_name = col[1]
23
+ col_type = col[2] or "TEXT"
24
+ pk = " PK" if col[5] else ""
25
+ print(f" {col_type} {col_name}{pk}")
26
+ print(" }")
27
+
28
+ for table in tables:
29
+ for fk in conn.execute(f"PRAGMA foreign_key_list({table})"):
30
+ ref_table = fk[2]
31
+ from_col = fk[3]
32
+ to_col = fk[4]
33
+ print(f" {ref_table} ||--o{{ {table} : \"{to_col} to {from_col}\"")
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()