Beispiel #1
0
 def testUnknownDeliveryCadence(self):
     dog1 = models.Dog("chicken", 32)
     dog2 = models.Dog("pork", 50)
     customer = models.Customer('foo')
     customer.AddDog(dog1)
     customer.AddDog(dog2)
     with self.assertRaises(Exception):
         self.assertEquals(cost_calc.GetTotalCost(customer), 117.03)
Beispiel #2
0
 def testUnknownRecipes(self):
     dog1 = models.Dog("Beef", 30)
     dog2 = models.Dog("Unknown", 126.555)
     customer = models.Customer('weekly')
     customer.AddDog(dog1)
     customer.AddDog(dog2)
     with self.assertRaises(Exception):
         self.assertEquals(cost_calc.GetTotalCost(customer), 117.03)
Beispiel #3
0
def get_data():
    session = db.session()
    name = request.form['name']
    date = request.form['jdate']
    address = request.form['address']
    email = request.form['email']

    c = models.Customer(name=name, jdate=date, address=address, email=email)
    session.add(c)
    session.commit()

    return redirect(url_for('hello'))
Beispiel #4
0
def add_new_customer():

    c1 = models.Customer()
    c1.firstname = input('Unesite ime customera: ')
    c1.lastname = input('Unesite prezime customera: ')
    c1.telephone_number = input('Unesite broj telefona:')
    try:
        db.add(c1)
        db.commit()
        db.close()
    except:
        print("Doslo do greske pri upisivanju u bazi!")
Beispiel #5
0
def create_customer():
    session = db.session()
    name = request.form['customer-name']
    address = request.form['address']
    email = request.form['email']
    customer = models.Customer(name = name,
                               jdate = datetime.date.today(),
                               address = address,
                               email = email)
    session.add(customer)
    session.commit()
    return redirect(url_for('hello'))
Beispiel #6
0
def create_customers():
    session = models.get_session()
    name = request.form['name']
    address = request.form['address']
    email = request.form['email']
    new_customer = models.Customer(jdate=datetime.date.today(),
                                   name=name,
                                   address=address,
                                   email=email)

    session.add(new_customer)
    session.commit()
    return redirect(url_for('hello', info="added"))
Beispiel #7
0
 def testGetTotalCost(self):
     dog1 = models.Dog("chicken", 30)
     dog2 = models.Dog("pork", 126.555)
     customer = models.Customer('weekly')
     customer.AddDog(dog1)
     customer.AddDog(dog2)
     # dog1: chicken, 30 lbs dog weight, weekly
     # 			int(29 * 30 * 0.453592 ** 0.8) / 590 * 1.49 * 14 = 16.3344
     # dog2: pork, 126 lbs dog weight, weekly
     # 			int(29 * 126 * 0.453592 ** 0.8) / 500 * 1.25 * 14 = 67.9467
     # totalcost: 84.269 + 0.12 * 14 * 2 + 29.4 = 117.03
     self.assertEquals(cost_calc.GetTotalCost(customer), 117.03)
     dog1 = models.Dog("chicken", 32)
     dog2 = models.Dog("pork", 50)
     customer = models.Customer('monthly')
     customer.AddDog(dog1)
     customer.AddDog(dog2)
     # dog1: chicken, 32 lbs dog weight, weekly
     # 			int(29 * 32 * 0.453592 ** 0.8) / float(590) * 1.49 * 56
     # dog2: pork, 50 lbs dog weight, weekly
     # 			int(29 * 50 * 0.453592 ** 0.8) / float(500) * 1.25 * 56
     # totalcost:  177.522 + 0.12 * 56 * 2 + 47.6 = 238.56
     self.assertEquals(cost_calc.GetTotalCost(customer), 238.56)
