Example #1
0
def login():
    ''' Login (create session) '''

    # Cleaning URL to get args being used by the next url
    args = request.args.to_dict()
    args.pop('next', None)
    args.pop('error', None)

    # Checking if there is already a valid session
    if 'user_id' in session and db.exists('CLIENT', 'id', session['user_id']):
        redirect(url_for(request.args.get('next'), **args))

    # request.form looks ugly and takes too much space...
    param = request.form
    keys = param.keys()
    required_keys = ['email', 'pass']

    # Checking for required parameters
    if not param or not check_keys(required_keys, keys):
        return redirect(url_for(request.args.get('next'), \
                                error = 'login_fails',
                                **args))

    # Super insecure authentication, don't try this outside localhost kids
    if db.exists('USER', ['email', 'password'], [ param['email'], param['pass'] ] ):
        session['user_id'] = db.get('USER', 'email', param['email'])['id']
    else:
        return redirect(url_for(request.args.get('next'), \
                            error = 'wrong_pass', \
                            **args))

    # Returning to origin
    return redirect(url_for(request.args.get('next'), **args))
Example #2
0
def test_exists():
    test_database = '___some_test_db___.db'

    print 'Testing exsits for case where database doesn\'t exist...',
    test1 = database.exists(test_database)
    if (test1 == False):
        print ('PASS')
    else:
        print ('FAIL')

    # Create an empty database
    with sqlite3.connect(test_database) as conn:
        pass

    print 'Testing exists for case where database exists...',
    test2 = database.exists(test_database)
    os.remove(test_database)

    if test2 == True:
        print 'PASS'
    else:
        print 'FAIL'
        return False

    return True
Example #3
0
def RegisterUser(username,email,password):
        #first of all check if the user is already present into the database
	if exists('user','email',email):
		d={}
		d['description']='the email is already registered'
		d['esit_register']=1
		return d
	
	if username==None:username=id_generator()
	if existsS('user','username',username):
                d={}
                d['description']='the username is already registered'
                d['esit_register']=3
                return d

	#if the user is not present...
	db=MySQLdb.connect(host=HOST,user=DBUSER,passwd=DBPASS,db=DBNAME, use_unicode=True,charset="utf8")
	#db=MySQLdb.connect(HOST,DBUSER,DBPASS,DBNAME)
        cursor=db.cursor(MySQLdb.cursors.DictCursor)
        sql="INSERT INTO user (username,email,password,active) VALUES ('%s','%s','%s',1);"%(username,email,password)
        userid=0
        try:
                cursor.execute(sql)
                userid=db.insert_id()
                db.commit()
        except:
                db.rollback()
        cursor.close()
        db.close()
	try:
		emailsend.sendemail(email)
	except Exception ,ems:
		ErrorLog("RegisterUser %s %s %s , exception:%s"%(username,email,password,ems))
Example #4
0
def LoginTwitter(username,email,twitterId,tokentwit):
        #first of all check if the user is already present into the database
        if exists('user','email',email):
                d={}
		d= ReturnUser(email)
		useruid=d['uid']
		SaveToken(token,1,useruid)
                #d['description']='the user is already registered'
                d['esit_register']=1
                return d
        #if the user is not present...
        db=MySQLdb.connect(host=HOST,user=DBUSER,passwd=DBPASS,db=DBNAME, use_unicode=True,charset="utf8")
	#db=MySQLdb.connect(HOST,DBUSER,DBPASS,DBNAME)
        cursor=db.cursor(MySQLdb.cursors.DictCursor)
        sql="INSERT INTO user (username,email,twitterid) VALUES ('%s','%s','%s');"%(username,email,twitterId)
        userid=0
        try:
                cursor.execute(sql)
                userid=db.insert_id()
                db.commit()
        except:
                db.rollback()
        cursor.close()
        db.close()

        d= ReturnUser(email)
        d['esit_register']=0
	
	useruid=d['uid']
        SaveToken(token,1,useruid)

        return d
