Ejemplo n.º 1
0
    def sell_trade(self,user,trade_info):

        portfolio_state_id = trade_info.get('portfolio_state_id',None)
        shares = trade_info.get('shares',None)

        try:
            portfolio = PortfolioList.objects.get(id=portfolio_state_id)
        except ObjectDoesNotExist:
            raise BadRequestException(message='invalid portfolio id')
        
        if shares is None or shares > portfolio.shares:
            raise BadRequestException(message='invalid shares quantity')

        # add current state in TradeHistory
        trade_hist = TradeHistory()
        trade_hist.user = user
        trade_hist.trade_type = 'sell'
        trade_hist.portfolio_state_id = portfolio.id
        trade_hist.buy_price = portfolio.buy_price
        trade_hist.shares = portfolio.shares
        trade_hist.is_active = True
        trade_hist.save()

        portfolio.shares -= shares
        portfolio.save() 

        return {"success":True,"message":"Trade sold successfully"}
Ejemplo n.º 2
0
def rename_index(index, parts):
    if not parts:
        raise BadRequestException("Usage: /index rename [newname]")

    # Check index name
    name = parts[0].upper()
    valid_index_name(name)

    try:
        existing_index = Index.objects.get(name=name)
        if existing_index.user_id == user.id:
            raise BadRequestException(
                "Your index is already named {}".format(name))
        else:
            raise BadRequestException(
                "{} already exists and belongs to {}".format(
                    name, existing_index.user.name))
    except Index.DoesNotExist:
        # Rename the user's current index name
        pass

    index.name = name
    index.save()

    return mattermost_text("Index renamed to {}".format(name))
Ejemplo n.º 3
0
def create_index(user, parts):
    usage_str = "Usage: /index create [name] [stock1:count, [stock2: count, [option1: count...]]]"

    if not parts:
        raise BadRequestException(usage_str)

    # Check for index name
    name = parts[0].upper()
    valid_index_name(name)

    index = None

    # Verify that this index name isn't already taken by someone else
    try:
        index = Index.objects.get(name=name)
        if index.user_id != user.id:
            raise BadRequestException("{} belongs to {}".format(
                name, index.user.name))
    except Index.DoesNotExist:
        pass

    if index:
        # Delete the index so that it can be recreated again
        index.delete()

    index = Index.objects.create(user=user, name=name)

    parts.pop(0)

    return update_index(index, parts)
Ejemplo n.º 4
0
def invite_applicant(applicant_user_id, current_user=current_user):
    if not is_senior_recruiter(current_user):
        raise ForbiddenException(
            'User {} cannot invite applicants.'.format(current_user.id))
    else:
        application = Application.get_submitted_for_user(applicant_user_id)
        if application is None:
            raise BadRequestException(
                'User {} is not in an open application.'.format(
                    applicant_user_id
                )
            )
        elif not application.is_accepted:
            raise BadRequestException(
                'User {} application is not accepted.'.format(
                    applicant_user_id
                )
            )
        elif application.is_invited:
            raise BadRequestException(
                'User {} application is already invited.'.format(
                    applicant_user_id
                )
            )
        else:
            send_mail(applicant_user_id, 'invite')
            application.is_invited = True
            db.session.commit()
            add_status_note(
                application, 'Application invited by {}.'.format(current_user.name))
Ejemplo n.º 5
0
def api_set_mail_template():
    """
    Sets a template.

    Template can include {name} in parts like 'Congratulations {name}', which
    will be filled using the to-character's name automatically later.

    Args:
        name (str) the endpoint name of the template" {'invite' | 'accept'}
        subject (str) email subject line
        template (str)

    Returns:
        {'status': 'ok'}

    Error codes:
        Forbidden (403): If logged in user is not an admin.
        Bad request (400): If any arguments are missing.
    """
    name = request.get_json().get('name')
    subject = request.get_json().get('subject')
    template = request.get_json().get('template')
    if name is None:
        raise BadRequestException('name argument is missing.')
    elif template is None:
        raise BadRequestException('template argument is missing.')
    elif subject is None:
        raise BadRequestException('subject argument is missing.')
    else:
        return jsonify(
            set_mail_template(name,
                              subject=subject,
                              text=template,
                              current_user=current_user))
Ejemplo n.º 6
0
    def validate_user(self, filters):
        user_id = filters.get("user_id", None)
        if user_id is None:
            raise BadRequestException(message='user_id is a must')

        try:
            user = User.objects.get(id=user_id)
        except:
            raise BadRequestException(message='user not found')

        return user