def reserve_room(db: Session, customer: schemas.Customer):
    ''' customer id is auto incremented so leaving that all the other required fields is given to reserve a room'''

    db_a = models.Customer(name=customer.name,
                           age=customer.age,
                           phone_no=customer.phone_no,
                           email=customer.email,
                           address=customer.address,
                           room_no=customer.room_no,
                           date=customer.date,
                           length_of_stay=customer.length_of_stay)
    db.add(db_a)
    db.commit()
    db.refresh(db_a)
    return db_a
Beispiel #9
0
def main(phone):
    user = None
    try:
        user = models.session.query(models.Customer).filter(
            models.Customer.telephone == phone).first()
    except:
        print('Ошибка запроса')
    if not user:
        user = models.Customer()
    post = Post()
    invoker = Invoker()
    recognize = Recognize(entity, intent, name, city, product, context_words)
    phrase = PromptStack(invoker, recognize, prompts_dict)
    context = Context(Hello(), user, invoker, phrase, recognize, post)
    context.request()
Beispiel #10
0
def main():
    randusers = random.sample(range(65368, 98110), 1000)

    for randuser in randusers:
        print "inserting to customer", randuser

        # assign random country to each chef
        countryid = random.randint(1, 260)
        zipcode = random.randint(1, 99999)

        customer = models.Customer("", "", "", "", zipcode, countryid,
                                   1234567890, "", randuser)
        models.db.session.add(customer)
        models.db.session.commit()

        print "done"
Beispiel #11
0
def create_customer():
    c_message = "Customer Created successfully!"
    if session.get('username') and session.get('type') == 'executive':

        with open('static/state_city.json') as datafile:
            data = json.load(datafile)
        if request.method == 'POST':
            ssnid = request.form['ssnid']
            name = request.form['name']
            age = request.form['age']
            address = request.form['address']
            skey = int(request.form['state'])
            ckey = int(request.form['city'])
            state = data['states'][skey]['state']
            city = data['states'][skey]['city'][ckey]
            if ssnid and name and age and address and state and city:
                customer = models.Customer.query.filter_by(ssnid=ssnid).first()
                if (customer == None):
                    customer = models.Customer(ssnid=ssnid,
                                               name=name,
                                               age=age,
                                               address=address,
                                               state=state,
                                               city=city)
                    db.session.add(customer)
                    db.session.commit()
                    customer = models.Customer.query.filter_by(
                        ssnid=ssnid).first()
                    c_status = models.CustomerStatus(
                        customer_cid=customer.cid,
                        customer_ssnid=customer.ssnid,
                        message=c_message,
                        status="active")
                    db.session.add(c_status)
                    db.session.commit()
                    flash(c_message, "success")
                else:
                    flash(
                        "Customer with SSN ID : " + ssnid + " already exists!",
                        "warning")
                return render_template('Customer/create_customer.html',
                                       data=data)
        elif request.method == 'GET':
            return render_template('Customer/create_customer.html', data=data)
    else:
        flash("Login first as a Executive", "danger")
        return redirect(url_for('login'))
Beispiel #12
0
def create_customer(db: Session, new_customer: str, ref_code: str):
    check_code = db.query(
        models.Customer).filter(models.Customer.own_code == ref_code).first()
    if check_code:
        new_ref_code = ref_code

    else:
        new_ref_code = "0"

    own_code = uuid.uuid4().hex[:6].upper()
    db_customer = models.Customer()
    db_customer.name = new_customer
    db_customer.own_code = own_code
    db_customer.ref_code = new_ref_code
    db.add(db_customer)
    db.commit()
    db.refresh(db_customer)
    return db_customer
Beispiel #13
0
def create_customer():
    data = request.get_json()

    if data['name'] and data['address'] and data['phone']:
        customer = models.Customer(
            public_id=str(uuid.uuid4()),
            name=data['name'],
            address=data['address'],
            phone=data['phone']
        )

        db.session.add(customer)
        db.session.commit()

        if customer:
            return jsonify({'message': 'Customer successfully created!', 'customer': customer.serialize()}), 201

        else:
            return jsonify({'message': 'Customer was not created! Something wrong on server'}), 502

    else:
        return jsonify({'message': 'All fields required!'}), 400