Example #5
0
def update_client():
    ''' Updates Client Information
    ---
    put:
        description: Updates editable client information.
        tags:
            - User
        requestBody:
            required: true
            content:
              application/json:
                schema:
                  type: object
                  properties:
                    NAME:
                      type: string
                      description: Updated User Name.
                    NIF:
                      type: number
                      description: Updated User NIF.
        responses:
            200:
                description: A JSON containing the result of payment.
                content:
                    application/json:
                      schema:
                        properties:
                          SUCCESS:
                            type: boolean
            400:
                description: A JSON containing the ERROR that identifies the problem.
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''

    if 'user_id' in session and db.exists('USER', 'id', session['user_id']):
        # request.form looks ugly and takes too much space...
        param = request.json
        keys = param.keys()
        expected_keys = ['NAME', 'NIF']

        # Checking for required parameters
        if not param or not check_keys(expected_keys, keys):
            return jsonify({'ERROR': error_message('invalid_request')}), 400

        try:
            db.update('CLIENT', ['nif', 'name'], [param['NIF'], param['NAME']], 'id', session['user_id'])
        except Exception as e:
            print(e)
            return jsonify({'SUCCESS': False, 'ERROR': error_message('db_error')}), 200

        # Everything went well
        return jsonify({'SUCCESS': True}), 200

    return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200
Example #6
0
def new_account():
    # Checking if it came from a error redirect
    if request.args.get('error'):
        return render_template('create.html', error = error_message(request.args.get('error'))), 200

    if 'user_id' in session and db.exists('CLIENT', 'id', session['user_id']):
        return render_template('profile.html'), 200

    return render_template('create.html'), 200
Example #7
0
def register():
    # Cleaning URL to get args being used by the next url
    args = request.args.to_dict()
    args.pop('error', None)

    # Checking if there is already a valid session
    if 'user_id' in session and db.exists('CLIENT', 'id', session['user_id']):
        redirect(url_for(request.args.get('next'), **args))

    # request.form looks ugly and takes too much space...
    param = request.form
    keys = param.keys()
    required_keys = ['name', 'email', 'pass']

    # Checking for required parameters
    if not param or not check_keys(required_keys, keys):
        return redirect(url_for('new_account', \
                                error = 'register_fails',
                                **args))

    # Super insecure authentication, don't try this outside localhost kids
    if db.exists('USER', ['email'], [param['email']]):
        return redirect(url_for('new_account', \
                                error = 'user_exists',
                                **args))
    else:
        try:
            token = None
            while True:
                token = secrets.token_urlsafe(16)
                if not db.exists('USER', 'id', token):
                    break

            db.insert('USER', \
                ('id', 'email', 'password'), \
                ( token, param['email'], param['pass']) )
            db.insert('CLIENT', ('id', 'name'), (token, param['name']))
        except:
            return redirect(url_for('new_account'), \
                                    error = 'db_error',
                                    **args)
    # Returning to origin
    args.pop('next', None)
    return redirect(url_for(request.args.get('next'), **args))
Example #8
0
def delete_credit_card():
    ''' Turns Credit Card invisible for the user
    ---
    delete:
        description: Deletes credit card for the user (invisible)
        tags:
            - User
        requestBody:
            required: true
            content:
              application/json:
                schema:
                  type: object
                  properties:
                    ID:
                      type: number
                      description: ID of credit card to delete
        responses:
            200:
                description: A JSON containing the result of payment.
                content:
                    application/json:
                      schema:
                        properties:
                          SUCCESS:
                            type: boolean
            400:
                description: A JSON containing the ERROR that identifies the problem.
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''

    if 'user_id' in session and db.exists('USER', 'id', session['user_id']):
        # request.form looks ugly and takes too much space...
        param = request.json
        keys = param.keys()
        expected_keys = ['ID']

        # Checking for required parameters
        if not param or not check_keys(expected_keys, keys):
            return jsonify({'ERROR': error_message('invalid_request')}), 400

        try:
            db.update('CREDIT_CARD', ['visibility'], [0], 'id', param['ID'])
        except Exception as e:
            print(e)
            return jsonify({'SUCCESS': False, 'ERROR': error_message('db_error')}), 200

        # Everything went well
        return jsonify({'SUCCESS': True}), 200

    return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200
Example #9
0
def index():
    ''' Index page, simply returns a login form for now '''
    # Checking if it came from a error redirect
    if request.args.get('error'):
        return render_template('index.html', error = error_message(request.args.get('error'))), 200

    if 'user_id' in session and db.exists('CLIENT', 'id', session['user_id']):
        return render_template('profile.html'), 200

    return render_template('index.html'), 200
