Skip to content

Commit

Permalink
Merge pull request #4 from vorostamas/process-favorites-only
Browse files Browse the repository at this point in the history
Process only favorite receipts
  • Loading branch information
vorostamas authored Nov 2, 2023
2 parents a46eb04 + 4b92e7e commit fb272d2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 42 deletions.
81 changes: 39 additions & 42 deletions lidgrosyncer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
LIDL_LANGUAGE = settings["LIDL_LANGUAGE"]
LIDL_COUNTRY = settings["LIDL_COUNTRY"]
LIDL_REFRESH_TOKEN = settings["LIDL_REFRESH_TOKEN"]
PROCESS_ONLY_FAVORITES = settings["PROCESS_ONLY_FAVORITES"]

GROCY_URL = settings["GROCY_URL"]
GROCY_PORT = settings["GROCY_PORT"]
Expand All @@ -25,7 +26,9 @@
default_consume_location_id = settings["GROCY_LOCATION_ID"]
grocy_shopping_location_id = settings["GROCY_SHOPPING_LOCATION_ID"]
default_best_before_days = settings["GROCY_DEFAULT_BEST_BEFORE_DAYS"]
default_best_before_days_after_thawing = settings["GROCY_DEFAULT_BEST_BEFORE_DAYS_AFTER_THAWING"]
default_best_before_days_after_thawing = settings[
"GROCY_DEFAULT_BEST_BEFORE_DAYS_AFTER_THAWING"
]
product_group_id = settings["GROCY_PRODUCT_GROUP_ID"]
qu_id_stock = settings["GROCY_QU_ID_STOCK"]
qu_id_purchase = settings["GROCY_QU_ID_PURCHASE"]
Expand Down Expand Up @@ -57,7 +60,7 @@ def save_receipt(receipt):
receipts_folder = "receipts"
if not os.path.exists(receipts_folder):
os.makedirs(receipts_folder)
with open(f"{receipts_folder}/{receipt['id']}.json", 'w', encoding="utf8") as f:
with open(f"{receipts_folder}/{receipt['id']}.json", "w", encoding="utf8") as f:
json.dump(receipt, f, ensure_ascii=False)


Expand All @@ -68,15 +71,15 @@ def create_best_before_date(purchase_date):

def purchase_product(product_id, amount, price, date, name=None):
best_before_date = create_best_before_date(date)
amount = float(amount.replace(',', '.'))
price = float(price.replace(',', '.'))
amount = float(amount.replace(",", "."))
price = float(price.replace(",", "."))
_LOGGER.info(
f"Purchasing product: product_id: {product_id}, name:{name} amount:{amount}, price:{price}, best_before_date: {best_before_date}")
f"Purchasing product: product_id: {product_id}, name:{name} amount:{amount}, price:{price}, best_before_date: {best_before_date}"
)
try:
grocy.add_product(product_id, amount, price, best_before_date)
except GrocyError as error:
_LOGGER.error(
"Error during product purchase, message: %s", error.message)
_LOGGER.error("Error during product purchase, message: %s", error.message)
raise Exception("Purchase error: ", error)


Expand Down Expand Up @@ -111,17 +114,20 @@ def create_new_product(name):
"not_check_stock_fulfillment_for_recipes": "0",
"hide_on_stock_overview": "0",
"no_own_stock": "0",
"parent_product_id": ""
"parent_product_id": "",
}

# Prevent creating a product with an existing product name
get_product_by_name = grocy.get_generic_objects_for_type(
EntityType.PRODUCTS, [f"name={name}"])
EntityType.PRODUCTS, [f"name={name}"]
)
if not get_product_by_name:
_LOGGER.info(name + " is not in product names, creating new product")
return grocy.add_generic(entity_type=EntityType.PRODUCTS, data=payload)['created_object_id']
response = grocy.add_generic(entity_type=EntityType.PRODUCTS, data=payload)
if response is not None:
return response["created_object_id"]
else:
return get_product_by_name[0]['id']
return get_product_by_name[0]["id"]