Beispiel #14
0
def create_customer():
    session = models.get_session()

    name = request.form['name']
    address = request.form['address']
    email = request.form['email']

    new_customer = models.Customer(name=name,
                                   jdate=datetime.date.today(),
                                   address=address,
                                   email=email)
    session.add(new_customer)
    f = faker.Faker()
    for i in range(5):
        invoice = models.Invoice(particulars=f.sentence(),
                                 date=f.date(),
                                 amount=random.randint(10, 99),
                                 customer=new_customer)
        session.add(invoice)

    session.commit()
    return redirect(url_for('hello', info="added"))
def populateCustomer():
    count = 100
    type_list = ['normal', 'student']
    age10 = list(range(5, 10))
    age20 = list(range(11, 19))
    age30 = list(range(20, 30))
    age50 = list(range(31, 50))
    age70 = list(range(51, 70))
    age100 = list(range(71, 100))
    wr = age10 * 10 + age20 * 30 + age30 * 50 + age50 * 5 + age70 * 4 + age100 * 1
    while count > 0:
        name = fake.name()
        age = random.choice(wr)
        type = 'normal'
        if age <= 10:
            type = 'child'
        elif age >= 60:
            type = 'senior'
        else:
            type = random.choice(type_list)
        customer = models.Customer(name=name, age=age, type=type)
        db.session.add(customer)
        db.session.commit()
        count -= 1
Beispiel #16
0
    def post(self):
        email = (self.request.get('email')).lower()
        password = self.request.get('password')
        auth = self.auth

        if not auth.get_user_by_session():
            accType = 'customer'
            customer = models.Customer()
        else:
            accType = self.request.get('accType')
            customer = models.Staff()

        customer.Email = email
        customer.First_Name = self.request.get('firstname')
        customer.Last_Name = self.request.get('lastname')
        customer.Contact_No = int(self.request.get('contact'))
        customer.Address = self.request.get('address')
        customer.postalCode = int(self.request.get('postalcode'))

        #unique_properties = ['email_address']
        acct_data = self.user_model.create_user(email,
                                                email_address=email,
                                                password_raw=password,
                                                first_name=customer.First_Name,
                                                accounType=accType,
                                                verified=False)

        if not mail.is_email_valid(email):
            self.display_message('invalid email entered')
            return

        if not acct_data[0]:  #acct_data is a tuple
            self.display_message('Unable to create user for email %s because \
            it already exist' % (email))
            return

        customer.put()
        user = acct_data[1]
        user_id = user.get_id()

        token = self.user_model.create_signup_token(user_id)

        verification_url = self.uri_for('verification',
                                        type='v',
                                        user_id=user_id,
                                        signup_token=token,
                                        _full=True)

        msg = 'Send an email to user in order to verify their address. \
          They will be able to do so by visiting <a href="{url}">{url}</a>'

        message = mail.EmailMessage()
        message.sender = '*****@*****.**'
        message.to = email
        message.body = """
        testing email
        %s
        """ % msg.format(url=verification_url)
        message.Send()

        #self.display_message(msg.format(url=verification_url))
        self.display_message(
            'A verification email has been sent to the respective email!')
