]> us-delaporte.pagekite.me Git - matrix-shop-bot.git/blob - matrix_shop_bot/db.py
a225f3c109731d4550e2e0482b8ce659ea9b1230
[matrix-shop-bot.git] / matrix_shop_bot / db.py
1 import logging
2 import os
3 from datetime import datetime as dt
4 from datetime import timedelta
5 from decimal import Decimal
6 from typing import List
7
8 from sqlmodel import Field, Session, SQLModel, create_engine, select, text, Relationship, func
9
10 from sqlite3 import IntegrityError
11
12 MODULE='shop'
13
14 DATE_FORMAT = '%Y-%m-%d'
15
16 def today():
17 return dt.now().strftime(DATE_FORMAT)
18
19
20 logger = logging.getLogger(__name__)
21
22 class ItemStoreLink(SQLModel, table=True):
23 item_id: int | None = Field(default=None, foreign_key="item.id", primary_key=True)
24 store_id: int | None = Field(default=None, foreign_key="store.id", primary_key=True)
25
26
27 class Item(SQLModel, table=True):
28 '''An item to shop for.'''
29 id: int | None = Field(default=None, primary_key=True)
30 name: str = Field(default=None, unique=True)
31 price: Decimal | None = Field(decimal_places=2)
32 stores: list["Store"] = Relationship(back_populates="shopping_list", link_model=ItemStoreLink)
33 purchase_date: dt | None = Field(default=None)
34 def __str__(self):
35 if(self.purchase_date):
36 return f'- [x] {self.name} (#{self.id})'
37 else:
38 return f'- [ ] {self.name} (#{self.id})'
39
40 class ItemZone(SQLModel, table=True):
41 '''Where an item is usually found.
42
43 Matched only by loose text matching, since items come and go, over time.
44 '''
45 id: int | None = Field(default=None, primary_key=True)
46 name: str = Field(default=None, unique=True) # milk
47 zone: str = Field(default=None, unique=False) # dairy section
48
49 class PreferStore(SQLModel, table=True):
50 '''Tracks which store we are shopping at, at the moment.'''
51 store_id: int | None = Field(default=None, foreign_key="store.id", primary_key=True)
52
53 def _get_item_zone(item_name, session) -> str:
54 zone = session.exec(select(ItemZone).where(func.lower(item_name).contains(func.lower(ItemZone.name)))).first()
55 if zone:
56 return zone.zone
57 return 'No Zone Assigned'
58
59 def _get_pretty_shopping_list(store_id, session) -> List[str]:
60 store = session.exec(_get_with_id(Store, store_id)).first()
61 results = []
62 results.append(f' ## {store.name}')
63 items = store.shopping_list
64 if not items:
65 results.append(f'-- Nothing to shop for at {store.name} --')
66
67 zones = {}
68
69 for item in items:
70 zone = str(_get_item_zone(item.name, session)).title() # Title Case
71 if not zone in zones:
72 zones[zone] = []
73 zones[zone].append(str(item))
74 for zone in zones:
75 results.append(f' ### {zone}')
76 for item in zones[zone]:
77 results.append(item)
78 return results
79
80 class Store(SQLModel, table=True):
81 '''A place to shop at.'''
82 id: int | None = Field(default=None, primary_key=True)
83 name: str = Field(default=None, unique=True)
84 shopping_list: list["Item"] = Relationship(back_populates="stores", link_model=ItemStoreLink)
85 # purchase_history: list["PurchaseRecord"] = Relationship(back_populates="store")
86 def __str__(self):
87 return f'{self.name} (#{self.id})'
88
89
90 class PurchaseRecord(SQLModel, table=True):
91 '''Tracks when and where items were purchased.'''
92 id: int | None = Field(default=None, primary_key=True)
93 name: str = Field(default=None)
94 price: Decimal | None = Field(decimal_places=2)
95 store: str | None = Field(default=None)
96 purchase_date: dt | None = Field(default=None)
97 def __str__(self):
98 date = self.purchase_date.strftime(DATE_FORMAT)
99 return f'Bought {self.name} at {self.store} on {date}'
100
101 def _get_with_id(cls, item_id):
102 return select(cls).where(cls.id == item_id)
103
104 def _get_with_name(cls, name):
105 return select(cls).where(func.lower(cls.name) == func.lower(name))
106
107
108 class Data():
109 def __init__(self, db_file=None):
110 if not db_file:
111 db_file = os.path.join(os.environ.get('MATRIX_DATA_DIR', ''), f'{MODULE}.db')
112
113 self.file = db_file
114 logger.debug(f'Shop bot is using db file {self.file}')
115 self.engine = self.get_engine()
116 self.last_store_id = None
117
118 def _set_pref_store_id(self, store_id):
119 with Session(self.engine) as session:
120 prefs = session.exec(select(PreferStore)).all()
121 for pref in prefs:
122 session.delete(pref)
123 pref = PreferStore()
124 pref.store_id = store_id
125 session.add(pref)
126 session.commit()
127
128 def _get_pref_store_id(self):
129 with Session(self.engine) as session:
130 pref = session.exec(select(PreferStore)).one()
131 return pref.store_id
132
133 def _add_with_name(self, cls, name):
134 item_id = -1
135 try:
136 with Session(self.engine) as session:
137 new = cls(name=name)
138 session.add(new)
139 session.commit()
140 item_id = new.id
141 except:
142 # duplicate add
143 # recover by returning the item_id
144 item = session.exec(select(Item).where(Item.name == name)).first()
145 item_id = item.id
146
147 return item_id
148
149 def add_store(self, name):
150 store_id = self._add_with_name(Store, name)
151 self._set_pref_store_id(store_id)
152 return store_id
153
154 def add_item(self, name):
155 names = name.split(',')
156 for name in names:
157 item_id = self._add_with_name(Item, name.strip())
158 store_id = self._get_pref_store_id()
159 self.assign_store(item_id, store_id)
160 return item_id
161
162 def assign_last_store(self, item_id):
163 store_id = self._get_pref_store_id()
164 self.assign_store(item_id, store_id)
165 return store_id
166
167 def assign_zone(self, item_name, zone_name):
168 item_id = -1
169 with Session(self.engine) as session:
170 try:
171 new = ItemZone(name=item_name)
172 new.zone = zone_name
173 session.add(new)
174 session.commit()
175 item_id = new.id
176 except:
177 pass # Already assigned
178 return item_id
179
180 def assign_store(self, item_id, store_id):
181 self._set_pref_store_id(store_id)
182
183 with Session(self.engine) as session:
184 store = session.exec(_get_with_id(Store, store_id)).first()
185 item = session.exec(_get_with_id(Item, item_id)).first()
186 try:
187 item.stores.append(store)
188 session.commit()
189 except:
190 pass # Already assigned
191 return ['Success']
192
193 def list_purchases(self, store_name):
194 '''List unique purchases at store in the past 90 days'''
195 with Session(self.engine) as session:
196 recent = dt.now() - timedelta(days=90)
197 cmd = select(PurchaseRecord).where(func.lower(PurchaseRecord.store) == func.lower(store_name)).where(PurchaseRecord.purchase_date > recent)
198 records = session.exec(cmd).all()
199 bought = set()
200 for item in records:
201 bought.add(item.name)
202 return list(bought)
203
204 def purchase_items(self, item_ids):
205 results = []
206 with Session(self.engine) as session:
207 # Mark items as purchased
208 for item_id in item_ids.split(' '):
209 item = session.exec(_get_with_id(Item, item_id)).first()
210 if item:
211 item.purchase_date = dt.today()
212
213 # Track purchase history (locally only!)
214 # to generate recommended shopping lists
215 record = PurchaseRecord()
216 record.name = item.name
217 record.price = item.price
218 record.purchase_date = item.purchase_date
219
220 shopping_at = self._get_pref_store_id() # We bought it here
221 cmd = select(Store).where(Store.id == shopping_at)
222 store = session.exec(cmd).one()
223 record.store = store.name
224 session.add(record)
225
226 results.append(str(record))
227 # results.append(str(item))
228
229 session.commit()
230 return results
231
232
233 def clear_list(self, store_name, clear_all=False):
234 results = []
235 with Session(self.engine) as session:
236 store = session.exec(_get_with_name(Store, store_name)).first()
237 if not store:
238 return [f'Store {store_name} not found.']
239
240 for item in store.shopping_list:
241 if clear_all or item.purchase_date:
242 session.delete(item)
243
244 session.commit()
245 results = _get_pretty_shopping_list(store.id, session)
246 return results
247
248 def get_stores(self):
249 with Session(self.engine) as session:
250 cmd = select(Store)
251 return session.exec(cmd).all()
252
253 def get_unsorted_list(self):
254
255 results = []
256 with Session(self.engine) as session:
257 cmd = select(Item).where(Item.stores == None)
258 items = session.exec(cmd).all()
259
260 if not items:
261 return [f'No unsorted items!']
262 return items
263
264 def get_last_shopping_list(self) -> List[str]:
265 store_id = self._get_pref_store_id()
266 with Session(self.engine) as session:
267 store = session.exec(_get_with_id(Store, store_id)).first()
268 if store:
269 return _get_pretty_shopping_list(store.id, session)
270 return [f'Last shopping list store not found.']
271
272 def get_shopping_list(self, store_name) -> List[str]:
273 retsults = []
274 with Session(self.engine) as session:
275 store = session.exec(_get_with_name(Store, store_name)).first()
276 if not store:
277 return [f'Store {store_name} not found.']
278 results = _get_pretty_shopping_list(store.id, session)
279 self._set_pref_store_id(store.id)
280 return results
281
282 def remove_item(self, item_id):
283 with Session(self.engine) as session:
284 item = session.exec(_get_with_id(Item, item_id)).first()
285 session.delete(item)
286 session.commit()
287
288 def remove_store(self, store_id):
289 with Session(self.engine) as session:
290 store = session.exec(_get_with_id(Store, store_id)).first()
291 session.delete(store)
292 session.commit()
293
294 def get_engine(self):
295 return create_engine(f"sqlite:///{self.file}")
296
297 def setup(self):
298 SQLModel.metadata.create_all(self.engine)
299 return 'Success'
300
301
302
303