def add_barcode(product_id, barcode):
Expand All @@ -131,23 +137,25 @@ def add_barcode(product_id, barcode):
"amount": "1",
"shopping_location_id": grocy_shopping_location_id,
"note": "Automatically added by LidGroSyncer",
"qu_id": "1"
"qu_id": "1",
}
try:
return grocy.add_generic(entity_type=EntityType.PRODUCT_BARCODES, data=payload)["created_object_id"]
response = grocy.add_generic(
entity_type=EntityType.PRODUCT_BARCODES, data=payload
)
if response is not None:
return response["created_object_id"]
except GrocyError as error:
_LOGGER.error(
"Error during barcode creation, message: %s", error.message)
_LOGGER.error("Error during barcode creation, message: %s", error.message)
raise Exception("Barcode creation exception: ", error)


def purchase_products(receipt):
_LOGGER.info(f"Processing ticket with id {receipt['id']}")
for item in receipt['itemsLine']:
name = item['name']
_LOGGER.debug(
f"Product name: {name}, amount: {item['quantity']}")
barcode = item['codeInput']
for item in receipt["itemsLine"]:
name = item["name"]
_LOGGER.debug(f"Product name: {name}, amount: {item['quantity']}")
barcode = item["codeInput"]
product = get_product_by_barcode(barcode)

if product is None:
Expand All @@ -156,9 +164,9 @@ def purchase_products(receipt):
else:
product_id = product.id

amount = item['quantity']
price = item['currentUnitPrice']
date = receipt['date']
amount = item["quantity"]
price = item["currentUnitPrice"]
date = receipt["date"]
purchase_product(product_id, amount, price, date, name)


Expand All @@ -169,29 +177,18 @@ def purchase_products(receipt):
grocy = Grocy(base_url=GROCY_URL, api_key=GROCY_API_KEY, port=GROCY_PORT)


def get_generic_object_ids(entity_type: EntityType, filename: str):
objects = grocy.get_generic_objects_for_type(entity_type)
with open(filename, "w") as file:
for object in objects:
file.write(f"Name: {object['name']}, ID: {object['id']} \n")


def process_receipts():
processed_ids = load_processed_ids()
for ticket in lidl.tickets():
receipt_id = ticket['id']
for ticket in lidl.tickets(PROCESS_ONLY_FAVORITES):
receipt_id = ticket["id"]
if receipt_id not in processed_ids:
if(ticket['isFavorite']):
receipt = lidl.ticket(receipt_id)
save_receipt(receipt)
purchase_products(receipt)
mark_receipt_processed(receipt_id)
else:
_LOGGER.info(
f"Skipping {receipt_id} because it's not favorite")
receipt = lidl.ticket(receipt_id)
save_receipt(receipt)
purchase_products(receipt)
mark_receipt_processed(receipt_id)
else:
_LOGGER.info(
f"Skipping {receipt_id} because it's already processed")
_LOGGER.info(f"Skipping {receipt_id} because it's already processed")


while True:
process_receipts()
Expand Down
Binary file modified requirements.txt
Binary file not shown.
1 change: 1 addition & 0 deletions settings_examlple.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"LIDL_LANGUAGE": os.environ.get("LIDL_LANGUAGE", "de"),
"LIDL_COUNTRY": os.environ.get("LIDL_COUNTRY", "DE"),
"LIDL_REFRESH_TOKEN": os.environ.get("LIDL_REFRESH_TOKEN", "555XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX555"),
"PROCESS_ONLY_FAVORITES": os.environ.get("PROCESS_ONLY_FAVORITES", True),
"GROCY_URL": os.environ.get("GROCY_URL", "http://192.168.1.111"),
"GROCY_PORT": os.environ.get("GROCY_PORT", 9283),
"GROCY_API_KEY": os.environ.get("GROCY_API_KEY", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"),
Expand Down

0 comments on commit fb272d2

Please sign in to comment.