Beispiel #17
0
    def setData(self):
        womens = [
            "Myrtis Kahn  ", "Margery Hou  ", "Georgianne Teneyck  ",
            "Zora Dunsmore  ", "Misha Calcagni  ", "Coral Watson  ",
            "Destiny Millet  ", "Willodean Severt  ", "Nanci Nicol  ",
            "Maris Credle  ", "Brittney Hawes  ", "Maryrose Butterworth  ",
            "Catherin Dobson  ", "Marylin Torpey  ", "Myrtle Tracy  ",
            "Velda Coy  ", "Lolita Maglio  ", "Stephaine Ciulla  ",
            "Regina Quarterman  ", "Dorine Bucy  "
        ]
        mans = [
            "Lowell Wightman  ", "Avery Harriger  ", "Alonso Marcello  ",
            "Johnson Rego  ", "Wilfred Mackay  ", "Trent Dimick  ",
            "Edgar Holtkamp  ", "Nicholas Chaudhry  ", "Bernard Bourbeau  ",
            "Gabriel Sperling  ", "Rolf Cirillo  ", "Ruben Turberville  ",
            "Ethan Dresser  ", "Spencer Bourque  ", "Marcelo Draves  ",
            "Galen Maybee  ", "Malcom Mckee  ", "Felix Moreles  ",
            "Reuben Villalpando  ", "Archie Liao  "
        ]
        sellers = []
        products = []
        customers = []
        for p in womens:
            sellers.append(
                self.sellers.insert_one(
                    models.Seller(p.split(" ")[0],
                                  p.split(" ")[1])).inserted_id)
            customers.append(
                self.customers.insert_one(
                    models.Customer(p.split(" ")[0],
                                    p.split(" ")[1])).inserted_id)
        for p in mans:
            sellers.append(
                self.sellers.insert_one(
                    models.Seller(p.split(" ")[0],
                                  p.split(" ")[1])).inserted_id)
            customers.append(
                self.customers.insert_one(
                    models.Customer(p.split(" ")[0],
                                    p.split(" ")[1])).inserted_id)
        for i in range(0, 100):
            products.append(
                self.products.insert_one(
                    models.Product("Product " + str(randint(0, 1000)),
                                   randint(0, 10000))).inserted_id)

        for i in range(0, 75000):
            pr = self.products.find_one(
                {'_id': ObjectId(products[randint(0,
                                                  len(products) - 1)])})
            count = randint(0, 10)

            sell = self.sellers.find_one(
                {"_id": sellers[randint(0,
                                        len(sellers) - 1)]})
            cust = self.customers.find_one(
                {"_id": customers[randint(0,
                                          len(customers) - 1)]})

            self.sales.insert_one(
                models.Sale(sell, cust, pr, count, count * pr["price"]))
Beispiel #18
0
wheel1 = models.Wheel("wheel1", 10, 30)
wheel2 = models.Wheel("wheel2", 8, 25)
wheel3 = models.Wheel("wheel3", 6, 20)

frame1 = models.Frame("frame1", 15, 40)
frame2 = models.Frame("frame2", 10, 50)
frame3 = models.Frame("frame3", 13, 45)

bike1 = models.Bicycle_Model("bike1", "manufacturer1", wheel1, frame1)
bike2 = models.Bicycle_Model("bike2", "manufacturer1", wheel2, frame2)
bike3 = models.Bicycle_Model("bike3", "manufacturer1", wheel3, frame3)
bike4 = models.Bicycle_Model("bike4", "manufacturer2", wheel1, frame1)
bike5 = models.Bicycle_Model("bike5", "manufacturer2", wheel2, frame2)
bike6 = models.Bicycle_Model("bike6", "manufacturer2", wheel3, frame3)

manufacturer1 = models.Bicycle_Manufacturer("manufacturer1", [bike1, bike2, bike3], 0.25)
manufacturer2 = models.Bicycle_Manufacturer("manufacturer2", [bike4, bike5, bike6], 0.20)

bike_shop_1 = models.Bike_Shop("bike shop 1", [manufacturer1, manufacturer2], 0.20)
bike_shop_2 = models.Bike_Shop("bike shop 2", [manufacturer1, manufacturer2], 0.25)

alex = models.Customer("Alex", 200)
ben = models.Customer("Ben", 500)
fred = models.Customer("Fred", 1000)

for manufacturer in bike_shop_1.manufacturers:
    for model in manufacturer.models:
        print model.name, model.weight

Beispiel #19
0
def charge():
    if request.form:
        stripe_token = request.form.get('stripeToken')
        stripe_email = request.form.get('stripeEmail')
        connected_user_id = session['connected_user_id']

        try:
            # Check if there is a Customer already created for this email
            platform_account_customers = stripe.Customer.list()
            platform_customer = [
                cus for cus in platform_account_customers
                if cus.email == stripe_email
            ]
            # If there was no customer, need to create a new platform customer
            if not platform_customer:
                stripe_customer = stripe.Customer.create(
                    email=stripe_email,
                    source=stripe_token,
                )
                # Check if we had the customer in he db
                if not db.session.query(models.Customer).filter(
                        'email' == stripe_email).count():
                    #Create the db user
                    new_customer = models.Customer(
                        stripe_id=stripe_customer.stripe_id,
                        email=stripe_customer.email,
                        account_balance=stripe_customer.account_balance,
                        creation_time=stripe_customer.created,
                        currency=stripe_customer.currency,
                        delinquent=stripe_customer.delinquent,
                        description=stripe_customer.description,
                    )
                    db.session.add(new_customer)
                    db.session.commit()

                # Need to recreate the token to be able to crete the customer on the connected account too
                cus_token = stripe.Token.create(
                    customer=stripe_customer.id,
                    stripe_account=connected_user_id)
                # Create the customer in the connected account
                connected_account_customer = stripe.Customer.create(
                    email=stripe_customer.email,
                    source=cus_token.id,
                    stripe_account=connected_user_id,
                )
                # Make the charge to the customer on the connected account
                amount = 10000
                stripe.Charge.create(
                    amount=amount,
                    currency='eur',
                    customer=connected_account_customer.id,
                    stripe_account=connected_user_id,
                    application_fee=123,
                )
            # Just make the charge
            else:
                # Amount is always in cents
                amount = 10000
                stripe.Charge.create(
                    amount=amount,
                    currency='eur',
                    source=stripe_token,
                    stripe_account=connected_user_id,
                    application_fee=123,
                )

        except Exception as e:
            print(repr(e))
            return render_template('error.html', error=repr(e))
        return render_template('success.html',
                               payment_amount=str(amount / 100),
                               connected_account_id=connected_user_id,
                               connected_account_email=stripe_email)
"""

import models
import helpers

start_amy = "Plus"
start_jak = "Infinite"

if (__name__ == '__main__'):
    """Jake is a character from the show Brooklyn 99. His website, password choices
    and subscription change frequency reveal who he is.
    """

    # Jake takes the infinite plan and three websites.
    # Jake is not known for being good with his finances.
    jake = models.Customer("Jake Peralta", "diehardfan", "@jakeperalta99.com")
    print(jake)
    jake.select_plan(start_jak, helpers.datetime_now())  # 249 0 0 249
    jake.add_website("superdupercop.com", True)
    jake.add_website("iamjohnmclane.com", False)
    jake.add_website("iheartpuzzles.com", False)

    print(jake)

    jake.move_to_plan(
        "Single",
        helpers.datetime_months_hence(helpers.datetime_get_last_event(jake),
                                      4))

    # Jake realizes he needs those sites again
    jake.move_to_plan(
Beispiel #21
0
def ingest(event, event_store):

    if event['type'] == 'CUSTOMER':
        #check if customer key exists in event store, if not add else check if the event verb is update and update the customer
        customer_id = str(event['key'])
        if customer_id not in event_store:
            event_time = models.convert_datetime(event['event_time'])
            last_name = event['last_name']
            adr_city = event['adr_city']
            adr_state = event['adr_state']
            customer = models.Customer(customer_id, event_time, last_name,
                                       adr_city, adr_state)
            event_store[customer_id] = {'customer_info': customer}
        else:
            #if the verb is Update. Update the customer
            if event['verb'] == 'UPDATE':
                customer = event_store[key]['customer_info']
                customer.event_time = models.convert_datetime(
                    event['event_time'])
                customer.last_name = event['last_name']
                customer.adr_city = event['adr_city']
                customer.adr_state = event['adr_state']

    if event['type'] == 'SITE_VISIT':
        #assign the site visit to the customer in the event store dict

        page_id = event['key']
        customer_id = event['customer_id']
        if customer_id not in event_store:
            raise ValueError('Customer does not exist for this site visit!')

        #site_visits is a dict with key as page_id and value as SiteVisit objecte
        if 'site_visits' not in event_store[customer_id]:
            event_store[customer_id]['site_visits'] = {}

        site_visits = event_store[customer_id]['site_visits']
        if page_id not in site_visits:
            event_time = models.convert_datetime(event['event_time'])
            customer_id = event['customer_id']
            tags = event['tags']
            site_visit = models.SiteVisit(page_id, event_time, customer_id,
                                          tags)
            site_visits[page_id] = site_visit

    if event['type'] == 'IMAGE':
        #assign the image upload to the customer in the event store dict

        image_id = event['key']
        customer_id = event['customer_id']
        if customer_id not in event_store:
            raise ValueError('Customer does not exist for this image upload!')

        #image_uploads is a dict with key as image_id and value as ImageUpload object
        if 'image_uploads' not in event_store[customer_id]:
            event_store[customer_id]['image_uploads'] = {}

        image_uploads = event_store[customer_id]['image_uploads']

        if image_id not in image_uploads:
            event_time = models.convert_datetime(event['event_time'])
            customer_id = event['customer_id']
            camera_make = event['camera_make']
            camera_model = event['camera_model']
            image_upload = models.ImageUpload(image_id, event_time,
                                              customer_id, camera_model,
                                              camera_make)
            image_uploads[image_id] = image_upload

    if event['type'] == 'ORDER':
        #assign the order to the customer in the event store dict

        order_id = event['key']
        customer_id = event['customer_id']
        if customer_id not in event_store:
            raise ValueError('Customer does not exist for this order!')

        #orders is a dict with key as orderid and value as Order object
        if 'orders' not in event_store[customer_id]:
            event_store[customer_id]['orders'] = {}

        orders = event_store[customer_id]['orders']

        if order_id not in orders:
            event_time = models.convert_datetime(event['event_time'])
            customer_id = event['customer_id']
            total_amount = event['total_amount']
            order = models.Order(order_id, event_time, customer_id,
                                 total_amount)
            orders[order_id] = order
        else:
            #if the verb is Update. Update the order
            if event['verb'] == 'UPDATE':
                order = event_store[customer_id]['orders'][order_id]
                order.event_time = models.convert_datetime(event['event_time'])
                order.customer_id = event['customer_id']
                order.total_amount = event['total_amount']

    return event_store
def as_customer_payload(dict):
    customer = models.Customer(dict['id'], dict['name'], dict['address'],
                               dict['credit'], dict['status'], dict['remarks'])
    return customer
Beispiel #23
0
import uuid

import models
from __init__ import db

# db.create_all()
#
# user = User('test', '*****@*****.**', '12345678')
#
# db.session.add(user)
# db.session.commit()

customer = models.Customer(public_id=str(uuid.uuid4()),
                           name='Rik Morty',
                           address='Ukraine, Kyiv, Soloma str., 234',
                           phone='+380989694355')
customer1 = models.Customer(public_id=str(uuid.uuid4()),
                            name='Erik Kirk',
                            address='USA, NY, Blabla str., 123d',
                            phone='+190989694355')
customer2 = models.Customer(public_id=str(uuid.uuid4()),
                            name='Megan Fox',
                            address='England, Barber str., 24a',
                            phone='+280989694355')

db.session.add(customer)
db.session.add(customer1)
db.session.add(customer2)
db.session.commit()

product = models.Product(public_id=str(uuid.uuid4()),
Beispiel #24
0
def add_client():
    try:
        # Проверка авторизации
        check_auth(request)

        # Проверка типа содержимого
        content_type = request.headers.get("Content-Type")

        if content_type.find('multipart/form-data') == -1:
            return "Содержимое запроса должно иметь тип 'multipart/form-data'", 400

        # Получение файла изображения из запроса
        if 'file' not in request.files:
            return "В запросе отсутствует файл изображения лица идентифицируемого человека", 400

        image = request.files['file'].read()
        image = Image.open(io.BytesIO(image))
        image = np.array(image)

        descriptor = get_descriptor(image)
        if descriptor is None:
            return "Не удалось извлечь дескриптор лица человека из изображения"

        attributes = request.form["attributes"]
        if attributes is None:
            return "В теле запроса отсутсвуют атрибуты посетителя", 400

        try:
            attributes = json.loads(attributes)
            attributes["Дата создания"] = datetime.now().strftime("%Y.%m.%d %H:%M:%S")
        except JSONDecodeError as ex:
            return "Атрибуты посетителя переданы в некорректном формате: {}".format(ex), 400

        if check_novelty(descriptor) != True:
            return "Пользователь уже известен в системе", 409

        session = create_session()
        customer = models.Customer(json.dumps(attributes))
        session.add(customer)
        session.flush()

        descriptors = models.Descriptors(descriptor, customer.id)
        session.add(descriptors)
        session.flush()

        face_image_id = uuid.uuid4()
        face_image = models.FaceImage(face_image_id, "{0}/{1}.jpg".format(customer.id, face_image_id), customer.id)
        session.add(face_image)
        session.flush()

        os.mkdir("files/{0}".format(customer.id))
        cv2.imwrite("files/{0}/{1}.jpg".format(customer.id, face_image_id), image)

        session.add(customer)

        session.expunge_all()
        session.commit()
        session.close()

        response_data = {
            'customer_id': str(customer.id)
        }

        return Response(json.dumps(response_data), content_type='application/json; charset=utf-8'), 200
    except AuthException as ex:
        return ex.message, 401
Beispiel #25
0
def index():
    errors = []
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(filename)

        with open(filename, 'r') as fp:
            content = fp.readlines()

        content = [line.strip().split('\t') for line in content]

        for line in content:
            # map columns to names
            customer_id = int(line[0])
            first_name = line[1]
            last_name = line[2]
            address = line[3]
            state = line[4]
            zip_code = line[5]
            status = line[6]
            product_id = int(line[7])
            product_name = line[8]
            price = line[9]
            date = datetime.strptime(line[10], '%Y-%m-%dT%H:%MZ')
            #check if customer in database
            customer = db.session.query(models.Customer).filter(
                models.Customer.id == customer_id).first()
            if not customer:
                c = models.Customer(customer_id, first_name, last_name,
                                    address, state, zip_code)
                db.session.add(c)
            else:
                if customer.address != address or customer.state != state or customer.zip != zip_code:

                    customer.address = address
                    customer.state = state
                    customer.zip = zip_code

                    db.session.commit()

            # check if product in db
            product = db.session.query(models.Product).filter(
                models.Product.id == product_id).first()
            if not product:
                p = models.Product(product_id, product_name)
                db.session.add(p)

            # process order data
            if status == 'canceled':
                o = db.session.query(models.Order).filter(
                    models.Order.customer_id == customer_id,
                    models.Order.product_id == product_id).first()

                if o:  # if the order is already in the db
                    if o.status == 'new' and o.date < date:  # if the status of the order is new and was placed before
                        o.status = status
                        db.session.commit()

                else:
                    errors.append(
                        'Order of product {p_name} does not exist for customer {c_name}'
                        .format(p_name=product_name,
                                c_name=first_name + ' ' + last_name))

            else:  # the order did not exist in the db, we will add this to the list of errors
                new_order = models.Order(customer_id, product_id, price,
                                         status, date)
                db.session.add(new_order)

        db.session.commit()

    return render_template('index.html', errors=errors)