grocy-cli/grocy/models/shopping.py

73 lines
2.8 KiB
Python

from grocy import RestService
import json
from tabulate import tabulate
from os import path
class Shopping(object):
GET_SHOPPING_LIST = '/get-objects/shopping_list'
GET_PRODUCT_BY_ID = '/get-object/products/{0}'
GET_QUANTITY_UNIIT_BY_ID = '/get-object/quantity_units/{0}'
GET_PRODUCT_GROUP_ID_BY_ID ='/get-object/product_groups/{0}'
def __init__(self, **entries):
self.__dict__.update(entries)
self._init_rest_service()
# 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_list(self):
try:
get_shopping_list = self.rest_service.get(Shopping.GET_SHOPPING_LIST)
table_headers = ['Group', 'Product', 'Amount']
# Get product names and location from ids and replace
product_ids = [entry['product_id'] for entry in get_shopping_list]
products = []
location_ids = []
table_entries = []
for index in range(len(product_ids)):
product_id = product_ids[index]
path = Shopping.GET_PRODUCT_BY_ID.format(product_id)
product = self.rest_service.get(path)
path = Shopping.GET_QUANTITY_UNIIT_BY_ID.format(product['qu_id_purchase'])
quantity_unit = self.rest_service.get(path)
min_amount = '{} {}'.format(product['min_stock_amount'], quantity_unit['name'])
if product['product_group_id'] == '':
product_group_name = 'Uncategorized'
else:
path = Shopping.GET_PRODUCT_GROUP_ID_BY_ID.format(product['product_group_id'])
product_group = self.rest_service.get(path)
product_group_name = product_group['name']
current_shopping_item = [product_group_name, product['name'], min_amount]
table_entries.append(current_shopping_item)
except Exception as e:
raise e
# Generate stock overview table
return tabulate(table_entries, headers=table_headers)