コード例 #1
0
    def post(self, request):
        postdata = request.POST
        fullname = postdata.get('fullname')
        phone = postdata.get('phone')
        email = postdata.get('email')
        password = postdata.get('password')
        image = postdata.get('image')
        value = {
            'fullname': fullname,
            'phone': phone,
            'email': email,
            'password': password,
            'image': image,
        }
        error_message = None
        customer = Customer(fullname=fullname,
                            email=email,
                            password=password,
                            phone=phone,
                            image=image)
        error_message = self.Validation(customer)

        if not error_message:
            customer.password = make_password(customer.password)
            customer.save()
            return redirect("login")
        else:
            data = {
                'error': error_message,
                'value': value,
            }

        return render(request, 'signup.html', data)
コード例 #2
0
def new_customer():
    request_body = request.get_json()
    if "name" in request_body and "postal_code" in request_body and "phone" in request_body:
        customer = Customer(**request_body)
        db.session.add(customer)
        db.session.commit()
        return jsonify(customer.customer_info()), 201
    else:
        return jsonify({"details": "Invalid data"}), 400
コード例 #3
0
def customers():
    request_body = request.get_json()
    if "name" not in request_body or "postal_code" not in request_body or "phone" not in request_body:
        return make_response({"details": "Invalid data"}, 400)
    else:
        new_customer = Customer(name=request_body["name"],
                                postal_code=request_body["postal_code"],
                                phone=request_body["phone"])
        new_customer.registered_at = datetime.now()
        db.session.add(new_customer)
        db.session.commit()
        return make_response({"id": new_customer.id}, 201)
コード例 #4
0
def customers_create():
    request_body = request.get_json()

    if invalid_customer_data(request_body):
        return {"message": "Invalid Request"}, 400

    name = request_body.get("name")
    postal_code = request_body.get("postal_code")
    phone = request_body.get("phone")

    customer = Customer(name=name, postal_code=postal_code, phone=phone)
    customer.save()

    return {
        "id": customer.id,
    }, 201
コード例 #5
0
    def check_out(cls, video_id, customer_id):
        new_rental = cls(video_id=video_id, customer_id=customer_id)
        if not new_rental:
            return None

        video = Video.get_video_by_id(new_rental.video_id)
        customer = Customer.get_customer_by_id(new_rental.customer_id)

        # If no available inventory, you can't rent the video
        if video.available_inventory <= 0:
            return None

        new_rental.save()
        video.available_inventory -= 1
        customer.videos_checked_out_count += 1
        video.save()
        customer.save()

        videos_checked_out_count = customer.videos_checked_out_count
        available_inventory = video.available_inventory

        return {
            # "id": new_rental.id,
            "video_id": new_rental.video_id,
            "customer_id": new_rental.customer_id,
            "videos_checked_out_count": videos_checked_out_count,
            "available_inventory": available_inventory,
            "due_date": new_rental.due_date
        }
コード例 #6
0
ファイル: controllers.py プロジェクト: hesterhawk/opensara
def all(project_token: str):
    project = Project.query.filter_by(token=project_token).first()
    
    page = request.args.get(get_page_parameter(), type=int, default=1)
    customers = Customer.query.filter_by(project_id=project.id).order_by(Customer.state, Customer.created_date).paginate(page, PER_PAGE, False).items
    pagination = Pagination(per_page=PER_PAGE, page=page, total=Customer.query.count(), record_name='customers', css_framework='bootstrap4')

    form = CreateCustomerForm()

    if form.validate_on_submit():
        customer = Customer(
            project_id=project.id, 
            state=form.state.data, 
            instagram_login=form.instagram_login.data, 
            created_date=datetime.now()
        )

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

        flash("Customer created successfully!")
        return redirect(url_for('note.all', project_token=project.token) + '?c=' + str(customer.id))

    return render_template(
        'customers.html', 
        _menu='customers',
        form=form,
        project=project, 
        customers=customers,
        pagination=pagination,
        select_customers=Customer.query.filter_by(project_id=project.id).all()
    )
コード例 #7
0
def create_customer(customer_payload):
    customer = Customer(
        first_name=customer_payload['first_name'],
        last_name=customer_payload['last_name'],
        national_id_number=customer_payload['national_id_number'],
        primary_phone_number=customer_payload['primary_phone_number'],
        primary_email=customer_payload['primary_email'],
        password=customer_payload['password'],
        account_status=CustomerStatus.INACTIVE,
        physical_address=customer_payload['physical_address'],
        city=customer_payload['city'],
        county=customer_payload['county'],
        postal_address=customer_payload['postal_address'],
        postal_code=customer_payload['postal_code'],
        gender=customer_payload['gender'],
        birth_date=customer_payload['birth_date'],
        kra_pin=customer_payload['kra_pin'],
        attachment_id_front=customer_payload['attachment_id_front'],
        attachment_id_back=customer_payload['attachment_id_front'])

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

    except Exception as exception:
        print("error : ", exception)
