Example #1
0
 def get(self):
     bidsObj = {}
     for bid in Bid.all():
         bidObj = {}
         # Extracting properties
         bidId = bid.key().id_or_name()
         time = bid.createdAt.strftime("%H:%M:%S")
         date = bid.createdAt.strftime("%Y-%m-%d")
         participation = bid.participation
         loanId = bid.loan.key().id_or_name()
         bidRate = bid.bidrate
         if bidRate > 0:
             orderType = 'Competitive'
         else:
             orderType = 'Noncompetitive'
         userId = bid.user.key().id_or_name()
         # Passing properties to the obj
         bidObj['bidId'] = bidId
         bidObj['date'] = date
         bidObj['time'] = time
         bidObj['bidType'] = 'Specified'
         bidObj['participation'] = participation
         bidObj['assetSubset'] = 'Loan'
         bidObj['loanId'] = loanId
         bidObj['orderType'] = orderType
         if (orderType == 'Competitive'):
             bidObj['bidRate'] = bidRate
         bidObj['orderTiming'] = 'Day Trade'
         bidObj['userId'] = userId
         # Inserting new object into the accumulation object
         bidsObj[bidId] = bidObj
     # Dumping to JSON the accumulation object
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(bidsObj))
Example #2
0
def create_bid():
    try:
        r = request.json
        auction = Auction.query.filter(Auction.cat_id == r['cat_id'])[0]
        bid = Bid(price=r['price'],
                  user_email=r['user_email'],
                  auction_id=auction.auction_id)
        db.session.add(bid)
        db.session.commit()
        return jsonify(bid.json), 200
    except Exception as e:
        print(e)
        return jsonify({'err': 'oops'}), 444
Example #3
0
 def get(self):
     usersObj = {}
     for bid in Bid.all():
         user = bid.user
         userId = user.key().id_or_name()
         if (userId not in usersObj):
             userObj = {}
             # Extracting properties
             fundsAvailable = user.fundsAvailable
             # Passing properties to the obj
             userObj['userId'] = userId
             userObj['fundsAvailable'] = fundsAvailable
             # Inserting new object into the accumulation object
             usersObj[userId] = userObj
     # Dumping to JSON the accumulation object
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(usersObj))
Example #4
0
  def get(self):
      page = Page.CALC
      parameters = getPageDict(page)
      parameters['User'] = "******" % (getCurrentUser(), getGroup())
      try:
          c = calc()
          logging.debug(80*"*")
          logging.debug("loans =")
          logging.debug(c['loans'])
          logging.debug(80*"*")
          logging.debug("bids =")
          logging.debug(c['bids'])
          if 'loans' in c and 'bids' in c:
              parameters['loans'] = c['loans']
              parameters['bids'] = c['bids']
          for i in range(1, len(c['bids'])):
              b = Bid.get_by_key_name(key_names = c['bids'][i][0]['bid'])
              for j in range(len(c['bids'][i])):
                  if 'key' in c['bids'][i][j]:
                      l = loan.getLoan(c['bids'][i][j]['key'])
                      if (l.curr_upb >= long(float(c['bids'][i][j]['val']))):
                          l.curr_upb -= long(float(c['bids'][i][j]['val']))
                          l.put()
                      else:
                          raise CalcError("ERROR: At discount Bit %s to Loan %s curr_upb %s" %
                                  (str(c['bids'][i][0]['bid']), str(l.collateral_key),
                                  str(l.curr_upb)))
 
              b.status = 'Accepted'
              b.put()
          self.response.out.write(template.render("templates/results.html",
                  parameters))
      except:
          g = getGroup()
          if g == 'Demo':
              c = Demo_Param_Calc()
              parameters['loans'] = c['loans']
              parameters['bids'] = c['bids']
              self.response.out.write(template.render(
                      "templates/results.html", parameters))
          else:
              self.response.out.write(template.render("templates/oops.html",
                      []))
