Esempio n. 1
0
def test_kind(db_conn, posts_table):
    """
    Expect a proposal to have a kind.
    """

    proposal = Proposal(
        {"user_id": "A", "topic_id": "B", "body": "C", "entity_version": {"id": "D", "kind": "unit"}, "name": "E"}
    )
    del proposal["kind"]
    proposal, errors = proposal.save(db_conn)
    assert len(errors) == 1
    proposal["kind"] = "proposal"
    proposal, errors = proposal.save(db_conn)
    assert len(errors) == 0
def test_adding_review_and_comment_to_proposal_in_database(database):
    """A reviewed proposal has a score and possible a comment added.

    Put a proposal with user and presenter into the database. Although this is not
    allowed in the application have the user score and comment on their proposal
    to show that this all works in the database.
    """
    user = User(**user_data)
    proposal = Proposal(user, **proposal_data)
    presenter = Presenter(**presenter_data)
    ProposalPresenter(proposal, presenter, True)
    score = Score(proposal, user, 10)
    comment = Comment(proposal, user, 'Perfect')
    database.session.add(user)
    database.session.add(proposal)
    database.session.add(presenter)
    database.session.add(score)
    database.session.add(comment)
    database.session.commit()
    query_result = Proposal.query.filter_by(proposer=user).all()
    assert len(query_result) == 1
    proposal = query_result[0]
    assert proposal.scores is not None
    assert len(proposal.scores) == 1
    assert proposal.scores[0].score == 10
    assert proposal.comments is not None
    assert len(proposal.comments) == 1
    assert proposal.comments[0].comment == 'Perfect'
Esempio n. 3
0
def create_group(body):
    if "user_id" not in body or "team_id" not in body:
        return

    if "contract_id" not in body and "proposal_id" not in body:
        return

    # 有contract_id 表示要发offer

    create_friend(body["user_id"], body["team_id"])

    if "proposal_id" not in body:
        return

    prop = Proposal.select().where(Proposal.id == body["proposal_id"]).first()
    if not prop:
        return

    img = IMGroup.select().where(IMGroup.proposal == prop).first()
    if not img:
        uri = "%s/create_group" % imserver
        param = {
            "req_user_id": body["req_user_id"],
            "group_name": body["group_name"],
            "group_type": 3,
            "token": "abc",
            "group_avatar": "",
            "user_id_list": [body["user_id"], body["team_id"]]
        }
        headers = {'user-agent': 'yunzujia async create group by zhenjing'}
        # {"error_code":0,"error_msg":"成功","group_id":194}
        try:
            res = requests.post(uri, headers=headers, data=json.dumps(param))
            logger.error("im server: %s, %s" % (res.status_code, res.content))

            cont = json.loads(res.content)
            if cont['error_code'] == 0:
                img = IMGroup()
                img.proposal = body["proposal_id"]
                if "contract_id" in body:
                    img.contract = body["contract_id"]
                img.im_group_id = cont['group_id']
                img.save()

                if "contract_id" in body:
                    contract = prop.contract
                    send_offer(contract, body, cont["group_id"])
            return
        except:
            logger.error("im server cannot connected")
            return

    if "contract_id" in body:
        contract = Contract.select().where(
            Contract.id == body["contract_id"]).first()
        group_id = img.im_group_id
        img.contract = contract
        img.save()

        send_offer(contract, body, group_id)
def test_putting_proposal_in_database(database, registrant, presenter_data, proposal_data):
    """Put a proposal item into the database.

    A proposal has to be submitted by a user so tehre must be a user.
    Proposals must also have at least one presenter, by default the user is
    the lead presenter.
    """
    user = User(**registrant)
    proposal = Proposal(user, **proposal_data)
    presenter = Presenter(**presenter_data)
    ProposalPresenter(proposal, presenter, True)
    assert proposal.presenters[0] == presenter
    assert presenter.proposals[0] == proposal
    presenter.is_lead = True
    database.session.add(user)
    database.session.add(proposal)
    database.session.add(presenter)
    database.session.commit()
    query_result = Proposal.query.filter_by(proposer=user).all()
    assert len(query_result) == 1
    proposal = query_result[0]
    assert proposal.proposer.email == user.email
    assert {
        'title': proposal.title,
        'session_type': proposal.session_type,
        'summary': proposal.summary,
        'notes': proposal.notes,
        'audience': proposal.audience,
    } == proposal_data
    assert proposal.status == ProposalState.submitted
    assert len(proposal.presenters) == 1
    proposal_presenter = proposal.presenters[0]
    is_lead = proposal_presenter.is_lead
    assert is_lead
    assert (proposal_presenter.email, proposal_presenter.name) == (user.email, user.name)
