def seed_db(): global test_driver_id global cust1_id global cust2_id db.session.rollback() db.drop_all() db.create_all() test_driver = User(email="*****@*****.**", token="testToken", api_id='demo') cust1 = Customer(**cust1_data) cust2 = Customer(**cust2_data) db.session.add(cust1) db.session.add(cust2) db.session.add(test_driver) db.session.commit() # global variables test_driver_id = test_driver.id cust1_id = cust1.id cust2_id = cust2.id
def seed_db(): global test_driver_id global cust1_id global cust2_id global test_note_text db.drop_all() db.create_all() test_driver = User(email="*****@*****.**", token="testToken", api_id='demo') cust1 = Customer(**cust1_data) cust2 = Customer(**cust2_data) db.session.add(cust1) db.session.add(cust2) db.session.add(test_driver) db.session.commit() test_note_text = "HELLO THERE!" note = Note(driver_id=test_driver.id, cust_id=cust1.id, note=test_note_text) db.session.add(note) db.session.commit() # variables to reference test_driver_id = test_driver.id cust1_id = cust1.id cust2_id = cust2.id test_note_text = test_note_text
def handle(self, *args, **options): with transaction.atomic(): Customer.objects.bulk_create([ Customer(name='Jane Doe'), Customer(name='John Doe'), ]) jane, john = Customer.objects.order_by('name') Product.objects.bulk_create([ Product(name='Apple', price=Decimal('2.50'), inventory=4), Product(name='Kiwi', price=Decimal('5.00'), inventory=3), Product(name='Orange', price=Decimal('3.00'), inventory=5), ]) apple, kiwi, orange = Product.objects.order_by('name') # Jane has placed two orders order = Order.objects.create_order( customer=jane, is_shipped=True, created_at=datetime.fromisoformat('2019-04-06T16:00:00+02:00'), products=[apple, kiwi], ) Order.objects.create_order( customer=jane, is_shipped=False, created_at=datetime.fromisoformat('2019-04-10T09:00:00+02:00'), products=[apple, kiwi], ) # John has placed three orders order = Order.objects.create_order( customer=john, is_shipped=True, created_at=datetime.fromisoformat('2019-03-31T15:00:00+01:00'), products=[apple, orange], ) order = Order.objects.create_order( customer=john, is_shipped=True, created_at=datetime.fromisoformat('2019-04-01T13:00:00+02:00'), products=[orange, kiwi], ) Order.objects.create_order( customer=john, is_shipped=False, created_at=datetime.fromisoformat('2019-04-07T12:00:00+02:00'), products=[apple], ) SalesTarget.objects.bulk_create([ SalesTarget(year=2019, month=3, target=Decimal('10.00')), SalesTarget(year=2019, month=4, target=Decimal('12.00')), ])
def create(request): if request.method == 'POST': if request.POST['username'] and request.POST[ 'password'] and request.POST['fullname'] and request.POST[ 'email'] and request.POST['phone']: try: customers = Customer.objects.get( username=request.POST['username']) return render(request, 'customers/create.html', {'error': 'Tên đăng nhập đã tồn tại'}) except Customer.DoesNotExist: customer = Customer() customer.address = "" customer.avatar = "" customer.email = request.POST['email'] customer.fullname = request.POST['fullname'] customer.gender = "" customer.info = "" customer.password = request.POST['password'] customer.phone = request.POST['phone'] customer.status = 1 customer.username = request.POST['username'] customer.save() follow = Follow() follow.cusdetail_id = customer.id follow.customer_id = customer.id follow.save() request.session['username'] = customer.username return redirect('/customers/detail/' + str(customer.id)) else: return render(request, 'customers/create.html', {'error': 'All fields are required.'}) else: return render(request, 'customers/create.html')
def test_get_customer_detail_token_from_another_user(self): new_customer = Customer(name='a', email='*****@*****.**') new_customer.save() response = self.client.get(f'/customers/{new_customer.id}/', HTTP_AUTHORIZATION=self.token) self.assertEqual(response.status_code, 401)
def handle(self, *args, **options): def validate(): if not options['tenant_name']: print 'tenant_name is a required option for this command' return False if not options['url']: print 'url is a required option for this command' return False if not options['company_name']: print 'company_name is a required option for this command' return False return True customer = Customer.objects.filter( schema_name=connection.schema_name).first() if customer.is_public_tenant(): if validate(): schema_name = options['tenant_name'] url = options['url'] company_name = options['company_name'] customer = Customer(domain_url=url, schema_name=schema_name, name=company_name) customer.save() print customer.domain_url return
def setUp(self): eduadmin = User.objects.create(username='******') eduadmin.set_password('eduadmin') eduadmin.save() teacher1 = Teacher.objects.create(name='teacher1') course1 = Courses.objects.create(name='course1', teacher_id=teacher1, total_sec=48, date=1, time='8:00') Courses.objects.create(name='course2', teacher_id=teacher1, total_sec=90, date=1, time='10:00') Courses.objects.create(name='course3', teacher_id=teacher1, total_sec=48, date=3, time='10:00') user = User.objects.create(username='******', password='******', user_type=USER_TYPE['customer']) customer = Customer(user=user, child_name='child1') customer.save() customer.takes.set(Courses.objects.all()[:2]) customer.save() CcRecord.objects.create(customer=customer, money='2999') CcRecord.objects.create(customer=customer, money='4800', course=course1)
def signup(request): if not request.user.is_authenticated(): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.save() password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=password) firstname = form.cleaned_data.get('firstname') lastname = form.cleaned_data.get('lastname') agentid = form.cleaned_data.get('agent') street = form.cleaned_data.get('street') city = form.cleaned_data.get('city') country = form.cleaned_data.get('country') customer = Customer() customer.customer_id = user customer.agent_id = agentid customer.first_name = firstname customer.last_name = lastname customer.street = street customer.city = city customer.country = country customer.save() auth_login(request, user) return HttpResponseRedirect(reverse('catalog:index')) else: return render(request, 'del3/signup.html', {'form': form}) else: form = SignUpForm() return render(request, 'del3/signup.html', {'form': form}) else: return HttpResponseRedirect(reverse('index'))
def Overview(request): if request.user.is_authenticated and request.user.ad: class CustomerReservationData(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) dataList = [] usedCustomers = [] customerReservationData = CustomerReservationData(customer=Customer(), amountReservations=0) reservations = Reservation.objects.all() reservationAmount = Reservation.objects.all().count() reservationAmount2 = reservationAmount / 2 for reservation in reservations: for customer in reservation.guests.all(): if customer not in usedCustomers: customerReservationData.customer = customer customerReservationData.amountReservations = Reservation.objects.filter( guests=customer).count() / Reservation.objects.all( ).count() * 100 dataList.append(customerReservationData) usedCustomers.append(customer) return render_to_response('overview.html', { 'data': dataList, 'reservations': reservationAmount, 'reservations2': reservationAmount2 }, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/')
def create(self, obj): email = obj.get('email') password = obj.get('password') password2 = obj.get('password2') first_name = obj.get('first_name') last_name = obj.get('last_name') phone_number = obj.get('phone_number') address_line_1 = obj.get('address_line_1') address_line_2 = obj.get('address_line_2') city = obj.get('city') postal_code = obj.get('postal_code') # qs = Customer.objects.filter(email__iexact=email) if password != password2: return Response('Passwords Must Match') user = Customer(email=email, password=password, username=email, first_name=first_name, last_name=last_name, phone_number=phone_number, address_line_1=address_line_1, address_line_2=address_line_2, city=city, postal_code=postal_code) user.is_active = False user.save() return user
def post(self): data = request.parsed_obj customer = Customer(name=data['name'], dob=data.get('dob', None), updated_at=datetime.now()) db.session.add(customer) db.session.commit() return customer
def setUp(self): self.client = Client() self.customer_name_1 = 'Teste' self.customer_email_1 = '*****@*****.**' self.customer_1 = Customer(name=self.customer_name_1, email=self.customer_email_1) self.customer_1.save() customer_name_2 = 'Testando' customer_email_2 = '*****@*****.**' self.customer_2 = Customer(name=customer_name_2, email=customer_email_2) self.customer_2.save() token_payload = {"id": self.customer_1.id} self.token = jwt.encode(token_payload, settings.JWT_SECRET, algorithm='HS256')
def test_string_representation(self): """ Ensure that string representation of a Customer object is correct """ customer = Customer(first_name="Mike", last_name="Kim") self.assertEqual( str(customer), "{} {}".format(customer.first_name, customer.last_name))
def setUp(self): customer_name = 'Teste' customer_email = '*****@*****.**' self.customer = Customer(name=customer_name, email=customer_email) self.customer.save() token_payload = {"id": self.customer.id} self.token = jwt.encode(token_payload, settings.JWT_SECRET, algorithm='HS256')
def setUp(self): self.company1 = CompanyFactory(name="Company 1") self.company2 = CompanyFactory(name="Company 2") aList = ListCustomer(name="test") aList.save() self.customer = Customer(name="MyCustomer", list=aList) self.customer.save() self.customer.companies.add(self.company1.pk, self.company2.pk)
def setUp(self): self.client = Client() customer_name = 'Teste' customer_email = '*****@*****.**' self.customer = Customer(name=customer_name, email=customer_email) self.customer.save() self.base_request_data = { "name": customer_name, "email": customer_email }
def test_customer_integration(self): """ This is a placeholder for a test :return: """ customer = Customer() customer.name = 'John Doe' customer.save() customers = Customer.objects.all() print customers.count()
def new_customer(): form = CustomerForm() if form.validate_on_submit(): customer = Customer(name=form.name.data) db.session.add(customer) db.session.commit() flash('Customer Record Created') return redirect(url_for('core_bp.index')) return render_template('/customers/register.html', form=form)
def setUp(self): self.client = Client() self.customer_name = 'Teste' self.customer_email = '*****@*****.**' self.customer = Customer(name=self.customer_name, email=self.customer_email) self.customer.save() token_payload = {"id": self.customer.id} self.token = jwt.encode(token_payload, settings.JWT_SECRET, algorithm='HS256') self.product_id = '1bf0f365-fbdd-4e21-9786-da459d78dd1f'
def test_validation_error_field_type(self): """ Test the validation of model. """ data = { 'is_active': FuzzyText().fuzz(), } customer = Customer(**data) try: customer.full_clean() except ValidationError as e: for key, _ in data.items(): self.assertTrue(key in e.message_dict)
def assign_customer_select_customer(request, id): """ Have user decide if site exists from list and reassign all rma to selected site and delete site :param request: :param id: :return: """ site = Customer.objects.get(pk=id) site_rmas = Rma.objects.filter(customer=site) if request.method == 'GET': data = { 'name': site_rmas[0].customer.name, } customer_name_site_form = CustomerCompanyAndSiteNameForm(initial=data) return render(request, 'operations/assign_customer_select_customer.html', { 'site': site, 'form': customer_name_site_form, 'site_rmas': site_rmas }, context_instance=RequestContext(request)) if request.method == 'POST': customer_name_site_form = CustomerCompanyAndSiteNameForm(request.POST) if customer_name_site_form.is_valid(): new_site_name = customer_name_site_form.cleaned_data['name'] existing_customer_id = int( customer_name_site_form.cleaned_data['customer']) existing_customer = CustomerCompany.objects.get( pk=existing_customer_id) new_site = Customer() new_site.customer = existing_customer new_site.name = new_site_name new_site.save() for s in site_rmas: s.customer = new_site s.save() site.delete() return HttpResponseRedirect( reverse('reassign_customers_to_customer_sites')) else: return render(request, 'operations/assign_customer_select_customer.html', { 'site': site, 'form': customer_name_site_form, 'site_rmas': site_rmas }, context_instance=RequestContext(request))
def test_update_email_existing_email(self): new_customer = Customer(name='a', email='*****@*****.**') new_customer.save() data = {"email": new_customer.email} response = self.client.put(f'/customers/{self.customer.id}/', data, content_type="application/json", HTTP_AUTHORIZATION=self.token) response_data = json.loads(response.content) self.assertEqual(response.status_code, 400) self.assertEqual( response_data, {'email': ['customer with this Email already exists.']})
def seed_db(): db.session.rollback() global test_driver_id global test_cust_id global test_delivery_id global test_order_id global order_data db.drop_all() db.create_all() user_data = {"email": "*****@*****.**", "token": "testToken", api_id='demo'} cust_data = {"id": '1', "name": "testuser1", "address": "Some Address", "phone": "203-881-7843"} test_driver = User(**user_data) test_cust = Customer(**cust_data) db.session.add(test_cust) db.session.add(test_driver) db.session.commit() delivery_data = {"driver_id": test_driver.id} test_delivery = Delivery(**delivery_data) db.session.add(test_delivery) db.session.commit() order_data = {"num": 112, "cust_id": test_cust.id, "del_id": test_delivery.id, "driver_id": test_driver.id, "date": datetime.date(2021, 4, 19)} test_order = Order(**order_data) db.session.add(test_order) db.session.commit() test_driver_id = test_driver.id test_cust_id = test_cust.id test_delivery_id = test_delivery.id test_order_id = (test_order.num, test_order.date)
def test_validation_error_field_value_out_of_scope(self): """ Test the validation of model with the field value out of scope. """ data = { 'name': FuzzyText('', 200).fuzz(), 'email': None, 'is_active': FuzzyText().fuzz(), } customer = Customer(**data) try: customer.full_clean() except ValidationError as e: for key, _ in data.items(): self.assertTrue(key in e.message_dict)
def setUp(self): self.count_customers = 126 self.count_customers_per_page = 10 self.num_pages = _calc_num_pages(self.count_customers, self.count_customers_per_page) self.test_id_customers_clear = [customer for customer in range(1, self.count_customers + 1)] for i in range(self.count_customers): Customer( first_name='first_name_' + str(i), last_name='last_name_' + str(i), email='email_' + str(i) + '@email.com', phone='phone_' + str(i), address='address_' + str(i), description='description_' + str(i), ).save()
def new(request): """new customer """ categories = get_categories() countries = get_countries() form = Form(request, schema=CustomerForm) if "form_submitted" in request.POST and form.validate(): dbsession = DBSession() customer = form.bind(Customer()) dbsession.add(customer) request.session.flash("warning;New Customer is saved!") return HTTPFound(location=request.route_url("customer_list")) return dict(form=FormRenderer(form), categories=categories, countries=countries, action_url=request.route_url("customer_new"))
def assign_customer_to_site_new_customer(request, id): if request.method == 'GET': site = Customer.objects.get(pk=id) site_rmas = Rma.objects.filter(customer=site) customer_name_form = CustomerForm() site_form = CustomerSiteIdNameForm(instance=site) return render(request, 'operations/edit_site_new_customer.html', { 'site': site, 'customer_name_form': customer_name_form, 'site_form': site_form, 'site_rmas': site_rmas }, context_instance=RequestContext(request)) if request.method == 'POST': site = Customer.objects.get(pk=id) error_count = 0 customer_name_form = CustomerForm(request.POST) site_form = CustomerSiteIdNameForm(request.POST, instance=site) site_rmas = Rma.objects.filter(customer=site) if site_form.is_valid() is not True: error_count += 1 if customer_name_form.is_valid() is not True: error_count += 1 if error_count > 0: return render(request, 'operations/edit_site_new_customer.html', { 'site': site, 'customer_name_form': customer_name_form, 'site_form': site_form, 'site_rmas': site_rmas, }, context_instance=RequestContext(request)) else: new_customer = customer_name_form.save() new_customer_site = Customer() new_customer_site.name = site_form.cleaned_data['name'] new_customer_site.customer = new_customer new_customer_site.save() return HttpResponseRedirect( reverse('view_customer_site_to_reassign', kwargs={'id': new_customer_site.id}))
def get_list_customer(self, path): with open(path, 'r', newline='') as csvfile: customer_list = list() total = 0 count = 0 for row in csv.DictReader(csvfile, skipinitialspace=True): city, created = City.objects.get_or_create(name=row["city"]) row["city"] = city row["gender"] = GENDERS_DICT[row["gender"]] customer_list.append(Customer(**row)) count = count + 1 if count >= 25: total = total + count count = 0 self.stdout.write( self.style.WARNING(f'Get {total} rows...')) self.stdout.write( self.style.WARNING(f'Saving {len(customer_list)} models...')) return customer_list
def import_data(): # Initial Imports # Processing model: customers.models.Customer from customers.models import Customer customers_customer_1 = Customer() customers_customer_1.created = dateutil.parser.parse("2017-03-31T13:27:37.470821+00:00") customers_customer_1.modified = dateutil.parser.parse("2017-03-31T13:27:37.470881+00:00") customers_customer_1.name = 'Nickel Pro' customers_customer_1.email = '' customers_customer_1.phone = '' customers_customer_1.description = '' customers_customer_1.financial_year_end_day = 31 customers_customer_1.financial_year_end_month = 12 customers_customer_1.review_rounds = 2 customers_customer_1.active = True customers_customer_1 = importer.save_or_locate(customers_customer_1)
def find_customer_by_device_credentials(device_mac: str, device_port: int = 0) -> Optional[Customer]: with connection.cursor() as cur: cur.execute( "SELECT * FROM find_customer_by_device_credentials(%s::macaddr, %s::smallint)", (device_mac, device_port), ) res = cur.fetchone() if res is None or res[0] is None: return None ( baseaccount_id, balance, ip_addr, descr, house, is_dyn_ip, auto_renw_srv, markers, curr_srv_id, dev_port_id, dev_id, gw_id, grp_id, last_srv_id, street_id, *others, ) = res return Customer( pk=baseaccount_id, balance=balance, description=descr, house=house, is_dynamic_ip=is_dyn_ip, auto_renewal_service=auto_renw_srv, markers=markers, current_service_id=curr_srv_id, device_id=dev_id, dev_port_id=dev_port_id, gateway_id=gw_id, group_id=grp_id, last_connected_service_id=last_srv_id, street_id=street_id, )