Example #5
0
 def get(self):
     loansObj = {}
     for bid in Bid.all():
         loan = bid.loan
         loanId = loan.key().id_or_name()
         if (loanId not in loansObj):
             loanObj = {}
             # Extracting properties
             mo = loan.customer_account_key
             loanAmount = loan.curr_upb
             # Passing properties to the obj
             loanObj['loanId'] = loanId
             loanObj['mortgageOriginator'] = mo
             loanObj['loanAmount'] = loanAmount
             # Inserting new object into the accumulation object
             loansObj[loanId] = loanObj
     # Dumping to JSON the accumulation object
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(json.dumps(loansObj))
def scan_inbox():
    for message in config.reddit.inbox.messages(limit=None):
        if message.new:

            # Get our team and conference
            nominating_team = None
            nominating_conf = None

            for idx in range(len(league.conferences)):
                nominating_team = league.conferences[
                    idx].team_assignments.team_from_coach(str(message.author))
                if nominating_team is not None:
                    nominating_conf = league.conferences[idx]
                    break

            # If this is not a message from a known coach, ignore it.
            if nominating_conf is None or nominating_team is None:
                # TODO: Add a direct link to the team thread in this message.
                message.mark_read()
                message.reply(
                    "It looks like you haven't registered your team in the team thread yet. "
                    +
                    "Please follow the directions in the team thread to register your team and then try "
                    + "your nomination again.")
                continue

            # Create an auction for the nominated player

            # TODO: Eventually try to validate player name against Google sheet
            player_name = str(message.subject)

            try:
                trunc_value = str(message.body).translate(
                    None, config.chars_to_strip).split(".")[0]
                bid_amount = Money(trunc_value, 'USD')
                bid_amount_str = str(bid_amount.format("en_US", '$#0', False))
            except ValueError:
                # If we can't make turn the bid into a valid bid amount, reject the nomination
                message.mark_read()
                message.reply(
                    "Unable to accept nomination for " + player_name +
                    ". Please make sure that your " +
                    "message subject is the player you're nominating and the message body is a starting "
                    +
                    "bid (e.g. $1). I'm unable to make cents of your bid as provided: "
                    + str(message.body) +
                    ". Ha Ha Ha. That was a great currency pun I just made.")
                continue

        # Attempt to nominate the player
            player = nominating_conf.draft.nominate_player(player_name)

            if player is None:
                # We don't want to respond to this more than once.
                message.mark_read()

                # TODO: Account for nomination order
                reply_body = "That player cannot be nominated at this time."

                # Get any existing auctions with the player
                auctions_for_player = nominating_conf.draft.get_auctions_for_player(
                    player_name)

                # Check if both copies have already been nominated
                if len(auctions_for_player) > 1:
                    reply_body = "Both copies of " + player_name + " have already been nominated."

                # Otherwise, check if the first copy is still actively being auctioned.
                elif len(auctions_for_player
                         ) == 1 and auctions_for_player[0].is_active():
                    reply_body = (
                        "You must wait for the auction for the first copy of "
                        + player_name +
                        " to conclude before you may nominate the second copy."
                    )

                message.reply(reply_body)
                break

            # TODO: Indicate which copy
            auction_comment = nominating_conf.draft.submission.reply(
                player.name + " (Copy " + str(player.copy) + ")")

            nominator = nominating_conf.team_assignments.team_from_coach(
                str(message.author))
            auction_url = config.reddit_base_url + str(
                auction_comment.permalink)
            auction = Auction(player, nominator, auction_url,
                              auction_comment.fullname, auction_comment)

            bid_comment = auction_comment.reply(bid_amount_str)

            bid = Bid(nominating_team, bid_amount,
                      datetime.fromtimestamp(message.created_utc),
                      bid_comment.fullname, bid_comment)
            auction.add_bid(bid)

            nominating_conf.draft.add_auction(auction)

            message.mark_read()