Esempio n. 5
0
def update_post_route(request, topic_id, post_id):
    """
    Update an existing post. Must be one's own post.

    For post:
    - Only the body field may be changed.

    For proposals:
    - Only the name, body, and status fields can be changed.
    - The status can only be changed to declined, and only when
      the current status is pending or blocked.

    For votes:
    - The only fields that can be updated are body and response.
    """

    db_conn = request['db_conn']

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    # ## STEP 1) Find existing post instance ## #
    post_ = get_post_facade(db_conn, post_id)
    if not post_:
        return abort(404)
    if post_['user_id'] != current_user['id']:
        return abort(403)
    post_kind = post_['kind']

    # ## STEP 2) Limit the scope of changes ## #
    post_data = request['params']['post']
    if post_kind is 'post':
        post_data = pick(post_data, ('body',))
    elif post_kind is 'proposal':
        post_data = pick(post_data, ('name', 'body', 'status',))
        if (post_data.get('status') != 'declined' or
                post_data.get('status') not in ('pending', 'blocked',)):
            del post_data['status']
    elif post_kind is 'vote':
        post_data = pick(post_data, ('body', 'response',))

    # ## STEP 3) Validate and save post instance ## #
    post_, errors = post_.update(db_conn, post_data)
    if errors:
        errors = prefix_error_names('post.', errors)
        return 400, {
            'errors': errors,
            'ref': 'E4LFwRv2WEJZks7use7TCpww'
        }

    # ## STEP 4) Make updates based on proposal / vote status ## #
    if post_kind == 'proposal':
        update_entity_status(db_conn, post_)
    if post_kind == 'vote':
        proposal = Proposal.get(db_conn, id=post_['replies_to_id'])
        update_entity_status(db_conn, proposal)

    # ## STEP 5) Return response ## #
    return 200, {'post': post_.deliver()}
Esempio n. 6
0
def test_entity(db_conn, posts_table):
    """
    Expect a proposal to require an entity version id.
    """

    proposal, errors = Proposal.insert(db_conn, {"user_id": "A", "topic_id": "B", "body": "C", "name": "E"})
    assert len(errors) == 2
    proposal["entity_version"] = {"id": "D", "kind": "unit"}
    proposal, errors = proposal.save(db_conn)
    assert len(errors) == 0
Esempio n. 7
0
def test_kind(db_conn, posts_table):
    """
    Expect a proposal to have a kind.
    """

    proposal = Proposal({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
    })
    del proposal['kind']
    proposal, errors = proposal.save()
    assert len(errors) == 1
    proposal['kind'] = 'proposal'
    proposal, errors = proposal.save()
    assert len(errors) == 0
Esempio n. 8
0
def test_kind(db_conn, posts_table):
    """
    Expect a proposal to have a kind.
    """

    proposal = Proposal({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
    })
    del proposal['kind']
    proposal, errors = proposal.save()
    assert len(errors) == 1
    proposal['kind'] = 'proposal'
    proposal, errors = proposal.save()
    assert len(errors) == 0
Esempio n. 9
0
def test_name(db_conn, posts_table):
    """
    Expect a proposal to require a name.
    """

    proposal, errors = Proposal.insert(
        db_conn, {"user_id": "A", "topic_id": "B", "body": "C", "entity_version": {"id": "D", "kind": "unit"}}
    )
    assert len(errors) == 1
    proposal["name"] = "E"
    proposal, errors = proposal.save(db_conn)
    assert len(errors) == 0
