Exemplo n.º 1
0
    def test_questions_evaluated_correctly(self):
        s = self.client.session
        newUser = AppUser(100000, "*****@*****.**", "notapassword", "Applicant", False, "Firstname", "Lastname")
        newUser.save()
        s.update({
            "id": 100000,
        })
        s.save()
        data = dict()
        testML = MLModel(1, "TestModel")
        testML.save()
        testOrganisation = Organisation(1, "TestOrg", True, "*****@*****.**", "01234567890")
        testOrganisation.save()
        testJob = Job(1, 1, 1, "TestJob", "TestDesc", "2019-03-15")
        testJob.save()

        testCV = CV(1, 1, '{"Name": "Bill", "Degree Qualification": "Computer Science BSc", "Degree Level": "1st", "University Attended": "University of Warwick", "Skills": [{"Skill": "Server setup", "Expertise": 10}, {"Skill": "Database Management", "Expertise": 10}], "Languages Known": [{"Language": "Python", "Expertise": 10}, {"Language": "Java", "Expertise": 10}, {"Language": "C#", "Expertise": 10}], "Hobbies": [{"Name": "Gaming", "Interest": 10}], "A-Level Qualifications": [{"Subject": "Computer Science", "Grade": "A"}, {"Subject": "Chemistry", "Grade": "A"}], "Previous Employment": [{"Company": "Microsoft", "Position": "CEO", "Length of Employment": 120}]}')
        test_question_one = TestQuestions(1, "What is 5 + 3?", "8", 1)
        test_question_one.save()
        test_question_two = TestQuestions(2, "What is 9 + 5?", "14", 1)
        test_question_two.save()
        test_question_three = TestQuestions(3, "What is 12 + 4?", "16", 1)
        test_question_three.save()
        test_question_four = TestQuestions(4, "What is 15 + 16?", "31", 1)
        test_question_four.save()
        data['extra_questionfield_0'] = "8"
        data['extra_questionfield_1'] = "14"
        data['extra_questionfield_2'] = "16"
        data['extra_questionfield_3'] = "73"
        response = self.client.post('/applicant/test/1/', data)
        self.assertEqual(200, response.status_code)
        newApplication = Application.objects.get(id=1)
        self.assertEqual(75.0, newApplication.answer_percent)
Exemplo n.º 2
0
def create_organisation():
    data = request.get_json()

    validate(data, post_create_organisation_schema)

    organisation = Organisation(**data)
    dao_create_organisation(organisation)
    return jsonify(organisation.serialize()), 201
Exemplo n.º 3
0
def save():
    '''
    Save a new or an existing organisation
    :return: User's organisations home page
    '''
    form = OrganisationForm()
    if form.validate_on_submit():
        # check if user is trying to edit
        id = request.form['id']
        new = id == "-1"
        user_can_edit = not new and user_has_rights(id)

        if not new and not user_has_rights(id):
            error = "Not allowed to edit this organisation"
            return to_403(error)

        # Create/get organisation
        if new:
            organisation = Organisation(
                name=request.form['name'],
                manager_name=request.form['manager_name'])
            organisation.users.append(g.user)
            db.session.add(organisation)
            db.session.commit()
        else:
            organisation = Organisation.query.get_or_404(id)
            organisation.name = request.form['name']
            organisation.manager_name = request.form['manager_name']

        if new:
            address = Address(address=request.form['address'],
                              city=request.form['city'],
                              province=request.form['province'],
                              country=request.form['country'],
                              postal_code=request.form['postal_code'],
                              organisation_id=organisation.id)
            db.session.add(address)
        else:
            address = organisation.addresses.first()
            address.address = request.form['address']
            address.city = request.form['city']
            address.province = request.form['province']
            address.country = request.form['country']
            address.postal_code = request.form['postal_code']
            address.organisation_id = organisation.id

        db.session.commit()

        flash(organisation.name + " has been saved")
        return redirect(url_for('organisations.index'))
Exemplo n.º 4
0
def create_organisation(
    name='test_org_1',
    active=True,
    organisation_type=None,
    domains=None,
    organisation_id=None,
    purchase_order_number=None,
    billing_contact_names=None,
    billing_contact_email_addresses=None,
    billing_reference=None,
):
    data = {
        'id': organisation_id,
        'name': name,
        'active': active,
        'organisation_type': organisation_type,
        'purchase_order_number': purchase_order_number,
        'billing_contact_names': billing_contact_names,
        'billing_contact_email_addresses': billing_contact_email_addresses,
        'billing_reference': billing_reference,
    }
    organisation = Organisation(**data)
    dao_create_organisation(organisation)

    for domain in domains or []:
        create_domain(domain, organisation.id)

    return organisation