Example #10
0
def delete_checkout():
    ''' EditCheckout
    ---
    delete:
        description: Deletes the checkout
        tags:
            - Payment
        parameters:
            - in: path
              name: checkout_token
              schema:
                type: string
              required: true
              description: Checkout's ID value given when it is created.
        responses:
            200:
                description: A JSON containing the result of the proccess.
                content:
                    application/json:
                      schema:
                        properties:
                          SUCCESS:
                            type: boolean
            400:
                description: A JSON containing a ERROR that identifies the problem
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''
    # request.args looks ugly and takes too much space...
    args = request.args
    keys = args.keys()
    required_keys = ['checkout_token']

    # Checking for required arguments
    if not args or not check_keys(required_keys, keys):
        return jsonify({'ERROR': error_message('invalid_request')}), 400

    # Checking if checkout exists
    if not db.exists('CHECKOUT', 'id', args['checkout_token']):
        return jsonify({'ERROR': error_message('invalid_checkout')}), 400

    # Delete from database
    try:
        db.delete('CHECKOUT', 'id', args['checkout_token'])
    except Exception as e:
        print(e)
        return jsonify({'ERROR': error_message('db_error')}), 500

    # Everything went well
    return jsonify({'SUCCESS': True}), 200
Example #11
0
def add_credit_to_user(credit_card, user_id):
    '''
        Adds credit card to list of cards owner by the user
    '''
    # If credit_card is already related to user ignore
    if not db.exists('CREDIT_CARD', ['user_id', 'cc_number'], [user_id, credit_card['card-number']]):
        try:
            db.insert('CREDIT_CARD', ['cc_number', 'csv', 'expiration', 'owner_name', 'user_id'],
                       [credit_card['card-number'], credit_card['cvc'], credit_card['exp'], credit_card['card-owner'], user_id])
        except Exception as e:
            print(e)
            return False

    return True
Example #12
0
def SaveToken(uid,fbt):
	try:
        	if database.existsS('accesstoken','user_uid',uid)==False:
                	mapI={}
                	mapI['accesstoken']=fbt
                	mapI['user_uid']=uid
                	database.Insert('accesstoken',mapI)
        	else:
                	mapex={}
                	mapex['user_uid']=uid
                	mapex['accesstoken']=fbt
                	if database.exists('accesstoken',mapex)==False:
                        	database.QueryS("UPDATE accesstoken SET accesstoken='%s' WHERE user_uid='%s';"%(fbt,uid))
	except Exception, f:
		ErrorLog("SaveToken , error: %s"%f)
Example #13
0
def pay():
    '''
        Payment page, the client comes to this page after clicking "Pay" on the merchant page
    '''

    # request.args looks ugly and takes too much space...
    args = request.args
    keys = args.keys()
    required_keys = ['checkout_token']

    # Checking for required arguments
    if not args or not check_keys(required_keys, keys):
        return redirect(url_for('index', error = "invalid_checkout"))

    # Getting row from database of the checkout
    checkout = db.get('CHECKOUT', 'id', args['checkout_token']);

    # Checking if checkout is valid
    if not checkout:
        return redirect(url_for('index', error = "invalid_checkout"))

    # Get items and merchant
    items = db.get_all('ITEM', 'checkout', args['checkout_token']);
    merchant = db.get('MERCHANT', 'id', checkout['merchant'])

    # Checking if checkout was already paid
    if checkout['status'] != "CREATED":
        return redirect(checkout['return_url'] + "?checkout_token=" + args['checkout_token'] )

    # Checking if user is already logged in
    login_form = False if 'user_id' in session and db.exists('CLIENT', 'id', session['user_id']) else True

    # Checking if there is error message to be shown
    error = False if not request.args.get('error') else request.args.get('error')

    return render_template('pay.html', amount = "{:.2f}".format(checkout['amount']),
                                       items = items,
                                       currency = checkout['currency'] if  checkout['currency'] else 'EUR',
                                       login_form = login_form,
                                       merchant_logo = merchant['logo'],
                                       merchant_name = merchant['name'],
                                       error = error_message(error) ), 200
Example #14
0
def add_address_to_user(address, user_id):
    '''
        Adds billing address to user
    '''

    # Checking if such BILLING_ADDRESS already exists
    if not db.exists('BILLING_ADDRESS', \
    ['first_name', 'last_name', 'country', 'city', 'address', 'post_code', 'phone', 'user_id'],\
    [address['first_name'], address['last_name'], address['country'], \
    address['city'], address['address'], address['post_code'], address['phone'], user_id]):
            try:
                return db.insert('BILLING_ADDRESS',\
                 ['first_name', 'last_name', 'country', 'city', 'address', 'post_code', 'phone', 'user_id'], \
                 [address['first_name'], address['last_name'], address['country'], \
                 address['city'], address['address'], address['post_code'], address['phone'], user_id])
            except Exception as e:
                print(e)
                return False

    return True
Example #15
0
def update_billing_address():
    ''' Updates Client Billing Address Information
    ---
    put:
        description: Updates editable billing address information.
        tags:
            - User
        requestBody:
            required: true
            content:
              application/json:
                schema:
                  type: object
                  properties:
                     ID:
                        type : number
                        description : ID of the billing address to be updated
                     FIRST_NAME:
                        type : string
                        description : First Name of the billing address.
                     LAST_NAME:
                        type : string
                        description : Last Name of the billing address.
                     COUNTRY:
                        type : string
                        description : Country of the billing address.
                     ADDRESS:
                        type : string
                        description : Street name and number of the billing address.
                     POST_CODE:
                        type : string
                        description : Post code of the billing address.
                     CITY:
                        type : string
                        description : City of the billing address.
                     PHONE:
                        type : number
                        description : Phone of the billing address.
        responses:
            200:
                description: A JSON containing the result of payment.
                content:
                    application/json:
                      schema:
                        properties:
                          SUCCESS:
                            type: boolean
            400:
                description: A JSON containing the ERROR that identifies the problem.
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''

    if 'user_id' in session and db.exists('USER', 'id', session['user_id']):
        # request.form looks ugly and takes too much space...
        param = request.json
        keys = param.keys()
        expected_keys = ['ID', 'FIRST_NAME', 'LAST_NAME', 'COUNTRY', 'ADDRESS', \
                            'POST_CODE', 'CITY', 'PHONE']

        # Checking for required parameters
        if not param or not check_keys(expected_keys, keys):
            return jsonify({'ERROR': error_message('invalid_request')}), 400

        try:
            db.update('BILLING_ADDRESS',\
                ['first_name', 'last_name', 'country', 'city', 'address', 'post_code', 'phone'] \
                ,[param['FIRST_NAME'], param['LAST_NAME'], param['COUNTRY'], param['CITY'], \
                    param['ADDRESS'], param['POST_CODE'], param['PHONE'] ], 'id', param['ID'])
        except Exception as e:
            print(e)
            return jsonify({'SUCCESS': False, 'ERROR': error_message('db_error')}), 200

        # Everything went well
        return jsonify({'SUCCESS': True}), 200

    return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200
