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
Exemple #3
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)
Exemple #4
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 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
Exemple #6
0
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
Exemple #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
Exemple #8
0
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
Exemple #9
0
    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)
Exemple #10
0
 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')
Exemple #11
0
 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 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()
Exemple #14
0
    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 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'
Exemple #16
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)
Exemple #17
0
    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 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 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 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
Exemple #21
0
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('/')
Exemple #22
0
    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)
Exemple #23
0
def checkout(request):
    order = Order.from_request(request)
    country = Country.objects.get(country_code='RW')
    initial_data = dict()

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            phone_number = form.cleaned_data['phone_number']
            phone_number = country.derive_international_number(phone_number)
            customer = Customer.get_or_create_customer(phone_number)
            customer.send_password()

            request.session['customer'] = customer
            return HttpResponseRedirect(reverse('public_login'))
    else:
        form = LoginForm(initial_data)

    context = dict(order=order,
                   country=country,
                   currency=country.currency,
                   form=form)
    return render_to_response('public/checkout.html',
                              context,
                              context_instance=RequestContext(request))
Exemple #24
0
 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))
Exemple #25
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()
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)
Exemple #27
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
Exemple #28
0
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)
Exemple #29
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)
 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)
Exemple #31
0
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}))
Exemple #32
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
Exemple #33
0
    def save_delivery(cls, delivery, driver_id, api_id):
        date = delivery['date']
        store = delivery['store']
        orders = delivery['orders']
        old_deliveries = set()

        delivery = Delivery(driver_id=driver_id)
        db.session.add(delivery)
        db.session.commit()
        ######
        # A little wasteful, good optimization possibility, I think
        for order in orders:
            # maybe change this to a hash of the phone and address
            customer_id = Customer.make_id_from_phone(order['phone'])
            customer = Customer.create_or_get(
                id=customer_id)
            # name = order['name'].split(' ')[0]

            db_order = Order.get(order['num'], date, store, api_id)
            if db_order:
                old_deliveries.add(db_order.del_id)
                db_order.del_id = delivery.id
                db_order.driver_id = driver_id
                db_order.cust_id = customer_id
            else:
                db_order = Order(
                    num=order['num'],
                    date=date,
                    store=store,
                    api_id=api_id,
                    del_id=delivery.id,
                    cust_id=customer_id,
                    driver_id=driver_id)
            db.session.add(db_order)
        db.session.commit()

        Delivery.dispose_of_empty_dels(old_deliveries)
        return delivery
Exemple #34
0
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}))
Exemple #35
0
def checkout(request):
    order = Order.from_request(request)
    country = Country.objects.get(country_code='RW')
    initial_data = dict()

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            phone_number = form.cleaned_data['phone_number']
            phone_number = country.derive_international_number(phone_number)
            customer = Customer.get_or_create_customer(phone_number)
            customer.send_password()

            request.session['customer'] = customer
            return HttpResponseRedirect(reverse('public_login'))
    else:
        form=LoginForm(initial_data)

    context = dict(order=order, country=country, currency=country.currency, form=form)
    return render_to_response('public/checkout.html', context, context_instance=RequestContext(request))
 def test_customer_slow(self):
     customer = Customer()
     customer.name = 'John Doe'
     customer.save()
     customers = Customer.objects.all()
     print customers.count()
 def handle(self, *args, **options):
     customer = Customer()
     customer.name = 'sample'
     customer.save()
 def test_customer(self):
     customer = Customer()
     customer.name = 'John Doe'
     customer.save()
Exemple #39
0
def create():
    body = request.get_json()

    if not 'invoice' in body:
        return '"invoice" parameter is missing', 400

    if not 'customer' in body['invoice']:
        return '"customer" parameter is missing', 400

    project = None
    if 'project' in body:
        project = Project.find_by_id(body['project'])

    customer = None
    if 'email' in body['invoice']['customer']:
        customer = Customer.find_by_email(body['invoice']['customer']['email'])
        if not customer and 'name' not in body['invoice']['customer']:
            return '"customer" not found', 404
    elif 'id' in body['invoice']['customer']:
        customer = Customer.find_by_id(body['invoice']['customer']['id'])
        if not customer:
            return '"customer" not found', 404

    if not customer:
        if not 'name' in body['invoice']['customer']:
            return '"customer.name" is required when creating one', 400

        customer = Customer.create(body['invoice']['customer'])

    invoice = Invoice('INVOICE', customer, project)
    invoice.currency = body['invoice']['currency'] if 'currency' in body['invoice'] else invoice.project.default_currency
    invoice.message = body['invoice']['message'] if 'message' in body['invoice'] else None
    invoice.due = body['invoice']['due'] if 'due' in body['invoice'] else None

    if 'reference' in body['invoice']:
        invoice.reference = body['invoice']['reference']
    else:
        try:
            invoice.set_reference()
        except IntegrityError:
            return 'Invalid Reference number given', 400

    if 'theme' in body:
        theme = Theme.find_by_id(body['theme'])
        if not theme:
            return "Invalid Theme ID : Theme not found", 404

        invoice.theme_id = theme.id
        invoice.theme = theme

    invoice.save()

    # Adding meta data
    for item in body['invoice']:
        if item in ['customer', 'currency', 'message', 'due', 'reference', 'entries', 'discounts', 'payments','refunds','notes','paid']:
            continue;
        InvoiceMeta.create(invoice, item, body['invoice'][item])


    if 'entries' in body['invoice']:
        entry_index = 1
        for entry in body['invoice']['entries']:
            if not 'description' in entry:
                return abort(400)

            if not 'amount' in entry:
                return abort(400)

            InvoiceEntry.create(invoice, entry, body['invoice']['tax'] if 'tax' in body['invoice'] else None, entry_index)
            entry_index += 1

    if 'discounts' in body['invoice']:
        for discount in body['invoice']['discounts']:
            if not 'amount' in discount:
                return abort(400)

            if not 'mode' in discount or discount['mode'] not in ['PERCENTAGE', 'FIXED']:
                return abort(400)

            if not 'option' in discount or discount['option'] not in ['SUBTOTAL', 'TOTAL']:
                discount['option'] = 'SUBTOTAL'

            InvoiceDiscount.create(invoice, discount)

    if 'payments' in body['invoice']:
        for payment in body['invoice']['payments']:
            if not 'amount' in payment:
                return abort(400)

            InvoicePayment.create(invoice, payment['amount'])

    if 'refunds' in body['invoice']:
        for refund in body['invoice']['refunds']:
            if not 'amount' in refund:
                return abort(400)

            InvoiceRefund.create(invoice, refund)

    if 'notes' in body['invoice']:
        for note in body['invoice']['notes']:
            if not 'description' in note:
                return abort(400)

            InvoiceNote.create(invoice, note['description'])

    if 'send' in body:
        # TODO later
        pass

    return jsonify(invoice.to_json()), 200