2

I'm puzzled why check50 shows me this error despite my portfolio and SQLite database correctly reflecting the sold shares

:( sell handles valid sale expected to find "56.00" in page, but it wasn't found

Following this answer, I tried running the staff solution

Below are the outputs after I bought 10 shares of BSE and sold 5 of them in both solutions:

Staff Solution: staff solution image

My Solution: My solution image

Here is my "sell" method code in application.py:

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    user_id = session["user_id"]

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        rows = db.execute("SELECT stock, SUM(shares) FROM history WHERE id = :id GROUP BY stock", id=user_id)

        selected_sym = request.form.get("symbol")

        try:
            shares = int(request.form.get("shares"))
            if shares <= 0:
                return apology("Please enter valid shares", 400)

            for i in range(len(rows)):
                if rows[i]["stock"] == selected_sym:
                    if shares > rows[i]["SUM(shares)"]:
                        return apology("Please enter valid shares", 400)

        except ValueError:
            return apology("Please enter valid shares", 400)

        quote = lookup(selected_sym)

        if quote != None:
            time = datetime.now()
            current_time = time.strftime('%Y-%m-%d %H:%M:%S')
            rows = db.execute("SELECT cash FROM users WHERE id = :id", id=user_id)
            updated_cash = round(rows[0]["cash"] + (shares * quote["price"]), 2)
            shares = -shares
            update_users = db.execute("UPDATE users SET cash = :cash WHERE id = :id", id=user_id, cash=updated_cash)
            insert_history = db.execute("INSERT INTO history (id, method, stock, price, shares, time) VALUES(:id, :method, :stock, :price, :shares, :time)",
                                        id=user_id, method="SOLD", stock=quote["symbol"], price=quote["price"], shares=shares, time=current_time)
            if not update_users:
                return apology("Sorry, stock could not be bought")
            if not insert_history:
                return apology("Sorry, stock bought could not be saved")

            return redirect(url_for("index"))

        return apology("Sorry, this stock is not valid!")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        rows = db.execute("SELECT DISTINCT stock FROM history WHERE id = :id", id=user_id)
        return render_template("sell.html", stocks=rows)

    return apology("Something went wrong")

I do not think there is a problem with formatting here as I have passed the following check50 tests:

:) buy handles valid purchase

Log

sending POST request to /login

sending POST request to /buy checking that "112.00" is in page

checking that "9,888.00" is in page

Complete Log: https://cs50.me/checks/bf480fb67ba5c92d487fb4f201f3bd155e4512d7

Please help me understand what is the actual problem here (is it a check50 bug or am I doing something wrong here?), as I am really flustered for not being able to pass the last check50 test despite evidently having implemented it correctly.

I'll be happy to share my IDE workspace if need be.

Edit:

As suggested in an answer, I added this to the top of my lookup function in helpers.py

if symbol == "AAAA": return {"name": "Test A", "price": 28.00, "symbol": "AAAA"}

Bought 4 shares of AAAA and then sold 2 shares of it and got an output shown by this screenshot:

Output screenshot of AAAA

10
  • Clarification please: The heading on index says "Current Price". Are you displaying the price at which the stock was purchased or current price as from lookup ? This check50 failure is invariably a problem in index (route or .html). Commented Sep 2, 2018 at 22:12
  • @DinoCoderSaurus by current price I mean price that is returned by the lookup function as is required in the specifications
    – Kewal Shah
    Commented Sep 3, 2018 at 4:48
  • Is there some value you don't format using usd filter for display? I failed at some point because I did the formatting myself at one point and displayed like $123.4 instead of $123.40. Changing all to usd fixed that for me.
    – Blauelf
    Commented Sep 3, 2018 at 9:03
  • @Blauelf yes I did encounter a similar problem, but i solved it by formatting my values to 2 decimal places ($123.4 instead of $123.40) and that is why check50 passes the :) buy handles valid purchase test. It is only in the sell portion that I am getting an error. Please check this log: cs50.me/checks/bf480fb67ba5c92d487fb4f201f3bd155e4512d7 and see if you can help me
    – Kewal Shah
    Commented Sep 3, 2018 at 9:15
  • Does your number formatting code work for values without decimals? Oh, must be, earlier tests already checked that :( Are you using correct field names in your form?
    – Blauelf
    Commented Sep 3, 2018 at 9:22

1 Answer 1

3

As suggested in a comment, add this to the top of your lookup function in helpers.py

if symbol == "AAAA":
    return {"name": "Test A", "price": 28.00, "symbol": "AAAA"}

and then, with a fresh account, buy 4 shares of AAAA and then sell 2 shares of it. Does the page that loads after your sale show 56.00 worth of shares and a cash balance of 9,944.00 ?

The issue doesn't seem to be in your code but in the schema of your history table. You created unique index for 'id' and 'time' but because check50 is purchasing and selling right after each other, it can sometimes be too quick for your index to be created and so it then fails.

12
  • Your question does not solve my question! My page shows show 56.00 worth of shares and a cash balance of 9,944.00 but check50 still returns an error
    – Kewal Shah
    Commented Sep 6, 2018 at 2:39
  • @KewalShah I know it doesn't. I'm trying to figure out if there's a bug with check50. Can you show a screenshot of what you see immediately after completing the sale (per my instructions)? The one you show doesn't have the commas in the dollar values, so I'm assuming you've changed something since then?
    – curiouskiwi
    Commented Sep 6, 2018 at 3:25
  • Hi thanks for replying, I've added the screenshot as per your suggestions. Can you figure out the problem now? (check50 log after adding AAAA: cs50.me/checks/47e415016e24a92b79d6df929ca036554acd3352)
    – Kewal Shah
    Commented Sep 7, 2018 at 12:37
  • Hi @KewalShah I've got a couple of people on the team looking into this, because, like me, they can't at first pass see why your code is failing that check50 test. I'll let you know what we discover once we do.
    – curiouskiwi
    Commented Sep 8, 2018 at 4:56
  • 1
    Don't know how to upvote a comment but thanks for this! I too created datetime as a unique index thinking no one should be buying and/or selling shares within one second. In retrospect multiple users logged in at the same time could easily do so. Anyway. Thanks for the help!!
    – eleusius
    Commented Oct 23, 2018 at 16:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .