Example #1
0
    def test_make_transaction(self):
        alg = self._init_test()
        self._prefill_db(alg)
        trs = Transactions(FILE_NAME)
        fnds = Funds(FILE_NAME)

        accs = alg.make_transaction('01', 100)
        self.assertEqual(500.0, alg.portfolio_total_fund)
        accounts = [
            (1, '01', 0.2, accs[0][3], 0, 0.7, 0.7, 1, accs[0][-1]),
            (2, '02', 0.2, accs[1][3], 50, 0.3, 0.9, 1, accs[1][-1]),
            (3, '03', 0.2, accs[2][3], -50, 0.3, 0.9, 1, accs[2][-1]),
            (4, '04', 0.4, accs[3][3], 0, 0.3, 0.9, 1, accs[3][-1]),
        ]
        self.assertEqual(accounts, accs)
        acc_trs = trs.retrieve_transactions_for_account(account_id=1)
        self.assertEqual(100, acc_trs[-1][1])
        acc_fnds = fnds.retrieve_funds_for_account(account_id=1)
        self.assertEqual(100, acc_fnds[-1][1])

        accs = alg.make_transaction('02', -100)
        self.assertEqual(400.0, alg.portfolio_total_fund)
        accounts = [
            (1, '01', 0.25, accs[0][3], 0, 0.7, 0.7, 1, accs[0][-1]),
            (2, '02', 0.0, accs[1][3], 50, 0.3, 0.9, 1, accs[1][-1]),
            (3, '03', 0.25, accs[2][3], -50, 0.3, 0.9, 1, accs[2][-1]),
            (4, '04', 0.5, accs[3][3], 0, 0.3, 0.9, 1, accs[3][-1]),
        ]
        self.assertEqual(accounts, accs)
        acc_trs = trs.retrieve_transactions_for_account(account_id=2)
        self.assertEqual(-100, acc_trs[-1][1])
        acc_fnds = fnds.retrieve_funds_for_account(account_id=2)
        self.assertEqual(0, acc_fnds[-1][1])

        accs = alg.make_transaction('03', -150)
        self.assertEqual(400.0, alg.portfolio_total_fund)
        self.assertEqual(False, accs)
        acc_trs = trs.retrieve_transactions_for_account(account_id=3)
        self.assertEqual(0, len(acc_trs))
        acc_fnds = fnds.retrieve_funds_for_account(account_id=3)
        self.assertEqual(100, acc_fnds[-1][1])
Example #2
0
 def test_refill_main_wallet(self, mock_unsubscribe, mock_subscribe):
     t = Transactions(service=settings.BTC_SERVICE,
                      testnet=settings.BTC_TESTNET,
                      username=settings.BTC_USERNAME,
                      password=settings.BTC_PASSWORD,
                      host=settings.BTC_HOST,
                      port=settings.BTC_PORT)
     unspents = t.get(settings.BTC_MAIN_WALLET,
                      min_confirmations=1).get('unspents', [])
     fees_before = filter(lambda d: d['amount'] == settings.BTC_FEE,
                          unspents)
     tokens_before = filter(lambda d: d['amount'] == settings.BTC_TOKEN,
                            unspents)
     refill_main_wallet.delay()
     unspents = t.get(settings.BTC_MAIN_WALLET,
                      min_confirmations=1).get('unspents', [])
     fees_after = filter(lambda d: d['amount'] == settings.BTC_FEE,
                         unspents)
     tokens_after = filter(lambda d: d['amount'] == settings.BTC_TOKEN,
                           unspents)
     self.assertEqual(len(fees_after), len(fees_before) + 50)
     self.assertEqual(len(tokens_after), len(tokens_before) + 150)
Example #3
0
    def __init__(self,
                 testnet=False,
                 service='blockr',
                 username='',
                 password='',
                 host='',
                 port='',
                 fee=None,
                 token=None):
        """
        Args:
            testnet (bool): Whether to use the mainnet or testnet.
                Defaults to the mainnet (:const:`False`).
            service (str): Bitcoin communication interface: ``'blockr'``,
                ``'daemon'``, or ``'regtest'``. ``'blockr'`` refers to the
                public api, whereas ``'daemon'`` and ``'regtest'`` refer
                to the jsonrpc inteface. Defaults to ``'blockr'``.
            username (str): username for jsonrpc communications
            password (str): password for jsonrpc communications
            hostname (str): hostname of the bitcoin node when using jsonrpc
            port (str): port number of the bitcoin node when using jsonrpc
            fee (int): transaction fee
            token (int): token

        """
        self.testnet = testnet
        self._netcode = 'XTN' if testnet else 'BTC'
        self._t = Transactions(service=service,
                               testnet=testnet,
                               username=username,
                               password=password,
                               host=host,
                               port=port)
        # simple cache for spent outputs. Useful so that rapid firing transactions don't use the same outputs
        self._spents = Queue(maxsize=self.SPENTS_QUEUE_MAXSIZE)
        self.fee = fee or self.FEE
        self.token = token or self.TOKEN
    def test_update_id(self):
        if os.path.isfile(FILE_NAME):
            os.remove(FILE_NAME)
        create_db(FILE_NAME)
        trs = Transactions(FILE_NAME)
        trs.create_transaction(10, 1)

        c = trs.update_id(id=1, amount=20, account_fk=2)
        ts = c[2]
        self.assertEqual((1, 20, ts, 2), c)

        c = trs.update_id(id=1, amount=10)
        ts = c[2]
        self.assertEqual((1, 10, ts, 2), c)

        c = trs.update_id(id=1, account_fk=1)
        ts = c[2]
        self.assertEqual((1, 10, ts, 1), c)

        c = trs.update_id(id=1, amount=0)
        ts = c[2]
        self.assertEqual((1, 0, ts, 1), c)

        os.remove(FILE_NAME)
Example #5
0
 def test_check_scripts(self):
     t = Transactions(testnet=True)
     tx = t.get(TXID)
     vouts = tx['vouts']
     verb = BlockchainSpider.check_script(vouts)
     self.assertEqual(verb, b'ASCRIBESPOOL01EDITIONS10')
def transactions():
    transaction_instance = Transactions()
    data = transaction_instance.get_transactions()
    return render_template('transactions.html', transactions=data)
Example #7
0
    def setUp(self):
        try:
            # flag to run the tests
            test = os.environ['TEST_SPOOL']
            if test == '2':
                username = os.environ['TESTNET_USERNAME']
                password = os.environ['TESTNET_PASSWORD']
                host = os.environ['TESTNET_HOST']
                port = os.environ['TESTNET_PORT']
            self.refill_pass = os.environ['TEST_REFILL_PASS']
            self.federation_pass = os.environ['TEST_FEDERATION_PASS']
            self.refill_root = Wallet(self.refill_pass,
                                      testnet=True).root_address
            self.federation_root = Wallet(self.federation_pass,
                                          testnet=True).root_address
        except KeyError:
            raise unittest.SkipTest(
                'TEST_REFILL_PASS and/or TEST_FEDERATION_PASS environment variables are not set.'
            )

        # set TEST_SPOOL=2 to test with bitcoind
        if test == '2':
            print('using bitcoind')
            self.t = Transactions(testnet=True,
                                  service='daemon',
                                  username=username,
                                  password=password,
                                  host=host,
                                  port=port)
            self.spool = Spool(testnet=True,
                               service='daemon',
                               username=username,
                               password=password,
                               host=host,
                               port=port)
        else:
            print('using blockr')
            self.t = Transactions(testnet=True)
            self.spool = Spool(testnet=True)

        self.user1_pass = self._get_pass()
        self.user2_pass = self._get_pass()
        self.user3_pass = self._get_pass()
        self.user1_root = Wallet(self.user1_pass, testnet=True).root_address
        self.user1_leaf = Wallet(self.user1_pass,
                                 testnet=True).address_from_path()
        self.user2_leaf = Wallet(self.user2_pass,
                                 testnet=True).address_from_path()
        self.user3_leaf = Wallet(self.user3_pass,
                                 testnet=True).address_from_path()
        self.file_hash = self._get_file_hash()

        print('user1_pass: '******'user2_pass: '******'user3_pass: '******'user1_root: ', self.user1_root)
        print('user1_leaf: ', self.user1_leaf)
        print('user2_leaf: ', self.user2_leaf)
        print('user3_leaf: ', self.user3_leaf)
        print('file_hash :', self.file_hash)

        self.spool._t.import_address(
            self.user1_root[1],
            "test",
        )
        self.spool._t.import_address(
            self.user1_leaf[1],
            "test",
        )
        self.spool._t.import_address(
            self.user2_leaf[1],
            "test",
        )
        self.spool._t.import_address(
            self.user3_leaf[1],
            "test",
        )
        self.spool._t.import_address(
            self.file_hash[0],
            "test",
        )
        self.spool._t.import_address(
            self.file_hash[1],
            "test",
        )
Example #8
0
    def bid_matching(self):

        self.compute()

        prob = pulp.LpProblem("DC optimal power flow", pulp.LpMinimize)

        ni = len(self.demand_bids)
        nj = len(self.generation_bids)

        alpha = np.empty((ni, nj), dtype=object)

        # declare alpha
        for i, j in product(range(ni), range(nj)):
            alpha[i, j] = pulp.LpVariable('alpha_' + str(i) + '_' + str(j), 0,
                                          1)

        gen_slack = np.empty(nj, dtype=object)
        for j in range(nj):
            gen_slack[j] = pulp.LpVariable('gen_slack_' + str(j))

        # objective function
        f = 0
        for i, j in product(range(ni), range(nj)):
            f += self.demand_bids[i].energy_mw * alpha[
                i, j] * self.generation_bids[j].price
        prob += f  #+ sum(gen_slack)

        #
        for j in range(nj):
            d_alpha = 0
            for i in range(ni):
                d_alpha += self.demand_bids[i].energy_mw * alpha[i, j]
            prob += (d_alpha <= self.generation_bids[j].energy_mw
                     )  #+ gen_slack[j])

        # sum of alpha per demand contract must be one
        for i in range(ni):
            prob += (sum(alpha[i, :]) == 1.0)

        # solve
        prob.solve()
        prob.writeLP('problem.lp')
        prob.writeMPS('problem.mps')
        print("Status:", pulp.LpStatus[prob.status], prob.status)

        #  -------------------------------------------------------------------------------------------------------------
        #  Generate the transactions

        transactions = Transactions()

        # problem solved
        for i, j in product(range(ni), range(nj)):
            id_gen = self.generation_bids[j].id
            id_demnd = self.demand_bids[i].id
            demand = self.demand_bids[i].energy_mw
            price = self.generation_bids[j].price
            val = alpha[i, j].value()
            if val != 0:
                print(id_demnd, 'buys from', id_gen, 'alpha', val)
                tr = Transaction(bid_id=str(id_gen) + '_' + str(id_demnd),
                                 seller_id=id_gen,
                                 buyer_id=id_demnd,
                                 energy_amount=val * demand,
                                 price=price,
                                 bid_type=self.demand_bids[i].bid_type)
                transactions.append(tr)

        return sorted(transactions, key=lambda x: x.bid_type, reverse=False)
Example #9
0
 def readFile(self, fname):
     with open(fname) as f:
         content = [x.strip('\n') for x in f.readlines()]
     t = Transactions(self.id)
     i = 0
     tcount = 0
     while i < len(content):
         transx = content[i].split(",")
         transType = transx[0]
         tcount = tcount + 1
         if transType == 'N':
             M = int(transx[4])
             c = int(transx[1])
             w = int(transx[2])
             d = int(transx[3])
             lis = content[i + 1:i + M + 1]
             t.neworder(c, w, d, lis)
             i = i + M
         elif transType == 'D':
             w = int(transx[1])
             c = int(transx[2])
             t.delivery(w, c)
         elif transType == 'P':
             w = int(transx[1])
             d = int(transx[2])
             c = int(transx[3])
             p = int(float(transx[4]))
             t.payment(c, w, d, p)
         elif transType == 'S':
             w = int(transx[1])
             d = int(transx[2])
             th = int(transx[3])
             l = int(transx[4])
             t.stocklevel(w, d, th, l)
         elif transType == 'O':
             w = int(transx[1])
             d = int(transx[2])
             c = int(transx[3])
             t.orderstatus(w, d, c)
         elif transType == 'I':
             w = int(transx[1])
             d = int(transx[2])
             l = int(transx[3])
             t.popularItem(w, d, l)
         elif transType == 'T':
             a = 0
             t.topbalance()
         else:
             print 'Input Mistmatch'
         i = i + 1
         i
     if t.ntime != 0:
         print self.id, "\tNew Order:\t", t.ntime, "\t\t", t.nc, "\t", t.nc / t.ntime
     if t.ptime != 0:
         print self.id, "\tPayment :\t", t.ptime, "\t\t", t.pc, "\t", t.pc / t.ptime
     if t.dtime != 0:
         print self.id, "\tDelivery:\t", t.dtime, "\t\t", t.dc, "\t", t.dc / t.dtime
     if t.otime != 0:
         print self.id, "\tOrder Status:\t", t.otime, "\t\t", t.oc, "\t", t.oc / t.otime
     if t.stime != 0:
         print self.id, "\tStock Level:\t", t.stime, "\t\t", t.sc, "\t", t.sc / t.stime
     if t.Itime != 0:
         print self.id, "\tPopular Item:\t", t.Itime, "\t\t", t.Ic, "\t", t.Ic / t.Itime
     if t.Ttime != 0:
         print self.id, "\tTop Balance:\t", t.Ttime, "\t\t", t.Tc, "\t", t.Tc / t.Ttime
     return tcount
Example #10
0
    def signatransaction(self):

        #global tx_signed
        tx_signed=""

        self.clearscreen()
        self.toolBar7.show()
        self.toolbarsign.show()

        #foundkeyfromqrcode=self.camscanner()
        foundkeyfromqrcode1=self.camscannermd5()
        foundkeyfromqrcode2=foundkeyfromqrcode1.split(",")[0]
        unsignedmsgnow=foundkeyfromqrcode2.split(":")[1]
        sendedcmdtocheck=foundkeyfromqrcode2.split(":")[0]

       

        foundkeyfromqrcodenow = str(unsignedmsgnow.strip())
        privatekeyusetosignnow = str(privatekeyusetosignnowarchive.strip())

    
        self.clearscreen()
        self.toolBar7.show()
        self.toolbarsign.show()




        transactions = Transactions(testnet=True)
        tx_signed=""


        if sendedcmdtocheck == 'signbtc':

            try:
                tx_signed = transactions.sign(foundkeyfromqrcodenow, privatekeyusetosignnow)
                #print tx_signed
            except:
                pass
                tx_signed=""
                #print "No RAW transactions, try base43 for electrum"

            if tx_signed =="":

                try:
                    rawis=self.base_decode(foundkeyfromqrcodenow);
                    tx_signed = transactions.sign(rawis, privatekeyusetosignnow)
                    #print tx_signed
                except:
                    pass
                    tx_signed=""
                    #print "Was no base43 either"
        


        self.clearscreen()
        self.toolBar7.show()

        if tx_signed !="":

            #self.showtransactionqrcode()

            tx_signed='btcbroadcast:'+tx_signed



            msgnow='Plase scan this QR to broadcast your transaction.'
            self.msgallround.show()
            self.allroundmsg(17,530,446,270,msgnow)

            self.showqrmovie(tx_signed,0,50,480,480)  #text, positie x,y,w,h 






        else:
            self.statusBar().showMessage("ERROR!!! I Cant sign the transaction.")
            self.toolbarsign.show()
Example #11
0
    def get_last(bills_qty=1):
        bills_details = Bills().get_last_with_details(bills_qty)
        transactions = Transactions().get_all()

        return BillTransactions.__process_bill_transactions(
            bills_details, transactions)
Example #12
0
    def __init__(self,master, login):
        self.login = login
        Toplevel.__init__(self,master)
        Tk.title(self,'managament app')
        Tk.geometry(self,'970x600+0+0')
        Tk.configure(self,bg='blue')
        self.resizable(False,False)

        #containers for data
        self.prodName = StringVar()
        self.prodOwner = StringVar()

        Tk.after(self,100,check())
        

        

        #frames
        Main = Frame(self, bg='green')
        Main.grid()

        Header = Frame(Main, bg='green', bd=2, padx=54, pady=8, relief=RIDGE) #////// title space
        Header.pack(side=TOP)

        self.Header_text = Label(Header, font=('times new roman', 40, 'bold'), text="managament", bg='green')
        self.Header_text.grid()

        ClickFrame = Frame(Main, bd=2, width=1350, height=70, padx=18, pady=10, bg='green', relief=RIDGE) #//// buttons space
        ClickFrame.pack(side=BOTTOM)

        Data = Frame(Main, bd=1, width=1300, height=400, padx=20, pady=20, relief=RIDGE, bg='white') #////// content space
        Data.pack(side=BOTTOM)

        DataLeft = LabelFrame(Data, bd=1, width=1000, height=600, padx=20, relief=RIDGE, bg='green', text='Product information\n', font=('arial', 20, 'bold'))
        DataLeft.pack(side=LEFT)

        DataRight = LabelFrame(Data, bd=1, width=450, height=300, padx=31, pady=3, relief=RIDGE, bg='green',  text='Product details\n', font=('arial', 20, 'bold'))
        DataRight.pack(side=RIGHT)



    
        con = sqlite3.connect('databases\\main.db')
        cur = con.cursor()
        cur.execute("SELECT money FROM users WHERE login=?",(login,))
        row = cur.fetchall()
        for r in row:
            self.budget = str(r[0])
        self.money_info = StringVar(self,'Available EURO: '+self.budget)
        self.Base = Label(DataLeft, textvariable=self.money_info, fg='blue')
        self.Base.grid(row=0, column=0)
           
        self.productName = Label(DataLeft, text='ITEM name')
        self.productName.grid(row=1, column=0, sticky=W)
        self.entry_name = Entry(DataLeft, width=39)
        self.entry_name.grid(row=1, column=1)

        self.productOwner = Label(DataLeft, text='ITEM value')
        self.productOwner.grid(row=2, column=0, sticky=W)
        self.entry_Owner = Entry(DataLeft, width=39)
        self.entry_Owner.grid(row=2, column=1)
        
        
        ### labels editing loop
        global test
        test = {self.productOwner, self.productName, self.Base}
        for button in test:
            button.configure(bg='green', padx=2, pady=2, font=('times new roman', 15, 'bold'))

        ## details window
        Details = Scrollbar(DataRight)
        Details.grid(row=0, column=1, padx=8)
        global ProductList
        ProductList = Listbox(DataRight, width=41, height=16, font=('arial',12,'bold'), yscrollcommand=Details.set)
        ProductList.bind('<<ListboxSelect>>', self.ChooseItem)
        ProductList.grid(row=0, column=0, padx=8)
        Details.configure(command=ProductList.yview)

        ##buttons

        self.buttonAdd = Button(ClickFrame, text='funds menu', command=lambda:funds(self, self.login))
        self.buttonAdd.grid(row=0, column=0)

        self.buttonDel = Button(ClickFrame, text='MY ITEMS', command=lambda:user_items(self,self.login))
        self.buttonDel.grid(row=0, column=1)

        self.buttonEdit = Button(ClickFrame, text='view', command=self.add_items)
        self.buttonEdit.grid(row=0, column=2)

        self.buttonEdit = Button(ClickFrame, text='buy', command=lambda:Transactions(self,
                                                                                    self.login,                                                            
                                                                                    self.entry_name,
                                                                                    self.entry_Owner,
                                                                                    
                                                                                    ))
        self.buttonEdit.grid(row=0, column=3)

        self.buttonExit = Button(ClickFrame, text='SELL')
        self.buttonExit.grid(row=0, column=4)
Example #13
0
    def delete(self):
        url = self.request.uri
        route = url.split('/')
        status_int = 200

        if 'cart' in route:
            uid = route[len(route) - 1]
            cart = Cart()
            items = Items()

            cart_id = cart.removeCart(uid=uid)
            if cart_id != '':
                items.removeItems(cart_id=cart_id)

                response_data = {
                    'message': 'successfully deleted cart',
                    'cart': {}
                }
            else:
                response_data = {
                    'message': 'cart not found',
                    'cart': {}
                }

        elif 'transactions' in route:
            id = route[len(route) - 1]
            uid = route[len(route) - 2]

            this_transactions = Transactions()
            transaction_list = this_transactions.removeTransaction(id=id,uid=uid)

            response_data = []
            for transaction in transaction_list:
                response_data.append(transaction.to_dict())

        elif 'products' in route:
            id = route[len(route) - 1]
            uid = route[len(route) - 2]

            this_product = Products()
            result = this_product.deleteProduct(uid=uid,id=id)
            if result != '':
                response_data = result.to_dict()
            else:
                status_int = 401
                response_data = {'message':'product not found'}

        elif 'dashboard' in route:
            uid = route[len(route) - 2]

            user_request = User.query(User.uid == uid)
            user_list =user_request.fetch()

            response_data = []
            if len(user_list) > 0:
                user = user_list[0]


                if ('banking' in route) and ('delete' in route) and user.is_admin:
                    # routes.api_dashboard_endpoint + `/banking/delete/${uid}/${banking_id}

                    banking_id = route[len(route) - 1]

                    this_banking = Banking()
                    result = this_banking.deleteBanking(banking_id=banking_id)

                    if result == True:
                        banking_query = Banking.query()
                        banking_list = banking_query.fetch()

                        for banking in banking_list:
                            response_data.append(banking.to_dict())
                    else:
                        status_int = 403
                        response_data = {'message': 'bank account record not found'}

                #TODO add more adminstrative tasks here
                else:
                    status_int = 401
                    response_data = {'message': 'your request is not understood'}

            else:
                status_int = 401
                response_data = {'message': 'your request is not understood'}

        else:
            status_int = 403
            response_data = {
                'message' : 'error resource not found'
            }

            


        self.response.headers['Content-Type'] = "application/json"
        self.response.status_int = status_int
        json_data = json.dumps(response_data)
        self.response.write(json_data)
Example #14
0
    def post(self):
        url = self.request.uri
        route = url.split('/')
        status_int = 200

        if 'contact' in route:
            json_data = json.loads(self.request.body)
            logging.info(json_data)

            this_contact = Contact()
            contact_key = this_contact.new_contact(contact=json_data)

            if contact_key != None:
                response_data = {'message': 'Thank you ' + str(json_data['names']) + ' for sending us this message we will be responding to you through this email ' + str(json_data['email']) }
            else:
                response_data = {'message' : 'Unfortunately we cannot process any more contact messages from you'}

        elif 'categories' in route:
            json_data = json.loads(self.request.body)                            
            this_category = Categories();
            this_category = this_category.addCategory(category=json_data)

            if this_category == '':
                status_int = 403
                response_data={'message':'error category already exist'}
            else:
                response_data = this_category.to_dict()

        elif 'products' in route:
            json_data = json.loads(self.request.body)            
            this_products = Products()
            this_products = this_products.addProduct(product=json_data)
            logging.info(this_products)            
            if this_products != None:
                response_data = {'message': 'product successfully added'}
            else:
                response_data = {'message': 'duplicate product error'}

        elif 'services' in route:            
            json_data = json.loads(self.request.body)                    
            this_service = Services()
            this_service = this_service.addService(service=json_data)

            if this_service != '':    
                response_data = this_service.to_dict()
            else:
                status_int = 403
                response_data = { 'message':'duplicate service'}

        elif 'physical-address' in route:
            json_data = json.loads(self.request.body)                        
            physical_address = PhysicalAddress()
            physical_address = physical_address.addPhysicalAddress(physical=json_data)
            response_data = physical_address.to_dict()

        elif 'contact-details' in route:
            json_data = json.loads(self.request.body)
            contact_details = ContactDetails()
            contact_details = contact_details.addContactDetails(contact=json_data)
            response_data = contact_details.to_dict()

        elif 'cart' in route:            
            
            json_data = json.loads(self.request.body)

            cart_owner_id = json_data['uid']
            item =  json_data['item']
            logging.info(item)

            cart_request = Cart.query(Cart.uid == cart_owner_id)
            cart_list = cart_request.fetch()

            if len(cart_list) > 0 :
                cart = cart_list[0]
            else:
                cart = Cart()
                cart.uid = cart_owner_id
                cart.cart_id = cart.create_cart_id()
                cart.is_active = True
                today = datetime.now()
                today = today.strftime("%d-%b-%Y")
                cart.date_created = today

                cart.sub_total = str(0)
                cart.tax = str(0)
                cart.total = str(0)

            items = Items()
            try:
                product_name = item['product_name']
                items.item_type = 'products'
                items.quantity = str(json_data['quantity'])
            except:
                items.item_type = 'services'
                items.quantity = str(json_data['quantity'])

            items.item_id = items.create_item_id()

            items.id_service_product = item['id']
            items.cart_id = cart.cart_id
            items.price = item['price']

            items.sub_total = str(float(items.price) * int(items.quantity))

            cart.sub_total = str(float(cart.sub_total) + float(items.sub_total))
            cart.tax = str(0)
            cart.total = str(float(cart.sub_total) + float(cart.tax))


            cart.total_items = str(int(cart.total_items) + int(items.quantity))

            cart.put() 
            items.put() 

            # add product to product requests and then add service to service requests

            if items.item_type == 'products':
                this_request = ProductRequests()
                this_request = this_request.addProduct(product=item,uid=cart_owner_id,total=items.quantity)
            else:
                this_request = ServiceRequests() 
                this_request = this_request.addService(service=item,uid=cart_owner_id,total=items.quantity)
                

            items_request = Items.query(Items.cart_id == cart.cart_id)
            items_list = items_request.fetch()
            ser_items = []
            for item in items_list:
                ser_items.append(item.to_dict())
            cart = cart.to_dict()
            # let results = {status : true, cart_items : [], cart : {}, error: {} };
            response_data = {
                    'status' : 'True' , 
                    'cart_items': ser_items,
                    'cart' : cart,
                    'error' : {}
                    }

        elif 'user' in route:
            json_data = json.loads(self.request.body)
            logging.info('User Data')
            logging.info(json_data)

            this_user = User()
            this_user = this_user.addUser(json_user=json_data)
            if this_user != '':
                response_data = this_user.to_dict()
            else:
                status_int = 403
                response_data = {'message': 'user not found'}

        elif 'store' in route:
            json_data = json.loads(self.request.body)

            this_store = Store()
            this_store = this_store.addStore(store=json_data)
            if(this_store != ''):
                response_data = this_store.to_dict()
            else:
                status_int = 403
                response_data = {'message': 'store not stored'}

        elif 'transactions' in route:
            json_data = json.loads(self.request.body)

            this_transaction = Transactions()
            result = this_transaction.addTransaction(transaction=json_data)
            logging.info(this_transaction)

            response_data = this_transaction.to_dict()

        elif 'sms' in route:
            uid = route[len(route) - 1]

            user = User()
            this_user = user.getUser(uid)

            if ('send' in route) and (this_user != ''):
                sms_message = json.loads(self.request.body)
                sms = SMSMessage()

                # once the message is sent results will be returned
                # through a webhook
                results = sms.addSMSmessage(sms_message=sms_message)
                response_data = {}
                response_data = results.to_dict()

            elif ('contact-lists' in route) and (this_user != ''):
                json_contact_lists = json.loads(self.request.body)

                contacts_lists = ContactLists()
                results = contacts_lists.addList(contact_list=json_contact_lists)
                response_data = {}
                response_data = results.to_dict()

            elif ('smscontact' in route) and (this_user != ''):
                json_contact = json.loads(self.request.body)
                logging.info(json_contact)

                sms_contact = SMSContacts()
                results = sms_contact.addContact(contact=json_contact)

                contact_list = sms_contact.fetchContactsByListID(id=json_contact['list_id'])

                response_data = []

                for contact in contact_list:
                    response_data.append(contact.to_dict())

            else:
                status_int = 303
                response_data = {'message':'request not understood'}

        elif 'dashboard' in route:
            uid = route[len(route) - 1]

            admin_user_query = User.query(User.uid == uid)
            admin_user_list = admin_user_query.fetch()

            response_data = ''

            if len(admin_user_list) > 0:
                admin_user = admin_user_list[0]
            
                if ('contact' in route) and admin_user.is_admin :

                    if 'response' in route :
                        response_message = json.loads(self.request.body)

                        this_response = Response()
                        results = this_response.createResponse(response_data=response_message, admin_user=admin_user)
                        response_data = results.to_dict()
                    else:
                        status_int = 400
                        response_data = {'message': 'request could not be understood'}

                elif ('banking' in route) and admin_user.is_admin:

                    banking_details = json.loads(self.request.body)

                    this_banking = Banking()
                    results =  this_banking.addAdminBank(banking_details=banking_details)
                    if (results != ''):
                        response_data = results.to_dict()
                    else:
                        status_int = 401
                        response_data = {'message': 'error saving banking details'}

                else:
                    status_int = 400
                    response_data = {
                        'message': 'request could not be understood'}
            else:
                status_int = 400
                response_data = {
                    'message': 'request could not be understood'}

        else:
            status_int = 400
            response_data = {'message': 'the server cannot process this request'}


        self.response.headers['Content-Type'] = "application/json"
        self.response.status_int = status_int
        json_data = json.dumps(response_data)
        self.response.write(json_data)
Example #15
0
    def get(self):
        url_route = self.request.uri
        route = url_route.split("/")

        logging.info('ROUTE INFORMATION')
        logging.info(route)
        
        status_int = 200

        if 'categories' in route:

            category_requests = Categories.query()
            categories_list = category_requests.fetch()

            response_data = []

            for category in categories_list:
                response_data.append(category.to_dict())

        elif 'products' in route:
            
            id = str(route[len(route) - 1])
            router = str(route[len(route) - 2])
            request = str(route[len(route) - 3])

            logging.info('PRODUCT ID')
            logging.info(id)

            if id == 'products':

                products_requests = Products.query()
                products_list = products_requests.fetch()
                
                response_data = []
                for product in products_list:
                    response_data.append(product.to_dict())

            elif router == 'user':

                products_request = Products.query(Products.uid == id)
                products_list = products_request.fetch()

                response_data = []
                for product in products_list:
                    response_data.append(product.to_dict())

            # requests here equals product requests

            elif router == 'search':

                search_text = id
                products_request = Products.query()
                products_list = products_request.fetch()
                
                response_data = []

                for product in products_list:
                    if (product.product_name != None) and (search_text.lower() in product.product_name.lower()):
                        response_data.append(product.to_dict())
                    elif (product.description != None) and (search_text.lower() in product.description.lower()):
                        response_data.append(product.to_dict())
                    elif (product.price != None) and search_text.lower() in product.price.lower():
                        response_data.append(product.to_dict())
                    else:
                        pass                                                        

            elif request == 'requests':
                # /requests/${uid}/${id}
                uid = router

                # id in here is the same as product_id in productRequests 
                this_query = ProductRequests.query(ProductRequests.product_id == id)
                this_product_requests_list = this_query.fetch()

                                
                response_data = []

                for product_request in this_product_requests_list:
                    # this insures that it wont be possible to get product requests if you are not the owner of the product
                    if product_request.uid == uid:
                        response_data.append(product_request.to_dict())
                    else:
                        pass

            else :
                products_requests = Products.query(Products.id == id)
                products_list = products_requests.fetch()

                if len(products_list) > 0:
                    product = products_list[0]
                    response_data = product.to_dict()
                else:
                    status_int = 403
                    response_data = {'message':'product not found'}

        elif 'services' in route:
            id = str(route[len(route) - 1])
            router = str(route[len(route) - 2])

            # fetch list of services
            if id == 'services':
                services_requests = Services.query()
                services_list = services_requests.fetch()

                response_data = []
                for service in services_list:
                    response_data.append(service.to_dict())

            elif router == 'user':
                
                services_request = Services.query(Services.uid == id)
                services_list = services_request.fetch()

                response_data = []
                for service in services_list:
                    response_data.append(service.to_dict())

            elif router == 'search':
                search_text = id
                services_request = Services.query()
                services_list = services_request.fetch()

                response_data = []

                for service in services_list:
                    if (service.service_name != None) and (search_text.lower() == service.service_name.lower()):
                        response_data.append(service.to_dict())
                    elif (service.description != None) and (search_text.lower() == service.description.lower()):
                        response_data.append(service.to_dict())
                    elif (service.price != None) and (search_text.lower() == service.price.lower()):
                        response_data.append(service.to_dict())
                    else:
                        pass

                    
            else:
                # fetch a single service
                services_requests = Services.query(Services.id == id)
                services_list = services_requests.fetch()

                if len(services_list) > 0:
                    service = services_list[0]

                    response_data = service.to_dict()
                else:
                    status_int = 403
                    response_data = {'message':'service not found'}

        elif 'physical-address' in route:

            uid = route[len(route) - 1]

            physical_request = PhysicalAddress.query(PhysicalAddress.uid == uid)
            physical_list = physical_request.fetch()

            if (len(physical_list) > 0):
                physical_address = physical_list[0]
                response_data = physical_address.to_dict()
            else:
                status_int = 403
                response_data ={'message':'physical address not found'}

        elif 'contact-details' in route:

            uid = route[len(route) - 1]

            contact_details_request = ContactDetails.query(ContactDetails.uid == uid)
            contact_details_list = contact_details_request.fetch()

            if (len(contact_details_list) > 0):
                contact_details = contact_details_list[0]
                response_data = contact_details.to_dict()
            else:
                status_int = 403
                response_data = {'message': 'contact details not found'}

        elif 'cart' in route:
            uid = route[len(route) - 1]

            cart_request = Cart.query(Cart.uid == uid)
            cart_list = cart_request.fetch()

            if len(cart_list) > 0:
                cart = cart_list[0]                
                items_request = Items.query(Items.cart_id == cart.cart_id)
                items_list = items_request.fetch()
                cart_items = []
                for item in items_list:
                    cart_items.append(item.to_dict())
                cart = cart.to_dict()
                
                # let results = {status : true, cart_items : [], cart : {}, error: {} };
                response_data = {
                    'status': True,
                    'cart_items': cart_items,
                    'cart': cart,
                    'error': {}
                }

            else:
                status_int = 403
                response_data = {
                    'status': False,
                    'cart_items': [],
                    'cart': {},
                    'error': {'message':'cart items not found'}
                }

        elif 'user' in route:
            uid = route[len(route) - 1]

            this_user = User()
            this_user = this_user.getUser(uid=uid)
            if this_user != '':
                response_data = this_user.to_dict()
            else:
                status_int = 400
                response_data = {'message': 'user not found in the system'}

        elif 'store' in route:
            uid = route[len(route) - 1]

            this_store = Store()
            this_store = this_store.getStore(uid)

            if this_store != '':
                response_data = this_store.to_dict()
            else:
                status_int = 403
                response_data = {'message': 'store not found'}

        elif 'transactions' in route:
            uid = route[len(route) - 1]

            this_transactions  = Transactions()
            transactions_list = this_transactions.fetchTransactions(uid)
            response_data = []
            for transaction in transactions_list:
                response_data.append(transaction.to_dict())

        elif 'dashboard' in route:
            uid = str(route[len(route) - 1])

            this_user = User()
            user = this_user.getUser(uid=uid)

            if ('payments' in route) and user.is_admin:
                
                payments_requests = Transactions.query()
                payments_list = payments_requests.fetch()

                response_data = []
                for payment in payments_list:
                    response_data.append(payment.to_dict())

            elif ('contacts' in route) and user.is_admin:
                contacts_requests = Contact.query()
                contacts_list = contacts_requests.fetch()

                response_data = []
                for contact in contacts_list:
                    response_data.append(contact.to_dict())

            elif ('users' in route) and user.is_admin:

                users_requests = User.query()
                user_list = users_requests.fetch()

                response_data = []

                for user in user_list:
                    response_data.append(user.to_dict())

            elif 'banking' in route and user.is_admin:

                banking_requests = Banking.query(Banking.is_admin_account == True)
                banking_list = banking_requests.fetch()

                response_data = []

                for banking in banking_list:
                    response_data.append(banking.to_dict())


            else:
                status_int = 403
                response_data = {'message':'you are not authorized to access dashboard'}
                    
        elif 'sms' in route:
            uid = route[len(route) - 1]

            # TODO use cron jobs to synchronize
            # local bundles with bundles on sasms crud

            user = User()
            this_user = user.getUser(uid=uid)
            response_data = []
            if ('bundles' in route) and (this_user != ''):

                bundles = SMSBundles()
                results = bundles.fetchBundles()

                for bundle in results:
                    response_data.append(bundle.to_dict())

            elif ('contact-lists' in route) and (this_user != ''):

                contacts_list = ContactLists()
                results = contacts_list.getContactList(uid=uid)

                for contact_list in results:
                    response_data.append(contact_list.to_dict())
                    
            elif ('bylistname' in route) and (this_user != ''):

                list_name = route[len(route) - 2]

                this_contact = SMSContacts()
                contact_list = this_contact.getContactByListName(list_name=list_name)

                for contact in contact_list:
                    response_data.append(contact.to_dict())

            elif ('bycontactid' in route) and (this_user != ''):
                list_id = route[len(route) - 2]

                this_contact = SMSContacts()
                contact_list = this_contact.getContactsByContactID(id=list_id)

                for contact in contact_list:
                    response_data.append(contact.to_dict())
            elif ('byuid' in route) and (this_user != ''):
                this_contact = SMSContacts()
                contact_list = this_contact.getContactsByUserID(uid=uid)

                for contact in contact_list:
                    response_data.append(contact.to_dict())
                
            else:
                status = 303
                response_data = {'message':'request not understood'}

        elif 'chat-rooms' in route:
            uid = route[len(route) - 1]
            chat_id = route[len(route) - 2]
            user = User()
            this_user = user.getUser(uid=uid)
            response_data = {}
            if this_user != '':
                chat_room_instance = ChatRoom()
                chat_room = chat_room_instance.getChatRoom(chat_id=chat_id)

                chat_messages = []
                chat_users = []
                if chat_room != '':
                    messages_instance = ChatMessages()
                    messages = messages_instance.getChatMessages(chat_id=chat_id)

                    for message in messages:
                        chat_messages.append(message.to_dict())

                    chat_users_instance = ChatUsers()
                    users = chat_users_instance.getChatUsers(chat_id=chat_id)

                    for user in users:
                        chat_users.append(user.to_dict())
                
                response_data = {
                    'chat_id' : chat_id,
                    'created_by' : chat_room.created_by,
                    'messages' : chat_messages,
                    'users' : chat_users
                };

            else:
                status_int = 401
                response_data = {
                    'message': 'user not recognised'
                }



        elif 'news' in route:
            pass













        else:
            status_int = 400
            response_data = {'message': 'the server cannot process this request'}

        self.response.headers['Content-Type'] = "application/json"
        self.response.status_int = status_int
        json_data = json.dumps(response_data)
        self.response.write(json_data)