Exemplo n.º 5
0
def add_organisation():
    """
    Add a organisation to the database
    """
    check_admin()

    add_organisation = True

    form = OrganisationForm()
    if request.method == "POST" and form.validate_on_submit():
        organisation = Organisation(code=form.code.data,
                                    vrn=form.vrn.data,
                                    name=form.name.data)
        try:
            # add organisation to the database
            db.session.add(organisation)
            db.session.commit()
            flash('You have successfully added a new organisation.')
        except:
            # in case organisation name already exists
            flash('Error: organisation name already exists.')

        # redirect to organisations page
        return redirect(url_for('home.organisations'))

    # load organisation template
    return render_template('home/organisation.html',
                           action="Add",
                           id=None,
                           add_organisation=add_organisation,
                           form=form,
                           title="Add Organisation")
Exemplo n.º 6
0
 def test_post(self, test_client, test_candidate, test_session,
               logged_in_user):
     higher_grade = Grade.query.filter(Grade.value == "SCS3").first()
     test_session.bulk_save_objects([
         Organisation(name="Number 11", department=False),
         Profession(value="Digital, Data and Technology"),
         Location(value="London"),
     ])
     test_session.commit()
     new_org = Organisation.query.first()
     new_profession = Profession.query.first()
     new_location = Location.query.first()
     data = {
         "new-grade": higher_grade.id,
         "start-date-day": "1",
         "start-date-month": "1",
         "start-date-year": "2019",
         "new-org": str(new_org.id),
         "new-profession": str(new_profession.id),
         "new-location": str(new_location.id),
         "role-change": "1",
         "new-title": "Senior dev",
     }
     test_client.post("/update/role", data=data)
     assert data.keys() == session.get("new-role").keys()
Exemplo n.º 7
0
def profile():
    user_organisation_id = current_user.organisation
    form = CreateOrganisationForm()

    if form.validate_on_submit():
        # Create an organisation object based on user input from the form
        new_organisation = Organisation(name=form.name.data, hourly_rate=form.hourly_rate.data)
        # Add the new organisation to the database
        db.session.add(new_organisation)
        db.session.commit()
        # Display a short message to the user
        flash('Congratulations, you just created and join the organisation {}'.format(new_organisation.name))

        # The user automatically joins the new organisation
        new_organisation = Organisation.query.filter_by(name=form.name.data).first()
        return redirect(url_for('join', organisation=new_organisation.id))
    
    # If the user is in an organisation
    if user_organisation_id:
        # Display user's profile with organisation info
        user_organisation = Organisation.query.get(user_organisation_id)
        return render_template('profile.html', title='Home Page', form=form, user_organisation=user_organisation)
    
    else:
        # Display the list of all organisation and a form to create a new one
        organisations = Organisation.query.all()
        return render_template('profile.html', title='Home Page', form=form, organisations=organisations)
Exemplo n.º 8
0
def broadcast_organisation(notify_db_session):
    org = Organisation.query.get(current_app.config['BROADCAST_ORGANISATION_ID'])
    if not org:
        org = Organisation(id=current_app.config['BROADCAST_ORGANISATION_ID'], name='broadcast organisation')
        dao_create_organisation(org)

    return org
Exemplo n.º 9
0
def create_service_model(user=None,
                         service_name="Test service",
                         restricted=False,
                         count_as_live=True,
                         research_mode=False,
                         active=True,
                         email_from=None,
                         prefix_sms=True,
                         message_limit=1000,
                         organisation_type='other',
                         go_live_user=None,
                         go_live_at=None,
                         crown=True,
                         organisation=None,
                         smtp_user=None):
    service = Service(
        name=service_name,
        message_limit=message_limit,
        restricted=restricted,
        email_from=email_from if email_from else service_name.lower().replace(
            ' ', '.'),
        created_by=user if user else create_user_model(),
        prefix_sms=prefix_sms,
        organisation_type=organisation_type,
        go_live_user=go_live_user,
        go_live_at=go_live_at,
        crown=crown,
        smtp_user=smtp_user,
        organisation=organisation if organisation else Organisation(
            id=uuid.uuid4(), name='sample organization'))
    service.active = active
    service.research_mode = research_mode
    service.count_as_live = count_as_live

    return service
