示例#1
0
class AuthenticationTestCase(TestCase):
    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 test_valid_token_decode(self):
        decoded_token = authenticate(customer_id=self.customer.id,
                                     token=self.token)

        self.assertTrue(decoded_token)

    def test_invalid_customer_id_for_token(self):
        wrong_id = self.customer.id + 1
        decoded_token = authenticate(customer_id=wrong_id, token=self.token)

        self.assertFalse(decoded_token)

    def test_invalid_token(self):
        wrong_token = self.token[:-1]
        decoded_token = authenticate(customer_id=self.customer.id,
                                     token=wrong_token)

        self.assertFalse(decoded_token)
示例#2
0
    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 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 import_customer(self, custrow):
        c = Customer.objects.filter(first_name=custrow['First Name'], last_name=custrow['Last Name'])
        if c:
            self.stdout.write('  - %s already exists -- skipping' % custrow['Customer Name'])
        else:
            self.stdout.write('  - Creating %s' % custrow['Customer Name'])
            c = Customer()
            m = Measurement()

            for k, v in custrow.items():
                if k == 'Customer Name' or (not v):
                    continue

                km = k.lower().replace('-', '').replace(' ', '_').replace('__', '_')
                if hasattr(c, km):
                    setattr(c, km, v)
                elif hasattr(m, km):
                    setattr(m, km, v)
                else:
                    raise ValueError('Unexpected attribute %s (%s)' % (km, k))

            c.save()
            m.customer = c
            m.save()

        return
示例#5
0
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')
示例#6
0
class CustomerTest(TestCase):
    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 tearDown(self):
        self.company1.delete()
        self.company2.delete()
        self.customer.delete()

    def test_can_list_companies(self):
        self.assertEqual("Company 1, Company 2",
                         self.customer.list_companies())

    def test_string_method(self):
        self.assertEqual("MyCustomer by Company 1, Company 2",
                         self.customer.__str__())

    def test_custom_save_method(self):
        #self.assertIsNone(self.customer.date_reviewed)
        self.customer.review = "My review"
        self.customer.save()
        #self.assertIsNotNone(self.customer.date_reviewed)
示例#7
0
    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
示例#8
0
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'))
示例#9
0
class LoginTestCase(TestCase):
    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_valid_response(self):
        data = json.dumps(self.base_request_data)
        response = self.client.post('/login',
                                    data,
                                    content_type="application/json")

        self.assertEqual(response.status_code, 200)

    def test_invalid_response(self):
        request_data = self.base_request_data
        request_data['name'] = 'Not Test'

        data = json.dumps(request_data)
        response = self.client.post('/login',
                                    data,
                                    content_type="application/json")

        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 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 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()
示例#13
0
 def save(self):
     customers_csv = csv.reader(self.cleaned_data["file"])
     Customer.objects.all().delete()
     for customer_csv in customers_csv:
         customer = Customer()
         customer.customer_id = customer_csv[0]
         customer.name = customer_csv[1]
         customer.adress = customer_csv[2]
         customer.phone_number = customer_csv[3]
         customer.contact = customer_csv[4]
         customer.save()
示例#14
0
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))
示例#15
0
    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.']})
示例#16
0
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}))
示例#17
0
class WishlistDetailTestCase(TestCase):
    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_get_inexisting_wishlist(self):
        response = self.client.get(f'/customers/{self.customer.id}/wishlist/')

        self.assertEqual(response.status_code, 404)

    def test_get_a_wishlist(self):
        wishlist = get_or_update(customer_id=self.customer.id,
                                 product_id=self.product_id)

        response = self.client.get(f'/customers/{self.customer.id}/wishlist',
                                   HTTP_AUTHORIZATION=self.token)
        response_data = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_data['customer'], self.customer.id)
        self.assertEqual(response_data['wishlist']['count'],
                         wishlist.wishlist['count'])
        self.assertEqual(response_data['wishlist']['products'][0]['id'],
                         self.product_id)

    def test_delete_a_wishlist(self):
        get_or_update(customer_id=self.customer.id, product_id=self.product_id)

        response = self.client.delete(
            f'/customers/{self.customer.id}/wishlist',
            HTTP_AUTHORIZATION=self.token)

        self.assertEqual(response.status_code, 204)
