62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
|
from grocy import RestService
|
||
|
from tabulate import tabulate
|
||
|
from os import path
|
||
|
|
||
|
class Stock(object):
|
||
|
GET_CURRENT_STOCK = '/stock/get-current-stock'
|
||
|
GET_PRODUCT_BY_ID = '/get-object/products/{0}'
|
||
|
def __init__(self, **entries):
|
||
|
self.__dict__.update(entries)
|
||
|
self._init_rest_service()
|
||
|
#self._set_default_table_formats()
|
||
|
#if not hasattr('tablefmt', self):
|
||
|
# self.tablefmt = None
|
||
|
#if not hasattr('colalign', self):
|
||
|
# self.colalign = None
|
||
|
|
||
|
|
||
|
def _set_default_table_formats(self):
|
||
|
if not hasattr('formats', self):
|
||
|
self.tablefmt = None
|
||
|
self.colalign = None
|
||
|
elif not hasattr('table', self.formats):
|
||
|
self.tableformat = None
|
||
|
elif not hasattr('col', self.formats):
|
||
|
self.colalign = None
|
||
|
|
||
|
|
||
|
def _init_rest_service(self):
|
||
|
if self.api.startswith == '/':
|
||
|
self.api = self.api[1:]
|
||
|
if self.api.endswith == '/':
|
||
|
self.api = self.api[1:-1]
|
||
|
self.rest_service = RestService(self.api, json=True)
|
||
|
self.rest_service.addHeader('Content-Type', 'application/json')
|
||
|
self.rest_service.addToken(self.token)
|
||
|
|
||
|
|
||
|
def get_entries(self):
|
||
|
try:
|
||
|
get_current_stock = self.rest_service.get(Stock.GET_CURRENT_STOCK)
|
||
|
|
||
|
# Get product names from ids and replace
|
||
|
product_ids = [entry['product_id'] for entry in get_current_stock]
|
||
|
table_entries = []
|
||
|
try:
|
||
|
for index in range(len(product_ids)):
|
||
|
product_id = product_ids[index]
|
||
|
path = Stock.GET_PRODUCT_BY_ID.format(product_id)
|
||
|
product = self.rest_service.get(path)
|
||
|
get_current_stock[index]['product_id'] = product['name']
|
||
|
table_entry = list(dict.values(get_current_stock[index]))
|
||
|
table_entries.append(table_entry)
|
||
|
|
||
|
except Exception as e:
|
||
|
raise e
|
||
|
|
||
|
# Generate stock overview table
|
||
|
table_headers = ['Product', 'Amount', 'Best Before Date', 'Amount Opened']
|
||
|
return tabulate(table_entries, headers=table_headers)
|
||
|
except Exception as e:
|
||
|
raise e
|