Exemplo n.º 10
0
def populate_organisations_from_file(file_name):
    # [0] organisation name:: name of the organisation insert if organisation is missing.
    # [1] sector:: Central | Local | NHS only
    # [2] crown:: TRUE | FALSE only
    # [3] argeement_signed:: TRUE | FALSE
    # [4] domains:: comma separated list of domains related to the organisation
    # [5] email branding name: name of the default email branding for the org
    # [6] letter branding name: name of the default letter branding for the org

    # The expectation is that the organisation, organisation_to_service
    # and user_to_organisation will be cleared before running this command.
    # Ignoring duplicates allows us to run the command again with the same file or same file with new rows.
    with open(file_name, 'r') as f:
        def boolean_or_none(field):
            if field == '1':
                return True
            elif field == '0':
                return False
            elif field == '':
                return None

        for line in itertools.islice(f, 1, None):
            columns = line.split('|')
            print(columns)
            email_branding = None
            email_branding_column = columns[5].strip()
            if len(email_branding_column) > 0:
                email_branding = EmailBranding.query.filter(EmailBranding.name == email_branding_column).one()
            letter_branding = None
            letter_branding_column = columns[6].strip()
            if len(letter_branding_column) > 0:
                letter_branding = LetterBranding.query.filter(LetterBranding.name == letter_branding_column).one()
            data = {
                'name': columns[0],
                'active': True,
                'agreement_signed': boolean_or_none(columns[3]),
                'crown': boolean_or_none(columns[2]),
                'organisation_type': columns[1].lower(),
                'email_branding_id': email_branding.id if email_branding else None,
                'letter_branding_id': letter_branding.id if letter_branding else None

            }
            org = Organisation(**data)
            try:
                db.session.add(org)
                db.session.commit()
            except IntegrityError:
                print("duplicate org", org.name)
                db.session.rollback()
            domains = columns[4].split(',')
            for d in domains:
                if len(d.strip()) > 0:
                    domain = Domain(domain=d.strip(), organisation_id=org.id)
                    try:
                        db.session.add(domain)
                        db.session.commit()
                    except IntegrityError:
                        print("duplicate domain", d.strip())
                        db.session.rollback()
Exemplo n.º 11
0
def add_org():
    form = AddOrganisationForm()
    if form.validate_on_submit():
        new_org = Organisation(org_name=form.org_name.data, phone_num=form.phone_num.data,
                               email=form.email.data, address=form.address.data)
        db.session.add(new_org)
        db.session.commit()
        return redirect(url_for("organisations"))
    return render_template("add_org.html", form=form)
Exemplo n.º 12
0
def create_organisation(name='test_org_1', active=True):
    data = {
        'name': name,
        'active': active
    }
    organisation = Organisation(**data)
    dao_create_organisation(organisation)

    return organisation
Exemplo n.º 13
0
def notify_db_session(request):

    meta = MetaData(bind=db.engine, reflect=True)

    # Set up dummy org, with a service and a job
    org = Organisation(id=1234, name="org test")
    token = Token(id=1234, token="1234", type='admin')
    service = Service(
        id=1234,
        name="service test",
        created_at=datetime.utcnow(),
        token=token,
        active=True,
        restricted=False,
        limit=100
    )
    job = Job(id=1234, name="job test", created_at=datetime.utcnow(), service=service)
    notification = Notification(
        id=1234,
        to="phone-number",
        message="this is a message",
        job=job,
        status="created",
        method="sms",
        created_at=datetime.utcnow()
    )

    # Setup a dummy user for tests
    user = User(
        id=1234,
        email_address="*****@*****.**",
        mobile_number="+449999234234",
        password=generate_password_hash('valid-password'),
        active=True,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow(),
        password_changed_at=datetime.utcnow(),
        role='admin'
    )

    service.users.append(user)

    db.session.add(token)
    db.session.add(org)
    db.session.add(service)
    db.session.add(notification)
    db.session.add(job)
    db.session.add(user)
    db.session.commit()

    def teardown():
        db.session.remove()
        for tbl in reversed(meta.sorted_tables):
            db.engine.execute(tbl.delete())

    request.addfinalizer(teardown)
Exemplo n.º 14
0
def create_organisation(organisation_id):
    org = Organisation.query.filter_by(id=organisation_id).first()
    if org:
        return (f'Organisation exists: {organisation_id}')
    else:
        # Create the organisation
        organisation = Organisation(id=organisation_id, \
            display_name=organisation_id, description="")
        db.session.add(organisation)
        db.session.commit()
        return (f'Organisation created: {organisation_id}')
