def pilot():
    # Reservation System
    capacity = 300000
    optimize_route_list = []
    optimize_start_list = []
    optimize_end_list = []
    run_optimize = False
    if request.method == "POST" and (request.form.get("add") or request.form.get("remove")):
        bulk_op = g.mongo.db.contracts.initialize_unordered_bulk_op()
        bulk_run = False
        if request.form.get("add"):
            bulk_run = True
            add_ids = [int(x) for x in request.form.get("add").split(",")]
            for db_id in add_ids:
                bulk_op.find({"_id.id": db_id}).update({"$set": {"reserved_by": session["CharacterName"]}})
        elif request.form.get("remove"):
            bulk_run = True
            remove_ids = [int(x) for x in request.form.get("remove").split(",")]
            for db_id in remove_ids:
                bulk_op.find({"_id.id": db_id}).update({"$unset": {"reserved_by": session["CharacterName"]}})
        if bulk_run:
            bulk_op.execute()
    elif request.method == "POST":
        run_optimize = True
        optimize_start_list = request.form.getlist("start")
        optimize_end_list = request.form.getlist("end")
        for optimize_start in optimize_start_list:
            for optimize_end in optimize_end_list:
                optimize_route_list.append("{0}{1}".format(optimize_start, optimize_end))
        capacity = request.form.get("capacity", 300000)
    try:
        capacity = int(capacity)
    except ValueError:
        capacity = 300000

    # JF Corporation Contracts
    jf_contracts = g.mongo.db.contracts.find({
        "_id.service": "jf_service",
        "status": "Outstanding",
        "type": "Courier"
    })
    contract_list = sorted(jf_contracts, key=itemgetter("volume"), reverse=True)

    total_volume = 0
    optimized_run = [["Issuer", "Start Station", "End Station", "Date Issued", "Date Expired", "Days", "Reward",
                      "Collateral", "Volume"]]
    reserved_contracts = [["Issuer", "Start Station", "End Station", "Date Issued", "Date Expired", "Days", "Reward",
                           "Collateral", "Volume"]]
    all_history = [["Issuer", "Start Station", "End Station", "Date Issued", "Date Expired", "Days", "Reward",
                    "Collateral", "Volume", "Reserved By"]]

    users_set = set()
    for contract in contract_list:
        users_set.update([contract["issuer_id"]])
    caches.character(users_set)
    optimized_reward = 0
    optimized_collateral = 0
    optimized_volume = 0
    optimized_ids = []
    reserved_reward = 0
    reserved_collateral = 0
    reserved_volume = 0
    reserved_ids = []
    route_start_set = set()
    route_end_set = set()

    for contract in contract_list:
        # Check for non-static stations
        start_station = g.mongo.db.stations.find_one({"_id": contract["start_station_id"]})["name"]
        end_station = g.mongo.db.stations.find_one({"_id": contract["end_station_id"]})["name"]
        current_route = "{0}{1}".format(contract["start_station_id"], contract["end_station_id"])
        route_start_set.add((contract["start_station_id"], start_station))
        route_end_set.add((contract["end_station_id"], end_station))
        issuer = conversions.character(contract["issuer_id"])
        color = validator(contract)

        if (not contract.get("reserved_by") and total_volume + contract["volume"] <= capacity) and (
                    color not in ["active", "info"] and (run_optimize and current_route in optimize_route_list)):
            optimized_reward += contract["reward"]
            optimized_collateral += contract["collateral"]
            optimized_volume += contract["volume"]
            optimized_run.append([
                color,
                issuer,
                start_station,
                end_station,
                contract["date_issued"],
                contract["date_expired"],
                contract["num_days"],
                "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])
            total_volume += contract["volume"]
            optimized_ids.append(str(contract["_id"]["id"]))
        if contract.get("reserved_by") == session["CharacterName"]:
            reserved_reward += contract["reward"]
            reserved_collateral += contract["collateral"]
            reserved_volume += contract["volume"]
            reserved_contracts.append([
                color,
                contract["_id"]["id"],
                issuer,
                start_station,
                end_station,
                contract["date_issued"],
                contract["date_expired"],
                contract["num_days"],
                "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])
            reserved_ids.append(str(contract["_id"]["id"]))
        all_history.append([
            color,
            contract["_id"]["id"],
            issuer,
            start_station,
            end_station,
            contract["date_issued"],
            contract["date_expired"],
            contract["num_days"],
            "{:0,.2f}".format(contract["reward"]),
            "{:0,.2f}".format(contract["collateral"]),
            "{:0,.2f}".format(contract["volume"]),
            contract.get("reserved_by")
        ])

    # Formatting
    optimized_volume = "{:0,.2f}".format(optimized_volume)
    optimized_collateral = "{:0,.2f}".format(optimized_collateral)
    optimized_reward = "{:0,.2f}".format(optimized_reward)
    reserved_volume = "{:0,.2f}".format(reserved_volume)
    reserved_collateral = "{:0,.2f}".format(reserved_collateral)
    reserved_reward = "{:0,.2f}".format(reserved_reward)

    optimized_return = ",".join(optimized_ids)
    reserved_return = ",".join(reserved_ids)

    # Personal Contracts
    personal_history = [["Assignee", "Issuer", "Start Station", "End Station", "Date Issued", "Date Expired",
                         "Days", "Reward", "Collateral", "Volume"]]
    personal_api_keys = g.mongo.db.api_keys.find_one({"_id": session["CharacterOwnerHash"]})
    if personal_api_keys:
        invalid_apis = caches.contracts([("personal", api_key["key_id"], api_key["vcode"],
                                          api_key["character_id"]) for api_key in personal_api_keys["keys"]
                                         if api_key.get("valid", True)])
        if invalid_apis:
            return redirect(url_for("account.home", keys=",".join([str(x) for x in invalid_apis])))
        personal_character_ids = [x["character_id"] for x in personal_api_keys["keys"]]
        personal_contracts = g.mongo.db.contracts.find({
            "_id.service": "personal",
            "status": "Outstanding",
            "type": "Courier",
            "assignee_id": {"$in": personal_character_ids}
        })
        users_set = set()
        for contract in personal_contracts:
            users_set.update([contract["issuer_id"], contract["assignee_id"]])
        caches.character(users_set)

        # Call db again because query has ended when updating cache
        personal_contracts = g.mongo.db.contracts.find({
            "_id.service": "personal",
            "status": "Outstanding",
            "type": "Courier",
            "assignee_id": {"$in": personal_character_ids}
        })
        for contract in personal_contracts:
            start_station = g.mongo.db.stations.find_one({"_id": contract["start_station_id"]})["name"]
            end_station = g.mongo.db.stations.find_one({"_id": contract["end_station_id"]})["name"]
            issuer = conversions.character(contract["issuer_id"])
            assignee = conversions.character(contract["assignee_id"])
            color = validator(contract)

            personal_history.append([
                color,
                assignee,
                issuer,
                start_station,
                end_station,
                contract["date_issued"],
                contract["date_expired"],
                contract["num_days"],
                "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])

    # Payment System
    jf_paid, jf_tax_total = jf_tax_calculator(session["CharacterOwnerHash"])
    db_jf_reimbursement = g.mongo.db.preferences.find_one({"_id": "jf_reimbursement"})

    if db_jf_reimbursement:
        jf_reimbursement = db_jf_reimbursement["amount"]
        jf_percent_paid = int(min(jf_paid / jf_reimbursement * 100, 100))
        jf_percent_owed = max(int(min(jf_tax_total / jf_reimbursement * 100, 100)) - jf_percent_paid, 0)
        jf_paid = "{:,.02f}".format(jf_paid)
        jf_tax_total = "{:,.02f}".format(jf_tax_total)
        jf_reimbursement = "{:,.02f}".format(jf_reimbursement)
    else:
        jf_reimbursement = "0.00"
        jf_percent_paid = 0
        jf_percent_owed = 0
        jf_paid = "0.00"
        jf_tax_total = "0.00"

    return render_template("jf_pilot.html", contract_list=contract_list, optimized_run=optimized_run,
                           reserved_contracts=reserved_contracts, all_history=all_history,
                           optimized_reward=optimized_reward, optimized_collateral=optimized_collateral,
                           optimized_volume=optimized_volume, optimized_return=optimized_return,
                           reserved_reward=reserved_reward, reserved_collateral=reserved_collateral,
                           reserved_volume=reserved_volume, reserved_return=reserved_return,
                           personal_history=personal_history, jf_percent=[jf_percent_paid, jf_percent_owed],
                           jf_reimbursement=jf_reimbursement, jf_taxes=[jf_paid, jf_tax_total],
                           route_start_set=list(route_start_set), capacity=capacity, route_end_set=list(route_end_set),
                           optimize_start_list=[int(x) for x in optimize_start_list],
                           optimize_end_list=[int(y) for y in optimize_end_list])
Esempio n. 2
0
def pilot():
    # Reservation System
    capacity = 300000
    optimize_route_list = []
    optimize_start_list = []
    optimize_end_list = []
    run_optimize = False
    if request.method == "POST" and (request.form.get("add")
                                     or request.form.get("remove")):
        bulk_op = g.mongo.db.contracts.initialize_unordered_bulk_op()
        bulk_run = False
        if request.form.get("add"):
            bulk_run = True
            add_ids = [int(x) for x in request.form.get("add").split(",")]
            for db_id in add_ids:
                bulk_op.find({
                    "_id.id": db_id
                }).update({"$set": {
                    "reserved_by": session["CharacterName"]
                }})
        elif request.form.get("remove"):
            bulk_run = True
            remove_ids = [
                int(x) for x in request.form.get("remove").split(",")
            ]
            for db_id in remove_ids:
                bulk_op.find({
                    "_id.id": db_id
                }).update(
                    {"$unset": {
                        "reserved_by": session["CharacterName"]
                    }})
        if bulk_run:
            bulk_op.execute()
    elif request.method == "POST":
        run_optimize = True
        optimize_start_list = request.form.getlist("start")
        optimize_end_list = request.form.getlist("end")
        for optimize_start in optimize_start_list:
            for optimize_end in optimize_end_list:
                optimize_route_list.append("{0}{1}".format(
                    optimize_start, optimize_end))
        capacity = request.form.get("capacity", 300000)
    try:
        capacity = int(capacity)
    except ValueError:
        capacity = 300000

    # JF Corporation Contracts
    jf_contracts = g.mongo.db.contracts.find({
        "_id.service": "jf_service",
        "status": "Outstanding",
        "type": "Courier"
    })
    contract_list = sorted(jf_contracts,
                           key=itemgetter("volume"),
                           reverse=True)

    total_volume = 0
    optimized_run = [[
        "Issuer", "Start Station", "End Station", "Date Issued",
        "Date Expired", "Days", "Reward", "Collateral", "Volume"
    ]]
    reserved_contracts = [[
        "Issuer", "Start Station", "End Station", "Date Issued",
        "Date Expired", "Days", "Reward", "Collateral", "Volume"
    ]]
    all_history = [[
        "Issuer", "Start Station", "End Station", "Date Issued",
        "Date Expired", "Days", "Reward", "Collateral", "Volume", "Reserved By"
    ]]

    users_set = set()
    for contract in contract_list:
        users_set.update([contract["issuer_id"]])
    caches.character(users_set)
    optimized_reward = 0
    optimized_collateral = 0
    optimized_volume = 0
    optimized_ids = []
    reserved_reward = 0
    reserved_collateral = 0
    reserved_volume = 0
    reserved_ids = []
    route_start_set = set()
    route_end_set = set()

    for contract in contract_list:
        # Check for non-static stations
        start_station = g.mongo.db.stations.find_one(
            {"_id": contract["start_station_id"]})["name"]
        end_station = g.mongo.db.stations.find_one(
            {"_id": contract["end_station_id"]})["name"]
        current_route = "{0}{1}".format(contract["start_station_id"],
                                        contract["end_station_id"])
        route_start_set.add((contract["start_station_id"], start_station))
        route_end_set.add((contract["end_station_id"], end_station))
        issuer = conversions.character(contract["issuer_id"])
        color = validator(contract)

        if (not contract.get("reserved_by")
                and total_volume + contract["volume"] <= capacity) and (
                    color not in ["active", "info"] and
                    (run_optimize and current_route in optimize_route_list)):
            optimized_reward += contract["reward"]
            optimized_collateral += contract["collateral"]
            optimized_volume += contract["volume"]
            optimized_run.append([
                color, issuer, start_station, end_station,
                contract["date_issued"], contract["date_expired"],
                contract["num_days"], "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])
            total_volume += contract["volume"]
            optimized_ids.append(str(contract["_id"]["id"]))
        if contract.get("reserved_by") == session["CharacterName"]:
            reserved_reward += contract["reward"]
            reserved_collateral += contract["collateral"]
            reserved_volume += contract["volume"]
            reserved_contracts.append([
                color, contract["_id"]["id"], issuer, start_station,
                end_station, contract["date_issued"], contract["date_expired"],
                contract["num_days"], "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])
            reserved_ids.append(str(contract["_id"]["id"]))
        all_history.append([
            color, contract["_id"]["id"], issuer, start_station, end_station,
            contract["date_issued"], contract["date_expired"],
            contract["num_days"], "{:0,.2f}".format(contract["reward"]),
            "{:0,.2f}".format(contract["collateral"]),
            "{:0,.2f}".format(contract["volume"]),
            contract.get("reserved_by")
        ])

    # Formatting
    optimized_volume = "{:0,.2f}".format(optimized_volume)
    optimized_collateral = "{:0,.2f}".format(optimized_collateral)
    optimized_reward = "{:0,.2f}".format(optimized_reward)
    reserved_volume = "{:0,.2f}".format(reserved_volume)
    reserved_collateral = "{:0,.2f}".format(reserved_collateral)
    reserved_reward = "{:0,.2f}".format(reserved_reward)

    optimized_return = ",".join(optimized_ids)
    reserved_return = ",".join(reserved_ids)

    # Personal Contracts
    personal_history = [[
        "Assignee", "Issuer", "Start Station", "End Station", "Date Issued",
        "Date Expired", "Days", "Reward", "Collateral", "Volume"
    ]]
    personal_api_keys = g.mongo.db.api_keys.find_one(
        {"_id": session["CharacterOwnerHash"]})
    if personal_api_keys:
        invalid_apis = caches.contracts([
            ("personal", api_key["key_id"], api_key["vcode"],
             api_key["character_id"]) for api_key in personal_api_keys["keys"]
            if api_key.get("valid", True)
        ])
        if invalid_apis:
            return redirect(
                url_for("account.home",
                        keys=",".join([str(x) for x in invalid_apis])))
        personal_character_ids = [
            x["character_id"] for x in personal_api_keys["keys"]
        ]
        personal_contracts = g.mongo.db.contracts.find({
            "_id.service": "personal",
            "status": "Outstanding",
            "type": "Courier",
            "assignee_id": {
                "$in": personal_character_ids
            }
        })
        users_set = set()
        for contract in personal_contracts:
            users_set.update([contract["issuer_id"], contract["assignee_id"]])
        caches.character(users_set)

        # Call db again because query has ended when updating cache
        personal_contracts = g.mongo.db.contracts.find({
            "_id.service": "personal",
            "status": "Outstanding",
            "type": "Courier",
            "assignee_id": {
                "$in": personal_character_ids
            }
        })
        for contract in personal_contracts:
            start_station = g.mongo.db.stations.find_one(
                {"_id": contract["start_station_id"]})["name"]
            end_station = g.mongo.db.stations.find_one(
                {"_id": contract["end_station_id"]})["name"]
            issuer = conversions.character(contract["issuer_id"])
            assignee = conversions.character(contract["assignee_id"])
            color = validator(contract)

            personal_history.append([
                color, assignee, issuer, start_station, end_station,
                contract["date_issued"], contract["date_expired"],
                contract["num_days"], "{:0,.2f}".format(contract["reward"]),
                "{:0,.2f}".format(contract["collateral"]),
                "{:0,.2f}".format(contract["volume"])
            ])

    # Payment System
    jf_paid, jf_tax_total = jf_tax_calculator(session["CharacterOwnerHash"])
    db_jf_reimbursement = g.mongo.db.preferences.find_one(
        {"_id": "jf_reimbursement"})

    if db_jf_reimbursement:
        jf_reimbursement = db_jf_reimbursement["amount"]
        jf_percent_paid = int(min(jf_paid / jf_reimbursement * 100, 100))
        jf_percent_owed = max(
            int(min(jf_tax_total / jf_reimbursement * 100, 100)) -
            jf_percent_paid, 0)
        jf_paid = "{:,.02f}".format(jf_paid)
        jf_tax_total = "{:,.02f}".format(jf_tax_total)
        jf_reimbursement = "{:,.02f}".format(jf_reimbursement)
    else:
        jf_reimbursement = "0.00"
        jf_percent_paid = 0
        jf_percent_owed = 0
        jf_paid = "0.00"
        jf_tax_total = "0.00"

    return render_template(
        "jf_pilot.html",
        contract_list=contract_list,
        optimized_run=optimized_run,
        reserved_contracts=reserved_contracts,
        all_history=all_history,
        optimized_reward=optimized_reward,
        optimized_collateral=optimized_collateral,
        optimized_volume=optimized_volume,
        optimized_return=optimized_return,
        reserved_reward=reserved_reward,
        reserved_collateral=reserved_collateral,
        reserved_volume=reserved_volume,
        reserved_return=reserved_return,
        personal_history=personal_history,
        jf_percent=[jf_percent_paid, jf_percent_owed],
        jf_reimbursement=jf_reimbursement,
        jf_taxes=[jf_paid, jf_tax_total],
        route_start_set=list(route_start_set),
        capacity=capacity,
        route_end_set=list(route_end_set),
        optimize_start_list=[int(x) for x in optimize_start_list],
        optimize_end_list=[int(y) for y in optimize_end_list])
def home():
    corp_rate = 0
    collateral_rate = 0
    general_rate = 0
    volume = ""
    corp_volume_cost = 0
    volume_cost = 0
    collateral = ""
    collateral_cost = 0
    price = ""
    corp_price = ""

    start_list = []
    end_list = []
    for station in g.mongo.db.jf_routes.distinct("start"):
        if request.args.get("start") == station:
            start_list.append([station, True])
        elif not request.args.get("start") and station == "Jita IV - Moon 4 - Caldari Navy Assembly Plant":
            start_list.append([station, True])
        else:
            start_list.append([station, False])
    for station in g.mongo.db.jf_routes.distinct("end"):
        if request.args.get("end") == station:
            end_list.append([station, True])
        elif not request.args.get("end") and station == "3KNA-N II - We have top men working on it":
            end_list.append([station, True])
        else:
            end_list.append([station, False])
    start_list.sort()
    end_list.sort()

    # Contract Calculations
    selected_route = "Not selected."
    input_error = False
    if request.args.get("start") and request.args.get("end"):
        start_station_id = g.mongo.db.stations.find_one({"name": request.args.get("start").strip()})["_id"]
        end_station_id = g.mongo.db.stations.find_one({"name": request.args.get("end").strip()})["_id"]
        selected_route = g.mongo.db.jf_routes.find_one({"_id": int(str(start_station_id) + str(end_station_id))})
        if selected_route:
            last_time = 0
            corp_rate = 0
            collateral_rate = 0
            general_rate = 0
            for price_history in selected_route["prices"]:
                if price_history["valid_after"] > last_time:
                    corp_rate = price_history["corp"]
                    general_rate = price_history["general"]
                    collateral_rate = price_history["collateral"]
                    last_time = price_history["valid_after"]

            try:
                volume = request.args.get("volume")
                volume = float(volume.replace(",", "") if volume else 0)
                collateral = request.args.get("collateral")
                collateral = float(collateral.replace(",", "") if collateral else 0)
            except ValueError:
                input_error = True
            else:
                volume_cost = general_rate * volume
                corp_volume_cost = corp_rate * volume
                collateral_cost = collateral * collateral_rate / 100.0
                price = volume_cost + collateral_cost
                corp_price = corp_volume_cost + collateral_cost

                # Mark Non-Inputted Values
                if not request.args.get("volume"):
                    volume = ""
                if not request.args.get("collateral"):
                    collateral = ""

    # Warnings
    warning_list = []
    if session.get("UI_Corporation"):
        compare_price = corp_price
    else:
        compare_price = price

    if input_error:
        warning_list.append("One of your inputs was not a number.")
    else:
        if compare_price and compare_price < 1000000:
            warning_list.append("Rewards must be at least 1M Isk")
            if session.get("UI_Corporation"):
                corp_price = 1000000
            else:
                price = 1000000
        if volume and volume > 300000:
            warning_list.append("Contracts must be less than 300k M3")
        if compare_price and compare_price > 1000000000:
            warning_list.append("Contracts should be below 1B isk")
        if not selected_route:
            warning_list.append("We do not service this route.")

        # Formatting
        corp_rate = "{:0,.2f}".format(corp_rate)
        volume_cost = "{:0,.2f}".format(volume_cost)
        corp_volume_cost = "{:0,.2f}".format(corp_volume_cost)
        collateral_cost = "{:0,.2f}".format(collateral_cost)
        collateral_rate = "{:0,.2f}".format(collateral_rate)
        price = "{:0,.2f}".format(price) if price else ""
        corp_price = "{:0,.2f}".format(corp_price) if price else ""
        volume = "{:0.2f}".format(volume) if volume else ""
        collateral = "{:0.2f}".format(collateral) if collateral else ""

    # Contract History

    next_update_query = g.mongo.db.caches.find_one({"_id": "jf_service"})
    next_update = next_update_query.get("next_check", "Not Scheduled") if next_update_query else "Unknown"

    if session.get("UI_Alliance"):
        # Check Caches
        caches.stations()

        users_set = set()
        # Find all users
        for contract in g.mongo.db.contracts.find({"_id.service": "jf_service",
                                                   "issued_int": {"$gt": int(time.time()) - 2629743}}):
            users_set.update([contract["issuer_id"], contract["acceptor_id"]])
        caches.character(users_set)

        contract_list = [["Issuer", "Acceptor", "Start", "End", "Status", "Date Issued", "Expiration Date", "Volume"]]
        personal_contract_list = [["Acceptor", "Start", "End", "Status", "Date Issued", "Expiration Date", "Volume",
                                   "Reward", "Collateral"]]

        # All related characters for personal list
        alt_characters_db = g.mongo.db.api_keys.find_one({"_id": session.get("CharacterOwnerHash")})
        alt_characters_list = []
        if alt_characters_db:
            for api_key in alt_characters_db["keys"]:
                alt_characters_list.append(api_key["character_name"])

        for contract in g.mongo.db.contracts.find({"_id.service": "jf_service", "type": "Courier",
                                                   "issued_int": {"$gt": int(time.time()) - 2629743}}):
            if contract["status"] not in ["Deleted", "Canceled"]:
                # Perform ID Conversions
                start_station = g.mongo.db.stations.find_one({"_id": contract["start_station_id"]})
                start_station = start_station.get("name") if start_station else "Unknown"
                end_station = g.mongo.db.stations.find_one({"_id": contract["end_station_id"]})
                end_station = end_station.get("name") if end_station else "Unknown"
                acceptor = conversions.character(contract["acceptor_id"])
                issuer = conversions.character(contract["issuer_id"])

                color = validator(contract)

                contract_list.append([
                    color,
                    issuer,
                    acceptor,
                    start_station,
                    end_station,
                    contract["status"],
                    contract["date_issued"],
                    contract["date_expired"],
                    "{:0,.2f}".format(contract["volume"])
                ])

                if session.get("CharacterOwnerHash") and (
                                issuer == session["CharacterName"] or issuer in alt_characters_list):
                    personal_contract_list.append([
                        color,
                        acceptor,
                        start_station,
                        end_station,
                        contract["status"],
                        contract["date_issued"],
                        contract["date_expired"],
                        "{:0,.2f}".format(contract["volume"]),
                        "{:0,.2f}".format(contract["reward"]),
                        "{:0,.2f}".format(contract["collateral"])
                    ])
    else:
        contract_list = []
        personal_contract_list = []

    # Check auth
    if session.get("CharacterOwnerHash"):
        jf_admin = auth_check("jf_admin")
        jf_pilot = auth_check("jf_pilot")
    else:
        jf_admin = None
        jf_pilot = None

    # Images
    with open("configs/base.json", "r") as base_config_file:
        base_config = json.load(base_config_file)
    corporation_logo = base_config["image_server"] + "/Corporation/" + str(base_config["corporation_id"]) + "_128.png"
    alliance_logo = base_config["image_server"] + "/Alliance/" + str(base_config["alliance_id"]) + "_128.png"

    return render_template("jf.html", start_list=start_list, end_list=end_list, general_rate=general_rate,
                           volume=volume, contract_list=contract_list, next_update=next_update, admin=jf_admin,
                           collateral=collateral, volume_cost=volume_cost, collateral_cost=collateral_cost,
                           warning_list=warning_list, personal_contract_list=personal_contract_list, pilot=jf_pilot,
                           corp_volume_cost=corp_volume_cost, corp_price=corp_price, corp_rate=corp_rate, price=price,
                           corporation_logo=corporation_logo, alliance_logo=alliance_logo,
                           collateral_rate=collateral_rate)
Esempio n. 4
0
def home():
    corp_rate = 0
    collateral_rate = 0
    general_rate = 0
    volume = ""
    corp_volume_cost = 0
    volume_cost = 0
    collateral = ""
    collateral_cost = 0
    price = ""
    corp_price = ""

    start_list = []
    end_list = []
    for station in g.mongo.db.jf_routes.distinct("start"):
        if request.args.get("start") == station:
            start_list.append([station, True])
        elif not request.args.get(
                "start"
        ) and station == "Jita IV - Moon 4 - Caldari Navy Assembly Plant":
            start_list.append([station, True])
        else:
            start_list.append([station, False])
    for station in g.mongo.db.jf_routes.distinct("end"):
        if request.args.get("end") == station:
            end_list.append([station, True])
        elif not request.args.get(
                "end"
        ) and station == "3KNA-N II - We have top men working on it":
            end_list.append([station, True])
        else:
            end_list.append([station, False])
    start_list.sort()
    end_list.sort()

    # Contract Calculations
    selected_route = "Not selected."
    input_error = False
    if request.args.get("start") and request.args.get("end"):
        start_station_id = g.mongo.db.stations.find_one(
            {"name": request.args.get("start").strip()})["_id"]
        end_station_id = g.mongo.db.stations.find_one(
            {"name": request.args.get("end").strip()})["_id"]
        selected_route = g.mongo.db.jf_routes.find_one(
            {"_id": int(str(start_station_id) + str(end_station_id))})
        if selected_route:
            last_time = 0
            corp_rate = 0
            collateral_rate = 0
            general_rate = 0
            for price_history in selected_route["prices"]:
                if price_history["valid_after"] > last_time:
                    corp_rate = price_history["corp"]
                    general_rate = price_history["general"]
                    collateral_rate = price_history["collateral"]
                    last_time = price_history["valid_after"]

            try:
                volume = request.args.get("volume")
                volume = float(volume.replace(",", "") if volume else 0)
                collateral = request.args.get("collateral")
                collateral = float(
                    collateral.replace(",", "") if collateral else 0)
            except ValueError:
                input_error = True
            else:
                volume_cost = general_rate * volume
                corp_volume_cost = corp_rate * volume
                collateral_cost = collateral * collateral_rate / 100.0
                price = volume_cost + collateral_cost
                corp_price = corp_volume_cost + collateral_cost

                # Mark Non-Inputted Values
                if not request.args.get("volume"):
                    volume = ""
                if not request.args.get("collateral"):
                    collateral = ""

    # Warnings
    warning_list = []
    if session.get("UI_Corporation"):
        compare_price = corp_price
    else:
        compare_price = price

    if input_error:
        warning_list.append("One of your inputs was not a number.")
    else:
        if compare_price and compare_price < 1000000:
            warning_list.append("Rewards must be at least 1M Isk")
            if session.get("UI_Corporation"):
                corp_price = 1000000
            else:
                price = 1000000
        if volume and volume > 300000:
            warning_list.append("Contracts must be less than 300k M3")
        if compare_price and compare_price > 1000000000:
            warning_list.append("Contracts should be below 1B isk")
        if not selected_route:
            warning_list.append("We do not service this route.")

        # Formatting
        corp_rate = "{:0,.2f}".format(corp_rate)
        volume_cost = "{:0,.2f}".format(volume_cost)
        corp_volume_cost = "{:0,.2f}".format(corp_volume_cost)
        collateral_cost = "{:0,.2f}".format(collateral_cost)
        collateral_rate = "{:0,.2f}".format(collateral_rate)
        price = "{:0,.2f}".format(price) if price else ""
        corp_price = "{:0,.2f}".format(corp_price) if price else ""
        volume = "{:0.2f}".format(volume) if volume else ""
        collateral = "{:0.2f}".format(collateral) if collateral else ""

    # Contract History

    next_update_query = g.mongo.db.caches.find_one({"_id": "jf_service"})
    next_update = next_update_query.get(
        "next_check", "Not Scheduled") if next_update_query else "Unknown"

    if session.get("UI_Alliance"):
        # Check Caches
        caches.stations()

        users_set = set()
        # Find all users
        for contract in g.mongo.db.contracts.find({
                "_id.service": "jf_service",
                "issued_int": {
                    "$gt": int(time.time()) - 2629743
                }
        }):
            users_set.update([contract["issuer_id"], contract["acceptor_id"]])
        caches.character(users_set)

        contract_list = [[
            "Issuer", "Acceptor", "Start", "End", "Status", "Date Issued",
            "Expiration Date", "Volume"
        ]]
        personal_contract_list = [[
            "Acceptor", "Start", "End", "Status", "Date Issued",
            "Expiration Date", "Volume", "Reward", "Collateral"
        ]]

        # All related characters for personal list
        alt_characters_db = g.mongo.db.api_keys.find_one(
            {"_id": session.get("CharacterOwnerHash")})
        alt_characters_list = []
        if alt_characters_db:
            for api_key in alt_characters_db["keys"]:
                alt_characters_list.append(api_key["character_name"])

        for contract in g.mongo.db.contracts.find({
                "_id.service": "jf_service",
                "type": "Courier",
                "issued_int": {
                    "$gt": int(time.time()) - 2629743
                }
        }):
            if contract["status"] not in ["Deleted", "Canceled"]:
                # Perform ID Conversions
                start_station = g.mongo.db.stations.find_one(
                    {"_id": contract["start_station_id"]})
                start_station = start_station.get(
                    "name") if start_station else "Unknown"
                end_station = g.mongo.db.stations.find_one(
                    {"_id": contract["end_station_id"]})
                end_station = end_station.get(
                    "name") if end_station else "Unknown"
                acceptor = conversions.character(contract["acceptor_id"])
                issuer = conversions.character(contract["issuer_id"])

                color = validator(contract)

                contract_list.append([
                    color, issuer, acceptor, start_station, end_station,
                    contract["status"], contract["date_issued"],
                    contract["date_expired"],
                    "{:0,.2f}".format(contract["volume"])
                ])

                if session.get("CharacterOwnerHash") and (
                        issuer == session["CharacterName"]
                        or issuer in alt_characters_list):
                    personal_contract_list.append([
                        color, acceptor, start_station, end_station,
                        contract["status"], contract["date_issued"],
                        contract["date_expired"],
                        "{:0,.2f}".format(contract["volume"]),
                        "{:0,.2f}".format(contract["reward"]),
                        "{:0,.2f}".format(contract["collateral"])
                    ])
    else:
        contract_list = []
        personal_contract_list = []

    # Check auth
    if session.get("CharacterOwnerHash"):
        jf_admin = auth_check("jf_admin")
        jf_pilot = auth_check("jf_pilot")
    else:
        jf_admin = None
        jf_pilot = None

    # Images
    with open("configs/base.json", "r") as base_config_file:
        base_config = json.load(base_config_file)
    corporation_logo = base_config["image_server"] + "/Corporation/" + str(
        base_config["corporation_id"]) + "_128.png"
    alliance_logo = base_config["image_server"] + "/Alliance/" + str(
        base_config["alliance_id"]) + "_128.png"

    return render_template("jf.html",
                           start_list=start_list,
                           end_list=end_list,
                           general_rate=general_rate,
                           volume=volume,
                           contract_list=contract_list,
                           next_update=next_update,
                           admin=jf_admin,
                           collateral=collateral,
                           volume_cost=volume_cost,
                           collateral_cost=collateral_cost,
                           warning_list=warning_list,
                           personal_contract_list=personal_contract_list,
                           pilot=jf_pilot,
                           corp_volume_cost=corp_volume_cost,
                           corp_price=corp_price,
                           corp_rate=corp_rate,
                           price=price,
                           corporation_logo=corporation_logo,
                           alliance_logo=alliance_logo,
                           collateral_rate=collateral_rate)