def test_already_reviewed(registrant, proposal_single_presenter,
                          proposal_multiple_presenters_single_lead):
    reviewer = User(**new_user)
    proposer = User(**registrant)
    proposals = (Proposal(
        proposer,
        proposal_single_presenter['title'],
        proposal_single_presenter['session_type'],
        proposal_single_presenter['summary'],
    ),
                 Proposal(
                     proposer,
                     proposal_multiple_presenters_single_lead['title'],
                     proposal_multiple_presenters_single_lead['session_type'],
                     proposal_multiple_presenters_single_lead['summary'],
                 ))
    assert not already_reviewed(proposals[0], reviewer)
    assert not already_reviewed(proposals[1], reviewer)
    score = Score(proposals[1], reviewer, 7)
    assert not already_reviewed(proposals[0], reviewer)
    assert already_reviewed(proposals[1], reviewer)
Esempio n. 11
0
def instance(data):
    """
    Given data from the database, return an appropriate model instance
    based on the `kind` field.
    """

    if data.get('kind') == 'proposal':
        return Proposal(data)
    if data.get('kind') == 'vote':
        return Vote(data)

    return Post(data)
Esempio n. 12
0
def create_group(body):
    if "user_id" not in body or "team_id" not in body:
        return

    if "contract_id" not in body and "proposal_id" not in body:
        return

    # 有contract_id 表示要发offer

    create_friend(body["user_id"], body["team_id"])

    if "proposal_id" not in body:
        return

    prop = Proposal.select().where(Proposal.id == body["proposal_id"]).first()
    if not prop:
        return

    img = IMGroup.select().where(IMGroup.proposal == prop).first()
    if not img:
        uri = "%s/create_group" % imserver
        param = {"req_user_id":body["req_user_id"], "group_name":body["group_name"],
                "group_type":3, "token":"abc", "group_avatar":"", "user_id_list":[body["user_id"], body["team_id"]]}
        headers = {'user-agent': 'yunzujia async create group by zhenjing'}
        # {"error_code":0,"error_msg":"成功","group_id":194}
        try:
            res = requests.post(uri, headers=headers, data=json.dumps(param))
            logger.error("im server: %s, %s" % (res.status_code, res.content))

            cont = json.loads(res.content)
            if cont['error_code'] == 0:
                img = IMGroup()
                img.proposal = body["proposal_id"]
                if "contract_id" in body:
                    img.contract = body["contract_id"]
                img.im_group_id = cont['group_id']
                img.save()

                if "contract_id" in body:
                    contract = prop.contract
                    send_offer(contract, body, cont["group_id"])
            return
        except:
            logger.error("im server cannot connected")
            return

    if "contract_id" in body:
        contract = Contract.select().where(Contract.id == body["contract_id"]).first()
        group_id = img.im_group_id
        img.contract = contract
        img.save()

        send_offer(contract, body, group_id)
Esempio n. 13
0
def job_view(body):
    if "uuid" not in body or "user_id" not in body:
        return

    job = Job.select().where(Job.job_uuid==body["uuid"]).first()
    if not job or job.user_id != body["user_id"]:
        return
    job.last_view_time = utils.now()
    job.save()

    qs = Proposal.update(is_view=True).where(Proposal.job==job)
    qs.execute()
    return
Esempio n. 14
0
def extract_ocr_data():
    doc = []
    if not request.data:
        response = {"response": {"status": 400, "error": "ValidationError", "message": "no request content found"}}
    else:
        content = request.get_json(silent=True)
        if "path" not in content:
            response = {"response": { "status": 400, "error": "ValidationError", "message": "path is required" }}
        elif "name" not in content:
            response = {"response": { "status": 400, "error": "ValidationError", "message": "name is required" }}
        else: 
            file_path = content["path"]
            file_name = content["name"]
            
            doc = run_ocr(file_path)
            proposal_obj = make_proposal_obj(doc)
            print(len(doc))
            proposal = Proposal(doc ,file_name, proposal_obj)
            proposal_id = proposal.save()
            response = {"response": { "status": 200, "data": proposal_obj }}
    print("Done!")
    return json.dumps(response)
