Commit c35b0117 authored by Robin Trioux's avatar Robin Trioux
Browse files

Huge refacto

Product selector tree created
watchout product dict is "force" coded
TODO: Convert google timestamp into QTime
parent f033e976
from Console import *
class UIProperties: class UIProperties:
def __init__(self): def __init__(self):
self.text = ( self.text = (
...@@ -50,8 +55,6 @@ class UIProperties: ...@@ -50,8 +55,6 @@ class UIProperties:
def getToolTip(self): def getToolTip(self):
return self.toolTip return self.toolTip
class Atom: class Atom:
def __init__(self): def __init__(self):
self.ui = UIProperties() self.ui = UIProperties()
...@@ -98,6 +101,37 @@ class Atom: ...@@ -98,6 +101,37 @@ class Atom:
def getToolTip(self): def getToolTip(self):
return self.ui.getToolTip() return self.ui.getToolTip()
def getUI(self):
return self.ui
class HappyHours(Atom):
def __init__(self):
super().__init__()
self.start = None # QTime
self.end = None # QTime
self.price = None # Eur
def setStart(self,start):
self.start = start
return self
def setEnd(self, end):
self.end = end
return self
def setPrice(self, price):
self.price = price
return self
def getStart(self):
return self.start
def getEnd(self):
return self.end
def getPrice(self):
return self.price
class User(Atom): class User(Atom):
def __init__(self): def __init__(self):
...@@ -108,12 +142,15 @@ class User(Atom): ...@@ -108,12 +142,15 @@ class User(Atom):
def setId(self, id): def setId(self, id):
self.id = id self.id = id
return self
def setBalance(self, balance): def setBalance(self, balance):
self.balance = balance self.balance = balance
return self
def setCanDrink(self, canDrink): def setCanDrink(self, canDrink):
self.canDrink = canDrink self.canDrink = canDrink
return self
def getId(self): def getId(self):
return self.id return self.id
...@@ -133,21 +170,36 @@ class Product(Atom): ...@@ -133,21 +170,36 @@ class Product(Atom):
self.code = None # short name self.code = None # short name
self.price = None # The price is either updated when it's in a the selctor, either retreived from database when it's in history self.price = None # The price is either updated when it's in a the selctor, either retreived from database when it's in history
self.quantity = None # When product is used as selector, quantity is 1 and when used in a basket, it may vary self.quantity = None # When product is used as selector, quantity is 1 and when used in a basket, it may vary
self.happyHours = None # List of happy hours
self.category = None # string e.g "Drinks.Alcool.Wine"
def setId(self, id): def setId(self, id):
self.id = id self.id = id
return self
def setName(self, name): def setName(self, name):
self.name = name self.name = name
return self
def setCode(self, code): def setCode(self, code):
self.code = code self.code = code
return self
def setPrice(self, price): def setPrice(self, price): # price is never a float but something inherited from Decimal (Money.Eur)
self.price = price self.price = price
return self
def setQuantity(self, quantity): def setQuantity(self, quantity):
self.quantity = quantity self.quantity = quantity
return self
def setHappyHours(self,happyHours):
self.happyHours = happyHours
return self
def setCategory(self, category):
self.category = category
return self
def getId(self): def getId(self):
return self.id return self.id
...@@ -164,6 +216,18 @@ class Product(Atom): ...@@ -164,6 +216,18 @@ class Product(Atom):
def getQuantity(self): def getQuantity(self):
return self.quantity return self.quantity
def getHappyHours(self):
return self.happyHours
def getCategory(self):
return self.category
def __repr__(self):
return "Product({0}, {1})".format(self.id,self.name)
def __str__(self):
return "{0}: {1}".format(self.id,self.name)
class Operation(Atom): class Operation(Atom):
def __init__(self): def __init__(self):
...@@ -177,18 +241,23 @@ class Operation(Atom): ...@@ -177,18 +241,23 @@ class Operation(Atom):
def setId(self, id): def setId(self, id):
self.id = id self.id = id
return self
def setLabel(self, label): def setLabel(self, label):
self.label = label self.label = label
return self
def setRefounded(self, refounded): def setRefounded(self, refounded):
self.refounded = refounded self.refounded = refounded
return self
def setCounterId(self, counterId): def setCounterId(self, counterId):
self.counterId = counterId self.counterId = counterId
return self
def setDate(self, date): def setDate(self, date):
self.date = date self.date = date
return self
def getId(self): def getId(self):
return self.id return self.id
...@@ -214,13 +283,16 @@ class Buying(Operation): ...@@ -214,13 +283,16 @@ class Buying(Operation):
self.basketItems = None # List of "Product", their unit price should be download from the history self.basketItems = None # List of "Product", their unit price should be download from the history
def setPrice(self, price): def setPrice(self, price):
self.price = print self.price = price
return self
def setPayment(self, payments): def setPayment(self, payments):
self.payments = payments self.payments = payments
return self
def setBasketItems(self, basketItems): def setBasketItems(self, basketItems):
self.basketItems = basketItems self.basketItems = basketItems
return self
def getPrice(self): def getPrice(self):
return self.price return self.price
...@@ -236,13 +308,22 @@ class Refilling(Operation): ...@@ -236,13 +308,22 @@ class Refilling(Operation):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.amount = None self.amount = None
self.newBalance = None
def setAmount(self, amount): def setAmount(self, amount):
self.amount = amount self.amount = amount
return self
def getAmount(self): def getAmount(self):
return self.amount return self.amount
def setNewBalance(self, balance):
self.newBalance = balance
return self
def getNewBalance(self):
return self.newBalance
class Counter(Atom): class Counter(Atom):
def __init__(self): def __init__(self):
...@@ -252,9 +333,11 @@ class Counter(Atom): ...@@ -252,9 +333,11 @@ class Counter(Atom):
def setId(self, id): def setId(self, id):
self.id = id self.id = id
return self
def setName(self, name): def setName(self, name):
self.name = name self.name = name
return self
def getId(self): def getId(self):
return self.id return self.id
...@@ -267,3 +350,82 @@ class Counter(Atom): ...@@ -267,3 +350,82 @@ class Counter(Atom):
def __str__(self): def __str__(self):
return "{0}: {1}".format(self.id,self.name) return "{0}: {1}".format(self.id,self.name)
class Distribution(Atom):
def __init__(self):
super().__init__()
self.userList = [] # list of user uid
self.userBalance = [] # the current balance of each user before transaction
self.amount = [] # the amount paid by each user
self.totalPrice = None # The total price to pay
def setUserList(self,uidList):
self.userList = uidList
return self
def getUserList(self):
return self.userList
def addUser(self,uid):
self.userList.append(uid)
return self
def removeUser(self,uid):
try:
indexUser = self.userList.index(uid)
del(self.userList[indexUser])
return self
except ValueError:
printE("User {} not found".format(uid))
return None
def setUserBalanceList(self, balanceList):
self.userBalance = balanceList
return self
def getUserBalanceList(self):
return self.userBalance
def setUserBalance(self, uid, balance):
try:
indexUser = self.userList.index(uid)
self.userBalance[indexUser] = balance
except ValueError:
printE("User {} not found".format(uid))
return None
def getUserBalance(self, uid):
try:
indexUser = self.userList.index(uid)
return self.userBalance[indexUser]
except ValueError:
printE("User {} not found".format(uid))
return None
def setAmountList(self, amountList):
self.amount
def setUserAmount(self, uid, amount):
try:
userIndex = self.userList.index(uid)
if amount <= self.userBalance[userIndex]:
self.amount[userIndex] = amount
else:
printWW("Insufficient balance for user {}".format(uid))
self.amount[userIndex] = self.userBalance[userIndex]
except ValueError:
printE("user {} not found".format(uid))
def getAmountList(self):
return self.amount
def getUserAmount(self, uid):
try:
userIndex = self.userList.index(uid)
return self.amount[userIndex]
except ValueError:
printE("user {} not found".format(uid))
def setFairDistribution(self):
pass
\ No newline at end of file
from __future__ import print_function from __future__ import print_function
import grpc import grpc
...@@ -6,10 +5,44 @@ from grpc import RpcError ...@@ -6,10 +5,44 @@ from grpc import RpcError
import com_pb2 import com_pb2
import com_pb2_grpc import com_pb2_grpc
from google.protobuf.timestamp_pb2 import Timestamp from google.protobuf.timestamp_pb2 import Timestamp
from google.protobuf.json_format import MessageToDict from QAtoms import *
from Atoms import *
from Console import * from Console import *
from convert import *
#def addProduct(product,categoryList):
# try:
# if isinstance(product,dict):
# productDict={categoryList[-1]:product}
# else:
# productDict={categoryList[-1]:[product]}
# return addProduct(productDict,categoryList[:-1])
# except IndexError:
# return product
#def parseProducts(productsReply):
# pbProductList = productsReply.products # get protobuff products
# for i in pbProductList:
# happyHoursList = []
# pbHappyHoursList = i.happy_hours
# for j in pbHappyHoursList:
# newHappyHour = HappyHours()
# newHappyHour.setStart(j.start) #Still need to be converted in QTime
# newHappyHour.setEnd(j.end)
# newHappyHour.setPrice(pb_money_to_eur(j.price)) # Since we choosed a securised money format we need to convert
# happyHoursList.append(newHappyHour)
# newProduct = Product()
# newProduct.setId(i.id)
# newProduct.setName(i.name)
# newProduct.setCode(i.code)
# newProduct.setPrice(pb_money_to_eur(i.default_price))
# newProduct.setHappyHours(happyHoursList)
# newProduct.setCategory(i.category)
#
class ClientSingleton(type): class ClientSingleton(type):
_instance = {} _instance = {}
...@@ -33,24 +66,7 @@ class Client(metaclass=ClientSingleton): ...@@ -33,24 +66,7 @@ class Client(metaclass=ClientSingleton):
repeated Payment payments repeated Payment payments
repeated BasketItem basket repeated BasketItem basket
""" """
# Mockup pass
mockupProduct = Product()
mockupProduct.price = 8
mockupProduct.quantity = 2
mockupProduct.name = "Bouteille"
mockupProduct.id = 0
mockupProduct.code = "BOUBOU"
buying = Buying()
buying.date = Timestamp().GetCurrentTime()
buying.id = 1
buying.label = "label"
buying.price = 16
buying.refounded = False
buying.counterId = 0
buying.basketItems = [mockupProduct]
return mockupProduct
def requestRefilling(self, **kwargs): def requestRefilling(self, **kwargs):
...@@ -61,18 +77,17 @@ class Client(metaclass=ClientSingleton): ...@@ -61,18 +77,17 @@ class Client(metaclass=ClientSingleton):
PaymentMethod payment_method PaymentMethod payment_method
double amount double amount
""" """
try:
# Mockup refillingRequest = com_pb2.RefillingRequest(**kwargs)
refilling = Refilling() refillingReply = self.stub.Refill(refillingRequest)
refilling.amount = 42 self.now = refillingReply.now
refilling.counterId = 0 newBalance = unpackMoney(refillingReply.amount)
refilling.date = Timestamp().GetCurrentTime() refilling = unpackRefilling(refillingReply.refilling)
refilling.id = 2 refilling.setNewBalance(newBalance)
refilling.label = "label" return refilling
refilling.refounded = False except RpcError:
printE("Unable to refill")
return refilling return None
def requestHistory(self, **kwargs): def requestHistory(self, **kwargs):
pass pass
...@@ -86,68 +101,65 @@ class Client(metaclass=ClientSingleton): ...@@ -86,68 +101,65 @@ class Client(metaclass=ClientSingleton):
""" """
int64 counter_id int64 counter_id
""" """
counterProduct = {} productList = []
try: try:
productsRequest = com_pb2.ProductsRequest(counter_id=kwargs['counter_id']) productsRequest = com_pb2.ProductsRequest(**kwargs)
productsReply = self.stub.Products(productsRequest) productsReply = self.stub.Products(productsRequest)
self.now = productsReply.now self.now = productsReply.now
return MessageToDict(productsReply)['items']
# Fill product List
pbProductList = productsReply.products # get protobuff products
for pb_product in pbProductList:
newProduct = unpackProduct(pb_product)
productList.append(newProduct)
return productList
except RpcError: except RpcError:
printE("Unable to get product list") printE("Unable to get product list")
return None return None
return None
# Mockup
mockupProduct1 = Product()
mockupProduct1.name = "Coca"
mockupProduct1.price = 1
mockupProduct1.quantity = 1
mockupProduct1.id = 0
mockupProduct1.code = "COCA"
mockupProduct2 = Product()
mockupProduct2.name = "Bièrre"
mockupProduct2.price = 2
mockupProduct2.quantity = 1
mockupProduct2.id = 1
mockupProduct2.code = "BIBINE"
products = {"Soft": mockupProduct1, "Alcool": mockupProduct2}
return products
def requestUserBalance(self, **kwargs): def requestUserBalance(self, **kwargs):
""" """
string customer_id string customer_id
""" """
# Mockup try:
return 30 balanceRequest = com_pb2.BalanceRequest(customer_id = kwargs['customer_id'])
balanceReply = self.stub.Balance(balanceRequest)
self.now = balanceReply.now
return unpackMoney(balanceReply.balance)
except RpcError:
printE("Unable to get customer balance")
return None
return None
def requestCounterList(self, **kwargs): def requestCounterList(self, **kwargs):
"""No parameters requiered""" """No parameters requiered"""
counterList = [] counterList = []
counterListRequest = com_pb2.CounterListRequest()
try: try:
counterListRequest = com_pb2.CounterListRequest()
counterListReply = self.stub.CounterList(counterListRequest) counterListReply = self.stub.CounterList(counterListRequest)
grpcCounterList = counterListReply.counters #get the payload pbCounterList = counterListReply.counters #get the payload
self.now = counterListReply.now #update the time self.now = counterListReply.now #update the time
for i in grpcCounterList: for pb_counter in pbCounterList:
newCounter = Counter() newCounter = unpackCounter(pb_counter)
newCounter.setId(i.id)
newCounter.setName(i.name)
counterList.append(newCounter) counterList.append(newCounter)
return counterList return counterList
except RpcError: except RpcError:
printE("Unable to get counter list") printE("Unable to get counter list")
return None return None
return None
def requestTransfert(self, **kwargs): def requestTransfert(self, **kwargs):
pass pass
from termcolor import colored from termcolor import colored
from babel.numbers import format_currency
# At the moment I assume we only print single strings # At the moment I assume we only print single strings
def printE(string): #Error def printE(string): #Error
...@@ -7,6 +8,9 @@ def printE(string): #Error ...@@ -7,6 +8,9 @@ def printE(string): #Error
def printW(string): #Warning def printW(string): #Warning
print(colored("WARNING: " + str(string),'yellow')) print(colored("WARNING: " + str(string),'yellow'))
def printWW(string): #Super Warning
print(colored("WARNING: " + str(string),'yellow',attrs=['bold']))