Example #16
0
def proccess_payment():
    '''
        After the client fills all the information the payment is proccessed
    '''

    # request.args looks ugly and takes too much space...
    args = request.args
    keys = args.keys()
    required_keys = ['checkout']

    # Checking for required arguments
    if not args or not check_keys(required_keys, keys):
        return redirect(url_for('index', error = "invalid_checkout"))

    # Making sure user is logged in
    if not 'user_id' in session or not db.exists('CLIENT', 'id', session['user_id']):
        return redirect(url_for('pay', error = "not_logged", checkout = args['checkout']))


    # Checking if checkout is valid
    if not db.exists('CHECKOUT', 'id', args['checkout']):
        return redirect(url_for('index', error = "invalid_checkout"))

    param = request.form.to_dict()
    keys = param.keys()
    required_keys = ['card-number', 'exp', 'cvc', 'card-owner', 'first_name', \
                    'old-id', 'using-old', 'old-id-ba', 'using-old-ba',\
                    'last_name', 'country', 'city', 'address', 'post_code', 'phone']

    # Checking for required parameters
    if not param or not check_keys(required_keys, keys):
        return redirect(url_for('pay', checkout_token = args['checkout'], error = "invalid_request"))

    # If using a new credit card add it to database
    if ( param['using-old'] == "false" ):
        # Create a relation of the credit card with the user
        if not add_credit_to_user(param, session['user_id']):
            return redirect(url_for('pay', checkout_token = args['checkout'], error = "db_error" ))
    # Else find the old credit card
    else:
        cc = db.get('CREDIT_CARD',['id', 'user_id'], [ param['old-id'], session['user_id'] ])
        param['card-number'] = cc['cc_number']

    # If using a new billing address add it to database
    billing_id = None
    if ( param['using-old-ba'] == "false" ):
        # Create a relation of the billing address with the user
        billing_id = add_address_to_user(param, session['user_id'])
        if not billing_id:
            return redirect(url_for('pay', checkout_token = args['checkout'], error = "db_error" ))
    # Else use old billing address
    else:
        billing_id = param['old-id-ba']

    # Save information about payment in the checkout
    return_url = prepare_checkout(args['checkout'], param['card-number'], billing_id, session['user_id'])

    # Checking if checkout was successfully updated
    if not return_url:
        return redirect(url_for('pay', checkout_token = args['checkout'], error = "db_error"))

    # Redirect to the URL given by the merchant
    return redirect(return_url + "?checkout_token=" + args['checkout'] )
Example #17
0
def numrgo(gpdm,dt):
    db = Mysql.getConn()
    dm = ''
    if gpdm[0] == '0':
        dm = 'sz' + gpdm 
    else:
        dm ='sh' + gpdm 
    fd = "%s-%s-%s" % (dt[0:4],dt[4:6],dt[6:8]) #yyyy-MM-dd
    try:
        turl = "http://stock.gtimg.cn/data/index.php?appn=detail&action=timeline&c=%s"
        durl = "http://stock.gtimg.cn/data/index.php?appn=detail&action=data&c=%s&p=%s"
        
        try:
            req = urllib2.Request(turl % dm)
            res_data = urllib2.urlopen(req)
            res = res_data.read()
            dd = None
            jj =0
            for line in res.split('|'):
                try:
                    durl_g = durl % (dm,jj)
                    hash_durl = hashlib.md5(durl_g).hexdigest()
                    if database.exists(hash_durl):
                        dres = database.get(hash_durl)
                    else:
                        req = urllib2.Request(durl_g)
                        res_data = urllib2.urlopen(req)
                        dres = res_data.read()
                        database.set(hash_durl,dres)
                    dres = dres.split(',')[1]
                    dres = dres[1:-2]
                    dres = dres.split('|')
                    dim = len(dres)
                    c = np.empty([dim,6],float)
                    ff = 0
#                     print dres
                    for l1 in dres:
                        ll2 =  l1.split('/')
                        c[ff,0] = bstimetosn(ll2[1])
                        c[ff,1]= float(ll2[2])
                        c[ff,2]=float(ll2[3])
                        c[ff,3]=float(ll2[4])
                        c[ff,4]=float(ll2[5])
                        c[ff,5]=bstonum(ll2[6])
                        ff = ff + 1
                    if dd is not None:
                        dd = np.vstack((dd,c))
                    else:
                        dd = c
                                
                except Exception,e:
                    print e
                jj = jj + 1
        except Exception,e:
            pass
        c = dd #np.loadtxt(fullfilename,delimiter='\t', skiprows=5,converters={0:bstimetosn,4:bstonum}, usecols=(0,1,2,3,4), unpack=False)
        f = np.reshape(c[...,0],(len(c[...,0]),1))
        c = np.hstack((c,f))
        d = np.fabs(np.diff(c[...,0]))
        d = np.hstack(([0],d))
        c[...,0] = d

        bze = np.sum(c[c[...,5]>0][...,4])
        bzl = np.sum(c[c[...,5]>0][...,3])
        sze = np.sum(c[c[...,5]<0][...,4])
        szl = np.sum(c[c[...,5]<0][...,3])
        pjbj = bze/bzl/ 100
        pjsj = sze/szl/ 100
        pjjbz = pjbj/pjsj
        pjjcz = pjbj - pjsj
        pjbl = np.mean(c[c[...,5]>0][...,3])
        pjsl = np.mean(c[c[...,5]<0][...,3])
        pjlbz = pjbl/ pjsl
        pjlcz = pjbl - pjsl
        zxpl = np.sum(c[c[...,5]==0][...,3])
        zxpe = np.sum(c[c[...,5]==0][...,4])
        zxpbz = zxpl/(zxpl + bzl + szl)
        fzxpbz = 1.0 - zxpbz
        zxpebz = zxpe/(zxpe + bze + sze)
        
        ptp = np.ptp(c[...,1])
        min = np.min(c[...,1])
        h= ptp * 0.618
        h= h + min
        m= ptp * 0.382
        m = m + min
        tc = c[c[...,1]> h]
        gjbde = np.sum(tc[tc[...,5]> 0][...,4])
        gjbdl = np.sum(tc[tc[...,5]> 0][...,3])
        gjbdj = gjbde/gjbdl/100
        gjbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        gjbdebz = gjbde/(zxpe + bze + sze)
        gjbdlbz = gjbdl/(zxpl + bzl + szl)
        gjbdfsbz = gjbdfs/daysecond 
        
        tc = c[c[...,1]> h]
        gjsde = np.sum(tc[tc[...,5]< 0][...,4])
        gjsdl = np.sum(tc[tc[...,5]< 0][...,3])
        gjsdj = gjsde/gjsdl/100
        gjsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        gjsdebz = gjsde/(zxpe + bze + sze)
        gjsdlbz = gjsdl/(zxpl + bzl + szl)
        gjsdfsbz = gjsdfs/daysecond 
        
        tc = c[c[...,1]< h]
        tc = tc[tc[...,1]>m]
        zjbde = np.sum(tc[tc[...,5]> 0][...,4])
        zjbdl = np.sum(tc[tc[...,5]> 0][...,3])
        zjbdj = zjbde/zjbdl/100
        zjbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        zjbdebz = zjbde/(zxpe + bze + sze)
        zjbdlbz = zjbdl/(zxpl + bzl + szl)
        zjbdfsbz = zjbdfs/daysecond 
        
        tc = c[c[...,1]< h]
        tc = tc[tc[...,1]>m]
        zjsde = np.sum(tc[tc[...,5]< 0][...,4])
        zjsdl = np.sum(tc[tc[...,5]< 0][...,3])
        zjsdj = zjsde/zjsdl/100
        zjsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        zjsdebz = zjsde/(zxpe + bze + sze)
        zjsdlbz = zjsdl/(zxpl + bzl + szl)
        zjsdfsbz = zjsdfs/daysecond 
        
        tc = c[c[...,1]< m]
        djbde = np.sum(tc[tc[...,5]> 0][...,4])
        djbdl = np.sum(tc[tc[...,5]> 0][...,3])
        djbdj = djbde/djbdl/100
        djbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        djbdebz = djbde/(zxpe + bze + sze)
        djbdlbz = djbdl/(zxpl + bzl + szl)
        djbdfsbz = djbdfs/daysecond 
        
        tc = c[c[...,1]< m]
        djsde = np.sum(tc[tc[...,5]< 0][...,4])
        djsdl = np.sum(tc[tc[...,5]< 0][...,3])
        djsdj = djsde/djsdl/100
        djsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        djsdebz = djsde/(zxpe + bze + sze)
        djsdlbz = djsdl/(zxpl + bzl + szl)
        djsdfsbz = djsdfs/daysecond 
        
        
        lh = (pjbl + pjsl) * 0.618
        lm = (pjbl + pjsl) * 0.382

        tc = c[c[...,3]> lh]
        glbde = np.sum(tc[tc[...,5]> 0][...,4])
        glbdl = np.sum(tc[tc[...,5]> 0][...,3])
        glbdj = glbde/glbdl/100
        glbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        glbdebz = glbde/(zxpe + bze + sze)
        glbdlbz = glbdl/(zxpl + bzl + szl)
        glbdfsbz = glbdfs/daysecond  
        
        tc = c[c[...,3]> lh]
        glsde = np.sum(tc[tc[...,5]< 0][...,4])
        glsdl = np.sum(tc[tc[...,5]< 0][...,3])
        glsdj = glsde/glsdl/100
        glsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        glsdebz = glsde/(zxpe + bze + sze)
        glsdlbz = glsdl/(zxpl + bzl + szl)
        glsdfsbz = glsdfs/daysecond 
        
        tc = c[c[...,3]< lh]
        tc = tc[tc[...,3]>lm]
        zlbde = np.sum(tc[tc[...,5]> 0][...,4])
        zlbdl = np.sum(tc[tc[...,5]> 0][...,3])
        zlbdj = zlbde/zlbdl/100
        zlbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        zlbdebz = zlbde/(zxpe + bze + sze)
        zlbdlbz = zlbdl/(zxpl + bzl + szl)
        zlbdfsbz = zlbdfs/daysecond 
        
        tc = c[c[...,3]< lh]
        tc = tc[tc[...,3]>lm]
        zlsde = np.sum(tc[tc[...,5]< 0][...,4])
        zlsdl = np.sum(tc[tc[...,5]< 0][...,3])
        zlsdj = zlsde/zlsdl/100
        zlsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        zlsdebz = zlsde/(zxpe + bze + sze)
        zlsdlbz = zlsdl/(zxpl + bzl + szl)
        zlsdfsbz = zlsdfs/daysecond

        tc = c[c[...,3]< lm]
        dlbde = np.sum(tc[tc[...,5]> 0][...,4])
        dlbdl = np.sum(tc[tc[...,5]> 0][...,3])
        dlbdj = dlbde/dlbdl/100
        dlbdfs = np.sum(tc[tc[...,5]> 0][...,0]) 
        dlbdebz = dlbde/(zxpe + bze + sze)
        dlbdlbz = dlbdl/(zxpl + bzl + szl)
        dlbdfsbz = dlbdfs/daysecond 
        
        tc = c[c[...,3]< lm]
        dlsde = np.sum(tc[tc[...,5]< 0][...,4])
        dlsdl = np.sum(tc[tc[...,5]< 0][...,3])
        dlsdj = dlsde/dlsdl/100
        dlsdfs = np.sum(tc[tc[...,5]< 0][...,0])
        dlsdebz = dlsde/(zxpe + bze + sze)
        dlsdlbz = dlsdl/(zxpl + bzl + szl)
        dlsdfsbz = dlsdfs/daysecond
        
        zs = c[0,1] -c[0,2]
    #     print 'zs',zs
        jk = c[0,1]
    #     print 'jk',jk
        zg = np.max(c[...,1])
    #     print 'zg',zg
        zd = np.min(c[...,1])
    #     print 'zd',zd
        zf = np.sum(c[...,2])
    #     print 'zf',zf
        zfz = zf/zs * 100
    #     print 'zfz',zfz
        js = c[-1,1]
        gjec = (gjbdebz - gjsdebz) * 100
        gjjc = gjbdj - gjsdj 
        gjlc = (gjbdlbz - gjsdlbz) * 100
        gjsc = (gjbdfsbz - gjsdfsbz) * 100
        
        zjec = (zjbdebz - zjsdebz) * 100 
        zjjc = zjbdj - zjsdj
        zjlc = (zjbdlbz - zjsdlbz) * 100
        zjsc = (zjbdfsbz - zjsdfsbz) * 100
         
        djec = (djbdebz -djsdebz) * 100
        djjc = djbdj - djsdj 
        djlc = (djbdlbz - djsdlbz) * 100
        djsc = (djbdfsbz - djsdfsbz) * 100
        
        glec = (glbdebz - glsdebz) * 100
        gljc = glbdj - glsdj
        gllc = (glbdlbz - glsdlbz) * 100
        glsc = (glbdfsbz - glsdfsbz) * 100
        
        zlec = (zlbdebz - zlsdebz ) * 100
        zljc = zlbdj - zlsdj
        zllc = (zlbdlbz - zlsdlbz) * 100
        zlsc = (zlbdfsbz - zlsdfsbz) * 100
        
        dlec = (dlbdebz - dlsdebz) * 100 
        dljc = dlbdj - dlsdj
        dllc = (dlbdlbz - dlsdlbz) * 100
        dlsc = (dlbdfsbz - dlsdfsbz) * 100
        
        try:
            cursor = db.cursor()            
            sql = "DELETE FROM FSCJMXHZ_MEM WHERE DM='%s' AND JYRQ='%s';" % (gpdm,fd)
            cursor.execute(sql)
    
        except Exception,e:
            pass