Esempio n. 15
0
def calc_user_discover(body):
    now = utils.now()
    start = utils.timedelta(now, days=-90)
    year_start = utils.timedelta(now, days=-365)
    id_start = 0
    while 1:
        users = User.select(User.id).where(User.id>id_start).limit(200)
        if not users:
            break

        for u in users:
            user_id = u.id
            id_start = u.id

            us = UserStatistics.select().where(UserStatistics.user == u.id).first()
            if not us:
                us = UserStatistics()
                us.user = u.id
            count = UserDiscover.select(fn.SUM(UserDiscover.view_num)).where(UserDiscover.user==user_id, UserDiscover.update_at.between(start, now)).scalar()
            us.season_view = count if count else 0

            # 90天内投标
            count = Proposal.select().where(Proposal.user==user_id,Proposal.ptype=='D',Proposal.create_at.between(start, now)).count()
            us.season_proposal = count

            # 90内沟通中
            count = Proposal.select().where(Proposal.user==user_id,
                                    Proposal.status=="interview",
                                    Proposal.update_at.between(start, now)).count()
            us.season_interview = count

            # 90天内被邀请
            count = Proposal.select().where(Proposal.user==user_id,Proposal.ptype=='I',Proposal.create_at.between(start, now)).count()
            us.season_invite = count

            # 90天内被邀请回复
            count = Proposal.select().where(Proposal.user==user_id,
                                    Proposal.ptype=='I',Proposal.status=="interview",
                                    Proposal.update_at.between(start, now)).count()
            us.season_reply = count
            # 90天内被邀请当天回复
            count1 = Proposal.select().where(Proposal.user==user_id,
                                    Proposal.ptype=='I',Proposal.day_reply==True,
                                    Proposal.update_at.between(start, now)).count()
            us.season_day_reply = count1

            # 90天内雇佣
            count = Proposal.select().where(Proposal.user==user_id,
                                    Proposal.status=="hire",
                                    Proposal.update_at.between(start, now)).count()
            us.season_hire = count

            # 一年内收总金额
            year_amount = MarginRecord.select(fn.SUM(MarginRecord.amount)).where(MarginRecord.user==user_id, 
                                        MarginRecord.record_type=="income", MarginRecord.create_at.between(year_start, now)).scalar()
            us.year_amount = year_amount if year_amount else 0
            us.update_at = now
            us.save()
Esempio n. 16
0
def test_entity(db_conn, posts_table):
    """
    Expect a proposal to require an entity version id.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'name': 'E',
    })
    assert len(errors) == 2
    proposal['entity_version'] = {'id': 'D', 'kind': 'unit'}
    proposal, errors = proposal.save()
    assert len(errors) == 0
def insert_keynotes_from_files():
    """Insert new keynote records from files in the keynote_directory directory."""
    # The directory contains one directory per keynote with person's name as the name.
    # The directory contains three files: details.txt, bio.adoc, and blurb.adoc.
    # The file details.txt contains key: value pairs one on each line, with title, email and country.
    keynotes_directory = Path(__file__).parent.parent / 'keynotes_directory'
    if keynotes_directory.exists():
        keynote_presenter_directories = os.listdir(keynotes_directory.as_posix())
        if len(keynote_presenter_directories) != 4:
            click.echo(click.style('There are not four keynotes', fg='red'))
        else:
            user = User.query.filter_by(email='*****@*****.**').all()
            assert len(user) == 1
            user = user[0]
            for directory in keynote_presenter_directories:
                with open(keynotes_directory / directory / 'bio.adoc') as f:
                    bio = f.read().strip()
                with open(keynotes_directory / directory / 'blurb.adoc') as f:
                    blurb = f.read().strip()
                assert bio
                assert blurb
                details = {}
                with open(keynotes_directory / directory / 'details.txt') as f:
                    for line in f.read().strip().splitlines():
                        key, value = [x.strip() for x in line.split(':')]
                        assert key
                        assert value
                        details[key] = value
                assert 'title' in details
                assert 'email' in details
                assert 'country' in details
                proposal = Proposal(user, details['title'], blurb, SessionType.keynote, status=ProposalState.acknowledged)
                # Protect against the case that the keynote has submitted a proposal.
                presenter = Presenter.query.filter_by(email=details['email']).all()
                if presenter:
                    assert len(presenter) == 1
                    presenter = presenter[0]
                else:
                    presenter = Presenter(details['email'], directory.replace('_', ' '), bio, details['country'])
                proposal_presenter = ProposalPresenter(proposal, presenter, True)
                db.session.add(proposal)
                db.session.add(presenter)
                db.session.add(proposal_presenter)
                db.session.commit()
    else:
        click.echo(click.style('Cannot find the keynotes_data directory', fg='red'))
Esempio n. 18
0
def test_replies(db_conn, posts_table):
    """
    Expect a proposal to allow a replies to id.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
        'replies_to_id': 'A',
    })
    assert len(errors) == 0
