11from collections import namedtuple
2+ from decimal import Decimal
23
3- Order = namedtuple (" Order" , " id, items" )
4- Item = namedtuple (" Item" , " type, description, amount, quantity" )
4+ Order = namedtuple (' Order' , ' id, items' )
5+ Item = namedtuple (' Item' , ' type, description, amount, quantity' )
56
7+ MAX_ITEM_AMOUNT = 100000 # maximum price of item in the shop
8+ MAX_QUANTITY = 100 # maximum quantity of an item in the shop
9+ MIN_QUANTITY = 0 # minimum quantity of an item in the shop
10+ MAX_TOTAL = 1e6 # maximum total amount accepted for an order
611
7- def validorder (order : Order ):
8- net = 0
12+ def validorder (order ):
13+ payments = Decimal ('0' )
14+ expenses = Decimal ('0' )
915
1016 for item in order .items :
11- if item .type == "payment" :
12- net += item .amount
13- elif item .type == "product" :
14- net -= item .amount * item .quantity
17+ if item .type == 'payment' :
18+ # Sets a reasonable min & max value for the invoice amounts
19+ if - MAX_ITEM_AMOUNT <= item .amount <= MAX_ITEM_AMOUNT :
20+ payments += Decimal (str (item .amount ))
21+ elif item .type == 'product' :
22+ if type (item .quantity ) is int and MIN_QUANTITY < item .quantity <= MAX_QUANTITY and MIN_QUANTITY < item .amount <= MAX_ITEM_AMOUNT :
23+ expenses += Decimal (str (item .amount )) * item .quantity
1524 else :
1625 return "Invalid item type: %s" % item .type
26+
27+ if abs (payments ) > MAX_TOTAL or expenses > MAX_TOTAL :
28+ return "Total amount payable for an order exceeded"
1729
18- if net != 0 :
19- return "Order ID: %s - Payment imbalance: $%0.2f" % (order .id , net )
30+ if payments != expenses :
31+ return "Order ID: %s - Payment imbalance: $%0.2f" % (order .id , payments - expenses )
2032 else :
21- return "Order ID: %s - Full payment received!" % order .id
33+ return "Order ID: %s - Full payment received!" % order .id
0 commit comments