Example #16
0
def searchByItemName():
    transactions = Transactions()

    return transactions.searchByItemName(retrieveRequestFor('itemName', request))
Example #17
0
def cook():
    transactions = Transactions()

    return transactions.cook(retrieveRequestFor('ingredients', request).split(","))
Example #18
0
def test_decode_transaction_with_blockr(signed_tx_hex):
    from transactions import Transactions
    transactions = Transactions(testnet=True)
    decoded_tx = transactions.decode(signed_tx_hex)
    assert decoded_tx
Example #19
0
 def __init__(self, accounts, transactionfile):
     self.loginType = ""
     self.accounts = accounts
     self.deletedAccounts = []
     self.sessionWithdraw = 0
     self.transactions = Transactions(transactionfile)
Example #20
0
def test_get_block_info_with_blockr(block_hash):
    from transactions import Transactions
    transactions = Transactions(testnet=True)
    block_data = transactions.get_block_info(block_hash)
    assert block_data
Example #21
0
bc = BlockChain()

acout.generate_public_key()

acout.generate_zylus_key()

acout.generate_private_key()

ac2.generate_public_key()

ac2.generate_private_key()

ac2.generate_zylus_key()

transes = Transactions(acout, 10, ac2)

block1 = Block(1, transes, time(), 1)

bc.createblock(block1)

bc.mineblock(block1)

<<<<<<< HEAD
bc.printchain()
trans = Transactions("Phantom", "Zack", 999)
trans.generate_public_key()
trans.generate_private_key()

from blockchain import Block, BlockChain
=======
Example #22
0
def test_transaction_creation_via_create_with_blockr(alice, bob):
    from transactions import Transactions
    trxs = Transactions(testnet=True)
    assert trxs.testnet is True
    simple_transaction = trxs.create(alice, (bob, 6), min_confirmations=1)
    assert simple_transaction
Example #23
0
import os
import useAPI
import clean_transactions
from url_builder import build_url

import io
from matplot import plot_histogram
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from transactions import Transactions

app = Flask(__name__)
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY

# Need to declare this out here?
transactions = Transactions()

# # sample data
#     {
#         'hash': 'dummy hash',
#         'from': 'from 1',
#         'to': 'to 1',
#         'value' : '100',
#     },
#     {
#         'hash': 'dummy hash 2',
#         'from': 'from 2',
#         'to': 'to 2',
#         'value': '200',
#     }
# ]
Example #24
0
def test_init_transaction_class_with_non_suported_service():
    from transactions import Transactions
    with pytest.raises(Exception):
        Transactions(service='dummy')