Ejemplo n.º 7
0
    def add_trade(self,user,trade_info):
        
        try:
            ticker_symbol = trade_info.get('ticker_symbol')
            buy_price = trade_info.get('buy_price')
            shares = trade_info.get('shares')
        except Exception as e:
            raise BadRequestException(message=str(e))
        
        if buy_price < 0 or shares <= 0:
            raise BadRequestException(message='invalid buy price or share quantity')

        try:
            ticker = TickerSymbol.get(comp_symbol=ticker_symbol)
        except ObjectDoesNotExist:
            raise BadRequestException(message="invalid company")
        
        # find if a trade already exist for this ticker
        try:
            old_trade = PortfolioList.objects.get(ticker=ticker,user=user,shares__gt=0)
            # add it in TradeHistory
            trade_hist = TradeHistory()
            trade_hist.user = user
            trade_hist.trade_type = 'add'
            trade_hist.portfolio_state_id = old_trade.id
            trade_hist.buy_price = old_trade.buy_price
            trade_hist.shares = old_trade.shares
            trade_hist.is_active = True
            trade_hist.save()
            new_buy = (old_trade.buy_price*old_trade.shares + buy_price*shares) / (old_trade.shares + shares)
            old_trade.buy_price = new_buy
            old_trade.shares += shares
            old_trade.save()
        except ObjectDoesNotExist:
            trade = PortfolioList()
            trade.user = user
            trade.ticker = ticker
            trade.buy_price = buy_price
            trade.shares = shares
            trade.save()

            # add it in the TradeHistory
            # store portfolio id and other fields as NULL indicating that this is the first trade made for that user
            trade_hist = TradeHistory()
            trade_hist.user = user
            trade_hist.trade_type = 'add'
            trade_hist.portfolio_state_id = None
            trade_hist.buy_price = None
            trade_hist.shares = None
            trade_hist.is_active = True
            trade_hist.save()
        
        return {"success":True,"message":"Trade added successfully"}
Ejemplo n.º 8
0
def remove_admin_list_item(kind, item_id, current_user=None):
    user_admin_access_check(current_user)
    if kind not in kind_dict:
        raise BadRequestException('Unknown Redlist')
    item = db.session.query(kind_dict[kind]).filter_by(
        id=item_id).one_or_none()
    if item is None:
        raise BadRequestException(f'Item {item_id} not found in List {kind}')
    elif not item.redlisted:
        raise BadRequestException(f'Item {item_id} not found in List {kind}')
    else:
        item.redlisted = False
        db.session.commit()
        return {'status': 'ok'}
Ejemplo n.º 9
0
def get_or_create_user(request):
    user_id = request.POST.get('user_id', None)
    user_name = request.POST.get('user_name', None)

    if not user_id:
        raise BadRequestException("user_id is not present")

    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        if not user_name:
            raise BadRequestException("user_name is not present")
        user = User(id=user_id, name=user_name)
        user.save()
    return user
Ejemplo n.º 10
0
 def remove_trade(self,user,trade_info):
     trade_id = trade_info('trade_id',None)
     if trade_id is None:
         raise BadRequestException(message='trade id is must')
     try:
         trade_hist = TradeHistory.objects.get(id=trade_id,is_active=True)
         portfolio = PortfolioList.objects.get(id=trade_hist.portfolio_state_id)
         trade_hist.is_active = False
         portfolio.buy_price = trade_hist.buy_price
         portfolio.shares = trade_hist.shares
         portfolio.save()
         trade_hist.save()
         return {"success":True,"message":"trade removed"}
     except:
         raise BadRequestException(message='invalid trade id')
Ejemplo n.º 11
0
def start_application(current_user=None):
    if is_admin(current_user) or is_recruiter(current_user) or is_senior_recruiter(current_user):
        raise BadRequestException('Recruiters cannot apply')
    character = Character.get(current_user.id)
    if character.blocked_from_applying:
        raise ForbiddenException('User is blocked')
    application = Application.get_for_user(current_user.id)
    if application:
        raise BadRequestException('An application is already open')
    # no application, start one
    application = Application(user_id=current_user.id, is_concluded=False)
    db.session.add(application)
    db.session.commit()
    add_status_note(application, 'Application created.')
    return {'status': 'ok'}
Ejemplo n.º 12
0
def validate_index_name(name):
    name = name.upper()
    if not re.match(INDEX_NAME_PATTERN, name):
        raise BadRequestException(
            "Invalid name: '{}'. Symbol must be an alphabetic string no longer than 14 characters."
            .format(name))
    if name == 'EVERYONE':
        raise BadRequestException(
            "'EVERYONE' is a reserved keyword. You must choose a different name for your index."
        )
    # Verify that this index name does not match a stock name
    if Stock.search(symbol=name):
        raise BadRequestException(
            "Can't use this name; a stock named {} already exists".format(
                name))