Example #18
0
def create_checkout():
    ''' Create/Update Checkout
    ---
    put:
        description: Updates the Checkout information. Updating the information will replace all the original information.
        tags:
            - Payment
        parameters:
            - in: path
              name: checkout_token
              schema:
                type: string
              required: true
              description: Checkout's ID value given when it is created.
        requestBody:
            required: true
            content:
              application/json:
                schema:
                  type: object
                  properties:
                    AMOUNT:
                      type: number
                      description: Total amount to be paid by the client. This value must be equal to the sum of the item's price.
                    MERCHANT:
                      type: string
                      description: ID that identifies merchant in the system.
                    RETURN_URL:
                      type: string
                      description: URL to where the client in redirect if the payment is successful
                    CANCEL_URL:
                      type: string
                      description: URL to where the client in redirect if the payment is cancelled
                    CURRENCY:
                      type: string
                      description: Three characters currency code. Default value is 'EUR'. [https://www.xe.com/iso4217.php]
                      default : EUR
                    ITEMS:
                      type: array
                      items:
                            type : object
                            properties:
                                NAME:
                                    type : string
                                    description: Checkout item's name. Default value is "Item". This parameter is required if you fill any other item parameter.
                                    default : Item
                                PRICE:
                                    type : number
                                    description: Checkout item's price. Default value is the one given in 'AMOUNT'. This parameter is required if you fill any other item parameter.
                                QUANTITY:
                                    type : integer
                                    description: Checkout item's quantity. Default value is 1. This parameter is not required at any situation.
                                    default : 1
                                IMAGE:
                                    type : string
                                    description: Checkout item's image URL. It must be from your domain. This parameter is not required at any situation.
                                URL:
                                    type : string
                                    description: Checkout item's URL to your domain. This parameter is not required at any situation.
                  required:
                    - AMOUNT
                    - MERCHANT
                    - RETURN_URL
                    - CANCEL_URL
        responses:
            201:
                description: A JSON containing result of the proccess
                content:
                    application/json:
                      schema:
                        properties:
                          SUCCESS:
                            type: boolean
            400:
                description: A JSON containing a ERROR that identifies the problem
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    post:
        description: Creates a checkout.
        tags:
            - Payment
        requestBody:
            required: true
            content:
              application/json:
                schema:
                  type: object
                  properties:
                    AMOUNT:
                      type: number
                      description: Total amount to be paid by the client. This value must be equal to the sum of the item's price.
                    MERCHANT:
                      type: string
                      description: ID that identifies merchant in the system.
                    RETURN_URL:
                      type: string
                      description: URL to where the client in redirect if the payment is successful
                    CANCEL_URL:
                      type: string
                      description: URL to where the client in redirect if the payment is cancelled
                    CURRENCY:
                      type: string
                      description: Three characters currency code. Default value is 'EUR'. [https://www.xe.com/iso4217.php]
                      default : EUR
                    ITEMS:
                      type: array
                      items:
                            type : object
                            properties:
                                NAME:
                                    type : string
                                    description: Checkout item's name. Default value is "Item". This parameter is required if you fill any other item parameter.
                                    default : Item
                                PRICE:
                                    type : number
                                    description: Checkout item's price. Default value is the one given in 'AMOUNT'. This parameter is required if you fill any other item parameter.
                                QUANTITY:
                                    type : integer
                                    description: Checkout item's quantity. Default value is 1. This parameter is not required at any situation.
                                    default : 1
                                IMAGE:
                                    type : string
                                    description: Checkout item's image URL. It must be from your domain. This parameter is not required at any situation.
                                URL:
                                    type : string
                                    description: Checkout item's URL to your domain. This parameter is not required at any situation.
                  required:
                    - AMOUNT
                    - MERCHANT
                    - RETURN_URL
                    - CANCEL_URL
        responses:
            201:
                description: A JSON containing a TOKEN that identifies the Checkout
                content:
                    application/json:
                      schema:
                        properties:
                          TOKEN:
                            type: string
            400:
                description: A JSON containing a ERROR that identifies the problem
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''
    # request.form looks ugly and takes too much space...
    param = request.json
    keys = param.keys()
    expected_keys = ['AMOUNT', 'RETURN_URL', 'CANCEL_URL', 'MERCHANT', 'CURRENCY', 'ITEMS']

    # Checking for required parameters
    if not param or not check_keys(expected_keys[:-2], keys):
        return jsonify({'ERROR': error_message('invalid_request')}), 400

    # Cheking if URI are valid
    if not uri_validator(param['RETURN_URL']) or not uri_validator(param['CANCEL_URL']):
        return jsonify({'ERROR': error_message('invalid_url')}), 400

    # Checking if amount is a valid number
    if not is_number(param['AMOUNT']):
        return jsonify({'ERROR': error_message('invalid_amount')}), 400

    # Checking if merchant exists
    if not db.exists('MERCHANT', 'id', param['MERCHANT']):
        return jsonify({'ERROR': error_message('invalid_merchant')}), 400

    # If request is POST a.k.a creating a new checkout
    if request.method == 'POST':
        while True:
            token = secrets.token_urlsafe(16)
            if not db.exists('CHECKOUT', 'id', token):
                break
    # Else updating existing one
    else:
        if(delete_checkout()[1] == 200):
            token = request.args['checkout_token']
        else:
            return jsonify({'ERROR': error_message('invalid_checkout')}), 400

    # Sorting keys according to db insertion order
    sorted(keys, key=lambda x: expected_keys.index(x))

    # Checking for optional parameters
    if not 'CURRENCY' in keys:
        param['CURRENCY'] = None

    # Inserting new checkout to database
    try:
        db.insert('CHECKOUT', \
            ('id', 'amount', 'return_url', 'cancel_url', 'merchant', 'currency'), \
            tuple( [token] + [param[k] for k in expected_keys[:-1]] ) )
    except Exception as e:
        print(e)
        return jsonify({'ERROR': error_message('db_error')}), 500

    # Adding items to checkout if given by the merchant
    if 'ITEMS' in keys and not add_items(param['ITEMS'], token, param['AMOUNT']):
        delete_checkout()
        return jsonify({'ERROR': error_message('add_items')}), 400

    # Everything went well, returning token for new checkout or true if it was an update
    return (jsonify({'CHECKOUT_TOKEN': token}), 201) if request.method == 'POST' else (jsonify({'SUCCESS': True}), 200)
Example #19
0
def become_merchant():
    if 'user_id' in session and db.exists('USER', 'id', session['user_id']):
        client = db.get('CLIENT', 'id', session['user_id']);
        db.insert('MERCHANT', ('id', 'name'), (session['user_id'], client['name']))
    return jsonify({'SUCCESS': True}), 200
Example #20
0
def get_user():
    ''' Get all information from user
    ---
    get:
        description: Returns user information such as name, email, credit cards and billing address's.
        tags:
            - User
        responses:
            200:
                description: A JSON containing user information.
                content:
                    application/json:
                      schema:
                        type: object
                        properties:
                          MERCHANT:
                            type: object
                            properties:
                                NAME:
                                    type : string
                                    description : Name of the merchant company.
                                DOMAIN:
                                    type : string
                                    description : Web domain of the merchant. Used for validation of items URL.
                                LOGO:
                                    type : string
                                    description : URI for merchant logo.
                                TOKEN:
                                    type : string
                                    description : Token for API access of merchant.
                          BUYER:
                            type: object
                            properties:
                                ID:
                                    type : string
                                    description : Checkout ID value given when it is created.
                                NAME:
                                    type : number
                                    description : Total amount of checkout, must be equal to the sum of the items.
                                NIF:
                                    type : string
                                    description : Current status of checkout. (CREATED/READY/PAID)
                                CREDIT_CARDS:
                                    type: array
                                    description : User credit card list.
                                    items:
                                        type: object
                                        properties:
                                           NUMBER:
                                              type : string
                                              description : Last digits of the credit card number.
                                           EXP:
                                              type : string
                                              description : Expiration data of the credit card.
                                BILLING_ADDRESS:
                                    type: array
                                    description : User billing address list.
                                    items:
                                        type: object
                                        properties:
                                           FIRST_NAME:
                                              type : string
                                              description : First Name of the billing address.
                                           LAST_NAME:
                                              type : string
                                              description : Last Name of the billing address.
                                           COUNTRY:
                                              type : string
                                              description : Country of the billing address.
                                           ADDRESS:
                                              type : string
                                              description : Street name and number of the billing address.
                                           POST_CODE:
                                              type : string
                                              description : Post code of the billing address.
                                           CITY:
                                              type : string
                                              description : City of the billing address.
                                           PHONE:
                                              type : number
                                              description : Phone of the billing address.

            400:
                description: A JSON containing a ERROR that identifies the problem
                content:
                    application/json:
                      schema:
                        properties:
                          ERROR:
                            type: string
    '''

    if 'user_id' in session and db.exists('USER', 'id', session['user_id']):
        # Getting info from user
        user = db.get('USER', 'id', session['user_id']);
        client = db.get('CLIENT', 'id', session['user_id']);
        merchant = db.get('MERCHANT', 'id', session['user_id']);

        # Getting credit card info
        cc_wallet = []
        cc_db = db.get_all('CREDIT_CARD', 'user_id', session['user_id'])
        for cc in cc_db:
            if cc['visibility']:
                cc_wallet.append({'NUMBER': '*' * 12 + str(cc['cc_number'])[-4:], 'EXP': cc['expiration'], 'ID' : cc['id']})
        # Getting Billing Address info
        billing_address_db = db.get_all('BILLING_ADDRESS', 'user_id', session['user_id'])
        billing_address = [ dict(i) for i in billing_address_db if i['visibility']]
        for i in billing_address:
            i.pop('user_id')
            i.pop('visibility')
            for k in list(i):
                i[k.upper()] = i.pop(k)

        # Building info
        info = {'BUYER' : { 'NAME': client['name'], 'EMAIL': user['email'], 'NIF': client['nif'],
                            'CREDIT_CARDS': cc_wallet,
                            'BILLING_ADDRESS': billing_address } }

        if merchant :
            info['MERCHANT'] = { 'NAME' : merchant['name'], 'DOMAIN' : merchant['domain'],
                          'LOGO' : merchant['logo'], 'TOKEN' : merchant['id'] }

        return jsonify(info);

    return jsonify({'SUCCESS': False, 'ERROR': error_message('no_login')}), 200