Exemplo n.º 15
0
def create_organisation(name='test_org_1', active=True, organisation_type=None, domains=None):
    data = {
        'name': name,
        'active': active,
        'organisation_type': organisation_type,
    }
    organisation = Organisation(**data)
    dao_create_organisation(organisation)

    for domain in domains or []:
        create_domain(domain, organisation.id)

    return organisation
Exemplo n.º 16
0
def create_organisation(name="test_org_1",
                        active=True,
                        organisation_type=None,
                        domains=None):
    data = {
        "name": name,
        "active": active,
        "organisation_type": organisation_type,
    }
    organisation = Organisation(**data)
    dao_create_organisation(organisation)

    for domain in domains or []:
        create_domain(domain, organisation.id)

    return organisation
Exemplo n.º 17
0
def create_organisation(name='test_org_1', active=True, organisation_type=None, domains=None):
    organisation = Organisation.query.filter_by(name=name).first()
    if organisation:
        organisation.active = active
        organisation.organisation_type = organisation_type
    else:
        data = {
            'name': name,
            'active': active,
            'organisation_type': organisation_type,
        }
        organisation = Organisation(**data)
        dao_create_organisation(organisation)

    for domain in domains or []:
        create_domain(domain, organisation.id)

    return organisation
Exemplo n.º 18
0
def sample_organisation(notify_db_session):
    org = Organisation(name='sample organisation')
    dao_create_organisation(org)
    return org
Exemplo n.º 19
0
 def org_name(self):
     from app.models import Organisation
     return Organisation.get(self.organisation_id).org_name
Exemplo n.º 20
0
def processSignup():
    return ("Signups for Kohoutek 2021 are now closed", 422)

    if ("organisation" not in request.form) or (request.form["organisation"]
                                                not in ["scouting", "guiding"
                                                        ]):
        return (
            "You haven't let us know whether you're in Guiding or Scouting",
            422)

    organisation = Organisation(request.form["organisation"])

    if "county" not in request.form or request.form["county"] not in [
            "avon",
            "bsg",
            "sn",
            "other",
    ]:
        return ("You need to select which County you're in", 422)

    county = County(request.form["county"])

    if (county in [County.avon, County.bsg, County.sn] and
        ("district" not in request.form or request.form["district"]
         == "")) or (county == County.other and
                     ((organisation == Organisation.scouting and
                       ("district-name" not in request.form
                        or request.form["district-name"] == "")) or
                      (organisation == Organisation.guiding and
                       ("division-name" not in request.form
                        or request.form["division-name"] == "")))):
        return (
            "You need to select your District/Division, or enter it's name",
            422)

    if county in [County.avon, County.bsg, County.sn]:
        district = District.query.filter_by(
            id=request.form["district"]).first()
        if district.county != county:
            return (
                "You need to select a District/Division that's in your chosen County",
                422,
            )

        else:
            district_id = district.id
            district_name = None

    else:
        district_id = None
        district_name = (request.form["district-name"]
                         if organisation == Organisation.scouting else
                         request.form["division-name"])

    if organisation == Organisation.scouting and (
            "group-name" not in request.form
            or request.form["group-name"] == ""):
        return ("You need to tell us the name of your Group", 422)

    if organisation == Organisation.guiding and (
            "unit-name" not in request.form
            or request.form["unit-name"] == ""):
        return ("You need to tell us the name of your Unit", 422)

    group_name = (request.form["group-name"] if organisation
                  == Organisation.scouting else request.form["unit-name"])

    if "troop-name" not in request.form or request.form["troop-name"] == "":
        troop_name = None
    else:
        troop_name = request.form["troop-name"]

    if "contact-name" not in request.form or request.form["contact-name"] == "":
        return ("You need to provide a contact name", 422)

    if "contact-email" not in request.form or request.form[
            "contact-email"] == "":
        return ("You need to provide a contact email address", 422)

    if ("confirm-email" not in request.form
            or request.form["confirm-email"] == ""
            or request.form["contact-email"].lower() !=
            request.form["confirm-email"].lower()):
        return ("You need to confirm your email address", 422)

    contact_email = request.form["contact-email"].lower()
    existing_signup = Entry.query.filter_by(
        contact_email=contact_email).first()

    if existing_signup:
        return ("This email address has already been used to sign up a group",
                422)

    if "rules" not in request.form or request.form["rules"] != "accepted":
        return (
            "You need to confirm you have read and accept the competition rules",
            422,
        )

    try:
        e = Entry(
            contact_name=request.form["contact-name"],
            contact_email=contact_email,
            organisation=organisation,
            county=county,
            district_id=district_id,
            district_name=district_name,
            group_name=group_name,
            troop_name=troop_name,
        )

        db.session.add(e)
        db.session.commit()

        e.sendConfirmationEmail()

        return ("OK", 200)

    except Exception as e:
        return (f"There was a problem processing the sign up - {e}", 422)