Ejemplo n.º 13
0
def display_index(request, index_name=None):
    user = get_or_create_user(request)
    index = None

    if index_name:
        try:
            index = Index.objects.get(name=index_name.upper())
        except Index.DoesNotExist:
            raise BadRequestException(
                "Index does not exist: '{}'".format(index_name))
    else:
        indexes = Index.objects.filter(user=user)
        if not indexes:
            return mattermost_text("You do not have any indexes.\n\t" +
                                   "\n\t".join([p.name for p in indexes]))
        elif len(indexes) == 1:
            index = indexes[0]
        else:
            return mattermost_text(
                "You have multiple indexes. Specify the index you want to view.\n\t"
                + "\n\t".join([p.name for p in indexes]))

    aggregator = Aggregator(index)

    return print_index(index, aggregator, index.user == user)
Ejemplo n.º 14
0
 def clean_descriptors_filter(self):
     descriptors_filter = self.cleaned_data['descriptors_filter']
     if 'descriptors_filter' in self.data and (
             not descriptors_filter or descriptors_filter.isspace()):
         raise BadRequestException('Invalid descriptors_filter.')
     return my_quote(
         descriptors_filter) if descriptors_filter is not None else ""
Ejemplo n.º 15
0
    def create(cls, request, *args, **kwargs):
	body_fields = tuple(['message'])
        try:
	    db_session = Session()
	    body_args = request.body_args
	    body_check(body_fields, body_args)

	    message = body_args['message'].strip()
	    at = datetime.now()
	    user_id = current_user.user_id

	    new_appversion = Appversion(message=message,
				    at=at,
		 		    user_id=user_id)
	    new_opratingsystem = Operatingsystem(message=message,
				    at=at,
				    user_id=user_id)
	    db_session.add(new_appversion)
	    db_session.commit()

	    properties = {'content':"add the appversion successfully"}
	    meta = {'id':new_appversion.id}

	    return cls(properties=properties, meta=meta)
	except Exception as exc:
	    if not isinstance(exc, HTTPBaseException):
		_logger.exception(exc)
		raise BadRequestException(message='Bad request')
	    else:
		raise exc
	finally:
	    db_session.close()
Ejemplo n.º 16
0
def str_to_duration(duration_str):
    duration_str = duration_str.strip().lower()
    match = re.match(DURATION_FORMAT, duration_str)
    if not match:
        raise BadRequestException(
            "Invalid span '{}'. Must be time unit and/or number, e.g. '3month'"
            .format(duration_str))

    unit = match.groups()[1][0]
    if unit == 'd':
        duration = timedelta(days=1)
    elif unit == 'w':
        duration = timedelta(days=7)
    elif unit == 'm':
        duration = timedelta(days=31)
    elif unit == 'y':
        duration = timedelta(days=365)
    elif unit == 'a':
        # Max duration available is 5 years
        return timedelta(days=365 * 5)

    if match.groups()[0]:
        # Multiply by provided duration
        duration *= int(match.groups()[0])

    return duration
Ejemplo n.º 17
0
def retrieve(game_id: int) -> Game:
    db_game = repo[game_id]

    if db_game is None:
        raise BadRequestException("Game not found")

    return db_game
Ejemplo n.º 18
0
def add_applicant_note(applicant_user_id,
                       text,
                       title=None,
                       is_chat_log=False,
                       current_user=None):
    application = Application.get_submitted_for_user(applicant_user_id)
    if application is None:
        raise BadRequestException('User {} is not an applicant'.format(
            User.get(applicant_user_id).name))
    else:
        if not is_recruiter(current_user):
            raise ForbiddenException('Current user is not a recruiter')
        elif (application.recruiter_id != current_user.id
              and not is_senior_recruiter(current_user)):
            raise ForbiddenException(
                'Current recruiter has not claimed applicant {}'.format(
                    applicant_user_id))
        note = Note(
            text=text,
            title=title,
            application_id=application.id,
            is_chat_log=is_chat_log,
            author_id=current_user.id,
        )
        db.session.add(note)
        db.session.commit()
        return {'status': 'ok'}
Ejemplo n.º 19
0
def retrieve(answer_id: int) -> Answer:
    db_answer = repo[answer_id]

    if db_answer is None:
        raise BadRequestException("Question not found")

    return db_answer
Ejemplo n.º 20
0
    def set_identifiers_to_load(self, items):
        for item in items:
            if type(item) in [Stock, Option]:
                self.instrument_map[item.url] = item
                self.instrument_map[item.identifier()] = item
                continue

            if type(item) == Index:
                self.set_identifiers_to_load(item.assets())
                continue

            if type(item) == Asset:
                identifier = item.instrument_url
            elif type(item) == str:
                identifier = item
            else:
                raise Exception("Cannot determine identifier for {}".format(
                    item.__class__.__name__))

            if self.stock_handler.valid_identifier(identifier):
                self.stock_identifiers.add(identifier)
            elif self.option_handler.valid_identifier(identifier):
                self.option_identifiers.add(identifier)
            else:
                raise BadRequestException(
                    "Invalid stock/option: '{}'".format(identifier))