示例#18
0
文件: views.py 项目: wolfmc3/itmemory
def import_add(request):
    from magonet.connector import MagoNet
    conn = MagoNet()
    conn.connect()
    rows = conn.getcustomer_byid(str(request.GET['code']))
    conn.disconnect()
    row = rows[0]
    cust_list = Customer.objects.filter(origin_code=row['CustSupp'])
    if cust_list:
        newcust = cust_list[0]
    else:
        newcust = Customer()
    newcust.address = row['Address']
    newcust.city = row['City']
    newcust.email = row['EMail']
    newcust.name = row['CompanyName']
    newcust.origin_code = row['CustSupp']
    newcust.telephone = row['Telephone1'] + " " + row['Telephone2'] + " " + row['Fax']
    newcust.save()
    return HttpResponseRedirect(reverse("customers:detail", kwargs={"pk": newcust.id}))
示例#19
0
    def post(self, request):
        requestBody = request.data

        if not(requestBody is None):
            customerSerializer = CustomerSerializer(data=requestBody)

            if(customerSerializer.is_valid()):
                customer = Customer(**requestBody)
                Customer.save(customer)
                response = Response(customerSerializer.data,
                                    status=status.HTTP_200_OK)
            else:
                response = Response(
                    'Invalid Customer Details',
                    status=status.HTTP_400_BAD_REQUEST)
        else:
            response = Response(
                'Error', status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return response
示例#20
0
    def post(self, request):
        form = RegisterForm(request.POST or None)
        if form.is_valid():
            formdata = form.cleaned_data.copy()
            formdata.pop('password2')
            formdata.pop('password')
            tenant = Customer()
            tenant.username = form.cleaned_data['username']
            tenant.first_name = form.cleaned_data['first_name']
            tenant.last_name = form.cleaned_data['last_name']
            tenant.email = form.cleaned_data['email']
            tenant.phone = form.cleaned_data['phone']
            tenant.timezone = form.cleaned_data['timezone']
            ph = parse(form.cleaned_data['phone'])
            region_code = region_code_for_country_code(ph.country_code)
            tenant.region_code = region_code
            tenant.save()
            print(tenant.__dict__)

            user_manager = UserManager()
            user_manager.create_user(
                customer=tenant,
                username=form.cleaned_data['username'],
                email=form.cleaned_data['email'],
                password=form.cleaned_data['password'],
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                phone=form.cleaned_data['phone'],
                is_owner=True,
                is_clinician=True,
                is_scheduler=True,
                is_biller=True,
                region_code=tenant.region_code,
                timezone=tenant.timezone,
            )
            ActivityStream(customer=tenant,
                           actor=form.cleaned_data['username'],
                           verb='signed up').save()
            return redirect('login')  # to be changed later
        context = {'form': form}
        return render(request, self.template, context)
示例#21
0
 def save_customer_data(self, image_large, response_email, response_gender, response_name, socialAccount):
     if response_email is None:
         return
     customers = Customer.objects.filter(email=response_email)
     # print (customers)
     if len(customers) > 0:
         if len(customers) == 1:
             customer = customers[0]
             if customer.social is None:
                 customer.social = socialAccount
             customer.customer_name = response_name
             customer.gender = response_gender
             customer.image = image_large
             customer.save()
     else:
         # user doesn't exist in customers
         customer = Customer(email=response_email, social=socialAccount, customer_name=response_name,
                             image=image_large,
                             gender=response_gender)
         customer.save()
         sendWelcomeMail(customer)
示例#22
0
def cliente():
    with open('/maladireta/database/clientes.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'{", ".join(row)}')
                line_count += 1
            elif line_count == 1:
                customer = Customer()
                customer.name = row[0]
                if row[1]:
                    customer.birth = to_datetime_inverted(row[1].split(' ')[0])
                customer.nickname = row[2]
                customer.reference = row[3]
                customer.state = row[4]
                customer.cep = row[5]
                customer.old_id = row[10]
                customer.note = row[11]
                customer.cpf = row[12]
                customer.rg = row[13]
                customer.phone_home = row[14]
                customer.phone_number = row[15]
                customer.cellphone = row[16]
                customer.complement = row[17]
                customer.street = row[18]
                customer.leadership = row[20]
                customer.location_reference = row[21]
                customer.number = row[26]
                customer.email = row[27]
                customer.profession = row[28]
                customer.neighborhood = row[29]
                customer.city = row[30]
                customer.recurrence = row[32]
                customer.subscription = row[38]
                customer.zone = row[39]
                customer.section = row[40]
                customer.save()
            else:
                break
示例#23
0
文件: views.py 项目: wolfmc3/itmemory
def import_add(request):
    from magonet.connector import MagoNet
    conn = MagoNet()
    conn.connect()
    rows = conn.getcustomer_byid(str(request.GET['code']))
    conn.disconnect()
    row = rows[0]
    cust_list = Customer.objects.filter(origin_code=row['CustSupp'])
    if cust_list:
        newcust = cust_list[0]
    else:
        newcust = Customer()
    newcust.address = row['Address']
    newcust.city = row['City']
    newcust.email = row['EMail']
    newcust.name = row['CompanyName']
    newcust.origin_code = row['CustSupp']
    newcust.telephone = row['Telephone1'] + " " + row[
        'Telephone2'] + " " + row['Fax']
    newcust.save()
    return HttpResponseRedirect(
        reverse("customers:detail", kwargs={"pk": newcust.id}))
示例#24
0
def save_cart_as_order(cart):
    address = None
    if cart.get('details').get('delivery_address'):
        address = Address(
        street_one = cart.get('details').get('delivery_address').get('street_one'),
        street_two = cart.get('details').get('delivery_address').get('street_two'),
        city = cart.get('details').get('delivery_address').get('city'),
        state = cart.get('details').get('delivery_address').get('state'),
        zipcode = cart.get('details').get('delivery_address').get('zipcode'),
        )
        address.save()
    customer = Customer(
    first_name = cart.get('details').get('contact_info').get('first_name'),
    last_name = cart.get('details').get('contact_info').get('last_name'),
    email = cart.get('details').get('contact_info').get('email'),
    phone_number = cart.get('details').get('contact_info').get('phone'),
    address = address,
    )
    customer.save()
    order = Order(
    ref_code = create_ref_code(),
    customer = customer,
    ordered_date = timezone.now(),
    pickup = cart.get('details').get('pickup'),
    note = cart.get('details').get('note'),
    )
    order.save()
    id_list = cart.get('details').get('item_id_list')
    for id in id_list:
        item = Item.objects.get(id=id)
        order_item = OrderItem(
        item = item,
        quantity = cart.get(str(id)).get('quantity'),
        note = cart.get(str(id)).get('note'),
        order = order,
        )
        order_item.save()
    return order
示例#25
0
    def form_valid(self, form):
        try:
            customer = Customer.objects.get(
                phone_number=form.data['phone_number'])
        except Customer.DoesNotExist:
            customer = Customer()
            customer.first_name = form.data['first_name']
            customer.last_name = form.data['last_name']
            customer.phone_number = form.data['phone_number']
            customer.save()

        cleaner = Cleaner.objects.filter(cities=form.data['city'])\
                                 .exclude(booking__date=form.data['date'])\
                                 .first()

        booking = Booking.objects.create(customer=customer,
                                         cleaner=cleaner,
                                         date=form.data['date'])

        template = render_to_string('booking/email_notification.txt',
                                    {'booking': booking})
        send_mail('New booking', template, settings.DEFAULT_FROM_EMAIL,
                  [cleaner.email])
        return super(BookingCreateView, self).form_valid(form)
示例#26
0
def logup_view(request):
    success_url = reverse_lazy('customersapp:customer')
    notification = {}
    if request.POST.get('logup'):
        usr_name = request.POST.get('username')
        psw = request.POST.get('password')
        avatar = request.FILES.get('avatar')
        checker = get_user(request)
        if checker.is_anonymous:
            try:
                customer = Customer(username=usr_name, _avatar=avatar)
                customer.is_active = True
                customer.set_password(psw)
                customer.save()

                notification = {
                    'user_name': usr_name,
                    'warn': 'Congratulations!'
                }
            except IntegrityError:
                notification = {
                    'user_name': usr_name,
                    'warn': 'Name is occupied! Choose another'
                }

            else:
                user = authenticate(username=usr_name, password=psw)

                if user and user.is_active:
                    auth_act = AuthApp.objects.create(user=user)
                    auth_act.logup = datetime.datetime.now()
                    auth_act.save()
                    login(request, user)
                    return redirect(success_url)

    return render(request, 'authapp/logup.html', notification)
示例#27
0
def customer_edit(request, customer_id=None):
    """
    顧客を新規作成/編集する
    """

    if customer_id:
        customer = get_object_or_404(Customer, pk=customer_id)
    else:
        customer = Customer()

    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            customer = form.save(commit=False)
            customer.save()
            return redirect('customers:list')
    else:
        form = CustomerForm(instance=customer)

    return render(
        request,
        'customers/edit.html',
        dict(form=form, customer_id=customer_id)
    )
示例#28
0
def taster5x(request):
    result = context = {}

    if request.method == "POST":

        if 'one-password1' in request.POST:
            rf = CustomRegistrationForm(request.POST, prefix='one')

            if rf.is_valid():
                result['success'] = True

                request.session['email'] = rf.cleaned_data['email']
                request.session['password'] = request.POST['one-password1']

                mailchimp_subscribe.delay(email=request.session.get('email'))
            else:
                errors = rf.errors
                return HttpResponse(json.dumps(errors))

        if 'two-first_name' in request.POST:
            cf = GS_CustomerForm(request.POST, prefix='two')
            pf = GS_PreferencesForm(request.POST, prefix='tri')

            if cf.is_valid():
                result['success'] = True

                request.session['first_name'] = request.POST['two-first_name']
                request.session['last_name'] = request.POST['two-last_name']
                request.session['line1'] = request.POST['two-line1']
                request.session['line2'] = request.POST['two-line2']
                request.session['postcode'] = request.POST['two-postcode']

                mailchimp_subscribe.delay(
                    email=request.session.get('email'),
                    merge_vars={
                        'FNAME': request.session.get('first_name'),
                        'LNAME': request.session.get('last_name'),
                    },
                )

            else:
                errors = cf.errors
                return HttpResponse(json.dumps(errors))

        if 'stripeToken' in request.POST:
            try:
                user = MyUser(email=request.session['email'])
                user.set_password(request.session['password'])
                user.save()
            except Exception as e:
                print e

            try:
                customer = Customer(
                    user=user,
                    first_name=request.session['first_name'],
                    last_name=request.session['last_name'],
                    line1=request.session['line1'],
                    line2=request.session['line2'],
                    postcode=request.session['postcode'],
                    stripe_id=request.session['stripe_id']
                    )
                customer.save()
                add_event.delay(
                    customer_id=customer.id,
                    event='signed-up',
                    data={'taster5x': True})

            except Exception as e:
                print e

            random_coffee = CoffeeType.objects.bags().filter(
                special=False).first()
            preferences = Preferences(
                customer=customer,
                coffee=random_coffee,
                brew=BrewMethod.objects.get(name_en='None'),
                package=Preferences.DRIP_BAGS
                )
            preferences.save()

            taster5x = CoffeeType.objects.get(name='Taster 5x')

            try:
                voucher = Voucher.objects.get(name='Taster 5x')
                voucher.count += 1
                voucher.save()
            except:
                voucher = Voucher(
                    name='Taster 5x',
                    discount=0,
                    count=1
                    )
                voucher.save()

            try:
                order = Order.objects.create(
                    customer=customer,
                    coffee=taster5x,
                    date=timezone.now(),
                    shipping_date=get_shipping_date(),
                    amount=taster5x.amount,
                    status=Order.ACTIVE,
                    brew=preferences.brew,
                    package=preferences.package,
                    interval=0,
                    voucher=voucher
                )
                add_event.delay(
                    customer_id=customer.id,
                    event='created-taster5x',
                    order_id=order.id)
            except Exception as e:
                print e

            new_user = authenticate(email=user.email,
                password=request.session['password'])
            login(request, new_user)

            context = {
                'coffee': taster5x.name,
                'image': taster5x.img.url,
            }

            # Send reminding email in a week
            ctz = timezone.get_current_timezone()
            now = ctz.normalize(timezone.now())

            # If there are other reminders (for example from Gets Started)
            # mark they as completed
            Reminder.objects.filter(email=user.email).update(completed=True)
            # Send email in a week if taster pack
            Reminder.objects.create(
                username=customer.first_name,
                email=customer.user.email,
                from_email='Hook Coffee <*****@*****.**>',
                subject='Which was your favourite?',
                template_name='Which was your favourite?',
                scheduled=now + timedelta(days=7),
            )

            # Send summary email
            send_email_async.delay(
                subject='Welcome on board!',
                template='O1 - First order on a subscription (done)',
                to_email=customer.get_email(),
                from_email='Ernest from Hook Coffee <*****@*****.**>',
                merge_vars={
                    'USERNAME': customer.first_name,
                    'DOMAIN_NAME': request.META.get('HTTP_HOST'),
                }
            )
            return render(request, 'get_started/thankyou-trial.html', context)

        return result

    else:
        rf = CustomRegistrationForm(prefix='one')
        cf = GS_CustomerForm(prefix='two')
        pf = GS_PreferencesForm(prefix='tri')

        context['reg_form'] = rf
        context['cus_form'] = cf
        context['pre_form'] = pf
        context['stripe_key'] = settings.PUBLISHABLE_KEY

    return render(request, 'taster/taster5x.html', context)
示例#29
0
for x in range(25):
    newcust = Customer()
    newcust.name = CUSTOMER_NAMES[random.randint(0, len(CUSTOMER_NAMES) - 1)].title() + ' ' + \
                   CUSTOMER_NAMES[random.randint(0, len(CUSTOMER_NAMES) - 1)] + ' ' + \
                   CUSTOMER_NAMES_TITLE[random.randint(0, len(CUSTOMER_NAMES_TITLE) - 1)]

    newcust.address = 'via {0}'.format(CUSTOMER_NAMES[random.randint(
        0,
        len(CUSTOMER_NAMES) - 1)])
    newcust.city = "City"
    newcust.email = "*****@*****.**"
    newcust.reference_person = CUSTOMER_NAMES[random.randint(
        0,
        len(CUSTOMER_NAMES) - 1)]
    newcust.origin_code = "sample"
    newcust.telephone = "008881123456"
    newcust.save()
    for sx in range(3):
        newws = WorkSite(customer=newcust)
        newws.name = "Branch {0} {1}".format(str(sx), newcust.name)
        newws.address = "via {0}".format(CUSTOMER_NAMES[random.randint(
            0,
            len(CUSTOMER_NAMES) - 1)])
        newws.city = "City"
        newws.email = "*****@*****.**"
        newws.reference_person = CUSTOMER_NAMES[random.randint(
            0,
            len(CUSTOMER_NAMES) - 1)]
        newws.origin_code = "sample"
        newws.telephone = "008881123456"
        newws.save()
示例#30
0
def registerPage(request):
    form = CreateUserForm()
    form_customer = Create_customer(request.POST)
    form_address = Create_address(request.POST)
    form_city = Create_city(request.POST)
    sports = Sport.objects.all()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid() and form_customer.is_valid(
        ) and form_address.is_valid() and form_city.is_valid():
            usuario = form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, F"Bienvenid@ {username}")
            login(request, usuario)

            user = request.user

            first_name1 = form_customer.cleaned_data.get('first_name')
            last_name1 = form_customer.cleaned_data.get('last_name')
            birthdate1 = form_customer.cleaned_data.get('birthdate')
            phone_number1 = form_customer.cleaned_data.get('phone_number')
            address1 = form_address.cleaned_data.get('address')
            city1 = form_city.cleaned_data.get('city_name')
            country1 = form_city.cleaned_data.get('country')

            city_created = City.objects.get(city_name=city1)

            lista = Address.objects.all()
            m = 0

            for q in lista:
                m += 1

            address_created = Address(address_id=m + 1,
                                      address=address1,
                                      city_id=city_created)
            address_created.save()

            customer_created = Customer(customer_id=user.id,
                                        first_name=first_name1,
                                        last_name=last_name1,
                                        birthdate=birthdate1,
                                        phone_number=phone_number1,
                                        address_id=address_created,
                                        auth_user_id=user)
            customer_created.save()

            lista_shop = Shopping_cart.objects.all()
            count = 0
            for i in lista_shop:
                count += 1

            day = date.today()
            dt = day.strftime("%Y-%m-%d")
            shopping_cart_crated = Shopping_cart(cart_id=count + 1,
                                                 effective_date=dt,
                                                 total=0,
                                                 customer_id=customer_created)
            shopping_cart_crated.save()
            return redirect('Home')
        else:
            for msg in form.error_messages:
                messages.error(request, form.error_messages[msg])
            context = {
                'form': form,
                'form_customer': form_customer,
                'form_address': form_address,
                'form_city': form_city,
                'sport': sports
            }
            return render(request, 'Home/Sign_up.html', context)

    context = {
        'form': form,
        'form_customer': form_customer,
        'form_address': form_address,
        'form_city': form_city,
        'sport': sports
    }
    return render(request, 'Home/Sign_up.html', context)
示例#31
0
 def handle(self, *args, **options):
     customer = Customer()
     customer.name = 'sample'
     customer.save()
示例#32
0
class CustomerListTestCase(TestCase):
    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_get_customer_list(self):
        response = self.client.get('/customers/')
        response_data = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(2, len(response_data))
        self.assertIn('name', response_data[0])
        self.assertIn('email', response_data[1])
        self.assertNotIn('id', response_data[0])

    def test_get_customer_list(self):
        response = self.client.get('/customers/')
        response_data = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(2, len(response_data))
        self.assertIn('name', response_data[0])
        self.assertIn('email', response_data[1])
        self.assertNotIn('id', response_data[0])

    def test_create_customer(self):
        request_data = {"name": 'created', "email": '*****@*****.**'}
        response = self.client.post('/customers/',
                                    request_data,
                                    content_type="application/json")
        response_data = json.loads(response.content)

        created_customer = Customer.objects.get(name=request_data['name'])

        self.assertEqual(response.status_code, 201)
        self.assertEqual(request_data['name'], response_data['name'])
        self.assertEqual(request_data['email'], response_data['email'])
        self.assertTrue(created_customer)

    def test_create_customer_with_existing(self):
        request_data = {"name": 'created', "email": self.customer_email_1}
        response = self.client.post('/customers/',
                                    request_data,
                                    content_type="application/json")
        response_data = json.loads(response.content)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            {'email': ['customer with this Email already exists.']},
            response_data)
 def test_customer_slow(self):
     customer = Customer()
     customer.name = 'John Doe'
     customer.save()
     customers = Customer.objects.all()
     print customers.count()
 def test_customer(self):
     customer = Customer()
     customer.name = 'John Doe'
     customer.save()