コード例 #8
0
def get_rentals_for_customer(customer_id):
    customer = Customer.get_customer_by_id(customer_id)
    if not customer:
        return {"message": f"Customer {customer_id} not found"}, 404

    rentals = customer.rentals

    results = [rental.to_json() for rental in rentals]
    return jsonify(results), 200
コード例 #9
0
def customers_delete(customer_id):
    customer = Customer.get_customer_by_id(customer_id)
    if not customer:
        return {"message": f"Customer {customer_id} was not found"}, 404

    customer.delete()

    return {
        "id": customer.id,
    }, 200
コード例 #10
0
 def generate_customer(self, ip=None, name=None):
     return Customer.generate_customer(server_id=self.user_id,
                                       phone=self.customer_phone,
                                       name=self.customer_name,
                                       account_id=self.account_id,
                                       province=self.province,
                                       city=self.city,
                                       district=self.district,
                                       customer_type=self.order_type,
                                       ip=ip,
                                       u_name=name)
コード例 #11
0
    def create_customer(self, customerid: str, name: str, lastname: str, address: str, phone: str, email: str, rents: list):
        """Creates a customer object. If the parameters fail in the validation, it returns False"""

        logging.info('Validating parameters')
        is_valid = Validators.valid_customer(customerid, name, lastname, address, phone, email, rents)
        if is_valid:
            logging.info('Parameters are ok, creating customer')
            customer = Customer(customerid, name, lastname, address, phone, email, rents)
            return customer
        else:
            logging.info('There has been an error in parameters validation, returning False')
            return False
コード例 #12
0
def customers():
    try:
        request_body = request.get_json()
        new_customer = Customer(name=request_body["name"],
                                postal_code=request_body["postal_code"],
                                phone=request_body["phone"])

        db.session.add(new_customer)
        db.session.commit()

        return jsonify({"id": new_customer.customer_id}), 201
    except KeyError:
        return jsonify({"details": "Invalid data"}), 400
コード例 #13
0
ファイル: routes.py プロジェクト: ivsgit/retro-video-store
def add_customer():
    customer_to_add = request.get_json()
    validation = customer_validation(customer_to_add)

    if not validation:
        return err_400()

    new_customer = Customer(name=customer_to_add["name"],
                            postal_code=customer_to_add["postal_code"],
                            phone=customer_to_add["phone"])

    db.session.add(new_customer)
    db.session.commit()

    return jsonify({"id": new_customer.client_id}), 201
コード例 #14
0
 def index(self):
     args = dict(account_id=g.current_account.id,
                 user=g.current_user,
                 customer_type=request.args.get("type", 1),
                 name=request.args.get("name"),
                 phone=request.args.get("phone"),
                 city=request.args.get("city"),
                 server_id=request.args.get("server_id"),
                 start_time=request.args.get("start_time"),
                 end_time=request.args.get("end_time"))
     customers, page = Customer.filter_customer(**args)
     return dict(msg="ok",
                 code=200,
                 customers=[c.to_json() for c in customers],
                 page=page)
コード例 #15
0
def create_customer():
    request_body = request.get_json()

    if ("name" not in request_body or "postal_code" not in request_body \
        or "phone" not in request_body):
        return jsonify({"erro": "Invalid data"}), 400

    else:
        customer = Customer(name=request_body["name"],
                            postal_code=request_body["postal_code"],
                            phone=request_body["phone"],
                            registered_at=datetime.now())

    db.session.add(new_customer)
    db.session.commit()
    return jsonify({"id": customer.id}), 201
コード例 #16
0
def customers_update(customer_id):
    customer = Customer.get_customer_by_id(customer_id)
    if not customer:
        return {"message": f"Customer {customer_id} was not found"}, 404

    request_body = request.get_json()
    if invalid_customer_data(request_body):
        return {"message": "Invalid data"}, 400

    customer.name = request_body.get("name")
    customer.postal_code = request_body.get("postal_code")
    customer.phone = request_body.get("phone")

    customer.save()

    return customer.to_json(), 200
コード例 #17
0
 def __get_customer_budget(self, customer_id, year):
     """Get customer budget for a specific year."""
     try:
         customer_model = CustomerModel.get(CustomerModel.id == customer_id)
         events = (EventModel.select(
             EventModel.id, EventModel.ticket_price,
             (fn.COUNT(TicketModel.id) *
              EventModel.ticket_price).alias('total_costs')).join(
                  TicketModel).join(CustomerModel).where(
                      CustomerModel.id == customer_id,
                      EventModel.date.year == year).group_by(EventModel.id))
         costs = 0
         for event in events:
             costs = costs + event.total_costs
         return customer_model.budget - costs
     except DoesNotExist:
         raise DbActorError("Customer not found.", 404) from DoesNotExist
コード例 #18
0
def add_new_customer():
    request_body = request.get_json()

    # ❗️ Wish I could have refactored this into a helper method (ran out of time) - I use this code so many times
    if (not request_body) or ("name" not in request_body) or (
            "postal_code" not in request_body) or ("phone"
                                                   not in request_body):
        return make_response({"details": "Invalid data"}, 400)
    new_customer = Customer(name=request_body["name"],
                            postal_code=request_body["postal_code"],
                            phone=request_body["phone"],
                            registered_at=datetime.datetime.now())

    db.session.add(new_customer)
    db.session.commit()

    return make_response({"id": new_customer.cust_id}, 201)
コード例 #19
0
 def create(cls, data):
     errors = cls.validate_data(data)
     if errors:
         return make_response(errors, 400)
     print(data)
     print(type(data))
     print(data["name"])
     print(data["postal_code"])
     print(data["phone"])
     new_customer = Customer(name=data["name"],
                             postal_code=data["postal_code"],
                             phone=data["phone"],
                             registered_at=datetime.now())
     db.session.add(new_customer)
     db.session.commit()
     json = cls.customer_json(new_customer)
     return make_response(json, 201)
コード例 #20
0
def create_customer():
    """Create a customer for the database"""
    request_body = request.get_json()
    if "name" not in request_body or "postal_code" not in request_body or "phone" not in request_body:
        return make_response(
            {
                "details":
                "Customer name, phone number and postal code must all be provided, and they must be strings"
            }, 400)
    new_customer = Customer(name=request_body["name"],
                            postal_code=request_body["postal_code"],
                            phone_number=request_body["phone"],
                            register_at=datetime.now())

    db.session.add(new_customer)
    db.session.commit()
    return make_response({"id": new_customer.customer_id}, 201)
コード例 #21
0
ファイル: login.py プロジェクト: aashish0010/profile1
    def post(self, request):
        fullname = request.POST.get('fullname')
        password = request.POST.get('password')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        customer = Customer.get_customer_by_email(email)
        error_message = None
        if customer:
            flag = check_password(password, customer.password)
            if flag:
                request.session['customer'] = customer.id
                request.session['email'] = customer.email
                request.session['fullname'] = customer.fullname

                return redirect('profile')
            else:
                error_message = 'password is invalid'

        else:
            error_message = 'Email is invalid...'
        return render(request, 'login.html', {'error': error_message})
コード例 #22
0
def check_in_video():
    request_body = request.get_json()

    if invalid_rental_data(request_body):
        return {"message": "Invalid request body"}, 400

    video = Video.get_video_by_id(request_body["video_id"])

    if not video:
        return {"message": f"Video {request_body['video_id']} not found."}, 404

    customer = Customer.get_customer_by_id(request_body['customer_id'])

    if not customer:
        return {
            "message": f"Customer {request_body['customer_id']} not found"
        }, 404

    result = Rental.check_in(video_id=video.id, customer_id=customer.id)

    return result
コード例 #23
0
    def check_in(cls, customer_id, video_id):
        checked_in_rental = cls.query.filter(
            Rental.customer_id == customer_id).filter(
                Rental.video_id == video_id).filter(
                    Rental.status == "Checked_out").first()

        if not checked_in_rental:
            return {
                "message":
                f"No outstanding rentals for customer # {customer_id} and video {video_id}"
            }, 400

        checked_in_rental.status = None

        video = Video.get_video_by_id(checked_in_rental.video_id)
        customer = Customer.get_customer_by_id(checked_in_rental.customer_id)

        if not video:
            return {"message": f"Movie id: {video_id} not found"}, 404

        if not customer:
            return {"message": f"Customer id: {customer_id} not found"}, 404

        video.available_inventory += 1
        customer.videos_checked_out_count -= 1

        checked_in_rental.save()
        video.save()
        customer.save()

        videos_checked_out_count = customer.videos_checked_out_count
        available_inventory = video.available_inventory

        return {
            # "id": checked_in_rental.id,
            "video_id": checked_in_rental.video_id,
            "customer_id": checked_in_rental.customer_id,
            "videos_checked_out_count": videos_checked_out_count,
            "available_inventory": available_inventory,
        }, 200
コード例 #24
0
 def __purchase_event_ticket(self, customer_id, event_id, quantity):
     """Purchase of a certain number of tickets for a specific event."""
     try:
         event_model = EventModel.get(EventModel.id == event_id)
     except DoesNotExist:
         raise DbActorError("Event not found.", 404) from DoesNotExist
     customer_model = CustomerModel.get(CustomerModel.id == customer_id)
     event_customer_ticket_models = (TicketModel.select().join(
         CustomerModel).switch(TicketModel).join(EventModel).where(
             CustomerModel.id == customer_id, EventModel.id == event_id))
     event_ticket_models = (TicketModel.select().join(EventModel).where(
         EventModel.id == event_id))
     total_price = event_model.ticket_price * quantity
     available_budget = self.__get_customer_budget(customer_model.id,
                                                   event_model.date.year)
     if available_budget - total_price < 0:
         raise DbActorError("The budget of the customer is not sufficient.",
                            400)
     if event_model.max_tickets_per_customer < len(
             event_customer_ticket_models) + quantity:
         raise DbActorError(
             ("With this purchase the maximum number of tickets per "
              "customer for this event would be exceeded."), 400)
     if event_model.max_tickets < len(event_ticket_models) + quantity:
         raise DbActorError(("With this purchase the maximum number of "
                             "tickets for this event would be exceeded."),
                            400)
     sale_not_started = event_model.sale_start_date > date.today()
     sale_end_date = event_model.sale_start_date + \
         timedelta(days=event_model.sale_period)
     sale_over = sale_end_date < date.today()
     if sale_not_started or sale_over:
         raise DbActorError(
             "Currently no tickets can be purchased for this event.", 400)
     for _ in range(quantity):
         ticket_model = TicketModel(order_date=date.today(),
                                    customer=customer_model,
                                    event=event_model)
         ticket_model.save()
コード例 #25
0
 def __check_customer_id(self, customer_id):
     """Check if customer exists."""
     try:
         CustomerModel.get(CustomerModel.id == customer_id)
     except DoesNotExist:
         raise DbActorError("Customer not found.", 404) from DoesNotExist
コード例 #26
0
def customers_index():
    customers = [
        customer.to_json() for customer in Customer.get_all_customers()
    ]
    return jsonify(customers), 200
コード例 #27
0
def customers_show(customer_id):
    customer = Customer.get_customer_by_id(customer_id)
    if not customer:
        return {"message": f"Customer {customer_id} was not found"}, 404

    return customer.to_json(), 200
コード例 #28
0
ファイル: user.py プロジェクト: jynnlow/PDD
    def mockUsers():
        State.addUser(
            Dentist(id=1,
                    username="******",
                    password="******",
                    fullName="Dr.Stanley",
                    nric="990203075164",
                    gender="Male",
                    contactNumber="0125822587",
                    address="26, Jalan Cantil, 16599,Penang, Malaysia"))

        State.addUser(
            Dentist(id=2,
                    username="******",
                    password="******",
                    fullName="Dr.Ong",
                    nric="893193891378",
                    gender="Male",
                    contactNumber="0164822695",
                    address="2, Lorong Teratai Indah, 13400,Penang, Malaysia"))

        State.addUser(
            Nurse(id=3,
                  username="******",
                  password="******",
                  fullName="Ms.Nurse",
                  nric="850123856584",
                  gender="Female",
                  contactNumber="01265876436",
                  address="13, Taman Kheng Tian, 13400,Penang, Malaysia"))

        State.addUser(
            Customer(
                id=4,
                username="******",
                password="******",
                fullName="Lee Kah Wei",
                nric="960411075647",
                gender="Male",
                contactNumber="0124912446",
                address=
                "50-6-10, Taman Sri Hijau, Jalan Van Praagh, 11600, Penang, Malaysia"
            ))

        State.addUser(
            Customer(
                id=5,
                username="******",
                password="******",
                fullName="Lee Min Er",
                nric="9604155689",
                gender="Female",
                contactNumber="0121235877",
                address=
                "49, Taman Cantik, Jalan Cantik, 15622, Penang, Malaysia"))

        State.addUser(
            Customer(
                id=6,
                username="******",
                password="******",
                fullName="Tan Yun Ching",
                nric="964123589646",
                gender="Female",
                contactNumber="0124555896",
                address="49, Taman Pondok, Jalan Yes, 45622, Penang, Malaysia")
        )

        State.addUser(
            Customer(
                id=7,
                username="******",
                password="******",
                fullName="Koay Evon",
                nric="956321458523",
                gender="Female",
                contactNumber="0169852364",
                address=
                "9, Taman Hjiau 4, Jalan Tomato, 45996, Penang, Malaysia"))

        State.addUser(
            Customer(id=8,
                     username="******",
                     password="******",
                     fullName="Low Lee Yee",
                     nric="95632555562",
                     gender="Male",
                     contactNumber="0124545926",
                     address="282, Taman Padini, 45622, Penang, Malaysia"))