Exemplo n.º 21
0
def generate():
    # Generate a few users
    try:
        edd = User(id='edd',
                   password=generate_password_hash('e'),
                   display_name='Edd Salkield',
                   description='My description',
                   primary_email='*****@*****.**',
                   developer=Developer())
        edd_role = MailUserRole(user=edd,
                                creator=True,
                                relationship='Interested')
        edd_role_c = MailUserRole(user=edd,
                                  creator=True,
                                  relationship='Current')
        edd_role_p = MailUserRole(user=edd, creator=True, relationship='Past')
        edd_role_o = MailUserRole(user=edd, creator=True, relationship='Other')
        db.session.add(edd)
        db.session.add(edd_role)
        rogan = User(id='rogan',
                     password=generate_password_hash('e'),
                     display_name='Rogan Clark',
                     description='My description',
                     primary_email='*****@*****.**',
                     developer=Developer())
        rogan_role = MailUserRole(user=rogan,
                                  creator=False,
                                  relationship='Current')
        db.session.add(rogan)
        db.session.add(rogan_role)
        mark = User(id='mark',
                    password=generate_password_hash('e'),
                    display_name='Mark Todd',
                    description='My description',
                    primary_email='*****@*****.**',
                    developer=Developer())
        mark_role = MailUserRole(user=mark, creator=False, relationship='Past')
        db.session.add(mark)
        db.session.add(mark_role)
        josh = User(id='josh',
                    password=generate_password_hash('e'),
                    display_name='Josh Smailes',
                    description='My description',
                    primary_email='*****@*****.**',
                    developer=Developer())
        josh_role = MailUserRole(user=josh,
                                 creator=False,
                                 relationship='Other')
        db.session.add(josh)
        db.session.add(josh_role)

        # Generate some organisations
        oxford_cs = Department(display_name='Computer Science',
                               description='''
            Oxford CS description
        ''',
                               users=[edd])
        oxford_anthro = Department(display_name='Anthropology',
                                   description='''
            Oxford Anthropology description
        ''',
                                   users=[edd])
        oxford = Organisation(display_name='University of Oxford',
                              description='''
            This is the description of the Universty of Oxford
        ''',
                              departments=[oxford_cs, oxford_anthro])

        cambridge_anthro = Department(display_name='Anthropology',
                                      description='''
            Cambridge Anthropology description
        ''',
                                      users=[edd])
        cambridge = Organisation(display_name='University of Cambridge',
                                 description='''
            This is the description of the Universty of Cambridge 
        ''',
                                 departments=[cambridge_anthro])

        db.session.add(oxford)
        db.session.add(cambridge)

        # Generate a group chat
        user_roles = [edd_role, rogan_role, mark_role, josh_role]
        empty_group = MailGroup(display_name='The empty chat',
                                user_roles=user_roles)
        db.session.add(empty_group)

        group = MailGroup(display_name='The friend chat',
                          user_roles=user_roles)
        db.session.add(group)
        group = MailGroup(display_name='The current chat',
                          user_roles=[edd_role_c])
        db.session.add(group)
        group = MailGroup(display_name='The past chat',
                          user_roles=[edd_role_p])
        db.session.add(group)
        group = MailGroup(display_name='The other chat',
                          user_roles=[edd_role_o])
        db.session.add(group)
        db.session.commit()

        # Create some messages
        messages = []
        message = MailMessage(user=edd,
                              body='yo wassup',
                              date_created=datetime.utcnow())
        db.session.add(message)
        messages.append(message)
        time.sleep(2)
        message = MailMessage(user=josh,
                              body='nm',
                              date_created=datetime.utcnow())
        db.session.add(message)
        messages.append(message)
        time.sleep(2)
        message = MailMessage(user=mark,
                              body='nm 2',
                              date_created=datetime.utcnow())
        db.session.add(message)
        messages.append(message)
        db.session.commit()
        group.messages = messages

        # Save changes
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        group = MailGroup.query.filter_by(
            display_name='The friend chat').first()
        return f'messages already generated. Group id: {group.id}'
    else:
        return 'messages generated'