Exemplo n.º 1
0
    def create(self, request, **kwargs):
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            user = save_user(request.data, UserPermissions.IS_CUSTOMER)
            city = City(**request.data["city"])
            customer = Customer(
                name=request.data["name"],
                type=UserType.CUSTOMER,
                lastName=request.data["lastName"],
                address=request.data["address"],
                identityDoc=request.data["identityDoc"],
                homePhone=request.data["homePhone"],
                cellPhone=request.data["cellPhone"],
                email=request.data["email"],
                city=city,
                user=user,
            )

            customer.save()
            return Response(
                {
                    "status": "SUCCESS",
                    "msg_status": "Cliente creado satisfactoriamente. Puede ingresar con su nueva contrasena.",
                }
            )
        else:
            messages = []
            make_error(serializer.errors.values(), messages)
            return Response({"status": "FAILURE", "msg_status": messages})
Exemplo n.º 2
0
def login(request):
    info = ''
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            
            if email == '*****@*****.**':
                if password == 'password':
                    request.session['is_admin'] = True
                    request.session['uid'] = '-1'
                    request.session['user'] = '******'
                    info = '登陆成功'
                else :
                    info = '密码错误!'
            elif not Customer.contain_email(email):
                info = 'EMAIL不存在!'
            elif not Customer.is_auth(email, password):
                info = '密码错误!'
            else:
                customer = Customer.objects.get(email = email)
                request.session['is_admin'] = False
                request.session['uid'] = customer.customer_id
                request.session['user'] = email
                info = '登录成功'
    form = LoginForm()
    return render(request, 'login.html', {'form' : form, 'info' : info})
Exemplo n.º 3
0
 def GetCustomerData(self,dataPost):
     customerData = Customer()
     customerData.email = dataPost['email']
     customerData.name_last = dataPost['lastName']
     customerData.name_first = dataPost['firstName']
     
     return customerData
Exemplo n.º 4
0
 def test_point_deletion(self):
     result = Customer.get_points_for('sudhirurl')
     start_count = len(result)
     first_point = result[0]
     Point.delete_point(first_point['key'], self.sudhir_gmail)
     new_result = Customer.get_points_for('sudhirurl')
     self.assertEqual(len(new_result), start_count - 1)
     self.assertFalse(self.find(new_result, first_point))
Exemplo n.º 5
0
    def test_get_current_user_url(self):
        url = Customer.get_url_by_user(self.sudhir_gmail)
        self.assertEqual(url, 'sudhirurl')

        url = Customer.get_url_by_user(users.User('*****@*****.**'))
        self.assertFalse(url)
        
        url = Customer.get_url_by_user(None)
        self.assertFalse(url)
Exemplo n.º 6
0
def create_customer(user):
    s1 = Customer(user=user,
            name=user.username,
            address= default_address,
            city= default_city,
            state= default_state,
            email=user.email,
            creation_date=datetime.datetime.now(),
            active=True)
    s1.save()
	def createCustomer(self,request):
		c_id = Customer.allocate_ids(size=1)[0]
		c_key = ndb.Key(Customer, c_id)
		data = {field.name: getattr(request, field.name) for field in request.all_fields()}
		data['key'] = c_key
		query = Customer.query().filter(Customer.mobileNumber == data['mobileNumber'])
		entity = query.get()
		if entity:
			raise Exception('unique_property must have a unique value!')
		Customer(**data).put()
		return self._copyCustomerToForm(c_key.get())
