Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf8 -*-
- from collections import defaultdict
- def discount_together(order_items, discounts, products=[], percent=0):
- ''' Скидки для групп товаров, присутствующих в заказе '''
- # выходим, если хотя бы один товар не найден
- if not set(products).issubset(order_items.keys()):
- return discounts
- # определяем кол-во найденных групп
- pairs = min([len(order_items[x]) for x in products])
- for p in products:
- for idx in range(pairs):
- key = order_items[p][idx]
- # пропускаем, если скидка для товара установлена
- if key in discounts:
- continue
- discounts[key] = percent
- print "discount_and: %s - %.2f" % (key, percent)
- return discounts
- def discount_oneof(order_items, discounts, products=[], percent=0, condition = []):
- ''' Скидки для каждого товара из группы, [при наличии другого товара из условия] '''
- # если задано условия, проверяем его в первую очередь
- if len(condition) and not set(condition).issubset(order_items.keys()):
- return basket
- for p in products:
- for key in order_items.get(p, []):
- # пропускаем, если скидка для товара уже задана
- if key in discounts:
- continue
- discounts[key] = percent
- print "discount_or: %s - %.2f" % (key, percent)
- return discounts
- def order_discount(order_items, ranges, exclude = []):
- ''' Скидка на сумму заказа, в зависимости от кол-ва товаров, [исключая некоторые позиции] '''
- # количество товаров в заказе, исключая позиции exclude
- total_len = sum([ len(items) for key, items in order_items.iteritems() if not key in exclude ])
- # выбираем скидку, соответствующую кол-ву товаров в заказе
- discount = ranges.get(str(total_len), 0)
- if discount > 0:
- print "total_discount: %.2f" % (discount)
- return discount
- def get_basket(order, products, discount_types=[], total_discount_options={}):
- ''' Расчёт потребительской корзины '''
- basket = {'items': [], 'total': {}}
- order_items = defaultdict(list)
- # преобразуем список в словарь (по уникальным товарам) - в значениях индексы исходного списка
- for i, item in enumerate(order):
- order_items[item].append(i)
- discounts = {}
- # вычисляем скидки в порядке следования
- for discount_item in discount_types:
- d_type = discount_item.get('type')
- d_options = discount_item.get('options')
- if d_type == 'together':
- discount_together(order_items, discounts, **d_options)
- if d_type == 'oneof':
- discount_oneof(order_items, discounts, **d_options)
- subtotal = 0
- # формируем корзину, подсчитываем подитог
- for i, item in enumerate(order):
- price = products[item]
- discount = discounts[i] if i in discounts else 0
- basket['items'].append({
- 'product': item,
- 'price': price,
- 'discount': discount
- })
- subtotal+=price*discount
- # вычисляем скидку на сумму заказа
- total_discount = order_discount(order_items, **total_discount_options)
- basket['total'] = {'subtotal': subtotal, 'discount': total_discount, 'total': subtotal*td}
- return basket
- def main():
- ''' Товары с ценами '''
- products = {
- 'A': 100,
- 'B': 100,
- 'C': 100,
- 'D': 100,
- 'E': 100,
- 'F': 100,
- 'G': 100,
- 'H': 100,
- 'I': 100,
- 'K': 100,
- 'L': 100,
- 'M': 100
- }
- ''' Список установленных скидок '''
- discounts = [
- {'type': 'together', 'options': {'products': ['A','B'], 'percent': 0.9 }},
- {'type': 'together', 'options': {'products': ['D','E'], 'percent': 0.95 }},
- {'type': 'together', 'options': {'products': ['E','F','G'], 'percent': 0.95 }},
- {'type': 'oneof', 'options': {'products': ['K','L','M'], 'percent': 0.95 , 'condition': ['A']}},
- ]
- ''' Скидки по сумме заказа '''
- total_discount_options = {'ranges': {'3': 0.95, '4': 0.9, '5': 0.8}, 'exclude': ['A','C']}
- ''' Исходный список товаров в заказе '''
- myorder = ['A', 'B', 'C', 'K', 'L', 'D', 'D', 'E']
- print get_basket(myorder, products, discounts, total_discount_options)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement