Ejemplo n.º 1
0
def create_process():
    if session.get('id', '') == '':
        return redirect('/business/')
    elif not Business.check_confirmed(session.get('id', '')):
        return redirect('/business/unconfirmed')
    b_id = session['id']
    form = CreateProcessForm()
    s_form = SelectFieldTypeForm()
    h = HelpForm()
    s_form.select_type.choices = [(p.id, p.type) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    d_form = DateForm()

    if form.validate_on_submit() and d_form.validate_on_submit():

        if Client.email_is_free(form.client_email.data):
            client = Client(form.client_email.data)
            cl_id = client.save()
        else:
            cl_id = Client.get_id(form.client_email.data)
        client_password = Client.random_password(10)
        number = Process.random_number()
        process = Process(s_form.select_type.data, form.description.data, b_id, cl_id, number, form.price.data,
                          client_password,
                          d_form.dt.data, 0)
        pr_id = process.save()
        id_stage = Stage.get_not_started(s_form.select_type.data)
        process = Process.query.filter_by(id=pr_id).first()
        process.current_stage = id_stage
        chat = Chat(pr_id, b_id)
        chat.save()
        process.save()

        Process.send_number(form.client_email.data, Business.get_name(b_id), number, client_password)

        # string = "Услуга была создана под номером: " + number
        return redirect(url_for('business.created_process', process_id=pr_id))
    elif form.validate_on_submit() and not d_form.validate_on_submit():
        d_form.dt.errors = ("Выберите дату", "")

    h.desc.choices = [(p.desc, p.desc) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    h.price.choices = [(p.price, p.price) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    h.pic.choices = [(p.picture, p.picture) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    return render_template('create_process.html', form=form, h=h, s_form=s_form, d_form=d_form, title='Создание заказа')
Ejemplo n.º 2
0
def register_client():
    client_name = request.form['client_name']
    grant_type = request.form['grant_type']
    token_endpoint_auth_method = request.form['token_endpoint_auth_method']
    client = Client(
        client_name=client_name, grant_type=grant_type,
        token_endpoint_auth_method=token_endpoint_auth_method)
    user = User.query.filter_by(username=client_name).first()
    if not user:
        return None
    client.user_id = user.id
    client.client_id = gen_salt(24)
    if client.token_endpoint_auth_method == 'none':
        client.client_secret = ''
    else:
        client.client_secret = gen_salt(48)
    db.session.add(client)
    db.session.commit()
    return jsonify({'client_id': client.client_id, 'client_secret': client.client_secret})
Ejemplo n.º 3
0
def get_all_clients():
    response = requests.get(
        "https://api.airtable.com/v0/appw4RRMDig1g2PFI/Clients",
        headers={"Authorization": str(os.environ.get("API_KEY"))},
    )
    response_json = response.json()
    list_of_clients = []
    for r in response_json["records"]:
        name = r["fields"].get("Name")
        notes = r["fields"].get("Notes")
        email = r["fields"].get("Client Email")
        attachments = r["fields"].get("Attachments")
        if name is not None:
            m = Client(name=name,
                       email=email,
                       notes=notes,
                       attachments=attachments)
            list_of_clients.append(m.serialize())
    return jsonify(list_of_clients)
Ejemplo n.º 4
0
def index():
    """ The main view function, serves the home page of the dashboard and handles 3 forms for
    adding Features, adding Clients and adding Product Areas"""
    clients = Client.query.limit(3).all()
    products = ProductArea.query.order_by('id').limit(5).all()
    features = Feature.query.order_by('client_priority').limit(5).all()
    feature_form = FeatureForm()
    feature_form.populate_choices()
    client_form = ClientForm()
    product_form = ProductAreaForm()

    if feature_form.submit_feature.data and feature_form.validate():
        # Get the form data
        form_data = feature_form.get_data()
        # process the form data and check for existing client priority and reorder the priorities of older features if there is a clash of priorities
        Feature.save_sort_algo(form_data, db)

        return redirect(url_for('main.index'))

    if client_form.submit_client.data and client_form.validate():
        data = dict()
        data["name"] = client_form.name.data
        data["email"] = client_form.email.data
        c = Client(**data)
        db.session.add(c)
        db.session.commit()
        return redirect(url_for('main.index'))

    if product_form.submit_product.data and product_form.validate():
        data = dict()
        data["name"] = product_form.name.data
        p = ProductArea(**data)
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('main.index'))

    return render_template('index.html',
                           product_list=products,
                           clients=clients,
                           features=features,
                           feature_form=feature_form,
                           client_form=client_form,
                           product_form=product_form)
Ejemplo n.º 5
0
async def register():
    params = await request.get_json()
    if params is None:
        data = await request.data
        params = loads(data.decode("utf-8"))

    hashed_password = hashpw(str(params["password"]).encode("utf-8"), gensalt())
    client = Client(
        first_name=params["first_name"],
        last_name=params["last_name"],
        passport_number=params["passport_number"],
        registration_date=date.today(),
        hashed_password=hashed_password
    )
    try:
        await Client.insert_client(client)
    except IntegrityError:
        return await make_response(jsonify({"status": "Such passport_number or id already exists"}), 400)
    return await make_response(jsonify({"status": "Ok"}), 200)
Ejemplo n.º 6
0
def get_a_client_from_email(email):
    response = requests.get(
        "https://api.airtable.com/v0/appw4RRMDig1g2PFI/Clients?filterByFormula=SEARCH('{}'"
        .format(email) + ", {Client Email})",
        headers={"Authorization": str(os.environ.get("API_KEY"))},
    )
    response_json = response.json()

    list_of_clients = []
    for r in response_json["records"]:
        name = r["fields"].get("Name")
        notes = r["fields"].get("Notes")
        attachments = r["fields"].get("Attachments")
        if name is not None:
            m = Client(name=name, notes=notes, attachments=attachments)
            list_of_clients.append(m.serialize())
            return jsonify(list_of_clients)
    else:
        return "There is no client with that email, please try again."
Ejemplo n.º 7
0
def add_client():
    form = ClientForm()
    if current_user.can(Permission.WRITE) and form.validate_on_submit():
        client = Client(name=form.name.data,
                        address=form.address.data,
                        user_id=current_user.id)
        db.session.add(client)
        db.session.commit()
        flash('Client account has been created', 'success')
        return redirect(url_for('clients.add_client'))
    page = request.args.get('page', 1, type=int)
    pagination = Client.query.order_by(Client.name.desc()).paginate(
        page, 5, False)
    clients = pagination.items
    return render_template('clients/add_client.html',
                           title='Add a Client Account',
                           form=form,
                           clients=clients,
                           pagination=pagination)
Ejemplo n.º 8
0
def client_put():
    """Creates a new client"""
    current_user = get_current_user()

    data = request.get_json()

    if "name" not in data.keys() or "description" not in data.keys():
        return jsonify({
            "status": "error",
            "detail": "Missing name or description"
        }), 400

    if Client.query.filter_by(name=data["name"]).first() != None:
        return jsonify({
            "status": "error",
            "detail": "Client already exists"
        }), 400

    if not_empty(data["name"]) and check_length(
            data["name"], 32) and check_length(data["description"], 128):

        new_client = Client(name=data["name"],
                            description=data["description"],
                            owner_id=current_user.id)

        new_client.gen_uid()

        db.session.add(new_client)

        db.session.commit()
        return jsonify({
            "status":
            "OK",
            "detail":
            "New client {} created successfuly".format(new_client.name)
        }), 201
    else:
        return jsonify({
            "status":
            "error",
            "detail":
            "Invalid data (name empty or too long or description too long)"
        }), 400
Ejemplo n.º 9
0
def client_put():
    """Creates a new client"""
    data = request.form

    if 'name' not in data.keys() or\
       'description' not in data.keys():
        return jsonify({
            'status': 'error',
            'detail': 'Missing name or description'
        }), 400

    if Client.query.filter_by(name=data['name']).first() != None:
        return jsonify({
            'status': 'error',
            'detail': 'Client already exists'
        }), 400

    if not_empty(data['name']) and check_length(
            data['name'], 32) and check_length(data['description'], 128):

        new_client = Client(name=data['name'],
                            description=data['description'],
                            owner_id=current_user.id)

        new_client.gen_uid()

        db.session.add(new_client)

        db.session.commit()
        return jsonify({
            'status':
            'OK',
            'detail':
            'New client {} created successfuly'.format(new_client.name)
        }), 201
    else:
        return jsonify({
            'status':
            'error',
            'detail':
            'Invalid data (name empty or too long or description too long)'
        }), 400
Ejemplo n.º 10
0
    def get(self):
        if request.args.get("code") is None:
            return jsonify({'code': -1, 'data': {"message": "code mistake"}})
        code = request.args.get("code")
        # result = get_access_token(code)
        result = wxpublic_get_access_token(code)
        if result is None:  # 验证失败,
            return jsonify({'code': -1, 'data': {'message': 'code mistake'}})
        userinfo = get_user_info(result.get('access_token'),
                                 result.get('openid'))

        nickname = userinfo['nickname']
        unionid = userinfo['unionid']
        sex = userinfo['sex']
        headimg = userinfo['headimgurl']

        # 用户更换头像会导致微信的头像URL失效,因此要先存七牛
        r = get_wx_head(headimg, unionid)
        # if (r == 0):  # 抓取不成功
        #    return redirect(url_for('main.index'))
        headimg = 'http://userhead.houxiaopang.com/' + unionid + '.jpg'
        # 存头像结束

        # 根据unionid是否在库,决定是去填表还是去个人中心
        client = Client.query.filter_by(unionid=unionid).first()
        if client is None:  # 第一次登陆
            #创建该用户实例
            client = Client(nickname=nickname,
                            unionid=unionid,
                            sex=sex,
                            headimg=headimg)
            db.session.add(client)
            try:
                db.session.commit()
            except:
                db.session.rollback()()

        token = client.generate_auth_token().decode()
        print(client)
        print(token)

        return jsonify({'code': 0, 'data': {"token": token}})
Ejemplo n.º 11
0
 def add_client(self, request: HttpRequest) -> json:
     data = get_request_param_json('data', request)
     client_id = int(data.get('client_id', ''))
     client_service = self.factory.get_service('client')
     client = Client()
     if client_id:
         client = client_service.get_client(client_id)
     client.name = data.get('client_name', '')
     client.mobile_no = data.get('client_mobile', '')
     client.email = data.get('client_email', '')
     client.property = {
         'address': data.get('client_address', ''),
         'country': data.get('client_country', ''),
         'country_code': data.get('client_country_code', ''),
         'zip_code': data.get('client_zip_code', ''),
         'company_name': data.get('client_c_n', ''),
         'company_website': data.get('client_c_w', ''),
     }
     client_service.add_update_client(client)
     return JsonResponse(data, safe=False)
Ejemplo n.º 12
0
def create_client():
    """Creates new user in database, also provides new api token"""
    data = json.loads(str(request.get_data().decode('utf-8')))
    if 'address' not in data or 'email' not in data or 'password' not in data:
        return bad_request('must include address, email and password fields')
    if 'name' not in data or 'surname' not in data:
        return bad_request('must include name and surname')
    if Notary.query.filter_by(address=data['address']).first():
        return bad_request('user with this address already exist')
    if Notary.query.filter_by(email=data['email']).first():
        return bad_request('please use a different email address')
    client = Client()
    client.from_dict(data, new_user=True)
    client.get_token()
    db.session.add(client)
    db.session.commit()
    response = jsonify(client.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('get_client', client_id=client.id)
    return response
Ejemplo n.º 13
0
def post_auth():
    if current_user.is_authenticated:
        return json.dumps({'state': 2}), 200, {
            'ContentType': 'application/json'
        }
    if not request.json or not 'clientInfo' in request.json:
        return json.dumps({'error': 'incorrect_params'}), 400, {
            'ContentType': 'application/json'
        }
    info = json.loads(request.json['clientInfo'])

    if Client.query.filter_by(mail=info['email']).first() is not None:
        return json.dumps({'state': 0}), 200, {
            'ContentType': 'application/json'
        }
    client = Client(login=info['name'], mail=info['email'], roleid=1)
    client.set_password(info['password'])
    db.session.add(client)
    db.session.commit()
    return json.dumps({'state': 1}), 200, {'ContentType': 'application/json'}
Ejemplo n.º 14
0
def dbinit():
		data = []
		data.append(File(filename="default.png"))
		data.append(Rol(descripcion="administrador"))
		data.append(Rol(descripcion="supervisor"))
		data.append(Rol(descripcion="agente"))
		data.append(Rol(descripcion="cliente"))
		data.append(State(descripcion="New"))
		data.append(State(descripcion="Proccess"))
		data.append(State(descripcion="Pending"))
		data.append(State(descripcion="Close"))
		data.append(State(descripcion="Re-Open"))
		data.append(State(descripcion="Abandoned"))
		data.append(Department(descripcion="IT"))
		data.append(Priority(descripcion="standar", respuesta = 8, resuelto = 72))
		data.append(Priority(descripcion="High", respuesta = 4, resuelto = 24, escalable = 1))
		data.append(Priority(descripcion="Critical", respuesta = 1, resuelto = 4 ))
		data.append(Priority(descripcion="Scheduled or Low", respuesta = 3, resuelto = 7))
		data.append(Client(nombre="Default"))
		db.session.add_all(data)
		db.session.commit()
		rolAdm =  Rol.query.filter_by(descripcion="administrador").first()
		sys = User(
			username="******",
			nombre = "COMPUTER",
			apellido = "SYS",
			email = "*****@*****.**",
			rol_id = rolAdm.id
		)
		administrador = User(
			username="******",
			nombre = "Super",
			apellido = "admin",
			email = "*****@*****.**",
			rol_id = rolAdm.id
		)
		administrador.set_password("admin")
		sys.set_password(''.join(random.choices(string.ascii_uppercase + string.digits, k = N)))
		db.session.add(sys)
		db.session.add(administrador)
		db.session.commit()
Ejemplo n.º 15
0
def get_a_client(id):
    response = requests.get(
        "https://api.airtable.com/v0/appw4RRMDig1g2PFI/Clients/{}".format(id),
        headers={"Authorization": str(os.environ.get("API_KEY"))},
    )
    if response.status_code == 200:
        response_json = response.json()
        client = []
        name = response_json["fields"].get("Name")
        notes = response_json["fields"].get("Notes")
        email = response_json["fields"].get("Client Email")
        attachments = response_json["fields"].get("Attachments")
        if name is not None:
            m = Client(name=name,
                       email=email,
                       notes=notes,
                       attachments=attachments)
            client.append(m.serialize())
            return jsonify(client)
    else:
        return "This client does not exist in the database."
Ejemplo n.º 16
0
def signup_client(request):
    if request.method == 'POST':
        form = SignUpFormClient(request.POST)
        if form.is_valid():
            form.save() #Sauvegarde/Creation d'un utilisateur de base
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password) #Authentification de l'utilisateur
            Utilisateur = User.objects.get(username=username)
            groupe_client = Group.objects.get(id='2')  # On ajoute l'utilisateur au groupe client ici (id groupe client = 2 )
            Utilisateur.groups.add(groupe_client)
            client = Client(numclient=Utilisateur, datenaissanceclient=form.cleaned_data.get('datenaissanceclient'), telephoneclient=form.cleaned_data.get('telephoneclient'), codepostalclient=form.cleaned_data.get('codepostalclient'), villeclient=form.cleaned_data.get('villeclient'), rueclient=form.cleaned_data.get('rueclient'), numclient_id=Utilisateur.id)
            client.save()  # Sauvegarde du client
            login(request, user) #Connexion au site
            estClient = True
            request.session['estClient'] = estClient  # On mémorise le fait que c'est un client en session
            request = init_panier(request)
            request = init_reservation(request) #On initiliase le panier et le panier_reservation de l'utilisateur
            return redirect('homepage')
    else:
        form = SignUpFormClient(request.POST)
    return render(request, 'signup_client.html', {'formClient': form})
Ejemplo n.º 17
0
    def run(self):
        clients = ['Client A', 'Client B', 'Client C']
        for client in clients:
            c = Client(name=client)
            db.session.add(c)
        products = ['Billing', 'Claims', 'Policies', 'Reports']
        for product in products:
            p = ProductArea(name=product)
            db.session.add(p)
        admin = user_datastore.create_user(username='******',
                                           password='******',
                                           email='*****@*****.**')
        admin_role = user_datastore.create_role(name='admin')
        user_datastore.add_role_to_user(admin, admin_role)

        developer1 = user_datastore.create_user(username='******',
                                                password='******',
                                                email='*****@*****.**')
        developer2 = user_datastore.create_user(username='******',
                                                password='******',
                                                email='*****@*****.**')
        db.session.commit()

        for i in range(12):
            ticket = Ticket(
                title='Sample Ticket {}'.format(i + 1),
                description='Sample Description {}'.format(i + 1),
                priority=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4][i],
                target=(datetime.datetime.now() +
                        datetime.timedelta(days=random.randint(-2, 4))).date(),
                ticket_url='http://ticket{}.example.com'.format(i + 1),
                client_id=(i % 3) + 1,
                product_area_id=(i % 4) + 1,
                assigned_to_id=(i % 2) + 2)
            db.session.add(ticket)
            db.session.commit()

        print('example data inserted into db')
Ejemplo n.º 18
0
    def post(self, request, *args, **kwargs):
        try:
            code = request.POST['code']
            name_client = request.POST['name_client']
            nit_client = request.POST['nit_client']
            address_client = request.POST['address_client']
            city_client = request.POST['city_client']
            prd_type = request.POST['prd_type']
            description = request.POST['description']

            try:
                client_exist = Client.objects.get(nit=nit_client)
                client = client_exist
            except Exception:
                client = Client(name=name_client,
                                nit=nit_client,
                                city=city_client,
                                address=address_client)
                client.save()

            try:
                product_type = TypeProductHistory.objects.get(name=prd_type)
                type_product = product_type
            except Exception:
                type_product = TypeProductHistory(name=prd_type)
                type_product.save()

            project = Project(client=client,
                              description=description,
                              type_product=type_product,
                              code=code)
            project.save()
            messages.success(request, 'Se ha creado el projecto correctamente')
        except Exception:
            messages.error(
                request, 'Ha ocurrido un error interno, por favor verifique '
                'e intentelo de nueo')
        return redirect('projects')
Ejemplo n.º 19
0
def run(refresh, verbose=False):
    devnull = open('/dev/null')

    while True:
        clients = []

        for name in settings.DYNAMIC_CLIENTS:
            code = subprocess.call(['ping', '-n', '-c', '1', '-q', name],
                                   stdout=devnull,
                                   stderr=devnull)
            up = code == 0

            clients.append(Client(name=name, up=up))

        if verbose:
            print('[%s] updating clients :' %
                  datetime.now().strftime('%Y-%m-%d %H:%M'))
            print('\n'.join('  ' + str(client) for client in clients))

        Client.objects.all().delete()
        Client.objects.bulk_create(clients)

        time.sleep(refresh)
Ejemplo n.º 20
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        db.create_all()
        client = Client(username=form.username.data,
                        name=form.name.data,
                        address=form.address.data,
                        city=form.city.data,
                        state=form.state.data,
                        zip=form.zip.data,
                        phone=form.phone.data,
                        email=form.email.data,
                        password=hashed_password)
        db.session.add(client)
        db.session.commit()
        flash('Your account has been created! You are now able to log in',
              'success')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Ejemplo n.º 21
0
def get_client(request):
    """
    Get a client or create if not exists
    :param request:
    :return:
    """
    uuid = request.headers.get('X-CLIENT-UUID')
    client_ip = get_client_ip(request)
    user_agent = request.headers.get('User-Agent')

    if uuid and Client.objects.filter(uuid=uuid, uuid__isnull=False).exists():
        return Client.objects.get(uuid=uuid, uuid__isnull=False)
    else:
        if Client.objects.filter(uuid__isnull=True,
                                 ip=client_ip,
                                 user_agent=user_agent).exists():
            return Client.objects.get(uuid__isnull=True,
                                      ip=client_ip,
                                      user_agent=user_agent)
        else:
            client = Client(uuid=uuid, ip=client_ip, user_agent=user_agent)
            client.save()
            logger.info('[+] new client : {}'.format(client))
            return client
Ejemplo n.º 22
0
def get_a_client_from_email(email):
    base_url = current_app.config["DATABASE_URL"]
    response = requests.get(
        "{}/Clients?filterByFormula=SEARCH('{}'".format(base_url, email)
        + ", {Client Email})",
        headers={"Authorization": str(os.environ.get("API_KEY"))},
    )
    # Convert to JSON
    response_json = response.json()

    # Validation check
    if (response.status_code // 100) != 2:
        return response_json["error"], response.status_code

    error = handleEmailResponse(response_json["records"])
    if error is not None:
        return error, 422

    # Get object's parameters
    id_number = response_json["records"][0]["id"]
    name = response_json["records"][0]["fields"].get("Name")
    email = response_json["records"][0]["fields"].get("Client Email")
    notes = response_json["records"][0]["fields"].get("Notes")
    attachments = response_json["records"][0]["fields"].get("Attachments")
    if name is None or email is None:
        return "There is no client with that email. Please try again.", 422

    # Create and return object
    c = Client(
        name=name,
        email=email,
        id_number=id_number,
        notes=notes,
        attachments=attachments,
    )
    return jsonify(c.serialize()), 200
Ejemplo n.º 23
0
	def populateClient(self, client_name):

		try:
			client_id = db.session.query(Client.client_id).filter_by(client_name=client_name).first()

			if client_id is not None:
				client_id = client_id[0]

			exists_client = db.session.query(Client.client_id).filter_by(client_id=client_id).scalar() is not None

			if exists_client:
				print("Client already exists in database")
			else:
				clientValue = Client(client_name=client_name,is_active=True)
				db.session.add(clientValue)
				db.session.commit()
				print("New entry is added in client table")

		except Exception as ex:
			date = datetime.utcnow()
			tb = sys.exc_info()[2]
			errorMsg = str(date) + " - File: AWSData.py - Function: populateClient - " + str(ex.args) + " - on line " + str(tb.tb_lineno) + " \r\n"
			f.write(errorMsg)
			f.close()
Ejemplo n.º 24
0
def render_request_done():
    form = RequestForm()
    if form.validate_on_submit():
        goal = int(form.goals.data)

        name = form.clientName.data
        phone = form.clientPhone.data

        client = Client(name=name, phone=phone)

        db.session.add(client)
        db.session.commit()

        db.session.add(
            Request(client=client.id, goals=goal, time=int(form.time.data)))
        db.session.commit()

        return render_template(
            "request_done.html",
            goal=Goal.query.filter(Goal.id == goal).first(),
            form=form,
        )
    else:
        return render_template("request.html", form=form)
Ejemplo n.º 25
0
    def setUp(self):
        TestFactory.setUp(self)
        data = []
        data.append(State(descripcion="abierto"))
        data.append(State(descripcion="cerrado"))
        data.append(Priority(descripcion="baja"))
        data.append(Priority(descripcion="Alta"))
        data.append(Department(descripcion="default"))
        data.append(Client(nombre="default"))
        db.session.add_all(data)
        db.session.commit()
        data = Ticket(
            titulo="prueba",
            content=
            """My money's in that office, right? If she start giving me some bullshit about it ain't there, and we got to go someplace 
			else and get it, I'm gonna shoot you in the head then and there. Then I'm gonna shoot that bitch in the kneecaps, find out where my 
			goddamn money is. She gonna tell me too. Hey, look at me when I'm talking to you, m**********r. You listen: we go in there, and that
			 n***a Winston or anybody else is in there, you the first m**********r to get shot. You understand?""",
            email="*****@*****.**",
            client_id=1,
            department_id=1,
            priority_id=1,
            state_id=1,
            user_id=1)
        db.session.add(data)
        db.session.commit()
        message = Message(
            body="fgkljhdfkljhgklfgjhkldfjhdk",
            privado=False,
            ticket_id=1,
            from_user_id=1,
            to_user_id=None,
        )
        db.session.add(message)
        db.session.commit()
        self.path = '/messages'
Ejemplo n.º 26
0
def client(id):
    client = Client.query.filter_by(id=id).first()
    form = NewClientForm()
    if form.validate_on_submit():
        client = Client(name=form.name.data,
                        representative_name=form.representative_name.data,
                        phone=form.phone.data,
                        email=form.email.data)
        client.name = form.name.data
        client.representative_name = form.representative_name.data
        client.phone = form.phone.data
        client.email = form.email.data
        db.session.commit()
        flash(_('Client edited!'))
        return redirect(url_for('main.client', id=id))
    elif request.method == 'GET':
        form.name.data = client.name
        form.representative_name.data = client.representative_name
        form.phone.data = client.phone
        form.email.data = client.email
    if client is None:
        flash(_('The client with this id was not found!'))
        return redirect(url_for('main.clients'))
    return render_template('client.html', form=form)
Ejemplo n.º 27
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
                  os.path.join(basedir, TEST_DB)
        self.app = app.test_client()
        db.create_all()

        dummy_client = Client(name='Client 1')
        db.session.add(dummy_client)

        dummy_product = Product(product='Product 1')
        db.session.add(dummy_product)

        dummy_request = Request(title='test title',
                                desc='test desc',
                                target_date=datetime.now().date(),
                                priority=2,
                                client=dummy_client,
                                product=dummy_product)
        db.session.add(dummy_request)

        db.session.commit()
    def handle(self, *args, **options):
        print("Creating users")
        fake = Faker()
        uniq = set()
        index = 0
        count = options['count']
        while index < count:
            profile = fake.profile()

            username = profile['username']
            if username not in uniq:
                u = User.objects.create_user(
                    username=username,
                    password=profile['mail'],
                    email=profile['mail']
                )

                user = Client(
                    user=u,
                    rating=randint(0, 100)
                )
                user.save()
                uniq.add(username)
                index += 1
Ejemplo n.º 29
0
 def test_create_client_without_useragent_client(self):
     client = Client(ip='129.168.0.1', user_agent=None)
     client.save()
Ejemplo n.º 30
0
def create_client():
    client = Client(name=request.json['name'], )
    db.session.add(client)
    db.session.commit()
    id = client.id
    return jsonify({"name": request.json['name'], "id": id})