diff --git a/main.py b/main.py index 16d7a00..526c123 100644 --- a/main.py +++ b/main.py @@ -185,4 +185,93 @@ def menu_decrease_stock(menu_id, qty): c.execute("UPDATE menu SET stok=?, tersedia=? WHERE id=?", (newstok, tersedia, menu_id)) conn.commit() conn.close() - return True, newstok \ No newline at end of file + return True, newstok + + + +# Bagian Promooo + + +def promo_add(code, ptype, value, min_total=0): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + c.execute("INSERT INTO promo (code,type,value,min_total) VALUES (?,?,?,?)", (code,ptype,value,min_total)) + conn.commit() + conn.close() + +def promo_update(code, ptype, value, min_total=0): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + c.execute("UPDATE promo SET type=?, value=?, min_total=? WHERE code=?", (ptype,value,min_total,code)) + conn.commit() + conn.close() + +def promo_delete(code): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + c.execute("DELETE FROM promo WHERE code=?", (code,)) + conn.commit() + conn.close() + +def promo_list(): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + c.execute("SELECT code,type,value,min_total FROM promo ORDER BY code") + rows = c.fetchall() + conn.close() + return rows + +def promo_get(code): + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + c.execute("SELECT code,type,value,min_total FROM promo WHERE code=?", (code,)) + r = c.fetchone() + conn.close() + return r + +def apply_discounts_and_promo(cart_items, promo_code=None): + """ + cart_items: list of dicts: [{'menu_id':..,'qty':..}, ...] + returns breakdown: subtotal, item_discount_total, promo_code, promo_discount, total + - uses item_discount_pct from menu table + - promo_code can be percent or fixed, with min_total + """ + conn = sqlite3.connect(DB_PATH) + c = conn.cursor() + subtotal = 0.0 + item_discount_total = 0.0 + for it in cart_items: + c.execute("SELECT harga,item_discount_pct FROM menu WHERE id=?", (it['menu_id'],)) + r = c.fetchone() + if not r: + continue + price, item_disc_pct = r + qty = it.get('qty',1) + line = price * qty + subtotal += line + if item_disc_pct and item_disc_pct > 0: + item_discount_total += (price * qty) * (item_disc_pct/100.0) + promo_discount = 0.0 + promo_applied = None + if promo_code: + c.execute("SELECT type,value,min_total FROM promo WHERE code=?", (promo_code,)) + row = c.fetchone() + if row: + ptype, val, min_total = row + if subtotal >= min_total: + if ptype == 'percent': + promo_discount = (subtotal - item_discount_total) * (val/100.0) + else: + promo_discount = val + promo_applied = promo_code + total = subtotal - item_discount_total - promo_discount + if total < 0: + total = 0.0 + conn.close() + return { + 'subtotal': round(subtotal,2), + 'item_discount': round(item_discount_total,2), + 'promo_code': promo_applied, + 'promo_discount': round(promo_discount,2), + 'total': round(total,2) + } \ No newline at end of file