Esempio n. 19
0
def test_replies(db_conn, posts_table):
    """
    Expect a proposal to allow a replies to id.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
        'replies_to_id': 'A',
    })
    assert len(errors) == 0
Esempio n. 20
0
def test_replies(db_conn, posts_table):
    """
    Expect a proposal to allow a replies to id.
    """

    prev, errors = Post.insert(db_conn, {"user_id": "A", "topic_id": "B", "body": "C"})
    proposal, errors = Proposal.insert(
        db_conn,
        {
            "user_id": "A",
            "topic_id": "B",
            "body": "C",
            "entity_version": {"id": "D", "kind": "unit"},
            "name": "E",
            "replies_to_id": prev["id"],
        },
    )
    assert len(errors) == 0
Esempio n. 21
0
def test_body(db_conn, posts_table):
    """
    Expect a proposal to require a body.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
    })
    assert len(errors) == 1
    proposal['body'] = 'C'
    proposal, errors = proposal.save()
    assert len(errors) == 0
Esempio n. 22
0
def test_entity(db_conn, posts_table):
    """
    Expect a proposal to require an entity version id.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'body': 'C',
        'name': 'E',
    })
    assert len(errors) == 2
    proposal['entity_version'] = {
        'id': 'D',
        'kind': 'unit'
    }
    proposal, errors = proposal.save()
    assert len(errors) == 0
Esempio n. 23
0
def test_body(db_conn, posts_table):
    """
    Expect a proposal to require a body.
    """

    proposal, errors = Proposal.insert({
        'user_id': 'A',
        'topic_id': 'B',
        'entity_version': {
            'id': 'D',
            'kind': 'unit'
        },
        'name': 'E',
    })
    assert len(errors) == 1
    proposal['body'] = 'C'
    proposal, errors = proposal.save()
    assert len(errors) == 0
Esempio n. 24
0
def test_user_id(db_conn, posts_table):
    """
    Expect a proposal to require a user id.
    """

    proposal, errors = Proposal.insert(
        db_conn, {
            'topic_id': 'B',
            'body': 'C',
            'entity_version': {
                'id': 'D',
                'kind': 'unit'
            },
            'name': 'E',
        })
    assert len(errors) == 1
    proposal['user_id'] = 'A'
    proposal, errors = proposal.save(db_conn)
    assert len(errors) == 0
Esempio n. 25
0
def add_a_proposal_as_user(user_email, proposal_data):
    """Given a user email and a dictionary of details about a proposal add the proposal to the database."""
    user = User.query.filter_by(email=user_email).first()
    proposal = Proposal(
        user,
        proposal_data['title'],
        proposal_data['summary'],
        proposal_data['session_type'],
    )
    db.session.add(proposal)
    for presenter_data in proposal_data['presenters']:
        presenter = Presenter(
            presenter_data['email'],
            presenter_data['name'],
            presenter_data['bio'],
            presenter_data['country'],
        )
        db.session.add(presenter)
        ProposalPresenter(proposal, presenter, presenter_data['is_lead'])
    db.session.commit()
def submit():
    check = is_acceptable_route()
    if not check[0]:
        return check[1]
    assert check[1] is None
    if is_logged_in():
        if request.method == 'POST':
            user = User.query.filter_by(email=session['email']).first()
            if user:
                proposal_data = request.json
                status, message = validate_proposal_data(proposal_data)
                if not status:
                    # NB This should never be executed.
                    response = jsonify(message)
                    response.status_code = 400
                    return response
                proposal = Proposal(
                    user,
                    proposal_data.get('title').strip(),
                    proposal_data.get('summary').strip(),
                    SessionType(proposal_data.get('session_type').strip()),
                    SessionAudience(proposal_data.get('audience').strip()) if proposal_data.get('audience') else SessionAudience.all,
                    proposal_data.get('keywords').strip() if proposal_data.get('keywords') else '',
                    proposal_data.get('no_video') if proposal_data.get('no_video') else False,
                    proposal_data.get('notes').strip() if proposal_data.get('notes') else '',
                    proposal_data.get('constraints').strip() if proposal_data.get('constraints') else '',
                )
                db.session.add(proposal)
                presenters_data = proposal_data.get('presenters')
                for presenter_data in presenters_data:
                    presenter = Presenter.query.filter_by(email=presenter_data['email']).all()
                    if presenter:
                        assert len(presenter) == 1
                        presenter = presenter[0]
                        if presenter.name != presenter_data['name']:
                            presenter.name = presenter_data['name']
                        if presenter.bio != presenter_data['bio']:
                            presenter.bio = presenter_data['bio']
                        if presenter.country != presenter_data['country']:
                            presenter.country = presenter_data['country']
                    else:
                        presenter = Presenter(
                            presenter_data['email'],
                            presenter_data['name'],
                            presenter_data['bio'],
                            presenter_data['country'],
                        )
                        db.session.add(presenter)
                    ProposalPresenter(proposal, presenter, presenter_data['is_lead'])
                db.session.commit()
                session['just_submitted'] = True
                return jsonify('submit_success')
            return render_template('general.html', page=md(base_page, {
                'pagetitle': 'Submit POST Error',
                'data': 'The logged in user is not in database. This cannot happen.',
            }))
        user = User.query.filter_by(email=session['email']).first()
        if user:
            presenter = Presenter.query.filter_by(email=user.email).all()
            if presenter:
                assert len(presenter) == 1
                presenter = presenter[0]
                (p_email, p_name, p_bio, p_country) = (presenter.email, presenter.name, presenter.bio, presenter.country)
            else:
                (p_email, p_name, p_bio, p_country) = (user.email, user.name, '', user.country)
            return render_template('submit.html', page=md(base_page, {
                'pagetitle': 'Submit a proposal',
                'data': Markup(submit_form_preface_markup),
                'title': '',
                'session_type': SessionType.session.value,
                'summary': '',
                'audience': SessionAudience.all.value,
                'keywords': '',
                'no_video': False,
                'notes': '',
                'constraints': '',
                'presenter': {
                    'email': p_email,
                    'name': p_name,
                    'is_lead': True,
                    'bio': p_bio,
                    'country': p_country,
                },
                'countries': sorted(countries),
                'submit_label': 'Submit',
            }))
        return render_template('general.html', page=md(base_page, {
            'pagetitle': 'Submission Problem',
            'data': 'The logged in user is not in database. This cannot happen.',
        }))
    return render_template('general.html', page=md(base_page, {
        'pagetitle': 'Submit Not Possible',
        'data': 'You must be registered and logged in to submit a proposal.'
    }))
Esempio n. 27
0
def update_post_route(request, topic_id, post_id):
    """
    Update an existing post. Must be one's own post.

    For post:
    - Only the body field may be changed.

    For proposals:
    - Only the name, body, and status fields can be changed.
    - The status can only be changed to declined, and only when
      the current status is pending or blocked.

    For votes:
    - The only fields that can be updated are body and response.
    """

    db_conn = request['db_conn']

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    # ## STEP 1) Find existing post instance ## #
    post_ = get_post_facade(db_conn, post_id)
    if not post_:
        return abort(404)
    if post_['user_id'] != current_user['id']:
        return abort(403)
    post_kind = post_['kind']

    # ## STEP 2) Limit the scope of changes ## #
    post_data = request['params']['post']
    if post_kind is 'post':
        post_data = pick(post_data, ('body', ))
    elif post_kind is 'proposal':
        post_data = pick(post_data, (
            'name',
            'body',
            'status',
        ))
        if (post_data.get('status') != 'declined'
                or post_data.get('status') not in (
                    'pending',
                    'blocked',
                )):
            del post_data['status']
    elif post_kind is 'vote':
        post_data = pick(post_data, (
            'body',
            'response',
        ))

    # ## STEP 3) Validate and save post instance ## #
    post_, errors = post_.update(db_conn, post_data)
    if errors:
        errors = prefix_error_names('post.', errors)
        return 400, {'errors': errors, 'ref': 'E4LFwRv2WEJZks7use7TCpww'}

    # ## STEP 4) Make updates based on proposal / vote status ## #
    if post_kind == 'proposal':
        update_entity_status(db_conn, post_)
    if post_kind == 'vote':
        proposal = Proposal.get(db_conn, id=post_['replies_to_id'])
        update_entity_status(db_conn, proposal)

    # ## STEP 5) Return response ## #
    return 200, {'post': post_.deliver()}
Esempio n. 28
0
def create_post_route(request, topic_id):
    """
    Create a new post on a given topic.
    Proposal: must include entity (card, unit, or set) information.
    Vote: must refer to a valid proposal.
    """

    db_conn = request['db_conn']

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    topic = get_topic({'id': topic_id}, db_conn)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'PCSFCxsJtnlP0x9WzbPoKcwM',
        }

    # ## STEP 1) Create post (and entity) instances
    post_data = request['params'].get('post')
    if not post_data:
        return 400, {
            'errors': [{
                'name': 'post',
                'message': 'Missing post data.',
            }],
            'ref': 'ykQpZwJKq54MTCxgkx0p6baW'
        }
    post_data = omit(post_data, (
        'id',
        'created',
        'modified',
    ))
    post_data['user_id'] = current_user['id']
    post_data['topic_id'] = topic_id
    post_ = instance_post_facade(post_data)
    post_kind = post_['kind']
    if post_kind == 'proposal':
        entity = instance_new_entity(request['params'])
        entity_kind = get_kind(request['params'])
        post_['entity_version'] = {
            'id': entity['id'],
            'kind': entity_kind,
        }

    # ## STEP 2) Validate post (and entity) instances
    errors = prefix_error_names('post.', post_.validate(db_conn))
    if post_kind == 'proposal':
        errors = (errors +
                  prefix_error_names('entity.', entity.validate(db_conn)))
    if len(errors):
        return 400, {'errors': errors, 'ref': 'tux33ztgFj9ittSpS7WKIkq7'}

    # ## STEP 3) Save post (and entity)
    post_.save(db_conn)
    if post_kind == 'proposal':
        entity.save(db_conn)

    # ## STEP 4) Add author as a follower
    insert_follow(
        {
            'user_id': current_user['id'],
            'entity': {
                'id': topic['id'],
                'kind': 'topic',
            }
        }, db_conn)
    # TODO-2 also follow the entity

    # ## STEP 5) Make updates based on proposal / vote status
    if post_kind == 'proposal':
        update_entity_status(db_conn, post_)
    if post_kind == 'vote':
        proposal = Proposal.get(db_conn, id=post_['replies_to_id'])
        update_entity_status(db_conn, proposal)

    # ## STEP 6) Send notices
    if post_kind == 'proposal':
        send_notices(db_conn,
                     entity_id=topic['entity']['id'],
                     entity_kind=topic['entity']['kind'],
                     notice_kind='create_proposal',
                     notice_data={
                         'user_name': current_user['name'],
                         'topic_name': topic['name'],
                         'entity_kind': topic['entity']['kind'],
                         'entity_name': topic['entity']['id'],
                     })

    # ## STEP 7) Return response
    return 200, {'post': post_.deliver()}
Esempio n. 29
0
def create_post_route(request, topic_id):
    """
    Create a new post on a given topic.
    Proposal: must include entity (card, unit, or set) information.
    Vote: must refer to a valid proposal.
    """

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    topic = Topic.get(id=topic_id)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'PCSFCxsJtnlP0x9WzbPoKcwM',
        }

    # ## STEP 1) Create post (and entity) instances
    post_data = request['params'].get('post')
    if not post_data:
        return 400, {
            'errors': [{
                'name': 'post',
                'message': 'Missing post data.',
            }],
            'ref': 'ykQpZwJKq54MTCxgkx0p6baW'
        }
    post_data = omit(post_data, ('id', 'created', 'modified',))
    post_data['user_id'] = current_user['id']
    post_data['topic_id'] = topic_id
    post_ = instance_post_facade(post_data)
    post_kind = post_['kind']
    if post_kind == 'proposal':
        entity = instance_new_entity(request['params'])
        entity_kind = get_kind(request['params'])
        post_['entity_version'] = {
            'id': entity['id'],
            'kind': entity_kind,
        }

    # ## STEP 2) Validate post (and entity) instances
    errors = prefix_error_names('post.', post_.validate())
    if post_kind == 'proposal':
        errors = errors + prefix_error_names('entity.', entity.validate())
    if len(errors):
        return 400, {
            'errors': errors,
            'ref': 'tux33ztgFj9ittSpS7WKIkq7'
        }

    # ## STEP 3) Save post (and entity)
    post_.save()
    if post_kind == 'proposal':
        entity.save()

    # ## STEP 4) Add author as a follower
    Follow.insert({
        'user_id': current_user['id'],
        'entity': {
            'id': topic['id'],
            'kind': 'topic',
        }
    })
    # TODO-2 also follow the entity

    # ## STEP 5) Make updates based on proposal / vote status
    if post_kind == 'proposal':
        update_entity_status(post_)
    if post_kind == 'vote':
        proposal = Proposal.get(id=post_['replies_to_id'])
        update_entity_status(proposal)

    # ## STEP 6) Return response
    return 200, {'post': post_.deliver()}
def submit():
    check = is_acceptable_route()
    if not check[0]:
        return check[1]
    assert check[1] is None
    page = {
        'title': 'Submit',
        'year': year,
    }
    if is_logged_in():
        if request.method == 'POST':
            user = User.query.filter_by(email=session['email']).first()
            if user:
                proposal_data = request.json
                status, message = validate_proposal_data(proposal_data)
                response = {}
                if status:
                    proposal = Proposal(
                        user,
                        proposal_data.get('title').strip(),
                        SessionType(proposal_data.get('session_type')),
                        proposal_data.get('abstract').strip())
                    db.session.add(proposal)
                    presenters_data = proposal_data.get('presenters')
                    for presenter_data in presenters_data:
                        presenter = Presenter(
                            presenter_data['email'],
                            presenter_data['name'],
                            'A human being.',
                            presenter_data['country'],
                            presenter_data['state'],
                        )
                        ProposalPresenter(proposal, presenter,
                                          presenter_data['lead'])
                        db.session.add(presenter)
                    db.session.commit()
                    response['success'] = True
                    response[
                        'message'] = '''Thank you, you have successfully submitted a proposal for the ACCU {} conference!
If you need to edit it you can via the 'My Proposal' menu item.'''.format(year)
                    response['redirect'] = '/'
                else:
                    response['success'] = False
                    response['message'] = message
                return jsonify(**response)
        else:
            user = User.query.filter_by(email=session['email']).first()
            if user:
                return render_template(
                    'submit.html',
                    page={
                        'title': 'Submit a proposal for ACCU {}'.format(year),
                        'name': user.name,
                        'proposer': {
                            'email': user.email,
                            'name': user.name,
                            'bio': 'A human being.',
                            'country': user.country,
                            'state': user.state,
                        }
                    })
    return render_template(
        'failure.html',
        page=md(page, {'data': 'Must be logged in to submit a proposal.'}))