]>
apps.delaporte.us Git - matrix-shop-bot.git/blob - matrix_shop_bot/db.py
3 from datetime
import datetime
as dt
4 from decimal
import Decimal
5 from typing
import List
7 from sqlmodel
import Field
, Session
, SQLModel
, create_engine
, select
, text
, Relationship
11 DATE_FORMAT
= '%Y-%m-%d'
14 return dt
.now().strftime(DATE_FORMAT
)
17 logger
= logging
.getLogger(__name__
)
18 logging
.basicConfig(filename
=f
'{MODULE}.log', encoding
='utf-8', level
=logging
.DEBUG
)
20 class ItemStoreLink(SQLModel
, table
=True):
21 item_id
: int |
None = Field(default
=None, foreign_key
="item.id", primary_key
=True)
22 store_id
: int |
None = Field(default
=None, foreign_key
="store.id", primary_key
=True)
25 class Item(SQLModel
, table
=True):
26 id: int |
None = Field(default
=None, primary_key
=True)
27 name
: str = Field(default
=None, unique
=True)
28 price
: Decimal |
None = Field(decimal_places
=2)
29 stores
: list["Store"] = Relationship(back_populates
="shopping_list", link_model
=ItemStoreLink
)
30 purchase_date
: dt |
None = Field(default
=None)
32 return f
'{self.name} (#{self.id})'
34 class PreferStore(SQLModel
, table
=True):
35 store_id
: int |
None = Field(default
=None, foreign_key
="store.id", primary_key
=True)
37 class Store(SQLModel
, table
=True):
38 id: int |
None = Field(default
=None, primary_key
=True)
39 name
: str = Field(default
=None, unique
=True)
40 shopping_list
: list["Item"] = Relationship(back_populates
="stores", link_model
=ItemStoreLink
)
41 # purchase_history: list["PurchaseRecord"] = Relationship(back_populates="store")
43 return f
'{self.name} (#{self.id})'
49 # May get used later...
50 #class PurchaseRecord(SQLModel, table=True):
51 # id: int | None = Field(default=None, primary_key=True)
52 # name: str = Field(default=None, unique=True)
53 # price: Decimal | None = Field(decimal_places=2)
54 # store: Store = Relationship(back_populates="purchase_history")
55 # purchase_date: dt | None = Field(default=None)
57 def _get_with_id(cls
, item_id
):
58 return select(cls
).where(cls
.id == item_id
)
62 def __init__(self
, db_file
=None):
64 db_file
= os
.path
.join(os
.environ
.get('MATRIX_DATA_DIR', ''), f
'{MODULE}.db')
67 self
.engine
= self
.get_engine()
68 self
.last_store_id
= None
70 def _set_pref_store_id(self
, store_id
):
71 with Session(self
.engine
) as session
:
72 prefs
= session
.exec(select(PreferStore
)).all()
76 pref
.store_id
= store_id
80 def _get_pref_store_id(self
):
81 with Session(self
.engine
) as session
:
82 pref
= session
.exec(select(PreferStore
)).one()
85 def _add_with_name(self
, cls
, name
):
87 with Session(self
.engine
) as session
:
94 def add_store(self
, name
):
95 store_id
= self
._add
_with
_name
(Store
, name
)
96 self
._set
_pref
_store
_id
(store_id
)
99 def add_item(self
, name
):
100 item_id
= self
._add
_with
_name
(Item
, name
)
101 store_id
= self
._get
_pref
_store
_id
()
102 self
.assign_store(item_id
, store_id
)
105 def assign_last_store(self
, item_id
):
106 store_id
= self
._get
_pref
_store
_id
()
107 self
.assign_store(item_id
, store_id
)
110 def assign_store(self
, item_id
, store_id
):
111 self
._set
_pref
_store
_id
(store_id
)
113 with Session(self
.engine
) as session
:
114 store
= session
.exec(_get_with_id(Store
, store_id
)).first()
115 item
= session
.exec(_get_with_id(Item
, item_id
)).first()
116 item
.stores
.append(store
)
120 def purchase_item(self
, item_id
):
121 with Session(self
.engine
) as session
:
122 item
= session
.exec(_get_with_id(Item
, item_id
)).first()
123 item
.purchase_date
= dt
.today()
127 def clear_list(self
, store_id
, clear_all
=False):
128 with Session(self
.engine
) as session
:
129 store
= session
.exec(_get_with_id(Store
, store_id
)).first()
130 for item
in store
.shopping_list
:
131 if clear_all
or item
.purchase_date
:
135 def get_stores(self
):
136 with Session(self
.engine
) as session
:
138 return session
.exec(cmd
).all()
140 def get_unsorted_list(self
):
143 with Session(self
.engine
) as session
:
144 cmd
= select(Item
).where(Item
.stores
== None)
145 items
= session
.exec(cmd
).all()
148 return [f
'No unsorted items!']
152 def get_shopping_list_for_store(self
, store_id
) -> List
[str]:
153 self
._set
_pref
_store
_id
(store_id
)
154 return self
.get_shopping_list(store_id
)
156 def get_last_shopping_list(self
) -> List
[str]:
157 store_id
= self
._get
_pref
_store
_id
()
158 return self
.get_shopping_list(store_id
)
160 def get_shopping_list(self
, store_id
) -> List
[str]:
162 with Session(self
.engine
) as session
:
163 cmd
= select(Store
).where(Store
.id == store_id
)
164 store
= session
.exec(cmd
).first()
166 return [f
'Store {store_id} not found.']
168 results
.append(f
' ## {store.name}')
170 items
= store
.shopping_list
172 results
.append(f
'-- Nothing to shop for at {store.name} --')
175 if(item
.purchase_date
):
176 results
.append(f
' - [x] {item}')
178 results
.append(f
' - [ ] {item}')
181 def remove_item(self
, item_id
):
182 with Session(self
.engine
) as session
:
183 item
= session
.exec(_get_with_id(Item
, item_id
)).first()
187 def remove_store(self
, store_id
):
188 with Session(self
.engine
) as session
:
189 store
= session
.exec(_get_with_id(Store
, store_id
)).first()
190 session
.delete(store
)
193 def get_engine(self
):
194 return create_engine(f
"sqlite:///{self.file}")
197 SQLModel
.metadata
.create_all(self
.engine
)