Ejemplo n.º 21
0
def api_get_mail_template(name):
    """
    Retrieves a mail template. Returns an empty template if not present.

    Args:
        name (str)

    Returns:
        response

    Example:

        {
            'info': {
                'name': 'accept',
                'subject': 'Congratulations!'
                'text': 'Lorem ipsum dolores sit amet...'
            }
        }

    Error codes:
        Forbidden (403): If logged in user is not an admin.
        Bad request (400): If any arguments are missing.
    """
    if name is None:
        raise BadRequestException('name argument is missing.')
    return jsonify(get_mail_template(name, current_user=current_user))
Ejemplo n.º 22
0
def retrieve(question_id: int) -> Question:
    db_question = repo[question_id]

    if db_question is None:
        raise BadRequestException("Question not found")

    return db_question
Ejemplo n.º 23
0
 def delete_movie(id):
     '''
     Delete a Movie
     ---
     tags:
       - Movies
     parameters:
       - name: id
         in: path
         type: number
     responses:
       200:
         description: Returns successful
     '''
     try:
         movie = Movie.query.filter(Movie.id == id).first()
         if movie is None:
             raise BadRequestException()
         movie.delete()
         return jsonify({"success": True, "timestamp": time.time()}), 200
     except AuthError:
         abort(401)
     except BadRequestException:
         db.session.rollback()
         abort(400)
     except Exception as err:
         db.session.rollback()
         abort(500)
     finally:
         db.session.close()
Ejemplo n.º 24
0
 def delete_actor(id):
     '''
     Delete an Actor
     ---
     tags:
       - Actors
     parameters:
       - name: id
         in: path
         type: number
     responses:
       200:
         description: Returns successful
     '''
     try:
         actor = Actor.query.filter(Actor.id == id).first()
         if actor is None:
             raise BadRequestException('No actor found with ID %i' % (id))
         actor.delete()
         return jsonify({"success": True, "timestamp": time.time()}), 200
     except AuthError:
         abort(401)
     except BadRequestException as err:
         db.session.rollback()
         abort(400, err)
     except Exception as err:
         db.session.rollback()
         abort(500)
     finally:
         db.session.close()
Ejemplo n.º 25
0
def submit_application(current_user=None):
    application = Application.get_for_user(current_user.id)
    if not application:
        raise BadRequestException(
            f'User {current_user.id} is not an applicant.')
    application.is_submitted = True
    db.session.commit()
    add_status_note(application, 'Application submitted.')
    return {'status': 'ok'}
Ejemplo n.º 26
0
def stock_info(request):
    symbol = request.POST.get('text', None)

    if not symbol:
        raise BadRequestException("No stock was specified")

    fundamentals = Stock.Fundamentals.get(symbol)
    response = fundamentals.description if fundamentals else 'Stock was not found'
    return mattermost_text(response)
Ejemplo n.º 27
0
def remove_question(question_id, current_user=None):
    user_admin_access_check(current_user)
    question = db.session.query(Question).filter_by(
        id=question_id).one_or_none()
    if question is None:
        raise BadRequestException('No question with id {}'.format(id))
    else:
        db.session.delete(question)
        db.session.commit()
    return {'status': 'ok'}
Ejemplo n.º 28
0
def rename_index(index, new_index_name):
    validate_index_name(new_index_name)

    try:
        existing_index = Index.objects.get(name=new_index_name)
        if existing_index.user_id == user.id:
            raise BadRequestException(
                "You already have an index named {}".format(new_index_name))
        else:
            raise BadRequestException(
                "{} already exists and belongs to {}".format(
                    new_index_name, existing_index.user.name))
    except Index.DoesNotExist:
        pass

    index.name = new_index_name
    index.save()

    return mattermost_text("Index renamed to {}".format(new_index_name))
Ejemplo n.º 29
0
def index(request):
    if not DATABASE_PRESENT:
        raise BadRequestException(
            "No indexes database has been configured for this StockBot instance."
        )

    if request.POST.get('text', None):
        return index_action(request)
    else:
        return display_index(request)
Ejemplo n.º 30
0
def get_admin_list(kind, current_user=None):
    user_admin_access_check(current_user)
    if kind not in kind_dict:
        raise BadRequestException(f'Unknown Redlist {kind}')
    response = []
    redlisted_items = db.session.query(
        kind_dict[kind]).filter_by(redlisted=True)
    for item in redlisted_items:
        response.append({'id': item.id, 'name': item.name})
    return {'info': response}