Exemplo n.º 8
0
def login(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            if not Customer.contain_email(email):
                return render(request, 'login.html', {'form' : form , 'non_exist_email' : True})
            elif not Customer.is_auth(email, password):
                return render(request, 'login.html', {'form' : form , 'wrong_password' : True})
            else:
                print "login successfully"
    form = LoginForm()
    return render(request, 'login.html', {'form' : form})
Exemplo n.º 9
0
 def post(self):
     if not self.is_logged_in():
         self.redirect(LOGIN_PAGE_URL)
     else:
         machine_id = self.get_argument('machine_id')
         timezone = self.get_argument('timezone')
         deactivation_entry_code = self.get_argument('deactivation_entry_code')
     
         customer = Customer.get_by_key_name(self.get_current_username())
         activation_credentials = ActivationCredentials.get_all_for_customer_and_machine_id(customer=customer, machine_id=machine_id)
         activation_credentials_list = []
         for credentials in activation_credentials:
             credentials_id = credentials.key().id()
             serial_number = self.get_argument('serial_number_ac_%d' % credentials_id)
             activation_code = self.get_argument('activation_code_ac_%d' % credentials_id)
             if serial_number == credentials.serial_number and activation_code == credentials.activation_code:
                 credentials.deactivation_code = self.get_argument('deactivation_code_ac_%d' % credentials_id)
                 credentials.deactivation_entry_code = deactivation_entry_code
                 credentials.timezone = timezone
                 credentials.when_deactivated = datetime.utcnow()
                 activation_credentials_list.append(credentials)
             else:
                 pass  # Error.
         db.put(activation_credentials_list)
         self.redirect('/dashboard')
Exemplo n.º 10
0
    def post(self):
        if not self.is_logged_in():
            self.redirect(LOGIN_PAGE_URL)
        else:
            customer = Customer.get_by_key_name(self.get_current_username())
            customer.first_name = self.get_argument('first_name')
            customer.last_name = self.get_argument('last_name')
            customer.timezone = self.get_argument('timezone')

            landline_key = self.get_argument('landline_key')
            landline = db.get(db.Key(landline_key))
            landline.number = self.get_argument('landline_number')

            mobile_key = self.get_argument('mobile_key')
            mobile = db.get(db.Key(mobile_key))
            mobile.number = self.get_argument('mobile_number')

            location_key = self.get_argument('location_key')
            location = db.get(db.Key(location_key))

            location.city = self.get_argument('city')
            location.country = self.get_argument('country')
            location.state_or_province = self.get_argument('state_or_province')
            location.area_or_suburb = self.get_argument('area_or_suburb')
            location.street_name = self.get_argument('street_name')
            location.zip_code = self.get_argument('zip_code')
            
            db.put([customer, mobile, landline, location])

            self.get()
Exemplo n.º 11
0
def login_api(request):
    info = ''
    status_code = -1
    customer = None
    if request.method == "GET":
        form = request.GET
        email = form['email']
        password = form['password']            
        if not Customer.contain_email(email):
            status_code = 1
        elif not Customer.is_auth(email, password):
            status_code = 2
        else:
            customer = Customer.objects.get(email = email)
            status_code = 0
    return render(request, 'auth.json', {'status_code' : status_code, 'customer' : customer})
Exemplo n.º 12
0
    def _handler(self, account_slug, customer_slug, post=False):
        user = users.get_current_user()
        if user:
            account = Account.all()\
                .filter('user ='******'slug =', account_slug).get()

            customer = Customer.all()\
                .filter('account =', account).filter('slug =', customer_slug).get()

            if post:
                form = CustomerForm(instance=customer, data=self.request.POST)
                if form.is_valid():
                    # Save the data, and redirect to the view page
                    form.save()
                    self.redirect(account.get_absolute_url())
            else:
                form = CustomerForm(instance=customer)

            path = os.path.join(os.path.dirname(__file__), 'templates/customer_details.html')
            self.response.out.write(template.render(path, {
                'account': account,
                'customer': customer,
                'form': form,
                'user': user,
                'logout_url': users.create_logout_url("/")
            }))
        else:
            self.redirect(users.create_login_url(self.request.uri))
Exemplo n.º 13
0
	def update_customer_credit_debit_total(self,data,c_key,credit):
		x = Customer.query(ancestor = data['custId'])
		obj = c_key.get()
		obj.debit = obj.debit + data['orderPrice']
		obj.credit = obj.credit + credit
		obj.total = obj.debit - obj.credit
		obj.put()
Exemplo n.º 14
0
def registration(request):
    if request.user.is_authenticated():
        # ideal, but not created yet, going with homepage
        #return HttpResponseRedirect('/profile/')
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        #fills out with whatever was posted
        form = RegistrationForm(request.POST)
        # runs all clean methods in form
        if form.is_valid():
            try: #customer exists
                cusAlreadyExists = User.objects.get(username=
                                form.cleaned_data['username'])
                username_taken = True
                context = {'form': form, 'username_taken': username_taken}
                return render_to_response('register.html', context,
                                context_instance=RequestContext(request))
            except User.DoesNotExist: #customer did not exist
                user = User.objects.create_user(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'])
                user.save()
                addr = Address(
                    AddressLineOne = form.cleaned_data['street'],
                    City = form.cleaned_data['city'],
                    State = form.cleaned_data['state'],
                    ZIPCode = form.cleaned_data['zipcode']
                )
                addr.save()
                customer = Customer(user=user, Address=addr,
                    FirstName = form.cleaned_data['firstName'],
                    LastName = form.cleaned_data['lastName']
                )
                customer.save()
                customer = authenticate(username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'])
                login(request, customer)
                return HttpResponseRedirect('/')
        else:
            return render_to_response('register.html', {'form': form},
                                    context_instance=RequestContext(request))
    else:
        #user not submitting the form, send blank form
        form = RegistrationForm()
        context = {'form': form}
        return render_to_response('register.html', context,
                                    context_instance=RequestContext(request))
Exemplo n.º 15
0
 def __init__(self, user, *args, **kwargs):
     super(IncomeForm, self).__init__(*args, **kwargs)
     self.fields['customer'].query = Customer.all().filter('user ='******'name').fetch(1000)
     self.fields['category'].query = Category.all()\
                                             .filter('user ='******'type =', 'Receita')\
                                             .order('name').fetch(1000)
Exemplo n.º 16
0
 def post(self):
     machine_id = self.get_argument('machine_id')
     customer = Customer.get_by_key_name(session.get_current_username())
     credentials = ActivationCredentials.get_all_active_for_customer_and_machine_id(
         customer=customer,
         machine_id=machine_id)
     self.set_header('Content-Type', 'application/json')
     self.write(json.dumps(len(credentials) > 0))
Exemplo n.º 17
0
	def getCustomerList(self,request):
		c = []
		query1 = Customer.query()
		for q in query1:
			setattr(q,'custId',q.key)
			c.append(self._copyCustomerTotalDetailToForm(q))
								
		return CustomerList(customerList=c)
Exemplo n.º 18
0
    def test_point_editing(self):
        result = Customer.get_points_for('sudhirurl')
        start_count = len(result)
        new_point_dict = dict(lat=7.0, lon=7.0, title="seven")
        new_point_key = Point.create_point(self.sudhir, new_point_dict).key().__str__()
        result = Customer.get_points_for('sudhirurl')

        self.assertEqual(len(result), start_count + 1)
        self.assertTrue(self.find(result, new_point_dict))

        new_point_dict = dict(lon=7.0, lat=8.0, title='seveneight')
        Point.edit(new_point_key, new_point_dict, self.sudhir_gmail)
        new_results = Customer.get_points_for('sudhirurl')

        self.assertEqual(len(new_results), start_count + 1)
        self.assertTrue(self.find(new_results, new_point_dict))
        self.assertRaises(db.BadValueError, Point.edit, new_point_key, dict(lon=2345, lat=3, title='invalid values'), self.sudhir_gmail)
Exemplo n.º 19
0
 def test_setting_points_for_user(self):
     mom = models.Customer(user=users.User('*****@*****.**'), url='momurl')
     mom.put()
     confirmation = Point.create_point(mom, dict(lat=34.678, lon= -44.3456))
     self.assertTrue(confirmation)
     result = Customer.get_points_for('momurl')
     self.assertEqual(len(result), 1)
     self.assertEqual(result.count(dict(lat=34.678, lon= -44.3456, title='Untitled', key=str(confirmation.key()))), 1) 
Exemplo n.º 20
0
 def clean_email(self):
     email = self.cleaned_data.get('email')
     name = self.cleaned_data.get('name',u'').strip()
     if name == noname:
         email='*****@*****.**'
     if email=='':
         raise forms.ValidationError("如果您要留名的话请输入邮箱地址")
  
     try:
         exist=Customer.objects.filter(name=name)[0]
     except:
         c=Customer(name=name,email=email)
         c.save()
         return email
     if exist.email != email:
         raise forms.ValidationError("邮箱与此用户名不匹配")
         return email
     return email
Exemplo n.º 21
0
    def test_get(self):
        c = Customer(name='foobar', sites=["foo.com", "bar.co.uk"])
        self.session.add(c)
        self.session.commit()

        b = Customer.get(c.id)
        self.assertEqual(c.id,    b.id)
        self.assertEqual(c.name,  b.name)
        self.assertEqual(c.sites, b.sites)
Exemplo n.º 22
0
 def save2db(self, details):
     
     for p in details:
         result = Customer.objects.filter(name__exact = p.get(helper.SHPDDataFile.NAME), 
                                          custom_no__exact= p.get(helper.SHPDDataFile.CUSTOMER_NO), 
                                          branch_name__exact = p.get(helper.SHPDDataFile.BRANCH))
         if len(result) == 1:
             'update'
             customer = result[0]
             customer.card_no = p.get(helper.SHPDDataFile.CARD_NO)
         else:
             'insert'
             customer = Customer(name=p.get(helper.SHPDDataFile.NAME), 
                                 custom_no = p.get(helper.SHPDDataFile.CUSTOMER_NO), 
                                 branch_name = p.get(helper.SHPDDataFile.BRANCH), 
                                 card_no = p.get(helper.SHPDDataFile.CARD_NO), 
                                 mobile=p.get(helper.SHPDDataFile.MOBILE))
         customer.save()
    def register(self, request, username, password, password_again):

        if password_again != password:
            raise Exception("Passwords don't match")

        user = User(username=username)
        user.set_password(password)
        try:
            user.save()
        except:
            raise Exception("Email already taken")

        customer = Customer(user=user)
        customer.save()

        self.login(request, username, password)

        return customer
Exemplo n.º 24
0
 def get(self):
     if not self.is_logged_in():
         self.redirect(LOGIN_PAGE_URL)
     else:
         customer = Customer.get_by_key_name(self.get_current_username())
         subscriptions = []
         for order in customer.orders:
             subscriptions.append(order.subscription)
         self.render('unsubscribe.html', subscriptions=subscriptions)
Exemplo n.º 25
0
 def save(self, user):
     try:	
         data = user.get_profile()
     except:
         data = Customer(user=user)
         
     print 'Inside save method of UserRegForm'
     
     data.first_name = self.cleaned_data["first_name"]
     data.last_name = self.cleaned_data["last_name"]
     data.address = self.cleaned_data["address"]
     data.city = self.cleaned_data["city"]
     data.zip = self.cleaned_data["zip"]
     data.date_of_birth = self.cleaned_data["date_of_birth"]
     data.save()
Exemplo n.º 26
0
 def post(self):
     if not self.is_logged_in():
         self.redirect(LOGIN_PAGE_URL)
     else:
         customer = Customer.get_by_key_name(self.get_current_username())
         if customer.is_password_correct(self.get_argument('old_password')):
             p = hash_password(self.get_argument('new_password'))
             customer.password_hash = p[0]
             customer.password_salt = p[1]
             customer.put()
         self.redirect('/dashboard')
Exemplo n.º 27
0
def register(request):
    """
    Save account info into db for customer and barber
    :param request: member raw_post_data should be raw json string,
                     with key username, password, gender, role
    :return: "success": save successfully
    """
    req = json.loads(request.body)
    usn = req['username']
    pwd = req['password']
    gd = req['gender']

    if cmp(req['role'], 'Customer') == 0:
        c = Customer(username=usn, password=pwd, gender=gd)
        c.save()
        return HttpResponse("success")
    else:
        b = Barber(username=usn, password=pwd, gender=gd)
        b.save()
        return HttpResponse("success")
Exemplo n.º 28
0
 def get(self):
     self.response.content_type = 'application/json'
     c = Customer.all().get()
     obj = {
         'name': "%s %s" % (c.first_name, c.last_name),
         'email': c.email,
         'orders': []
     }
     for o in c.orders:
         obj['orders'].append(o.record)
     self.response.write(json.encode(obj))
Exemplo n.º 29
0
def  register(request):
	register = Customer(firstname 	= 	request.POST.get('firstName'),
						lastname 	= 	request.POST.get('lastName'),
						username 	= 	request.POST.get('userName'),
						password 	= 	request.POST.get('password'),
						contactno 	= 	request.POST.get('contactNo'))
	register.save()
	custId = register.custid

	addAccount = Account(customerid = custId,
						 balance= request.POST.get('balance'))

	addAccount.save()
	# cust_id = res[0].id
	# return HttpResponse(cust_id)
	#return render(request,"myprojects/welcome.html")
	t 		= 	get_template("myprojects/sucess.html")
	text 	= 	'Registered Sucessfully'
	c 		= 	RequestContext(request, { 'text' : text } )
	return HttpResponse(t.render(c))
Exemplo n.º 30
0
 def post(self):
     email = self.get_argument('login-email')
     password = self.get_argument('login-password')
     customer = Customer.get_by_key_name(email)
     if customer:
         if customer.is_password_correct(password):
             self.do_login(email)
             self.redirect('/dashboard')
         else:
             self.redirect('/?error=login_failed')
     else:
         self.redirect('/?error=login_failed')
Exemplo n.º 31
0
    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        customer = Customer.query(
            Customer.first_name == self.first_name.data,
            Customer.last_name == self.last_name.data).get()
        if customer:
            self.first_name.errors.append(
                'Customer with name - {} {} already exists'.format(
                    self.first_name.data, self.last_name.data))
            return False
        self.customer = customer

        return True
Exemplo n.º 32
0
def importFromXLS():
    import xlrd
    customList = xlrd.open_workbook("list.xls")
    worksheet = customList.sheet_by_name("Sheet1")

    for i in range(9, 3582):
        if worksheet.cell(i, 9).value != "":
            city = worksheet.cell(i, 9).value
        if worksheet.cell(i, 7).value != "":
            uniqueCode = worksheet.cell(i, 3).value
            customer = worksheet.cell(i, 7).value
            address = worksheet.cell(i, 14).value
            customerObject = Customer()
            customerObject.cName = customer
            customerObject.address = address
            customerObject.city = city
            customerObject.usn = uniqueCode
            customerObject.save()
Exemplo n.º 33
0
def populate():
    x = [["*****@*****.**", "Giusto Aloia", "Singer", "acoustic", "Turin", "Via Volto San Luca 15",     "10020", 45, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1460723237483-7a6dc9d0b212.jpeg"],
    ["*****@*****.**", "Paolo Selvaggio", "Singer", "pop", "Turin", "Via Giberti 101", "10080",     400, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1463453091185-61582044d556.jpeg"],
    ["*****@*****.**", "Leontina Biancardi", "Singer", "acoustic", "Turin", "Via Enrico Fermi 15",     "10027", 35, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1474959783111-a0f551bdad25.jpeg"],
    ["*****@*****.**", "Giona Bellomo", "Singer", "acoustic", "Turin", "Via Adua 94", "10091", 30,     "https://spoint.s3-sa-east-1.amazonaws.com/photo-1492562080023-ab3db95bfbce.jpeg"],
    ["*****@*****.**", "Irma Pittaluga",     "Stand-up Comedy",'', "Turin", "Via Volto San Luca 134", "10086", 100, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1493666438817-866a91353ca9.jpeg"],
    ["*****@*****.**", "Susanna Farro", "Singer", "rock", "Turin", "Via Giberti 25", "10080", 60,     "https://spoint.s3-sa-east-1.amazonaws.com/photo-1494790108377-be9c29b29330.jpeg"],
    ["*****@*****.**", "Pio Carnevale", "Singer", "acoustic", "Turin", "Via Volto San Luca 119", "10099",     39, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1499996860823-5214fcc65f8f.jpeg"],
    ["*****@*****.**", "Floro Scordato", "Singer", "jazz", "Turin", "Via del Pontiere 58", "10050",     70, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1506794778202-cad84cf45f1d.jpeg"],
    ["*****@*****.**", "Sebastiana Airaldi", "Singer", "rock", "Milan", "Via Nazario Sauro 140",     "20020", 20, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1512310604669-443f26c35f52.jpeg"],
    ["*****@*****.**", "Andreina Sessa", "Singer", "rock", "Milan", "Via San Pietro Ad Aram 72",     "20080", 25, "https://spoint.s3-sa-east-1.amazonaws.com/photo-1524504388940-b1c1722653e1.jpeg"],
    ["*****@*****.**", "Orsola Natale", "Singer", "pop", "Rome", "Via Longhena 75", "00047", 650,     "https://spoint.s3-sa-east-1.amazonaws.com/photo-1534751516642-a1af1ef26a56.jpeg"],
    ["*****@*****.**", "Giuseppina Padovano", "Stand-up Comedy", "pop", "Rome",     "Via Colonnello Galliano 5", "00020", 220,     "https://spoint.s3-sa-east-1.amazonaws.com/photo-1557555187-23d685287bc3.jpeg"],
    ["*****@*****.**", "Loretta Rocco", "Singer", "pop", "Rome", "Via Longhena 82", "00040", 120,     "https://spoint.s3-sa-east-1.amazonaws.com/photo-1593697821252-0c9137d9fc45.jpeg"]]

    for performer in x:
        password = '******'

        password_hash = bcrypt.generate_password_hash(password).encode('utf-8')
        newuser = User(email=performer[0], password=password_hash, role="Performer")

        db.session.add(newuser)
        db.session.commit()

        birthday = '20-02-1999'
        birthday = datetime.strptime(birthday, '%d-%m-%Y')

        newperformer = Performer(email=performer[0], user=newuser, name=performer[1], category=performer[2], genre=performer[3], birthday=birthday,
                                 cost_per_hour=performer[7], fiscal_code=performer[6], address=performer[5], search_city=performer[4], profile_pic_url=performer[8])

        db.session.add(newperformer)
        db.session.commit()

    password_hash = bcrypt.generate_password_hash(password).encode('utf-8')
    newuser = User(email='*****@*****.**', password=password_hash, role="Customer")

    db.session.add(newuser)
    db.session.commit()

    newcustomer = Customer(email='*****@*****.**', user=newuser, name='Professor',
                           fiscal_code="10129", address='Corso Duca degli Abruzzi, 24', profile_pic_url='https://scontent.fgru5-1.fna.fbcdn.net/v/t1.0-9/17309045_192522311236382_5190942424822553922_n.png?_nc_cat=109&ccb=3&_nc_sid=09cbfe&_nc_ohc=TYzPv6VGpxwAX9p0x4E&_nc_ht=scontent.fgru5-1.fna&oh=2157905807786214bfa4f02fa0bdf939&oe=605DBB98')

    db.session.add(newcustomer)
    db.session.commit()

    return "Everything populated"
Exemplo n.º 34
0
def get_single_animal(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            a.id animal_id,
            a.name animal_name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id,
            l.name location_name,
            l.address location_address,
            c.name customer_name,
            c.id customer_id,
            c.address
        FROM animal a
        JOIN location l
            ON l.id = a.location_id
        JOIN customer c
            ON c.id = a.customer_id
        WHERE a.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an animal instance from the current row
        animal = Animal(data['animal_id'], data['animal_name'], data['breed'],
                        data['status'], data['location_id'],
                        data['customer_id'])

        location_object = Location(data['location_id'], data['location_name'],
                                   data['location_address'])
        animal.location = location_object.__dict__

        customer = Customer(data['customer_id'], data['customer_name'],
                            data['address'])
        animal.customer = customer.__dict__

        return json.dumps(animal.__dict__)
Exemplo n.º 35
0
def register():
	error = None
	if request.method == "POST":
		if not request.form['username']:
			error = 'You have to enter a username'
		elif not request.form['password']:
			error = 'You have to enter a password'
		else:
			cust = Customer(request.form['username'], generate_password_hash(request.form['password']))
			db.session.add(cust)
			db.session.commit()
			db.session.flush()

			flash("Welcome " + request.form['username'] + "! ")
			flash("You have successfully registered for an account!")
			session['cust_id'] = cust.user_id # Allows the session to remember user is logged in
	return render_template('register.html', error=error)
Exemplo n.º 36
0
def get_single_animal(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute("""
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id,
            l.name location_name,
            l.address location_address,
            c.name customer_name,
            c.address customer_address,
            c.email customer_email,
            c.password customer_password
        FROM Animal a
        JOIN Location l
            ON l.id = a.location_id
        JOIN Customer c
            ON c.id = a.customer_id
        WHERE a.id = ?
        """, ( id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an animal instance from the current row
        animal = Animal(data['id'], data['name'], data['breed'],
                            data['status'], data['location_id'],
                            data['customer_id'])
        # Create a Location instance from the current row
        location = Location(data['id'], data['location_name'], data['location_address'],)
        # Create a Location instance from the current row
        customer = Customer(data['id'], data['customer_name'], data['customer_address'], data['customer_email'], data['customer_password'])
        # Add the dictionary representation of the location to the animal
        animal.location = location.__dict__
        # Add the dictionary representation of the location to the animal
        animal.customer = customer.__dict__

        return json.dumps(animal.__dict__)
Exemplo n.º 37
0
def comp_request(user):
    flag = 0
    requests = Transactions.select().where(
        (Transactions.sender_acc == user.acc_num) & (Transactions.done == 0))
    if not requests.exists():
        print("No pending requests")
        dummy = input("Press any key")
    else:
        while True:
            os.system("clear")
            table = PrettyTable(
                ['Id', 'Request by Acc No', 'Amount', 'Comments'])
            for each_request in requests:
                table.add_row([
                    each_request.id, each_request.receiver_acc,
                    each_request.amount,
                    str(each_request.comment)[:25]
                ])
            print(table)
            if flag == 1:
                print("Inavlid entry!")
                flag = 0
            if flag == 2:
                print("Transaction amount exceeds available balance!")
            choice_id = input("Choose by ID: ")
            choice = Transactions.select().where(Transactions.id == choice_id)
            if not choice.exists():
                flag = 1
            else:
                choice = choice.get()
                if choice.amount > user.balance:
                    flag = 2
                    continue
                withdraw(user,
                         f"Tsfr to {choice.receiver_acc}",
                         trans_type=1,
                         withdraw_am=choice.amount)
                receiver = Customer.get(
                    Customer.acc_num == choice.receiver_acc)
                deposit(receiver,
                        f"Tsfr by {user.acc_num}",
                        trans_type=1,
                        deposit_am=choice.amount)
                choice.done = 1
                choice.save()
                break
Exemplo n.º 38
0
 def get(self, room_id):
     try:
         room = Room.get(id=room_id)
         customers = Customer.select().join(Booking).join(Room).where(Room.id == room_id)
         customers = map(lambda customer: model_to_dict(
             customer,
             append_attrs={'url': self.reverse_url('customer', customer.id)}),
             customers)
         room = model_to_dict(
             room,
             append_attrs=dict(customers=customers)
             )
         self.set_response(dict(room=room))
     except Room.DoesNotExist:
         self.set_response(
             {'message': 'A room with id #{} not found'.format(room_id)},
             status=404)
Exemplo n.º 39
0
def importFromXLS1():
    import xlrd
    customList = xlrd.open_workbook("VVM STOCKIEST LIST.XLS")
    worksheet = customList.sheet_by_name("Sheet1")

    for i in range(5, 707, 6):
        code = worksheet.cell(i, 1).value
        customer = worksheet.cell(i, 3).value

        address1 = worksheet.cell(i + 1, 3).value
        address2 = worksheet.cell(i + 2, 3).value
        address3 = worksheet.cell(i + 3, 3).value
        city = worksheet.cell(i + 4, 3).value
        customerObject = Customer()
        customerObject.cName = customer
        customerObject.address = address1 + " " + address2 + " " + address3
        customerObject.city = city
        customerObject.usn = code
        customerObject.save()
Exemplo n.º 40
0
def importFromXLS6():
    import xlrd
    customList = xlrd.open_workbook("ALL STOCKIEST.xlsx")
    worksheet = customList.sheet_by_name("MARG ERP 9+ Excel Report")

    for i in range(5, 58):
        customer = worksheet.cell(i, 1).value
        city = worksheet.cell(i, 2).value
        customerObject = Customer()
        customerObject.cName = customer
        customerObject.city = city
        customerObject.save()
Exemplo n.º 41
0
 def test_get_start_and_end(self):
     customer = Customer(name='Teemu Teekkari',
                         email='teemu.teekkari@aalto fi')
     date = QtCore.QDate.currentDate()
     resource = Resource(name="Resource1", resource_type="ROOM")
     for x in range(8, 19):
         start_time = QtCore.QTime(x, 0)
         end_time = QtCore.QTime(x + 1, 0)
         start = QtCore.QDateTime(date, start_time)
         end = QtCore.QDateTime(date, end_time)
         new_reservation = Reservation(customer=customer,
                                       resource=resource,
                                       start=start,
                                       end=end)
         self.db.save(new_reservation)
     (first, last) = self.db.get_start_and_end(date)
     self.assertEqual(first, 8)
     self.assertEqual(last, 20)
Exemplo n.º 42
0
def create_customer(current_user):

    if not current_user.admin:
        return jsonify({'message': 'Have no permission!'})

    data = request.get_json()

    #Current UTC time
    now_utc = datetime.datetime.now(timezone('UTC'))
    #Convert to Singapore time zone
    now_singapore = now_utc.astimezone(singapore)
    #Create new customer
    new_customer = Customer(name=data['name'],
                            dob=data['dob'],
                            updated_at=now_singapore)
    db.session.add(new_customer)
    db.session.commit()
    return jsonify({'message': 'New Customer created'})
Exemplo n.º 43
0
def add_customers():
    form = CustomerForm(request.form)
    error = None
    if form.validate():
        customer = Customer(form.first_name.data, form.last_name.data,
                            form.email.data, form.age.data)
        flash('You sucessfully added a new customer!')
        session.add(customer)
        session.commit()
        return redirect(url_for('customers'))
    else:
        error = "Fields are not filled correctly!"
        return render_template('customer_form.html',
                               form=form,
                               method="POST",
                               action="/add",
                               error=error,
                               submit_text="Save")
Exemplo n.º 44
0
def contact_message():
    contact_form = ContactForm()
    customer = Customer(name=contact_form.name.data,
                        email=contact_form.email.data,
                        phone=contact_form.phone.data,
                        company=contact_form.company.data)
    if not contact_form.validate_on_submit():
        customer.registered == False
        db.session.add(customer)
        db.session.commit()
        return redirect(request.referrer)
    else:
        db.session.add(customer)
        db.session.commit()
        return "message sent"
    content = render_template('contact_confirmation.html',
                              contact_form=contact_form)
    return content
Exemplo n.º 45
0
 def get(self, customer_id):
     fields = self.get_only_fields()
     try:
         rooms = Room.select().join(Booking).where(Booking.customer_id == customer_id)
         rooms = map(lambda item: model_to_dict(
             item,
             append_attrs={'url': self.reverse_url('room', item.id)},
             exclude=[Booking.customer]),
             rooms)
         customer = model_to_dict(
             Customer.get(id=customer_id),
             append_attrs=dict(rooms=rooms),
             only=fields)
         self.set_response(dict(customer=customer))
     except Customer.DoesNotExist:
         self.set_response(
             {'message': 'A customer with id #{} not found'.format(customer_id)},
             status=404)
Exemplo n.º 46
0
def logout():
    global user_logged
    user_logged = False
    global user_name

    Session = sessionmaker(bind=engine)
    session = Session()
    customer_id = Customer.get_id_by_username(user_name)
    res = session.query(Cart).filter(Cart.customer_id == customer_id).all()
    if res:
        for elem in res:
            session.delete(elem)
            session.flush()
            session.commit()

    session.close()
    user_name = "Not Logged"
    return render_template("main_page.html", user_logged=user_logged, user_name=user_name)
Exemplo n.º 47
0
def create_customer(jwt):
    body = request.get_json()

    if body is None:
        abort(422)

    customer = Customer()

    customer.name = body.get('name')
    customer.phone = body.get('phone')
    customer.email = body.get('email')

    customer.insert()

    return jsonify(
        {
            'customer': customer.format(),
            'success': True
        }
    )
Exemplo n.º 48
0
def users():

    email = request.json.get('email')
    user = User.query.filter_by(email=email).first()
    if user:
        return "This email is already registered"

    password_hash = bcrypt.generate_password_hash(request.json.get('password')).encode('utf-8')
    role = request.json.get('role')
    name = request.json.get('name')
    fiscal_code = request.json.get('fiscal_code')
    address = request.json.get('address')
    profile_pic_url = "ABC"

    if request.json.get('profile_pic_url'):
        profile_pic_url = request.json.get('profile_pic_url')

    newuser = User(email=email, password=password_hash, role=role)
    db.session.add(newuser)
    db.session.commit()

    if role == 'Performer':
        category = request.json.get('category')
        genre = "None"
        if request.json.get('genre'):
            genre = request.json.get('genre')
        cost_per_hour = request.json.get('cost_per_hour')
        birthday = request.json.get('birthday')
        birthday = datetime.strptime(birthday, '%d-%m-%Y')
        search_city = request.json.get('search_city')
        newperformer = Performer(email=email, user=newuser, name=name, category=category, genre=genre, birthday=birthday,
                                 cost_per_hour=cost_per_hour, fiscal_code=fiscal_code, address=address, search_city=search_city,
                                 profile_pic_url=profile_pic_url)
        db.session.add(newperformer)
        performer_schema = PerformerSchema()
        output = performer_schema.dump(newperformer).data
    if role == 'Customer':
        newcustomer = Customer(email=email, user=newuser, name=name,
                               fiscal_code=fiscal_code, address=address, profile_pic_url=profile_pic_url)
        db.session.add(newcustomer)
        customer_schema = CustomerSchema()
        output = customer_schema.dump(newcustomer).data
    db.session.commit()
    return jsonify(output)
Exemplo n.º 49
0
def customers(self):
    # -------------------------
    # List all customers
    # -------------------------
    try:
        customers = Customer().list_all_customers()

        if customers is None:
            app.logger.info('Customers table is empty?')
            abort(422)

        return render_template(
            'grocery/customers.html', data=customers,
            nickname=session[conf_profile_key]['nickname'] if
            'POSTMAN_TOKEN' not in request.headers and
            'test_permission' not in request.headers else 'Guest')
    except BaseException:
        app.logger.info('An error occurred. Customers not available')
        abort(422)
Exemplo n.º 50
0
def api_customer_insert():
    new_customer = request.get_json()
    customer = Customer(id=new_customer['id'],
                        firstname=new_customer['firstname'],
                        surname=new_customer['surname'],
                        phone=new_customer['phone'],
                        city=new_customer['city'],
                        street=new_customer['street'])
    db.session.add(customer)
    db.session.commit()
    customer_json = {
        "id_customer": customer.id,
        "name_customer": customer.firstname,
        "surname_customer": customer.surname,
        "phone_customer": customer.phone,
        "city_customer": customer.city,
        "street_customer": customer.street
    }
    return jsonify(customer_json)
Exemplo n.º 51
0
def add_customer():
    """ Renders Customer Add page

    :return: add_customer.html
    """
    if request.method == "GET":
        return render_template("add_customer.html")
    company = request.form["company"]
    last_name = request.form["last_name"]
    first_name = request.form["first_name"]
    address_line_1 = request.form["address_line_1"]
    address_line_2 = request.form["address_line_2"]
    city = request.form["city"]
    state = request.form["state"]
    zip_code = float(request.form["zip_code"])
    new_customer = Customer(company, last_name, first_name, address_line_1, address_line_2, city, state, zip_code)
    db.session.add(new_customer)
    db.session.commit()
    return redirect("/view_customers")
Exemplo n.º 52
0
    def test_put(
        self,
        db,
        sample_data,
        test_client,
        endpoint,
        model_id,
        data,
        fail,
        expected_status
    ):
        try:
            response = test_client.put(
                endpoint.format(model_id),
                data=json.dumps(data),
                content_type="application/json"
            )

        except ValueError:
            if fail:
                assert True
            else:
                assert False

        if expected_status in (STATUS_OK, STATUS_NOT_FOUND):
            # check for expected status
            assert response.status_code == expected_status, "endpoint did not \
                return expected status: status {0}: expected_status {1}"\
                    .format(response.status_code, expected_status)

            # make sure its valid json
            data = json.loads(response.data)
            assert data == response.json

            # the customer model can't intiate with
            # websites so remove if present
            if "websites" in data:
                del data["websites"]

            # check response contains model
            model = Customer(**data)
            # validate data against schema
            CustomerSchema().load(model)
Exemplo n.º 53
0
def remove_product(email_or_uuid: str, product_uuid: str, credentials: HTTPBasicCredentials = Depends(assert_credentials)):
    '''
    Remove a product for customer wishlist.
    If all validation succeed, return code 204.
    If not, return a validation error on api or code 404.
    '''

    customer = MongoCustomer.get_customer(email_or_uuid)

    if customer is None:
        return JSONResponse(status_code=404, content={"message": "Customer not found"})

    if customer.check_product(product_uuid):
        new_products = [product for product in customer.products if str(product.uuid) != product_uuid]
        customer.products = new_products
        customer.save()
        return JSONResponse(status_code=204, content={"message": "Product deleted!"})

    return JSONResponse(status_code=404, content={"message": "Product not found for this customer!"})
Exemplo n.º 54
0
 def create_customer(self,
                     stripe_id=None,
                     email=None,
                     account_balance=None,
                     creation_time=None,
                     currency=None,
                     delinquent=None,
                     description=None):
     new_customer = Customer(
         stripe_id=stripe_id,
         email=email,
         account_balance=account_balance,
         creation_time=creation_time,
         currency=currency,
         delinquent=delinquent,
         description=description,
     )
     db.session.add(new_customer)
     db.session.commit()
Exemplo n.º 55
0
def get_single_customer(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
            SELECT
                c.id,
                c.name,
                c.address,
                c.email
            FROM customer c
            WHERE c.id = ?
        """, (id,))

        data = db_cursor.fetchone()

        customer = Customer(data['id'], data['name'], data['address'], data['email'])
        return json.dumps(customer.__dict__)
Exemplo n.º 56
0
def new_cust(loc_name):
    print 'new cust ' + loc_name
    try:
        location = Location.get(
            Location.name == loc_name)  #get location if exists
    except Location.DoesNotExist:
        location = Location.create(name=loc_name, curr_number=0,
                                   high_number=0)  #create location if not
        queues[location.name] = Queue()  #create new queue for location
        pass
    location.high_number += 1  #increment location's high number
    location.save()  #write to database
    #add new customer to queue
    queues[location.name].put(
        Customer.create(location=location,
                        number=location.high_number,
                        checkin=datetime.now()))
    return 'Adding cust at ' + location.name + ' with num ' + str(
        location.high_number)
Exemplo n.º 57
0
def get_all_customers():
    # Open a connection to the database
    with sqlite3.connect("./kennel.db") as conn:

        # Just use these. It's a Black Box.
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT
            c.id,
            c.email,
            c.name,
            c.address,
            c.password
        FROM customer c
        """)

        # Initialize an empty list to hold all animal representations
        customers = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an animal instance from the current row.
            # Note that the database fields are specified in
            # exact order of the parameters defined in the
            # Animal class above.
            customer = Customer(id=row['id'],
                                email=row['email'],
                                name=row['name'],
                                address=row['address'],
                                password=row['password'])

            customers.append(customer.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(customers)
Exemplo n.º 58
0
def process_iden_conversation(msg, created=True, conv=None):
    resp = VoiceResponse()
    app.logger.info('customer is registered')
    conversation = new_conversation()
    if created:
        input_msg=''
    else:
        input_msg=request.form['SpeechResult'] if 'SpeechResult' in request.form else 'donno'
    app.logger.info('input_message [%s] created [%s]', input_msg, created)
    #conv.log_json()
    watson_response = new_conversation_msg(conversation, context=conv.context, input_msg=input_msg, first=False)
    conv.store_context()
    # check if watson identified the customer
    twilio_resp, watson_dialog = create_response(watson_response, conv, twilio_voice=resp)
    app.logger.info('output_message [%s] ', watson_dialog)
    if 'action' in conv.context:
        if conv.context['action'] == 'register_customer':
            cust=Customer.create(
                name=str(conv.context['name']).lower(),
                business=conv.business,
                phone=conv.call_number
            )
            conv.customer = cust
        elif conv.context['action'] == 'create_app':
            app_date = conv.context['app_date']
            app_time = conv.context['app_time']
            start = datetime.strptime(f"{app_date} {app_time}", '%Y-%m-%d %H:%M:%S')
            end = start+timedelta(hours=float(conv.context['app_duration']))
            appoint = Appointment(
                customer=conv.customer,
                note='tutoring',
                start=start,
                end=end
            )
            app.logger.info(f"created a new appointment {start} to {end}")
            appoint.save()
            conv.context['success'] = 'true'
        elif conv.context['action'] == 'end':
            twilio_resp.hangup()
        conv.context.pop('action', None)
    conv.save()
    return str(resp)
Exemplo n.º 59
0
def get_customer_by_email(email):
    with sqlite3.connect("./Kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()
        db_cursor.execute(
            """
        select
            c.id,
            c.name,
            c.address,
            c.email,
            c.password
        from Customer c
        WHERE c.email = ?
        """, (email, ))
        data = db_cursor.fetchone()
        # Create an customer instance from the current row
        customer = Customer(data['id'], data['name'], data['address'])
        # Return the JSON serialized Customer object
        return json.dumps(customer.__dict__)
Exemplo n.º 60
0
def register_customer():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = CustomerRegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user = User(Name=form.name.data,
                    PhoneNumber=form.phone.data,
                    Email=form.email.data,
                    Password=hashed_password,
                    Customer=Customer())
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created! You are now able to log in.',
              'success')
        return redirect(url_for('login'))
    return render_template('register-customer.html',
                           title='Register',
                           form=form)