示例#35
0
'''Using django-tenants
Creating a Tenant
Creating a tenant works just like any other model in django. The first thing we should do is to create the public
tenant to make our main website available. We’ll use the previous model we defined for Client.
https://django-tenants.readthedocs.io/en/latest/use.html
'''

from customers.models import Customer, Domain

# create your public tenant
tenant = Customer(schema_name='public',
                username='******',
                first_name='public_firstname',
                last_name='public_last_name',
                email='*****@*****.**',
                phone='0000000000',
                )
tenant.save()

# Add one or more domains for the tenant
domain = Domain()
domain.domain = 'localhost' # don't add your port or www here! on a local server you'll want to use localhost here
domain.tenant = tenant
domain.is_primary = True
domain.save()

 def handle(self, *args, **options):
     customer = Customer()
     customer.name = 'sample'
     customer.save()
示例#37
0
class CustomerDetailTestCase(TestCase):
    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')

    def test_get_customer_detail_without_headers(self):
        response = self.client.get(f'/customers/{self.customer.id}/')

        self.assertEqual(response.status_code, 400)

    def test_get_customer_detail_valid_token(self):
        response = self.client.get(f'/customers/{self.customer.id}/',
                                   HTTP_AUTHORIZATION=self.token)
        response_data = json.loads(response.content)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.customer.name, response_data['name'])
        self.assertEqual(self.customer.email, response_data['email'])

    def test_get_customer_detail_invalid_token(self):
        invalid_token = 'ayJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NH0.-aLaOKeSHBU2cul6JzhHn1mmXANz1QGL2KYIhOBHpQc'
        response = self.client.get(f'/customers/{self.customer.id}/',
                                   HTTP_AUTHORIZATION=invalid_token)

        self.assertEqual(response.status_code, 401)

    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 test_update_customer(self):
        data = {"name": "New test name"}
        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, 200)
        self.assertEqual(response_data['name'], data['name'])
        self.assertEqual(response_data['email'], self.customer.email)

    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 test_delete_customer(self):
        response = self.client.delete(f'/customers/{self.customer.id}/',
                                      HTTP_AUTHORIZATION=self.token)

        self.assertEqual(response.status_code, 204)

        with self.assertRaises(Customer.DoesNotExist):
            Customer.objects.get(name=self.customer_name,
                                 email=self.customer_email)