-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
94 lines (81 loc) · 2.73 KB
/
db.py
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
import sqlite3
STOCK_FIELDS = [
"Date",
"Coût",
"Type",
"Marque",
"Taille",
"Couleur",
"Note",
]
VENTES_FIELDS = [
"DateAchat",
"DateVente",
"PrixAchat",
"PrixVente",
]
class InventoryData:
def __init__(self):
self.conn = sqlite3.connect("data/inventory.db")
self.cursor = self.conn.cursor()
self.initialize_database()
def initialize_database(self):
self.cursor.execute(
f"CREATE TABLE IF NOT EXISTS stock (ID INTEGER PRIMARY KEY, {', '.join(map(lambda label: f'{label} TEXT', STOCK_FIELDS))})"
)
self.cursor.execute(
f"CREATE TABLE IF NOT EXISTS ventes (ID INTEGER PRIMARY KEY, {', '.join(map(lambda label: f'{label} TEXT', VENTES_FIELDS))})"
)
self.conn.commit()
def list_stock(self):
self.cursor.execute("SELECT * FROM stock")
return [
{
"ID": row[0],
**{label: row[i] for i, label in enumerate(STOCK_FIELDS, start=1)},
}
for row in self.cursor.fetchall()
]
def list_ventes(self):
self.cursor.execute("SELECT * FROM ventes")
return [
{
"ID": row[0],
**{label: row[i] for i, label in enumerate(VENTES_FIELDS, start=1)},
}
for row in self.cursor.fetchall()
]
def get_from_stock(self, item_id):
self.cursor.execute("SELECT * FROM stock WHERE ID = ?", (item_id,))
row = self.cursor.fetchone()
return {
"ID": row[0],
**{label: row[i] for i, label in enumerate(STOCK_FIELDS, start=1)},
}
def get_from_ventes(self, item_id):
self.cursor.execute("SELECT * FROM ventes WHERE ID = ?", (item_id,))
row = self.cursor.fetchone()
return {
"ID": row[0],
**{label: row[i] for i, label in enumerate(VENTES_FIELDS, start=1)},
}
def add_item_to_stock(self, item):
self.cursor.execute(
f"INSERT INTO stock ({', '.join(STOCK_FIELDS)}) VALUES ({', '.join('?' for _ in STOCK_FIELDS)})",
tuple(item[label] for label in STOCK_FIELDS),
)
self.conn.commit()
def delete_item_from_stock(self, item_id):
self.cursor.execute("DELETE FROM stock WHERE ID = ?", (item_id,))
self.conn.commit()
def edit_item_from_stock(self, item_id, new_item):
self.cursor.execute(
f"UPDATE stock SET {', '.join(map(lambda label: f'{label} = ?', STOCK_FIELDS))} WHERE ID = ?",
(
*tuple(new_item[label] for label in STOCK_FIELDS),
item_id,
),
)
self.conn.commit()
def __del__(self):
self.conn.close()