def scan_drafts():
    for submission in config.subreddit.hot(limit=None):
        # Check if this is a draft thread
        if submission.link_flair_text == config.draft_flair:
            # check for the conference name in the thread title
            draft_conf = None
            for idx in range(len(league.conferences)):
                if league.conferences[idx].name in str(submission.title):
                    draft_conf = league.conferences[idx]
                    break

            if draft_conf is None:
                continue

            # Check if we already have a draft for this conference
            if draft_conf.draft is None:
                draft_conf.draft = Draft(submission.fullname, submission)

            needs_auctioneer = True

            for comment in submission.comments:
                # Make sure the message isn't removed
                if comment.removed:
                    continue

                # If the comment author is this bot and not stickied
                if is_mine(comment) and not comment.stickied:

                    # Retrieve the auction
                    auction = draft_conf.draft.auction_from_id(
                        comment.fullname)
                    if auction is None:
                        # TODO: Better error handling here.
                        print("ERROR GETTING AUCTION FOR PLAYER: " +
                              str(comment.body) + ", ID: " + comment.fullname)

                        # Remove the post
                        comment.mod.remove()
                        continue

                    for reply in comment.replies:
                        # Make sure the message isn't removed
                        if reply.removed:
                            continue

                        # Skip the opening bid post made by this bot
                        if is_mine(reply):
                            continue

                        # Get the team doing the bidding
                        bidding_team = draft_conf.team_assignments.team_from_coach(
                            str(reply.author.name))

                        # Only count the bid if we have a valid team assignment
                        if bidding_team is not None:

                            # Try to make sense of the bid amount
                            try:

                                trunc_value = str(reply.body).translate(
                                    None, config.chars_to_strip).split(".")[0]
                                bid_amount = Money(trunc_value, 'USD')

                                # If the comment has been edited, we use the edit time instead of the created time.
                                bid_time_unix = reply.created_utc
                                if reply.edited:
                                    bid_time_unix = reply.edited

                                bid_timestamp = datetime.fromtimestamp(
                                    bid_time_unix)

                                bid = Bid(bidding_team, bid_amount,
                                          bid_timestamp, reply.fullname, reply)
                                auction.add_bid(bid)
                            except ValueError:
                                # If we can't make turn the bid into a valid bid amount, reject the nomination
                                message_subject = "Bid Error"
                                message_body = (
                                    "Unable to accept your bid for " +
                                    str(comment.body) +
                                    ". Please make sure that you " +
                                    "are only posting a dollar amount for your bid. e.g. $5. Do not include anything "
                                    +
                                    "else within your post. Your post was removed, so please try again."
                                )
                                config.reddit.redditor(reply.author).message(
                                    message_subject, message_body)
                                reply.mod.remove()
                                continue

                        else:
                            # TODO: Make this look up team/conference by author and direct to correct thread.
                            author = str(reply.author)
                            subject = "Attempted bid on " + auction.player.name
                            body = (
                                "You have attempted to bid on " +
                                auction.player.name + " in the " +
                                draft_conf.name + " conference draft. " +
                                "You either have not yet registered your team in the team thread, "
                                +
                                "or you are bidding in another conference's draft."
                            )

                            config.reddit.redditor(author).message(
                                subject, body)
                            reply.mod.remove()

                    auction.update_status()

                elif is_mine(comment) and comment.stickied:
                    # Check if anyone has replied to this post directly
                    # TODO: Make the nomination instructions be a template that can be used in multiple places.
                    for reply in comment.replies.replace_more(limit=None):
                        # Ignore if already removed.
                        if comment.removed:
                            continue

                        remove_post_bad_reply(reply)

                    needs_auctioneer = False
                    comment.edit(build_auctioneer_body(draft_conf.draft))

                else:
                    # Someone has replied to the OP, assume it's a nomination attempt and remove it.
                    remove_post_bad_reply(comment)

            # If this draft thread doesn't already have an auctioneer post, we need to add one.
            if needs_auctioneer:
                auctioneer_comment = submission.reply(
                    build_auctioneer_body(draft_conf.draft))
                auctioneer_comment.mod.distinguish('yes', True)