コード例 #1
0
def issues():
    editor = auth_check("user_admin")
    if request.form.get("action") == "submit":
        g.mongo.db.issues.insert({
            "submitter": session["CharacterName"],
            "issue": request.form.get("issue").strip()
        })
    elif request.form.get("action") == "delete":
        if editor:
            g.mongo.db.issues.remove({"_id": ObjectId(request.form.get("id"))})
        else:
            g.mongo.db.issues.remove({
                "_id": ObjectId(request.form.get("id")),
                "submitter": session["CharacterName"]
            })

    issue_list = []
    for db_issue in g.mongo.db.issues.find():
        timestamp = ObjectId(
            db_issue["_id"]).generation_time.strftime("%Y-%m-%d %H:%M:%S")
        can_delete = True if editor or session["CharacterName"] == db_issue[
            "submitter"] else False
        issue_list.append([
            timestamp, db_issue["issue"], db_issue["submitter"], can_delete,
            db_issue["_id"]
        ])

    return render_template("issues.html", issue_list=issue_list)
コード例 #2
0
def admin():
    # Auth Check
    is_admin = auth_check("ordering_admin")
    if request.form.get("action") == "tax" and request.form.get("tax") and is_admin:
        g.mongo.db.preferences.update({"_id": "ordering"}, {"$set": {"tax": float(request.form.get("tax", 0))}},
                                      upsert=True)
    elif request.form.get("action") == "tax_corp" and request.form.get("tax") and is_admin:
        g.mongo.db.preferences.update({"_id": "ordering"}, {"$set": {"tax_corp": float(request.form.get("tax", 0))}},
                                      upsert=True)
    tax_db = g.mongo.db.preferences.find_one({"_id": "ordering"})
    tax = "{:.02f}".format(tax_db.get("tax", 0)) if tax_db else 0
    tax_corp = "{:.02f}".format(tax_db.get("tax_corp", 0)) if tax_db else 0

    # Invoice List
    one_month_oid = ObjectId.from_datetime(datetime.datetime.today() - datetime.timedelta(30))
    invoice_table = []
    marketeer_invoice_table = []
    new_invoice_table = []
    for invoice_db in g.mongo.db.invoices.find({"$or": [{"_id": {"$gt": one_month_oid}},
                                                        {"status": {"$not": re.compile("Completed")}}]}):
        invoice_status = invoice_db.get("status", "Not Processed")
        invoice_timestamp = ObjectId(invoice_db["_id"]).generation_time.strftime("%Y-%m-%d %H:%M:%S")
        invoice_color = ""
        if invoice_status == "Shipping - Completed":
            invoice_color = "primary"
        elif invoice_status == "Processing" or invoice_status.startswith("Shipping"):
            invoice_color = "warning"
        elif invoice_status in ["Failed", "Rejected", "Hold"]:
            invoice_color = "danger"
        elif invoice_status == "Completed":
            invoice_color = "success"

        finish_time = invoice_db.get("finish_time")
        if finish_time:
            time_to_delivery = finish_time - int(ObjectId(invoice_db["_id"]).generation_time.timestamp())
            ttd_days = time_to_delivery // (60 * 60 * 24)
            ttd_hours = time_to_delivery % (60 * 60 * 24) // (60 * 60)
            ttd_minutes = time_to_delivery % (60 * 60 * 24) % (60 * 60) // 60
            ttd_format = "{0}D{1}H{2}M".format(ttd_days, ttd_hours, ttd_minutes)
        else:
            ttd_format = "N/A"

        invoice_row = [invoice_color, invoice_timestamp, ttd_format, invoice_db["_id"], invoice_db["jf_end"],
                       "{:,.02f}".format(invoice_db["order_total"]), invoice_db.get("character"),
                       invoice_db.get("marketeer"), invoice_status]

        invoice_table.append(invoice_row)
        if invoice_db.get("marketeer") == session["CharacterName"]:
            marketeer_invoice_table.append(invoice_row)
        if invoice_status in ["Not Processed", "Submitted"]:
            new_invoice_table.append(invoice_row)

    return render_template("ordering_admin.html", invoice_table=invoice_table, tax=tax, is_admin=is_admin,
                           marketeer_invoice_table=marketeer_invoice_table, new_invoice_table=new_invoice_table,
                           tax_corp=tax_corp)
コード例 #3
0
ファイル: main.py プロジェクト: tritanium-industries/TITDev
def issues():
    editor = auth_check("user_admin")
    if request.form.get("action") == "submit":
        g.mongo.db.issues.insert({
            "submitter": session["CharacterName"],
            "issue": request.form.get("issue").strip()
        })
    elif request.form.get("action") == "delete":
        if editor:
            g.mongo.db.issues.remove({"_id": ObjectId(request.form.get("id"))})
        else:
            g.mongo.db.issues.remove({"_id": ObjectId(request.form.get("id")), "submitter": session["CharacterName"]})

    issue_list = []
    for db_issue in g.mongo.db.issues.find():
        timestamp = ObjectId(db_issue["_id"]).generation_time.strftime("%Y-%m-%d %H:%M:%S")
        can_delete = True if editor or session["CharacterName"] == db_issue["submitter"] else False
        issue_list.append([timestamp, db_issue["issue"], db_issue["submitter"], can_delete, db_issue["_id"]])

    return render_template("issues.html", issue_list=issue_list)
コード例 #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)
コード例 #5
0
def form(key):
    # Highest Role
    role = None
    if auth_check("security_officer"):
        role = "security_officer"
    elif auth_check("recruiter"):
        role = "recruiter"

    # Recruitment Info
    try:
        if request.form.get("action") == "submit":
            insert = {}
            for question_key, value in request.form.items():
                if question_key not in ["action", "submitted"]:
                    key_split = question_key.split("_")
                    if key_split[1] == "bool":
                        insert[key_split[0]] = value == "True"
                    else:
                        insert[key_split[0]] = value.strip()
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)}, {
                    "$set": {
                        "questions": insert,
                        "submitted": True,
                        "status": "Submitted"
                    }
                },
                return_document=ReturnDocument.AFTER)
            # Discord Integration
            g.redis.publish(
                'titdev-recruitment',
                "@everyone: {0} has submitted a recruitment form: {1}".format(
                    session["CharacterName"],
                    url_for("recruitment.form", key=key, _external=True)))

            if request.form.get("submitted") == "True":
                flash("Application edited", "success")
            else:
                flash("Application submitted", "success")
        elif request.form.get("action") in [
                "process", "interview", "accept", "reject", "release"
        ] and role == "security_officer":
            status_strings = {
                "process":
                "Processing",
                "interview":
                "Interview Required",
                "accept":
                "Accepted",
                "reject":
                "Rejected",
                "release":
                "Submitted"
                if request.form.get("submitted") == "True" else "Not Submitted"
            }
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)}, {
                    "$set": {
                        "status": status_strings[request.form.get("action")],
                        "reason": request.form.get("reason")
                    }
                },
                return_document=ReturnDocument.AFTER)
            # Discord Integration
            if request.form.get("action") not in ["process", "release"]:
                g.redis.publish(
                    'titdev-recruitment',
                    "@everyone: {0} has marked a form as {2}: {1}".format(
                        session["CharacterName"],
                        url_for("recruitment.form", key=key, _external=True),
                        status_strings[request.form.get("action")]))
        elif request.form.get("action") == "flag" and role:
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)}, {
                    "$set": {
                        "met_recruiter":
                        request.form.get("met_recruiter") == "False"
                    }
                },
                return_document=ReturnDocument.AFTER)
        elif request.form.get(
                "action") == "delete" and role == "security_officer":
            if request.form.get("confirm") == key:
                g.mongo.db.applications.delete_one({"_id": ObjectId(key)})
                flash("Application Deleted", "success")
                return redirect(url_for("recruitment.home"))
            else:
                app_info = g.mongo.db.applications.find_one(
                    {"_id": ObjectId(key)})
                flash("Key doesn't match", "error")
        elif request.form.get(
                "action") == "officer_edit" and role == "security_officer":
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {"$set": {
                    "officer_notes": request.form.get("officer_edit")
                }},
                return_document=ReturnDocument.AFTER)
            flash("Officer Notes Edited", "success")
        elif request.form.get("action") == "recruiter_edit" and role:
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)}, {
                    "$set": {
                        "recruiter_notes": request.form.get("recruiter_edit")
                    }
                },
                return_document=ReturnDocument.AFTER)
            flash("Recruiter Notes Edited", "success")
        elif request.form.get("action") == "recruiter":
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {"$set": {
                    "recruiter": request.form.get("recruiter")
                }},
                return_document=ReturnDocument.AFTER)
            flash("Recruiter Changed", "success")
        else:
            app_info = g.mongo.db.applications.find_one({"_id": ObjectId(key)})
    except bson.errors.InvalidId:
        flash("Invalid Key", "error")
        return redirect(url_for("recruitment.home"))

    if app_info:
        key_owner = app_info.get("owner")
        if not key_owner:
            g.mongo.db.applications.update_one({"_id": ObjectId(key)}, {
                "$set": {
                    "owner": session["CharacterOwnerHash"],
                    "character_name": session["CharacterName"]
                }
            })
            key_owner = session["CharacterOwnerHash"]
        if key_owner == session["CharacterOwnerHash"] or role:
            app_key = key.strip()
            app_status = app_info.get("status", "Not submitted")
            app_reason = app_info.get("reason")
        else:
            flash("Key Already Used", "error")
            return redirect(url_for("recruitment.home"))
    else:
        flash("Key Not Found", "error")
        return redirect(url_for("recruitment.home"))

    # APIs
    error_list = []
    if request.method == "POST":
        if request.form.get("action") == "add":
            error_list = caches.api_keys(
                [(request.form.get("key_id"), request.form.get("vcode"))],
                dashboard_id=key_owner)
        elif request.form.get("action") == "remove":
            g.mongo.db.api_keys.update_one({"_id": key_owner}, {
                "$pull": {
                    "keys": {
                        "key_id": int(request.form.get("key_id"))
                    }
                }
            })
            g.mongo.db.api_keys.update_one({"_id": key_owner}, {
                "$push": {
                    "old_keys": {
                        "key_id": int(request.form.get("key_id")),
                        "vcode": request.form.get("vcode"),
                        "delete_time": int(time.time())
                    }
                }
            })
        elif request.form.get(
                "action") == "remove_old" and role == "security_officer":
            g.mongo.db.api_keys.update_one({"_id": key_owner}, {
                "$pull": {
                    "old_keys": {
                        "key_id": int(request.form.get("key_id"))
                    }
                }
            })

    associated_keys = []
    associated_old_keys = []
    # List of characters
    db_key_doc = g.mongo.db.api_keys.find_one({"_id": key_owner})
    if db_key_doc:
        for key in db_key_doc["keys"]:
            associated_keys.append([
                key["character_id"], key["character_name"], key["key_id"],
                key["vcode"], key["cached_str"],
                key.get("valid", True)
            ])
        if db_key_doc.get("old_keys"):
            for key in db_key_doc["old_keys"]:
                associated_old_keys.append([
                    key["key_id"], key["vcode"],
                    time.strftime("%Y-%m-%d %H:%M:%S",
                                  time.gmtime(key["delete_time"]))
                ])

    # User Information
    db_user_info = g.mongo.db.users.find_one({"_id": key_owner})
    user_info = [
        db_user_info["_id"], db_user_info["character_name"],
        db_user_info["corporation_name"], db_user_info["alliance_name"]
    ]

    # Images
    with open("configs/base.json", "r") as base_config_file:
        base_config = json.load(base_config_file)
    image_list = [
        base_config["image_server"] + "/Character/" +
        str(db_user_info["character_id"]) + "_256.jpg",
        base_config["image_server"] + "/Corporation/" +
        str(db_user_info["corporation_id"]) + "_128.png",
        base_config["image_server"] + "/Alliance/" +
        str(db_user_info["alliance_id"]) + "_128.png"
    ]
    access_mask = base_config["access_mask"]

    # Questions
    question_list = g.mongo.db.app_questions.find()
    question_pre_table = []
    question_table = []
    if question_list:
        for question in question_list:
            if question["bool"]:
                question_type = "bool"
            elif question["long"]:
                question_type = "long"
            else:
                question_type = "text"
            question_pre_table.append([
                question["text"], question_type,
                "{0}_{1}".format(str(question["_id"]), question_type)
            ])
    answers = app_info.get("questions")
    for row in question_pre_table:
        if answers:
            reply = answers.get(row[2].split("_")[0], "")
            if row[1] == "long":
                question_table.append(row + [reply, reply.splitlines()])
            else:
                question_table.append(row + [reply])
        else:
            question_table.append(row + [""])

    # Recruiters
    recruiter_users = g.mongo.db.eve_auth.find_one({"_id": "recruiter"})
    recruiter_list = [
        user["character_name"] for user in g.mongo.db.users.find(
            {"_id": {
                "$in": recruiter_users["users"]
            }})
    ]

    return render_template("recruitment_form.html",
                           error_list=error_list,
                           image_list=image_list,
                           access_mask=access_mask,
                           user_info=user_info,
                           associated_keys=associated_keys,
                           app_key=app_key,
                           app_status=app_status,
                           app_reason=app_reason,
                           role=role,
                           recruiter_notes=[
                               app_info.get("recruiter_notes",
                                            "").splitlines(),
                               app_info.get("recruiter_notes", "")
                           ],
                           officer_notes=[
                               app_info.get("officer_notes", "").splitlines(),
                               app_info.get("officer_notes", "")
                           ],
                           question_table=question_table,
                           met_recruiter=app_info.get("met_recruiter", False),
                           submitted=app_info.get("submitted", False),
                           recruiter_list=recruiter_list,
                           app_recruiter=app_info.get("recruiter"),
                           associated_old_keys=associated_old_keys)
コード例 #6
0
def invoice(invoice_id=""):
    timestamp = None
    current_time = None

    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)
    market_hub_name = base_config["market_hub_name"]

    if not invoice_id:
        cart = g.mongo.db.carts.find_one({"_id": session["CharacterOwnerHash"]})
        if request.args.get("action") == "order":
            cart["user"] = cart.pop("_id")
            cart["external"] = False
            cart["character"] = session["CharacterName"]
            cart["status"] = "Submitted"
            invoice_id = g.mongo.db.invoices.insert(cart)
            g.mongo.db.carts.remove({"_id": cart["user"]})

            # Discord Integration
            g.redis.publish('titdev-marketeer',
                            "@everyone: {0} has created an invoice: {1}".format(
                                session["CharacterName"],
                                url_for("ordering.invoice", invoice_id=invoice_id, _external=True)
                            ))
            return redirect(url_for("ordering.invoice", invoice_id=invoice_id))
    else:
        cart = g.mongo.db.invoices.find_one({"_id": ObjectId(invoice_id)})
        timestamp = ObjectId(invoice_id).generation_time.strftime("%Y-%m-%d %H:%M:%S")
        if not cart:
            return redirect(url_for("account.home"))

    # Invoice Editing
    status = cart.get("status", "Not Processed")
    ordering_admin = auth_check("ordering_admin")
    ordering_marketeer = auth_check("ordering_marketeer")
    editor = True if ordering_admin or ordering_marketeer else False
    can_delete = True if status == "Submitted" and (
        cart.get("user") == session["CharacterOwnerHash"] or ordering_admin) else False
    can_edit = True if ordering_admin or (
        cart.get("marketeer") == session["CharacterName"] or status == "Submitted") else False
    if request.method == "POST":
        # Not Processed, Failed, Processing, Submitted, Hold, Rejected
        if request.form.get("action") == "delete" and can_delete:
            g.mongo.db.invoices.remove({"_id": ObjectId(invoice_id)})
            return redirect(url_for("account.home"))
        elif request.form.get("action") == "reject" and status in ["Not Processed", "Failed",
                                                                   "Processing", "Submitted", "Hold"] and editor:
            current_time = int(time.time())
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {"$set": {"status": "Rejected",
                                                                                "marketeer": session["CharacterName"],
                                                                                "reason": request.form.get("reason"),
                                                                                "finish_time": current_time
                                                                                }})
            # Discord Integration
            g.redis.publish('titdev-marketeer',
                            "{0} has rejected an invoice: {1}".format(
                                session["CharacterName"],
                                url_for("ordering.invoice", invoice_id=invoice_id, _external=True)
                            ))
        elif request.form.get("action") == "process" and status in ["Not Processed", "Failed", "Rejected",
                                                                    "Submitted", "Hold"] and editor:
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {"$set": {"status": "Processing",
                                                                                "marketeer": session["CharacterName"]
                                                                                },
                                                                       "$unset": {
                                                                           "reason": request.form.get("reason")}})
        elif request.form.get("action") == "release" and status in ["Processing", "Failed", "Rejected", "Hold"] and (
                        cart.get("marketeer") == session["CharacterName"] or ordering_admin
        ):
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {"$unset": {"marketeer": session["CharacterName"],
                                                                                  "reason": request.form.get("reason")
                                                                                  },
                                                                       "$set": {"status": "Submitted"}})
        elif request.form.get("action") == "hold" and status in ["Failed", "Processing", "Submitted", "Rejected"]:
            if g.mongo.db.invoices.find_one({"_id": ObjectId(invoice_id)}).get("status") != "Hold":
                g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)},
                                           {
                                               "$set": {"status": "Hold",
                                                        "marketeer": session["CharacterName"],
                                                        "reason": request.form.get("reason")}
                                           })
                # Discord Integration
                g.redis.publish('titdev-marketeer',
                                "@everyone: {0} has put an invoice on hold: {1} for the following reason: {2}".format(
                                    session["CharacterName"],
                                    url_for("ordering.invoice", invoice_id=invoice_id, _external=True),
                                    request.form.get("reason")
                                ))
        elif request.form.get("action") == "fail" and editor:
            current_time = int(time.time())
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {"$set": {"status": "Failed",
                                                                                "marketeer": session["CharacterName"],
                                                                                "reason": request.form.get("reason"),
                                                                                "finish_time": current_time
                                                                                }})
            # Discord Integration
            g.redis.publish('titdev-marketeer',
                            "{0} has failed an invoice: {1} for the following reason: {2}".format(
                                session["CharacterName"],
                                url_for("ordering.invoice", invoice_id=invoice_id, _external=True),
                                request.form.get("reason")
                            ))
        elif request.form.get("action") == "complete" and editor:
            if g.mongo.db.invoices.find_one({"_id": ObjectId(invoice_id)}).get("status") != "Completed":
                current_time = int(time.time())
                g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)},
                                           {
                                               "$set": {"status": "Completed",
                                                        "marketeer": session["CharacterName"],
                                                        "finish_time": current_time},
                                               "$unset": {"reason": request.form.get("reason")}
                                           })
                # Discord Integration
                g.redis.publish('titdev-marketeer',
                                "{0} has completed an invoice: {1}".format(
                                    session["CharacterName"],
                                    url_for("ordering.invoice", invoice_id=invoice_id, _external=True)
                                ))
        elif request.form.get("action") == "shipping" and editor:
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {"$set": {
                "external": not cart.get("external", False)}})
        return redirect(url_for("ordering.invoice", invoice_id=invoice_id))

    # Check shipping
    if not cart.get("external") and status == "Processing":
        shipping_contract = g.mongo.db.contracts.find_one({"title": invoice_id})
        if shipping_contract:
            status = "Shipping - " + shipping_contract["status"]

    # Set buttons
    if status == "Not Processed" or status == "Failed" or status == "Submitted":
        button = "Process"
    else:
        button = "Release"

    invoice_info = [["Name", "Qty", "Vol/Item", "Isk/Item", "Vol Subtotal", "Isk Subtotal"]]
    for item in cart["item_table"].values():
        invoice_info.append([item["name"], item["qty"], "{:,.02f}".format(item["volume"]),
                             "{:,.02f}".format(item["price"]), "{:,.02f}".format(item["volume_total"]),
                             "{:,.02f}".format(item["price_total"])])

    # Round order total
    cart["order_total"] = round(cart["order_total"] + 50000, -5)

    # Formatting
    finish_time = cart.get("finish_time", current_time)
    if finish_time:
        finish_time = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(finish_time))

    return render_template("ordering_invoice.html", invoice_info=invoice_info, market_hub_name=market_hub_name,
                           prices_usable=cart["prices_usable"], total_volume="{:,.02f}".format(cart["volume"]),
                           sell_price="{:,.02f}".format(cart["sell_price"]),
                           order_tax_total="{:,.02f}".format(cart["order_tax_total"]),
                           order_tax="{:,.02f}".format(cart["order_tax"]), jf_end=cart["jf_end"],
                           jf_rate="{:,.02f}".format(cart["jf_rate"]),
                           jf_total="{:,.02f}".format(cart["jf_total"]),
                           order_total="{:,.02f}".format(cart["order_total"]),
                           timestamp=timestamp, can_delete=can_delete, editor=editor,
                           status=status, button=button, marketeer=cart.get("marketeer"), reason=cart.get("reason"),
                           external=cart.get("external", False), can_edit=can_edit, character=cart.get("character"),
                           contract_to=cart.get("contract_to"), notes=cart.get("notes"), invoice_id=invoice_id,
                           finish_time=finish_time)
コード例 #7
0
def home(item=""):
    cart_item_list = {}
    error_string = request.args.get("error_string")

    bulk_op_update = g.mongo.db.carts.initialize_unordered_bulk_op()
    bulk_run_update = False

    # Change qty if post from this page
    if request.method == "POST" and request.form.get("action") == "qty":
        for key, value in request.form.items():
            if key != "action" and not key.startswith("DataTables"):
                if value.strip():
                    if int(float(value)) != 0:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$set": {"items." + key: int(float(value))}})
                    else:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$unset": {"items." + key: int(float(value))}})
                    bulk_run_update = True
    if request.method == "POST" and request.form.get("action") == "clear":
        g.mongo.db.carts.remove({"_id": session["CharacterOwnerHash"]})

    # Add new item to database
    input_string = request.form.get("parse", session.get("fitting"))
    if item or input_string:
        if item:
            try:
                item_adjustment_list = item.split(":")
                for adjustment_item in item_adjustment_list:
                    adjustment_item_info = adjustment_item.split(";")
                    if request.args.get("action") == "edit":
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$set": {"items." + adjustment_item_info[0]: int(adjustment_item_info[1])}})
                    else:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$inc": {"items." + adjustment_item_info[0]: int(adjustment_item_info[1])}})
                    bulk_run_update = True
            except IndexError:
                error_string = "Was not able to add {}".format(item)
        elif input_string:
            session.pop("fitting", None)
            parse_error = None
            parse_result = ""
            try:
                if input_string.startswith("["):
                    eft_parser = conversions.eft_parsing(input_string)
                    parse_result = eft_parser[3]  # DNA String
                    parse_error = eft_parser[4]
                else:
                    parse_array = []
                    item_input, item_qty = conversions.manual_parsing(input_string)[1:3]
                    pre_parse_db = g.mongo.db.items.find({"name": {"$in": item_input}})
                    for pre_parse_item in pre_parse_db:
                        parse_array.append(str(pre_parse_item["_id"]) + ";" +
                                           str(item_qty[pre_parse_item["name"].upper()]))
                    if len(parse_array) != len(item_input):
                        error_string = "There is an item that could not be parsed. Check your input and try again."
                    parse_result = ":".join(parse_array)
            except KeyError:
                error_string = "Could not parse the input. Please ensure it is correctly formatted."
            if parse_error:
                if parse_error == "parsing":
                    error_string = "Could not parse the EFT-Formatted fit. Please ensure it is correctly formatted."
                else:
                    error_string = parse_error
            parse_item_list = parse_result.split(":")
            for parse_item in parse_item_list:
                if parse_item:
                    direct_info = parse_item.split(";")
                    if len(direct_info) == 1:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$inc": {"items." + direct_info[0]: 1}})
                        bulk_run_update = True
                    else:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$inc": {"items." + direct_info[0]: int(direct_info[1])}})
                        bulk_run_update = True

    if bulk_run_update:
        bulk_op_update.execute()

    if item or input_string:
        flash(error_string)
        return redirect(url_for("ordering.home"))
    else:
        error_string = get_flashed_messages()
        error_string = error_string[0] if error_string else None

    # Load cart
    total_volume = 0
    sell_price = 0
    current_cart = g.mongo.db.carts.find_one({"_id": session["CharacterOwnerHash"]})
    fittings_info = []
    fittings_breakdown = {}

    # Redirect to fittings if saving pack
    ordering_admin = auth_check("ordering_admin")
    if ordering_admin and request.form.get("action") == "pack":
        pack_fit = {
            "fit": "",
            "items": {},
            "submitter": session["CharacterOwnerHash"],
            "price": 0,
            "volume": 0,
            "name": request.form.get("pack"),
            "notes": None,
            "dna": None,
            "ship": "Pack",
            "source": None,
            "doctrine": False
        }
        fit_array = []
        dna_array = []
        for table_key, table_info in current_cart.get("item_table", {}).items():
            pack_fit["items"][table_info["name"]] = table_info["qty"]
            fit_array.append(table_info["name"] + " " + str(table_info["qty"]))
            dna_array.append(table_key + ";" + str(table_info["qty"]))
        pack_fit["fit"] = "\n".join(fit_array)
        pack_fit["dna"] = ":".join(dna_array)

        fit_id = g.mongo.db.fittings.insert(pack_fit)
        return redirect(url_for("fittings.fit", fit_id=fit_id))

    # Determine processing cost
    order_db = g.mongo.db.preferences.find_one({"_id": "ordering"})
    if session["UI_Corporation"]:
        order_tax = order_db.get("tax_corp", 0) if order_db else 0
    else:
        order_tax = order_db.get("tax", 0) if order_db else 0

    # Continue loading cart
    if current_cart and current_cart.get("items"):
        cart_item_list_pre = current_cart["items"]

        # Filter fittings from items
        fittings_id_list = []
        for cart_item_id, cart_item_qty in cart_item_list_pre.items():
            try:
                fittings_id_list.append(ObjectId(cart_item_id))
            except bson.errors.InvalidId:
                cart_item_list[cart_item_id] = cart_item_qty

        # Unpack fittings
        for selected_fit in g.mongo.db.fittings.find({"_id": {"$in": fittings_id_list}}):
            fit_item_list = selected_fit["dna"].split(":")
            fittings_info.append([str(selected_fit["_id"]),
                                  "[Fit] " + selected_fit["name"],
                                  current_cart["items"][str(selected_fit["_id"])],
                                  "{:,.02f}".format(selected_fit["volume"]),
                                  "{:,.02f}".format(selected_fit["price"] * (1 + order_tax / 100)),
                                  "{:,.02f}".format(selected_fit["volume"] *
                                                    current_cart["items"][str(selected_fit["_id"])]),
                                  "{:,.02f}".format(selected_fit["price"] *
                                                    current_cart["items"][str(selected_fit["_id"])] *
                                                    (1 + order_tax / 100))
                                  ])
            sell_price += selected_fit["price"] * current_cart["items"][str(selected_fit["_id"])]
            for fit_item in fit_item_list:
                if fit_item:
                    item_info = fit_item.split(";")
                    fittings_breakdown.setdefault(item_info[0], 0)
                    if len(item_info) == 1:
                        fittings_breakdown[item_info[0]] += 1 * current_cart["items"][str(selected_fit["_id"])]
                    else:
                        fittings_breakdown[item_info[0]] += int(item_info[1]) * current_cart["items"][
                            str(selected_fit["_id"])]

    cart_item_list_int = [int(x) for x in cart_item_list.keys()]
    fittings_breakdown_int = [int(x) for x in fittings_breakdown.keys()]
    prices_int = cart_item_list_int + fittings_breakdown_int
    prices, prices_usable = market_hub_prices(prices_int) if prices_int else ({}, True)

    full_cart = {}

    invoice_info = [["Name", "Qty", "Vol/Item", "Isk/Item + Markup",
                     "Vol Subtotal", "Isk Subtotal w/ Markup"]] + fittings_info
    for db_item in g.mongo.db.items.find({"_id": {"$in": cart_item_list_int}}):
        invoice_info.append([
            db_item["_id"],
            db_item["name"],
            cart_item_list[str(db_item["_id"])],
            "{:,.02f}".format(db_item["volume"]),
            "{:,.02f}".format(prices[db_item["_id"]]["sell"] * (1 + order_tax / 100)),
            "{:,.02f}".format(db_item["volume"] * cart_item_list[str(db_item["_id"])]),
            "{:,.02f}".format(prices[db_item["_id"]]["sell"] * cart_item_list[str(db_item["_id"])] *
                              (1 + order_tax / 100))
        ])
        full_cart[str(db_item["_id"])] = {
            "name": db_item["name"],
            "qty": cart_item_list[str(db_item["_id"])],
            "volume": db_item["volume"],
            "price": prices[db_item["_id"]]["sell"],
            "volume_total": db_item["volume"] * cart_item_list[str(db_item["_id"])],
            "price_total": prices[db_item["_id"]]["sell"] * cart_item_list[str(db_item["_id"])]
        }
        total_volume += db_item["volume"] * cart_item_list[str(db_item["_id"])]
        sell_price += prices[db_item["_id"]]["sell"] * cart_item_list[str(db_item["_id"])]

    breakdown_info = [["Name", "Qty", "Vol/Item", "Isk/Item + Markup", "Vol Subtotal", "Isk Subtotal w/ Markup"]]
    for db_item_breakdown in g.mongo.db.items.find({"_id": {"$in": fittings_breakdown_int}}):
        breakdown_info.append([
            db_item_breakdown["_id"],
            db_item_breakdown["name"],
            fittings_breakdown[str(db_item_breakdown["_id"])],
            "{:,.02f}".format(db_item_breakdown["volume"]),
            "{:,.02f}".format(prices[int(db_item_breakdown["_id"])]["sell"] * (1 + order_tax / 100)),
            "{:,.02f}".format(db_item_breakdown["volume"] * fittings_breakdown[str(db_item_breakdown["_id"])]),
            "{:,.02f}".format(prices[int(db_item_breakdown["_id"])]["sell"] *
                              fittings_breakdown[str(db_item_breakdown["_id"])] * (1 + order_tax / 100))
        ])
        total_volume += db_item_breakdown["volume"] * fittings_breakdown[str(db_item_breakdown["_id"])]
        if full_cart.get(str(db_item_breakdown["_id"])):
            full_cart[str(db_item_breakdown["_id"])]["qty"] += fittings_breakdown[str(db_item_breakdown["_id"])]
            full_cart[str(db_item_breakdown["_id"])]["volume_total"] += (db_item_breakdown["volume"] *
                                                                         fittings_breakdown[
                                                                             str(db_item_breakdown["_id"])])
            full_cart[str(db_item_breakdown["_id"])]["price_total"] += (prices[int(db_item_breakdown["_id"])]["sell"] *
                                                                        fittings_breakdown[
                                                                            str(db_item_breakdown["_id"])])
        else:
            full_cart[str(db_item_breakdown["_id"])] = {
                "id": db_item_breakdown["_id"],
                "name": db_item_breakdown["name"],
                "qty": fittings_breakdown[str(db_item_breakdown["_id"])],
                "volume": db_item_breakdown["volume"],
                "price": prices[int(db_item_breakdown["_id"])]["sell"],
                "volume_total": db_item_breakdown["volume"] * fittings_breakdown[str(db_item_breakdown["_id"])],
                "price_total": (prices[int(db_item_breakdown["_id"])]["sell"] *
                                fittings_breakdown[str(db_item_breakdown["_id"])])
            }

    # List routes
    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)

    market_hub_name = base_config["market_hub_name"]
    min_id_limit = base_config["market_hub_station"] * 100000000
    max_id_limit = base_config["market_hub_station"] * 100000000 + 100000000
    market_hub_routes = g.mongo.db.jf_routes.find({"_id": {"$gte": min_id_limit, "$lt": max_id_limit}})

    if request.args.get("end"):
        selected_route = int(request.args.get("end"))
    else:
        selected_route = 0

    valid_stations = []
    route_name = ""
    new_cart = g.mongo.db.carts.find_one({"_id": session["CharacterOwnerHash"]})
    for route in market_hub_routes:
        if request.args.get("end"):
            if route["_id"] == int(request.args.get("end")):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route["_id"] if selected_route == 0 else selected_route
                route_name = route["end"]
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif new_cart:
            if route["_id"] == new_cart.get("route"):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route["_id"] if selected_route == 0 else selected_route
                route_name = route["end"]
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif not request.args.get("end") and route["end"] == base_config["default_ship_to"]:
            valid_stations.append([route["_id"], route["end"], True])
            selected_route = route["_id"] if selected_route == 0 else selected_route
            route_name = route["end"]
        else:
            valid_stations.append([route["_id"], route["end"], False])

    # JF Calculations
    if selected_route == 0:
        selected_route = int(str(base_config["market_hub_station"]) + str(base_config["home_station"]))
    selected_route_info = g.mongo.db.jf_routes.find_one({"_id": selected_route})
    if selected_route_info:
        rate_info = conversions.valid_value(selected_route_info["prices"], time.time())
        if session.get("UI_Corporation"):
            jf_rate = rate_info["corp"]
        else:
            jf_rate = rate_info["general"]

        jf_total = jf_rate * total_volume
        # Min 1 Mil Isk
        if jf_total < 1000000:
            jf_total = 1000000
    else:
        jf_rate = 0
        jf_total = 0

    order_tax_total = sell_price * order_tax / 100
    order_total = jf_total + sell_price + order_tax_total

    # List of characters and notes
    character_list = []
    db_api_list = g.mongo.db.api_keys.find_one({"_id": session["CharacterOwnerHash"]})
    if not request.args.get("action") == "character" and current_cart and request.args.get("action") != "order":
        current_character = current_cart.get("contract_to")
    elif request.args.get("character"):
        current_character = request.args.get("character")
    else:
        current_character = session["CharacterName"]
    if not request.args.get("action") == "notes" and current_cart and request.args.get("action") != "order":
        notes = current_cart.get("notes", "")
    else:
        notes = request.args.get("notes", "")
    if db_api_list:
        for character in db_api_list["keys"]:
            if character["character_name"] == current_character:
                character_list.append((character["character_name"], True))
            else:
                character_list.append((character["character_name"], False))

    # Update DB
    g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]},
                            {"$set": {
                                "item_table": full_cart,
                                "route": selected_route,
                                "volume": total_volume,
                                "jf_rate": jf_rate,
                                "jf_total": jf_total,
                                "sell_price": sell_price,
                                "order_total": order_total,
                                "jf_end": route_name,
                                "order_tax": order_tax,
                                "order_tax_total": order_tax_total,
                                "prices_usable": prices_usable,
                                "notes": notes,
                                "contract_to": current_character
                            }}, upsert=True)

    if request.args.get("action") == "order":
        return redirect(url_for("ordering.invoice"))

    # Round order total
    order_total = round(order_total + 50000, -5)

    # Formatting
    total_volume = "{:,.02f}".format(total_volume)
    sell_price = "{:,.02f}".format(sell_price)
    jf_total = "{:,.02f}".format(jf_total)
    order_total = "{:,.02f}".format(order_total)
    order_tax = "{:,.02f}".format(order_tax)
    order_tax_total = "{:,.02f}".format(order_tax_total)

    return render_template("ordering.html", invoice_info=invoice_info, total_volume=total_volume,
                           sell_price=sell_price, valid_stations=valid_stations, jf_rate=jf_rate,
                           jf_total=jf_total, order_total=order_total, market_hub_name=market_hub_name,
                           prices_usable=prices_usable, error_string=error_string, breakdown_info=breakdown_info,
                           order_tax=order_tax, order_tax_total=order_tax_total, character_list=character_list,
                           notes=notes, ordering_admin=ordering_admin)
コード例 #8
0
def admin():
    # Auth Check
    is_admin = auth_check("ordering_admin")
    if request.form.get("action") == "tax" and request.form.get(
            "tax") and is_admin:
        g.mongo.db.preferences.update(
            {"_id": "ordering"},
            {"$set": {
                "tax": float(request.form.get("tax", 0))
            }},
            upsert=True)
    elif request.form.get("action") == "tax_corp" and request.form.get(
            "tax") and is_admin:
        g.mongo.db.preferences.update(
            {"_id": "ordering"},
            {"$set": {
                "tax_corp": float(request.form.get("tax", 0))
            }},
            upsert=True)
    tax_db = g.mongo.db.preferences.find_one({"_id": "ordering"})
    tax = "{:.02f}".format(tax_db.get("tax", 0)) if tax_db else 0
    tax_corp = "{:.02f}".format(tax_db.get("tax_corp", 0)) if tax_db else 0

    # Invoice List
    one_month_oid = ObjectId.from_datetime(datetime.datetime.today() -
                                           datetime.timedelta(30))
    invoice_table = []
    marketeer_invoice_table = []
    new_invoice_table = []
    for invoice_db in g.mongo.db.invoices.find({
            "$or": [{
                "_id": {
                    "$gt": one_month_oid
                }
            }, {
                "status": {
                    "$not": re.compile("Completed")
                }
            }]
    }):
        invoice_status = invoice_db.get("status", "Not Processed")
        invoice_timestamp = ObjectId(
            invoice_db["_id"]).generation_time.strftime("%Y-%m-%d %H:%M:%S")
        invoice_color = ""
        if invoice_status == "Shipping - Completed":
            invoice_color = "primary"
        elif invoice_status == "Processing" or invoice_status.startswith(
                "Shipping"):
            invoice_color = "warning"
        elif invoice_status in ["Failed", "Rejected", "Hold"]:
            invoice_color = "danger"
        elif invoice_status == "Completed":
            invoice_color = "success"

        finish_time = invoice_db.get("finish_time")
        if finish_time:
            time_to_delivery = finish_time - int(
                ObjectId(invoice_db["_id"]).generation_time.timestamp())
            ttd_days = time_to_delivery // (60 * 60 * 24)
            ttd_hours = time_to_delivery % (60 * 60 * 24) // (60 * 60)
            ttd_minutes = time_to_delivery % (60 * 60 * 24) % (60 * 60) // 60
            ttd_format = "{0}D{1}H{2}M".format(ttd_days, ttd_hours,
                                               ttd_minutes)
        else:
            ttd_format = "N/A"

        invoice_row = [
            invoice_color, invoice_timestamp, ttd_format, invoice_db["_id"],
            invoice_db["jf_end"], "{:,.02f}".format(invoice_db["order_total"]),
            invoice_db.get("character"),
            invoice_db.get("marketeer"), invoice_status
        ]

        invoice_table.append(invoice_row)
        if invoice_db.get("marketeer") == session["CharacterName"]:
            marketeer_invoice_table.append(invoice_row)
        if invoice_status in ["Not Processed", "Submitted"]:
            new_invoice_table.append(invoice_row)

    return render_template("ordering_admin.html",
                           invoice_table=invoice_table,
                           tax=tax,
                           is_admin=is_admin,
                           marketeer_invoice_table=marketeer_invoice_table,
                           new_invoice_table=new_invoice_table,
                           tax_corp=tax_corp)
コード例 #9
0
def invoice(invoice_id=""):
    timestamp = None
    current_time = None

    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)
    market_hub_name = base_config["market_hub_name"]

    if not invoice_id:
        cart = g.mongo.db.carts.find_one(
            {"_id": session["CharacterOwnerHash"]})
        if request.args.get("action") == "order":
            cart["user"] = cart.pop("_id")
            cart["external"] = False
            cart["character"] = session["CharacterName"]
            cart["status"] = "Submitted"
            invoice_id = g.mongo.db.invoices.insert(cart)
            g.mongo.db.carts.remove({"_id": cart["user"]})

            # Discord Integration
            g.redis.publish(
                'titdev-marketeer',
                "@everyone: {0} has created an invoice: {1}".format(
                    session["CharacterName"],
                    url_for("ordering.invoice",
                            invoice_id=invoice_id,
                            _external=True)))
            return redirect(url_for("ordering.invoice", invoice_id=invoice_id))
    else:
        cart = g.mongo.db.invoices.find_one({"_id": ObjectId(invoice_id)})
        timestamp = ObjectId(invoice_id).generation_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        if not cart:
            return redirect(url_for("account.home"))

    # Invoice Editing
    status = cart.get("status", "Not Processed")
    ordering_admin = auth_check("ordering_admin")
    ordering_marketeer = auth_check("ordering_marketeer")
    editor = True if ordering_admin or ordering_marketeer else False
    can_delete = True if status == "Submitted" and (
        cart.get("user") == session["CharacterOwnerHash"]
        or ordering_admin) else False
    can_edit = True if ordering_admin or (
        cart.get("marketeer") == session["CharacterName"]
        or status == "Submitted") else False
    if request.method == "POST":
        # Not Processed, Failed, Processing, Submitted, Hold, Rejected
        if request.form.get("action") == "delete" and can_delete:
            g.mongo.db.invoices.remove({"_id": ObjectId(invoice_id)})
            return redirect(url_for("account.home"))
        elif request.form.get("action") == "reject" and status in [
                "Not Processed", "Failed", "Processing", "Submitted", "Hold"
        ] and editor:
            current_time = int(time.time())
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                "$set": {
                    "status": "Rejected",
                    "marketeer": session["CharacterName"],
                    "reason": request.form.get("reason"),
                    "finish_time": current_time
                }
            })
            # Discord Integration
            g.redis.publish(
                'titdev-marketeer', "{0} has rejected an invoice: {1}".format(
                    session["CharacterName"],
                    url_for("ordering.invoice",
                            invoice_id=invoice_id,
                            _external=True)))
        elif request.form.get("action") == "process" and status in [
                "Not Processed", "Failed", "Rejected", "Submitted", "Hold"
        ] and editor:
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                "$set": {
                    "status": "Processing",
                    "marketeer": session["CharacterName"]
                },
                "$unset": {
                    "reason": request.form.get("reason")
                }
            })
        elif request.form.get("action") == "release" and status in [
                "Processing", "Failed", "Rejected", "Hold"
        ] and (cart.get("marketeer") == session["CharacterName"]
               or ordering_admin):
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                "$unset": {
                    "marketeer": session["CharacterName"],
                    "reason": request.form.get("reason")
                },
                "$set": {
                    "status": "Submitted"
                }
            })
        elif request.form.get("action") == "hold" and status in [
                "Failed", "Processing", "Submitted", "Rejected"
        ]:
            if g.mongo.db.invoices.find_one({
                    "_id": ObjectId(invoice_id)
            }).get("status") != "Hold":
                g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                    "$set": {
                        "status": "Hold",
                        "marketeer": session["CharacterName"],
                        "reason": request.form.get("reason")
                    }
                })
                # Discord Integration
                g.redis.publish(
                    'titdev-marketeer',
                    "@everyone: {0} has put an invoice on hold: {1} for the following reason: {2}"
                    .format(
                        session["CharacterName"],
                        url_for("ordering.invoice",
                                invoice_id=invoice_id,
                                _external=True), request.form.get("reason")))
        elif request.form.get("action") == "fail" and editor:
            current_time = int(time.time())
            g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                "$set": {
                    "status": "Failed",
                    "marketeer": session["CharacterName"],
                    "reason": request.form.get("reason"),
                    "finish_time": current_time
                }
            })
            # Discord Integration
            g.redis.publish(
                'titdev-marketeer',
                "{0} has failed an invoice: {1} for the following reason: {2}".
                format(
                    session["CharacterName"],
                    url_for("ordering.invoice",
                            invoice_id=invoice_id,
                            _external=True), request.form.get("reason")))
        elif request.form.get("action") == "complete" and editor:
            if g.mongo.db.invoices.find_one({
                    "_id": ObjectId(invoice_id)
            }).get("status") != "Completed":
                current_time = int(time.time())
                g.mongo.db.invoices.update({"_id": ObjectId(invoice_id)}, {
                    "$set": {
                        "status": "Completed",
                        "marketeer": session["CharacterName"],
                        "finish_time": current_time
                    },
                    "$unset": {
                        "reason": request.form.get("reason")
                    }
                })
                # Discord Integration
                g.redis.publish(
                    'titdev-marketeer',
                    "{0} has completed an invoice: {1}".format(
                        session["CharacterName"],
                        url_for("ordering.invoice",
                                invoice_id=invoice_id,
                                _external=True)))
        elif request.form.get("action") == "shipping" and editor:
            g.mongo.db.invoices.update(
                {"_id": ObjectId(invoice_id)},
                {"$set": {
                    "external": not cart.get("external", False)
                }})
        return redirect(url_for("ordering.invoice", invoice_id=invoice_id))

    # Check shipping
    if not cart.get("external") and status == "Processing":
        shipping_contract = g.mongo.db.contracts.find_one(
            {"title": invoice_id})
        if shipping_contract:
            status = "Shipping - " + shipping_contract["status"]

    # Set buttons
    if status == "Not Processed" or status == "Failed" or status == "Submitted":
        button = "Process"
    else:
        button = "Release"

    invoice_info = [[
        "Name", "Qty", "Vol/Item", "Isk/Item", "Vol Subtotal", "Isk Subtotal"
    ]]
    for item in cart["item_table"].values():
        invoice_info.append([
            item["name"], item["qty"], "{:,.02f}".format(item["volume"]),
            "{:,.02f}".format(item["price"]),
            "{:,.02f}".format(item["volume_total"]),
            "{:,.02f}".format(item["price_total"])
        ])

    # Round order total
    cart["order_total"] = round(cart["order_total"] + 50000, -5)

    # Formatting
    finish_time = cart.get("finish_time", current_time)
    if finish_time:
        finish_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                    time.gmtime(finish_time))

    return render_template("ordering_invoice.html",
                           invoice_info=invoice_info,
                           market_hub_name=market_hub_name,
                           prices_usable=cart["prices_usable"],
                           total_volume="{:,.02f}".format(cart["volume"]),
                           sell_price="{:,.02f}".format(cart["sell_price"]),
                           order_tax_total="{:,.02f}".format(
                               cart["order_tax_total"]),
                           order_tax="{:,.02f}".format(cart["order_tax"]),
                           jf_end=cart["jf_end"],
                           jf_rate="{:,.02f}".format(cart["jf_rate"]),
                           jf_total="{:,.02f}".format(cart["jf_total"]),
                           order_total="{:,.02f}".format(cart["order_total"]),
                           timestamp=timestamp,
                           can_delete=can_delete,
                           editor=editor,
                           status=status,
                           button=button,
                           marketeer=cart.get("marketeer"),
                           reason=cart.get("reason"),
                           external=cart.get("external", False),
                           can_edit=can_edit,
                           character=cart.get("character"),
                           contract_to=cart.get("contract_to"),
                           notes=cart.get("notes"),
                           invoice_id=invoice_id,
                           finish_time=finish_time)
コード例 #10
0
def home(item=""):
    cart_item_list = {}
    error_string = request.args.get("error_string")

    bulk_op_update = g.mongo.db.carts.initialize_unordered_bulk_op()
    bulk_run_update = False

    # Change qty if post from this page
    if request.method == "POST" and request.form.get("action") == "qty":
        for key, value in request.form.items():
            if key != "action" and not key.startswith("DataTables"):
                if value.strip():
                    if int(float(value)) != 0:
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update(
                            {"$set": {
                                "items." + key: int(float(value))
                            }})
                    else:
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update(
                            {"$unset": {
                                "items." + key: int(float(value))
                            }})
                    bulk_run_update = True
    if request.method == "POST" and request.form.get("action") == "clear":
        g.mongo.db.carts.remove({"_id": session["CharacterOwnerHash"]})

    # Add new item to database
    input_string = request.form.get("parse", session.get("fitting"))
    if item or input_string:
        if item:
            try:
                item_adjustment_list = item.split(":")
                for adjustment_item in item_adjustment_list:
                    adjustment_item_info = adjustment_item.split(";")
                    if request.args.get("action") == "edit":
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update({
                            "$set": {
                                "items." + adjustment_item_info[0]:
                                int(adjustment_item_info[1])
                            }
                        })
                    else:
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update({
                            "$inc": {
                                "items." + adjustment_item_info[0]:
                                int(adjustment_item_info[1])
                            }
                        })
                    bulk_run_update = True
            except IndexError:
                error_string = "Was not able to add {}".format(item)
        elif input_string:
            session.pop("fitting", None)
            parse_error = None
            parse_result = ""
            try:
                if input_string.startswith("["):
                    eft_parser = conversions.eft_parsing(input_string)
                    parse_result = eft_parser[3]  # DNA String
                    parse_error = eft_parser[4]
                else:
                    parse_array = []
                    item_input, item_qty = conversions.manual_parsing(
                        input_string)[1:3]
                    pre_parse_db = g.mongo.db.items.find(
                        {"name": {
                            "$in": item_input
                        }})
                    for pre_parse_item in pre_parse_db:
                        parse_array.append(
                            str(pre_parse_item["_id"]) + ";" +
                            str(item_qty[pre_parse_item["name"].upper()]))
                    if len(parse_array) != len(item_input):
                        error_string = "There is an item that could not be parsed. Check your input and try again."
                    parse_result = ":".join(parse_array)
            except KeyError:
                error_string = "Could not parse the input. Please ensure it is correctly formatted."
            if parse_error:
                if parse_error == "parsing":
                    error_string = "Could not parse the EFT-Formatted fit. Please ensure it is correctly formatted."
                else:
                    error_string = parse_error
            parse_item_list = parse_result.split(":")
            for parse_item in parse_item_list:
                if parse_item:
                    direct_info = parse_item.split(";")
                    if len(direct_info) == 1:
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update(
                            {"$inc": {
                                "items." + direct_info[0]: 1
                            }})
                        bulk_run_update = True
                    else:
                        bulk_op_update.find({
                            "_id":
                            session["CharacterOwnerHash"]
                        }).upsert().update({
                            "$inc": {
                                "items." + direct_info[0]: int(direct_info[1])
                            }
                        })
                        bulk_run_update = True

    if bulk_run_update:
        bulk_op_update.execute()

    if item or input_string:
        flash(error_string)
        return redirect(url_for("ordering.home"))
    else:
        error_string = get_flashed_messages()
        error_string = error_string[0] if error_string else None

    # Load cart
    total_volume = 0
    sell_price = 0
    current_cart = g.mongo.db.carts.find_one(
        {"_id": session["CharacterOwnerHash"]})
    fittings_info = []
    fittings_breakdown = {}

    # Redirect to fittings if saving pack
    ordering_admin = auth_check("ordering_admin")
    if ordering_admin and request.form.get("action") == "pack":
        pack_fit = {
            "fit": "",
            "items": {},
            "submitter": session["CharacterOwnerHash"],
            "price": 0,
            "volume": 0,
            "name": request.form.get("pack"),
            "notes": None,
            "dna": None,
            "ship": "Pack",
            "source": None,
            "doctrine": False
        }
        fit_array = []
        dna_array = []
        for table_key, table_info in current_cart.get("item_table",
                                                      {}).items():
            pack_fit["items"][table_info["name"]] = table_info["qty"]
            fit_array.append(table_info["name"] + " " + str(table_info["qty"]))
            dna_array.append(table_key + ";" + str(table_info["qty"]))
        pack_fit["fit"] = "\n".join(fit_array)
        pack_fit["dna"] = ":".join(dna_array)

        fit_id = g.mongo.db.fittings.insert(pack_fit)
        return redirect(url_for("fittings.fit", fit_id=fit_id))

    # Determine processing cost
    order_db = g.mongo.db.preferences.find_one({"_id": "ordering"})
    if session["UI_Corporation"]:
        order_tax = order_db.get("tax_corp", 0) if order_db else 0
    else:
        order_tax = order_db.get("tax", 0) if order_db else 0

    # Continue loading cart
    if current_cart and current_cart.get("items"):
        cart_item_list_pre = current_cart["items"]

        # Filter fittings from items
        fittings_id_list = []
        for cart_item_id, cart_item_qty in cart_item_list_pre.items():
            try:
                fittings_id_list.append(ObjectId(cart_item_id))
            except bson.errors.InvalidId:
                cart_item_list[cart_item_id] = cart_item_qty

        # Unpack fittings
        for selected_fit in g.mongo.db.fittings.find(
            {"_id": {
                "$in": fittings_id_list
            }}):
            fit_item_list = selected_fit["dna"].split(":")
            fittings_info.append([
                str(selected_fit["_id"]), "[Fit] " + selected_fit["name"],
                current_cart["items"][str(selected_fit["_id"])],
                "{:,.02f}".format(selected_fit["volume"]), "{:,.02f}".format(
                    selected_fit["price"] * (1 + order_tax / 100)),
                "{:,.02f}".format(
                    selected_fit["volume"] *
                    current_cart["items"][str(selected_fit["_id"])]),
                "{:,.02f}".format(
                    selected_fit["price"] *
                    current_cart["items"][str(selected_fit["_id"])] *
                    (1 + order_tax / 100))
            ])
            sell_price += selected_fit["price"] * current_cart["items"][str(
                selected_fit["_id"])]
            for fit_item in fit_item_list:
                if fit_item:
                    item_info = fit_item.split(";")
                    fittings_breakdown.setdefault(item_info[0], 0)
                    if len(item_info) == 1:
                        fittings_breakdown[
                            item_info[0]] += 1 * current_cart["items"][str(
                                selected_fit["_id"])]
                    else:
                        fittings_breakdown[item_info[0]] += int(
                            item_info[1]) * current_cart["items"][str(
                                selected_fit["_id"])]

    cart_item_list_int = [int(x) for x in cart_item_list.keys()]
    fittings_breakdown_int = [int(x) for x in fittings_breakdown.keys()]
    prices_int = cart_item_list_int + fittings_breakdown_int
    prices, prices_usable = market_hub_prices(prices_int) if prices_int else (
        {}, True)

    full_cart = {}

    invoice_info = [[
        "Name", "Qty", "Vol/Item", "Isk/Item + Markup", "Vol Subtotal",
        "Isk Subtotal w/ Markup"
    ]] + fittings_info
    for db_item in g.mongo.db.items.find({"_id": {"$in": cart_item_list_int}}):
        invoice_info.append([
            db_item["_id"], db_item["name"],
            cart_item_list[str(db_item["_id"])],
            "{:,.02f}".format(db_item["volume"]), "{:,.02f}".format(
                prices[db_item["_id"]]["sell"] * (1 + order_tax / 100)),
            "{:,.02f}".format(db_item["volume"] *
                              cart_item_list[str(db_item["_id"])]),
            "{:,.02f}".format(prices[db_item["_id"]]["sell"] *
                              cart_item_list[str(db_item["_id"])] *
                              (1 + order_tax / 100))
        ])
        full_cart[str(db_item["_id"])] = {
            "name":
            db_item["name"],
            "qty":
            cart_item_list[str(db_item["_id"])],
            "volume":
            db_item["volume"],
            "price":
            prices[db_item["_id"]]["sell"],
            "volume_total":
            db_item["volume"] * cart_item_list[str(db_item["_id"])],
            "price_total":
            prices[db_item["_id"]]["sell"] *
            cart_item_list[str(db_item["_id"])]
        }
        total_volume += db_item["volume"] * cart_item_list[str(db_item["_id"])]
        sell_price += prices[db_item["_id"]]["sell"] * cart_item_list[str(
            db_item["_id"])]

    breakdown_info = [[
        "Name", "Qty", "Vol/Item", "Isk/Item + Markup", "Vol Subtotal",
        "Isk Subtotal w/ Markup"
    ]]
    for db_item_breakdown in g.mongo.db.items.find(
        {"_id": {
            "$in": fittings_breakdown_int
        }}):
        breakdown_info.append([
            db_item_breakdown["_id"], db_item_breakdown["name"],
            fittings_breakdown[str(db_item_breakdown["_id"])],
            "{:,.02f}".format(db_item_breakdown["volume"]),
            "{:,.02f}".format(prices[int(db_item_breakdown["_id"])]["sell"] *
                              (1 + order_tax / 100)),
            "{:,.02f}".format(
                db_item_breakdown["volume"] *
                fittings_breakdown[str(db_item_breakdown["_id"])]),
            "{:,.02f}".format(
                prices[int(db_item_breakdown["_id"])]["sell"] *
                fittings_breakdown[str(db_item_breakdown["_id"])] *
                (1 + order_tax / 100))
        ])
        total_volume += db_item_breakdown["volume"] * fittings_breakdown[str(
            db_item_breakdown["_id"])]
        if full_cart.get(str(db_item_breakdown["_id"])):
            full_cart[str(
                db_item_breakdown["_id"])]["qty"] += fittings_breakdown[str(
                    db_item_breakdown["_id"])]
            full_cart[str(db_item_breakdown["_id"])]["volume_total"] += (
                db_item_breakdown["volume"] *
                fittings_breakdown[str(db_item_breakdown["_id"])])
            full_cart[str(db_item_breakdown["_id"])]["price_total"] += (
                prices[int(db_item_breakdown["_id"])]["sell"] *
                fittings_breakdown[str(db_item_breakdown["_id"])])
        else:
            full_cart[str(db_item_breakdown["_id"])] = {
                "id":
                db_item_breakdown["_id"],
                "name":
                db_item_breakdown["name"],
                "qty":
                fittings_breakdown[str(db_item_breakdown["_id"])],
                "volume":
                db_item_breakdown["volume"],
                "price":
                prices[int(db_item_breakdown["_id"])]["sell"],
                "volume_total":
                db_item_breakdown["volume"] *
                fittings_breakdown[str(db_item_breakdown["_id"])],
                "price_total":
                (prices[int(db_item_breakdown["_id"])]["sell"] *
                 fittings_breakdown[str(db_item_breakdown["_id"])])
            }

    # List routes
    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)

    market_hub_name = base_config["market_hub_name"]
    min_id_limit = base_config["market_hub_station"] * 100000000
    max_id_limit = base_config["market_hub_station"] * 100000000 + 100000000
    market_hub_routes = g.mongo.db.jf_routes.find(
        {"_id": {
            "$gte": min_id_limit,
            "$lt": max_id_limit
        }})

    if request.args.get("end"):
        selected_route = int(request.args.get("end"))
    else:
        selected_route = 0

    valid_stations = []
    route_name = ""
    new_cart = g.mongo.db.carts.find_one(
        {"_id": session["CharacterOwnerHash"]})
    for route in market_hub_routes:
        if request.args.get("end"):
            if route["_id"] == int(request.args.get("end")):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route[
                    "_id"] if selected_route == 0 else selected_route
                route_name = route["end"]
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif new_cart:
            if route["_id"] == new_cart.get("route"):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route[
                    "_id"] if selected_route == 0 else selected_route
                route_name = route["end"]
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif not request.args.get(
                "end") and route["end"] == base_config["default_ship_to"]:
            valid_stations.append([route["_id"], route["end"], True])
            selected_route = route[
                "_id"] if selected_route == 0 else selected_route
            route_name = route["end"]
        else:
            valid_stations.append([route["_id"], route["end"], False])

    # JF Calculations
    if selected_route == 0:
        selected_route = int(
            str(base_config["market_hub_station"]) +
            str(base_config["home_station"]))
    selected_route_info = g.mongo.db.jf_routes.find_one(
        {"_id": selected_route})
    if selected_route_info:
        rate_info = conversions.valid_value(selected_route_info["prices"],
                                            time.time())
        if session.get("UI_Corporation"):
            jf_rate = rate_info["corp"]
        else:
            jf_rate = rate_info["general"]

        jf_total = jf_rate * total_volume
        # Min 1 Mil Isk
        if jf_total < 1000000:
            jf_total = 1000000
    else:
        jf_rate = 0
        jf_total = 0

    order_tax_total = sell_price * order_tax / 100
    order_total = jf_total + sell_price + order_tax_total

    # List of characters and notes
    character_list = []
    db_api_list = g.mongo.db.api_keys.find_one(
        {"_id": session["CharacterOwnerHash"]})
    if not request.args.get(
            "action") == "character" and current_cart and request.args.get(
                "action") != "order":
        current_character = current_cart.get("contract_to")
    elif request.args.get("character"):
        current_character = request.args.get("character")
    else:
        current_character = session["CharacterName"]
    if not request.args.get(
            "action") == "notes" and current_cart and request.args.get(
                "action") != "order":
        notes = current_cart.get("notes", "")
    else:
        notes = request.args.get("notes", "")
    if db_api_list:
        for character in db_api_list["keys"]:
            if character["character_name"] == current_character:
                character_list.append((character["character_name"], True))
            else:
                character_list.append((character["character_name"], False))

    # Update DB
    g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]}, {
        "$set": {
            "item_table": full_cart,
            "route": selected_route,
            "volume": total_volume,
            "jf_rate": jf_rate,
            "jf_total": jf_total,
            "sell_price": sell_price,
            "order_total": order_total,
            "jf_end": route_name,
            "order_tax": order_tax,
            "order_tax_total": order_tax_total,
            "prices_usable": prices_usable,
            "notes": notes,
            "contract_to": current_character
        }
    },
                            upsert=True)

    if request.args.get("action") == "order":
        return redirect(url_for("ordering.invoice"))

    # Round order total
    order_total = round(order_total + 50000, -5)

    # Formatting
    total_volume = "{:,.02f}".format(total_volume)
    sell_price = "{:,.02f}".format(sell_price)
    jf_total = "{:,.02f}".format(jf_total)
    order_total = "{:,.02f}".format(order_total)
    order_tax = "{:,.02f}".format(order_tax)
    order_tax_total = "{:,.02f}".format(order_tax_total)

    return render_template("ordering.html",
                           invoice_info=invoice_info,
                           total_volume=total_volume,
                           sell_price=sell_price,
                           valid_stations=valid_stations,
                           jf_rate=jf_rate,
                           jf_total=jf_total,
                           order_total=order_total,
                           market_hub_name=market_hub_name,
                           prices_usable=prices_usable,
                           error_string=error_string,
                           breakdown_info=breakdown_info,
                           order_tax=order_tax,
                           order_tax_total=order_tax_total,
                           character_list=character_list,
                           notes=notes,
                           ordering_admin=ordering_admin)
コード例 #11
0
def home():
    dna_string = None
    error_string = None

    # Check if fittings admin
    admin = auth_check("fittings_admin")

    if request.args.get("error"):
        if request.args.get("error") == "parsing":
            error_string = "Could not parse the EFT-Formatted fit. Please ensure it is correctly formatted."
        elif request.args.get("error") == "not_found":
            error_string = "Could not find the fit. It may have been deleted."
        elif request.args.get("error"):
            error_string = request.args.get("error")

    if request.method == "POST" and request.form.get("action") == "fit_submit":
        if not request.form.get("fit_string"):
            return redirect(url_for("fittings.home"))

        fit_name, ship, item_counter, dna_string, parse_error = conversions.eft_parsing(request.form.get("fit_string"))

        if parse_error:  # Error in parsing
            return redirect(url_for("fittings.home", error=parse_error))

        fit_id = g.mongo.db.fittings.insert({
            "fit": request.form.get("fit_string"),
            "items": item_counter,
            "submitter": session["CharacterOwnerHash"],
            "price": 0,
            "volume": 0,
            "name": fit_name,
            "notes": request.form.get("notes"),
            "dna": dna_string,
            "ship": ship,
            "source": request.form.get("source"),
            "doctrine": True if request.form.get("doctrine") and admin else False
        })

        return redirect(url_for("fittings.fit", fit_id=fit_id))
    elif request.method == "POST" and request.form.get("action") == "direct_to_cart":
        session["fitting"] = request.form.get("fit_string")
        return redirect(url_for("ordering.home"))

    # Fit Listings

    all_fittings = g.mongo.db.fittings.find()
    user_corporation = g.mongo.db.users.find_one({"_id": session["CharacterOwnerHash"]})["corporation_name"]

    header = ["Name", "Ship", "Submitter", "Price", "Volume", "Notes", "Action"]
    personal_fits = [header]
    doctrine_fits = [header]
    corporation_fits = [header]
    alliance_fits = [header]
    all_fits = [header]
    packs = [header]
    for db_fit in all_fittings:
        submitter = g.mongo.db.users.find_one({"_id": db_fit["submitter"]})
        # Delete Check
        can_delete = False
        if submitter["_id"] == session["CharacterOwnerHash"] or auth_check("fittings_admin"):
            can_delete = True

        fit_info = [db_fit["name"], db_fit["ship"], submitter["character_name"],
                    "{:,.02f}".format(db_fit["price"]), "{:,.02f}".format(db_fit["volume"]), db_fit["notes"],
                    can_delete, str(db_fit["_id"]), db_fit["dna"]]
        if db_fit.get("doctrine"):
            doctrine_fits.append(fit_info)
        elif db_fit["submitter"] == session["CharacterOwnerHash"]:
            personal_fits.append(fit_info)
        elif submitter["corporation_name"] == user_corporation:
            corporation_fits.append(fit_info)
        else:
            alliance_fits.append(fit_info)

        if db_fit["ship"] == "Pack":
            packs.append(fit_info)
        else:
            all_fits.append(fit_info)

    return render_template("fittings.html", doctrine_fits=doctrine_fits, corporation_fits=corporation_fits,
                           alliance_fits=alliance_fits, dna_string=dna_string, personal_fits=personal_fits,
                           all_fits=all_fits, error_string=error_string, admin=admin, packs=packs)
コード例 #12
0
def fit(fit_id=None):
    if not fit_id:
        abort(404)

    # Redirect if fit is purchased
    if request.method == "GET" and request.args.get("action") == "purchase":
        return redirect(url_for("ordering.home", item=fit_id + ";" + request.args.get("multiply", 1)))

    selected_fit = None
    try:
        selected_fit = g.mongo.db.fittings.find_one({"_id": ObjectId(fit_id)})
    except bson.errors.InvalidId:
        abort(404)

    if not selected_fit:
        return redirect(url_for("fittings.home", error="not_found"))
    elif request.method == "GET" and request.args.get("action") == "direct":
        # Use direct to cart
        session["fitting"] = selected_fit["fit"]
        return redirect(url_for("ordering.home"))

    # Check if fittings admin
    admin = auth_check("fittings_admin")

    # Delete Permissions
    if selected_fit["submitter"] == session["CharacterOwnerHash"] or admin:
        can_delete = True
    else:
        can_delete = False

    # Modifications
    notes_change = request.args.get("notes") if request.args.get("notes") else selected_fit["notes"]
    source_change = request.args.get("source") if request.args.get("source") else selected_fit.get("source")
    doctrine_change = bool(request.args.get("doctrine")) if request.args.get("doctrine") else False
    if request.args.get("action") == "delete" and can_delete:
        g.mongo.db.fittings.remove({"_id": ObjectId(fit_id)})
        return redirect(url_for("fittings.home"))
    elif request.args.get("action") == "edit" and can_delete:
        g.mongo.db.fittings.update({"_id": ObjectId(fit_id)},
                                   {"$set": {
                                       "notes": notes_change,
                                       "source": source_change,
                                       "doctrine": doctrine_change
                                   }})
        return redirect(url_for("fittings.fit", fit_id=fit_id))

    fit_by_line = selected_fit["fit"].splitlines()

    with open("resources/nameConversions.json") as name_conversions_file:
        name_conversions = json.load(name_conversions_file)
    actual_fit_items = []
    pre_name_conversion = {}
    for pre_filter_item in selected_fit["items"].keys():
        pre_filter_item = pre_filter_item.replace("Thermic", "Thermal")  # EVE parallax patch
        actual_fit_items.append(name_conversions.get(pre_filter_item, pre_filter_item))
        if name_conversions.get(pre_filter_item):
            pre_name_conversion[name_conversions.get(pre_filter_item)] = pre_filter_item

    # ID Matching
    item_list = list(g.mongo.db.items.find({"name": {"$in": actual_fit_items}}))
    item_prices, prices_usable = eve_central.market_hub_prices([x["_id"] for x in item_list])

    item_table = [["Name", "Qty", "Isk/Item", "Vol/Item", "Total Isk", "Total Volume"]]
    total_fit_isk = 0
    total_volume = 0
    multiply = 1 if not request.args.get("multiply") else int(request.args.get("multiply"))

    for fit_item in item_list:
        try:
            # Check if thermal is correct in fit
            qty = selected_fit["items"][fit_item["name"]] * multiply
        except KeyError:
            try:
                # Check if it's an old fit with thermic
                qty = selected_fit["items"][fit_item["name"].replace("Thermal", "Thermic")] * multiply
            except KeyError:
                # Check if the item name has changed
                qty = selected_fit["items"][pre_name_conversion[fit_item["name"]]] * multiply
        isk_per_item = item_prices[fit_item["_id"]]["sell"]
        vol_per_item = fit_item["volume"]
        item_isk_total = qty * isk_per_item
        item_vol_total = qty * vol_per_item
        total_fit_isk += item_isk_total
        total_volume += item_vol_total
        # Formatting
        isk_per_item = "{:,.02f}".format(isk_per_item)
        vol_per_item = "{:,.02f}".format(vol_per_item)
        item_isk_total = "{:,.02f}".format(item_isk_total)
        item_vol_total = "{:,.02f}".format(item_vol_total)
        item_table.append([fit_item["name"], qty, isk_per_item, vol_per_item, item_isk_total, item_vol_total])

    if multiply == 1 and prices_usable:
        g.mongo.db.fittings.update({"_id": ObjectId(fit_id)}, {"$set": {
            "price": total_fit_isk, "volume": total_volume}})

    # List routes
    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)

    market_hub_name = base_config["market_hub_name"]
    min_id_limit = base_config["market_hub_station"] * 100000000
    max_id_limit = base_config["market_hub_station"] * 100000000 + 100000000
    market_hub_routes = g.mongo.db.jf_routes.find({"_id": {"$gte": min_id_limit, "$lt": max_id_limit}})

    if request.args.get("end"):
        selected_route = int(request.args.get("end"))
    else:
        selected_route = 0

    valid_stations = []
    current_route = g.mongo.db.carts.find_one({"_id": session["CharacterOwnerHash"]})
    for route in market_hub_routes:
        if request.args.get("end") and route["_id"] == int(request.args.get("end")):
            valid_stations.append([route["_id"], route["end"], True])
            g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]},
                                    {"$set": {"route": route["_id"]}}, upsert=True)
        elif current_route:
            if route["_id"] == current_route.get("route"):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route["_id"] if selected_route == 0 else selected_route
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif not request.args.get("end") and route["end"] == base_config["default_ship_to"]:
            valid_stations.append([route["_id"], route["end"], True])
            g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]},
                                    {"$set": {"route": route["_id"]}}, upsert=True)
            selected_route = route["_id"] if selected_route == 0 else selected_route
        else:
            valid_stations.append([route["_id"], route["end"], False])

    # JF Calculations
    selected_route_info = g.mongo.db.jf_routes.find_one({"_id": selected_route})
    if selected_route_info:
        rate_info = conversions.valid_value(selected_route_info["prices"], time.time())
        if session.get("UI_Corporation"):
            jf_rate = rate_info["corp"]
        else:
            jf_rate = rate_info["general"]

        jf_total = jf_rate * total_volume
    else:
        jf_rate = 0
        jf_total = 0
    order_total = jf_total + total_fit_isk

    # Submission date
    date_added = ObjectId(fit_id).generation_time.strftime("%Y-%m-%d %H:%M:%S")

    # Formatting
    total_fit_isk = "{:,.02f}".format(total_fit_isk)
    total_volume = "{:,.02f}".format(total_volume)
    jf_total = "{:,.02f}".format(jf_total)
    jf_rate = "{:,.02f}".format(jf_rate)
    order_total = "{:,.02f}".format(order_total)

    return render_template("fittings_fit.html", item_table=item_table, fit_string=fit_by_line,
                           total_fit_isk=total_fit_isk, total_volume=total_volume, valid_stations=valid_stations,
                           market_hub_name=market_hub_name, jf_rate=jf_rate, jf_total=jf_total, order_total=order_total,
                           dna_string=selected_fit["dna"], fit_name=selected_fit["name"], multiply=multiply,
                           can_delete=can_delete, notes=selected_fit["notes"], source=selected_fit.get("source"),
                           admin=admin, doctrine=selected_fit["doctrine"], prices_usable=prices_usable,
                           category=selected_fit.get("category"), date_added=date_added)
コード例 #13
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)
コード例 #14
0
def home():
    dna_string = None
    error_string = None

    # Check if fittings admin
    admin = auth_check("fittings_admin")

    if request.args.get("error"):
        if request.args.get("error") == "parsing":
            error_string = "Could not parse the EFT-Formatted fit. Please ensure it is correctly formatted."
        elif request.args.get("error") == "not_found":
            error_string = "Could not find the fit. It may have been deleted."
        elif request.args.get("error"):
            error_string = request.args.get("error")

    if request.method == "POST" and request.form.get("action") == "fit_submit":
        if not request.form.get("fit_string"):
            return redirect(url_for("fittings.home"))

        fit_name, ship, item_counter, dna_string, parse_error = conversions.eft_parsing(
            request.form.get("fit_string"))

        if parse_error:  # Error in parsing
            return redirect(url_for("fittings.home", error=parse_error))

        fit_id = g.mongo.db.fittings.insert({
            "fit":
            request.form.get("fit_string"),
            "items":
            item_counter,
            "submitter":
            session["CharacterOwnerHash"],
            "price":
            0,
            "volume":
            0,
            "name":
            fit_name,
            "notes":
            request.form.get("notes"),
            "dna":
            dna_string,
            "ship":
            ship,
            "source":
            request.form.get("source"),
            "doctrine":
            True if request.form.get("doctrine") and admin else False
        })

        return redirect(url_for("fittings.fit", fit_id=fit_id))
    elif request.method == "POST" and request.form.get(
            "action") == "direct_to_cart":
        session["fitting"] = request.form.get("fit_string")
        return redirect(url_for("ordering.home"))

    # Fit Listings

    all_fittings = g.mongo.db.fittings.find()
    user_corporation = g.mongo.db.users.find_one(
        {"_id": session["CharacterOwnerHash"]})["corporation_name"]

    header = [
        "Name", "Ship", "Submitter", "Price", "Volume", "Notes", "Action"
    ]
    personal_fits = [header]
    doctrine_fits = [header]
    corporation_fits = [header]
    alliance_fits = [header]
    all_fits = [header]
    packs = [header]
    for db_fit in all_fittings:
        submitter = g.mongo.db.users.find_one({"_id": db_fit["submitter"]})
        # Delete Check
        can_delete = False
        if submitter["_id"] == session["CharacterOwnerHash"] or auth_check(
                "fittings_admin"):
            can_delete = True

        fit_info = [
            db_fit["name"], db_fit["ship"], submitter["character_name"],
            "{:,.02f}".format(db_fit["price"]),
            "{:,.02f}".format(db_fit["volume"]), db_fit["notes"], can_delete,
            str(db_fit["_id"]), db_fit["dna"]
        ]
        if db_fit.get("doctrine"):
            doctrine_fits.append(fit_info)
        elif db_fit["submitter"] == session["CharacterOwnerHash"]:
            personal_fits.append(fit_info)
        elif submitter["corporation_name"] == user_corporation:
            corporation_fits.append(fit_info)
        else:
            alliance_fits.append(fit_info)

        if db_fit["ship"] == "Pack":
            packs.append(fit_info)
        else:
            all_fits.append(fit_info)

    return render_template("fittings.html",
                           doctrine_fits=doctrine_fits,
                           corporation_fits=corporation_fits,
                           alliance_fits=alliance_fits,
                           dna_string=dna_string,
                           personal_fits=personal_fits,
                           all_fits=all_fits,
                           error_string=error_string,
                           admin=admin,
                           packs=packs)
コード例 #15
0
def fit(fit_id=None):
    if not fit_id:
        abort(404)

    # Redirect if fit is purchased
    if request.method == "GET" and request.args.get("action") == "purchase":
        return redirect(
            url_for("ordering.home",
                    item=fit_id + ";" + request.args.get("multiply", 1)))

    selected_fit = None
    try:
        selected_fit = g.mongo.db.fittings.find_one({"_id": ObjectId(fit_id)})
    except bson.errors.InvalidId:
        abort(404)

    if not selected_fit:
        return redirect(url_for("fittings.home", error="not_found"))
    elif request.method == "GET" and request.args.get("action") == "direct":
        # Use direct to cart
        session["fitting"] = selected_fit["fit"]
        return redirect(url_for("ordering.home"))

    # Check if fittings admin
    admin = auth_check("fittings_admin")

    # Delete Permissions
    if selected_fit["submitter"] == session["CharacterOwnerHash"] or admin:
        can_delete = True
    else:
        can_delete = False

    # Modifications
    notes_change = request.args.get("notes") if request.args.get(
        "notes") else selected_fit["notes"]
    source_change = request.args.get("source") if request.args.get(
        "source") else selected_fit.get("source")
    doctrine_change = bool(request.args.get("doctrine")) if request.args.get(
        "doctrine") else False
    if request.args.get("action") == "delete" and can_delete:
        g.mongo.db.fittings.remove({"_id": ObjectId(fit_id)})
        return redirect(url_for("fittings.home"))
    elif request.args.get("action") == "edit" and can_delete:
        g.mongo.db.fittings.update({"_id": ObjectId(fit_id)}, {
            "$set": {
                "notes": notes_change,
                "source": source_change,
                "doctrine": doctrine_change
            }
        })
        return redirect(url_for("fittings.fit", fit_id=fit_id))

    fit_by_line = selected_fit["fit"].splitlines()

    with open("resources/nameConversions.json") as name_conversions_file:
        name_conversions = json.load(name_conversions_file)
    actual_fit_items = []
    pre_name_conversion = {}
    for pre_filter_item in selected_fit["items"].keys():
        pre_filter_item = pre_filter_item.replace(
            "Thermic", "Thermal")  # EVE parallax patch
        actual_fit_items.append(
            name_conversions.get(pre_filter_item, pre_filter_item))
        if name_conversions.get(pre_filter_item):
            pre_name_conversion[name_conversions.get(
                pre_filter_item)] = pre_filter_item

    # ID Matching
    item_list = list(g.mongo.db.items.find({"name": {
        "$in": actual_fit_items
    }}))
    item_prices, prices_usable = eve_central.market_hub_prices(
        [x["_id"] for x in item_list])

    item_table = [[
        "Name", "Qty", "Isk/Item", "Vol/Item", "Total Isk", "Total Volume"
    ]]
    total_fit_isk = 0
    total_volume = 0
    multiply = 1 if not request.args.get("multiply") else int(
        request.args.get("multiply"))

    for fit_item in item_list:
        try:
            # Check if thermal is correct in fit
            qty = selected_fit["items"][fit_item["name"]] * multiply
        except KeyError:
            try:
                # Check if it's an old fit with thermic
                qty = selected_fit["items"][fit_item["name"].replace(
                    "Thermal", "Thermic")] * multiply
            except KeyError:
                # Check if the item name has changed
                qty = selected_fit["items"][pre_name_conversion[
                    fit_item["name"]]] * multiply
        isk_per_item = item_prices[fit_item["_id"]]["sell"]
        vol_per_item = fit_item["volume"]
        item_isk_total = qty * isk_per_item
        item_vol_total = qty * vol_per_item
        total_fit_isk += item_isk_total
        total_volume += item_vol_total
        # Formatting
        isk_per_item = "{:,.02f}".format(isk_per_item)
        vol_per_item = "{:,.02f}".format(vol_per_item)
        item_isk_total = "{:,.02f}".format(item_isk_total)
        item_vol_total = "{:,.02f}".format(item_vol_total)
        item_table.append([
            fit_item["name"], qty, isk_per_item, vol_per_item, item_isk_total,
            item_vol_total
        ])

    if multiply == 1 and prices_usable:
        g.mongo.db.fittings.update(
            {"_id": ObjectId(fit_id)},
            {"$set": {
                "price": total_fit_isk,
                "volume": total_volume
            }})

    # List routes
    with open("configs/base.json") as base_config_file:
        base_config = json.load(base_config_file)

    market_hub_name = base_config["market_hub_name"]
    min_id_limit = base_config["market_hub_station"] * 100000000
    max_id_limit = base_config["market_hub_station"] * 100000000 + 100000000
    market_hub_routes = g.mongo.db.jf_routes.find(
        {"_id": {
            "$gte": min_id_limit,
            "$lt": max_id_limit
        }})

    if request.args.get("end"):
        selected_route = int(request.args.get("end"))
    else:
        selected_route = 0

    valid_stations = []
    current_route = g.mongo.db.carts.find_one(
        {"_id": session["CharacterOwnerHash"]})
    for route in market_hub_routes:
        if request.args.get("end") and route["_id"] == int(
                request.args.get("end")):
            valid_stations.append([route["_id"], route["end"], True])
            g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]},
                                    {"$set": {
                                        "route": route["_id"]
                                    }},
                                    upsert=True)
        elif current_route:
            if route["_id"] == current_route.get("route"):
                valid_stations.append([route["_id"], route["end"], True])
                selected_route = route[
                    "_id"] if selected_route == 0 else selected_route
            else:
                valid_stations.append([route["_id"], route["end"], False])
        elif not request.args.get(
                "end") and route["end"] == base_config["default_ship_to"]:
            valid_stations.append([route["_id"], route["end"], True])
            g.mongo.db.carts.update({"_id": session["CharacterOwnerHash"]},
                                    {"$set": {
                                        "route": route["_id"]
                                    }},
                                    upsert=True)
            selected_route = route[
                "_id"] if selected_route == 0 else selected_route
        else:
            valid_stations.append([route["_id"], route["end"], False])

    # JF Calculations
    selected_route_info = g.mongo.db.jf_routes.find_one(
        {"_id": selected_route})
    if selected_route_info:
        rate_info = conversions.valid_value(selected_route_info["prices"],
                                            time.time())
        if session.get("UI_Corporation"):
            jf_rate = rate_info["corp"]
        else:
            jf_rate = rate_info["general"]

        jf_total = jf_rate * total_volume
    else:
        jf_rate = 0
        jf_total = 0
    order_total = jf_total + total_fit_isk

    # Submission date
    date_added = ObjectId(fit_id).generation_time.strftime("%Y-%m-%d %H:%M:%S")

    # Formatting
    total_fit_isk = "{:,.02f}".format(total_fit_isk)
    total_volume = "{:,.02f}".format(total_volume)
    jf_total = "{:,.02f}".format(jf_total)
    jf_rate = "{:,.02f}".format(jf_rate)
    order_total = "{:,.02f}".format(order_total)

    return render_template("fittings_fit.html",
                           item_table=item_table,
                           fit_string=fit_by_line,
                           total_fit_isk=total_fit_isk,
                           total_volume=total_volume,
                           valid_stations=valid_stations,
                           market_hub_name=market_hub_name,
                           jf_rate=jf_rate,
                           jf_total=jf_total,
                           order_total=order_total,
                           dna_string=selected_fit["dna"],
                           fit_name=selected_fit["name"],
                           multiply=multiply,
                           can_delete=can_delete,
                           notes=selected_fit["notes"],
                           source=selected_fit.get("source"),
                           admin=admin,
                           doctrine=selected_fit["doctrine"],
                           prices_usable=prices_usable,
                           category=selected_fit.get("category"),
                           date_added=date_added)
コード例 #16
0
def form(key):
    # Highest Role
    role = None
    if auth_check("security_officer"):
        role = "security_officer"
    elif auth_check("recruiter"):
        role = "recruiter"

    # Recruitment Info
    try:
        if request.form.get("action") == "submit":
            insert = {}
            for question_key, value in request.form.items():
                if question_key not in ["action", "submitted"]:
                    key_split = question_key.split("_")
                    if key_split[1] == "bool":
                        insert[key_split[0]] = value == "True"
                    else:
                        insert[key_split[0]] = value.strip()
            app_info = g.mongo.db.applications.find_one_and_update({"_id": ObjectId(key)},
                                                                   {"$set": {"questions": insert,
                                                                             "submitted": True,
                                                                             "status": "Submitted"}},
                                                                   return_document=ReturnDocument.AFTER)
            # Discord Integration
            g.redis.publish('titdev-recruitment',
                            "@everyone: {0} has submitted a recruitment form: {1}".format(
                                session["CharacterName"],
                                url_for("recruitment.form", key=key, _external=True)
                            ))

            if request.form.get("submitted") == "True":
                flash("Application edited", "success")
            else:
                flash("Application submitted", "success")
        elif request.form.get("action") in [
            "process", "interview", "accept", "reject", "release"
        ] and role == "security_officer":
            status_strings = {
                "process": "Processing",
                "interview": "Interview Required",
                "accept": "Accepted",
                "reject": "Rejected",
                "release": "Submitted" if request.form.get("submitted") == "True" else "Not Submitted"
            }
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {
                    "$set": {
                        "status": status_strings[request.form.get("action")],
                        "reason": request.form.get("reason")
                    }
                },
                return_document=ReturnDocument.AFTER)
            # Discord Integration
            if request.form.get("action") not in ["process", "release"]:
                g.redis.publish('titdev-recruitment',
                                "@everyone: {0} has marked a form as {2}: {1}".format(
                                    session["CharacterName"],
                                    url_for("recruitment.form", key=key, _external=True),
                                    status_strings[request.form.get("action")]
                                ))
        elif request.form.get("action") == "flag" and role:
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {
                    "$set":
                        {
                            "met_recruiter": request.form.get("met_recruiter") == "False"
                        }
                }, return_document=ReturnDocument.AFTER)
        elif request.form.get("action") == "delete" and role == "security_officer":
            if request.form.get("confirm") == key:
                g.mongo.db.applications.delete_one({"_id": ObjectId(key)})
                flash("Application Deleted", "success")
                return redirect(url_for("recruitment.home"))
            else:
                app_info = g.mongo.db.applications.find_one({"_id": ObjectId(key)})
                flash("Key doesn't match", "error")
        elif request.form.get("action") == "officer_edit" and role == "security_officer":
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {
                    "$set":
                        {
                            "officer_notes": request.form.get("officer_edit")
                        }
                }, return_document=ReturnDocument.AFTER)
            flash("Officer Notes Edited", "success")
        elif request.form.get("action") == "recruiter_edit" and role:
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {
                    "$set":
                        {
                            "recruiter_notes": request.form.get("recruiter_edit")
                        }
                }, return_document=ReturnDocument.AFTER)
            flash("Recruiter Notes Edited", "success")
        elif request.form.get("action") == "recruiter":
            app_info = g.mongo.db.applications.find_one_and_update(
                {"_id": ObjectId(key)},
                {
                    "$set":
                        {
                            "recruiter": request.form.get("recruiter")
                        }
                }, return_document=ReturnDocument.AFTER)
            flash("Recruiter Changed", "success")
        else:
            app_info = g.mongo.db.applications.find_one({"_id": ObjectId(key)})
    except bson.errors.InvalidId:
        flash("Invalid Key", "error")
        return redirect(url_for("recruitment.home"))

    if app_info:
        key_owner = app_info.get("owner")
        if not key_owner:
            g.mongo.db.applications.update_one({"_id": ObjectId(key)}, {"$set": {
                "owner": session["CharacterOwnerHash"],
                "character_name": session["CharacterName"]
            }})
            key_owner = session["CharacterOwnerHash"]
        if key_owner == session["CharacterOwnerHash"] or role:
            app_key = key.strip()
            app_status = app_info.get("status", "Not submitted")
            app_reason = app_info.get("reason")
        else:
            flash("Key Already Used", "error")
            return redirect(url_for("recruitment.home"))
    else:
        flash("Key Not Found", "error")
        return redirect(url_for("recruitment.home"))

    # APIs
    error_list = []
    if request.method == "POST":
        if request.form.get("action") == "add":
            error_list = caches.api_keys([(request.form.get("key_id"), request.form.get("vcode"))],
                                         dashboard_id=key_owner)
        elif request.form.get("action") == "remove":
            g.mongo.db.api_keys.update_one({"_id": key_owner},
                                           {
                                               "$pull": {
                                                   "keys": {"key_id": int(request.form.get("key_id"))}
                                               }
                                           })
            g.mongo.db.api_keys.update_one({"_id": key_owner},
                                           {
                                               "$push": {
                                                   "old_keys": {
                                                       "key_id": int(request.form.get("key_id")),
                                                       "vcode": request.form.get("vcode"),
                                                       "delete_time": int(time.time())
                                                   }
                                               }
                                           })
        elif request.form.get("action") == "remove_old" and role == "security_officer":
            g.mongo.db.api_keys.update_one({"_id": key_owner},
                                           {
                                               "$pull": {
                                                   "old_keys": {"key_id": int(request.form.get("key_id"))}
                                               }
                                           })

    associated_keys = []
    associated_old_keys = []
    # List of characters
    db_key_doc = g.mongo.db.api_keys.find_one({"_id": key_owner})
    if db_key_doc:
        for key in db_key_doc["keys"]:
            associated_keys.append([key["character_id"], key["character_name"], key["key_id"], key["vcode"],
                                    key["cached_str"], key.get("valid", True)])
        if db_key_doc.get("old_keys"):
            for key in db_key_doc["old_keys"]:
                associated_old_keys.append([key["key_id"], key["vcode"],
                                            time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(key["delete_time"]))])

    # User Information
    db_user_info = g.mongo.db.users.find_one({"_id": key_owner})
    user_info = [db_user_info["_id"], db_user_info["character_name"], db_user_info["corporation_name"],
                 db_user_info["alliance_name"]]

    # Images
    with open("configs/base.json", "r") as base_config_file:
        base_config = json.load(base_config_file)
    image_list = [base_config["image_server"] + "/Character/" + str(db_user_info["character_id"]) + "_256.jpg",
                  base_config["image_server"] + "/Corporation/" + str(db_user_info["corporation_id"]) + "_128.png",
                  base_config["image_server"] + "/Alliance/" + str(db_user_info["alliance_id"]) + "_128.png"]
    access_mask = base_config["access_mask"]

    # Questions
    question_list = g.mongo.db.app_questions.find()
    question_pre_table = []
    question_table = []
    if question_list:
        for question in question_list:
            if question["bool"]:
                question_type = "bool"
            elif question["long"]:
                question_type = "long"
            else:
                question_type = "text"
            question_pre_table.append([question["text"], question_type,
                                       "{0}_{1}".format(str(question["_id"]), question_type)])
    answers = app_info.get("questions")
    for row in question_pre_table:
        if answers:
            reply = answers.get(row[2].split("_")[0], "")
            if row[1] == "long":
                question_table.append(row + [reply, reply.splitlines()])
            else:
                question_table.append(row + [reply])
        else:
            question_table.append(row + [""])

    # Recruiters
    recruiter_users = g.mongo.db.eve_auth.find_one({"_id": "recruiter"})
    recruiter_list = [user["character_name"] for user in g.mongo.db.users.find(
        {"_id": {"$in": recruiter_users["users"]}})]

    return render_template("recruitment_form.html", error_list=error_list, image_list=image_list,
                           access_mask=access_mask, user_info=user_info, associated_keys=associated_keys,
                           app_key=app_key, app_status=app_status, app_reason=app_reason, role=role,
                           recruiter_notes=[app_info.get("recruiter_notes", "").splitlines(),
                                            app_info.get("recruiter_notes", "")],
                           officer_notes=[app_info.get("officer_notes", "").splitlines(),
                                          app_info.get("officer_notes", "")],
                           question_table=question_table,
                           met_recruiter=app_info.get("met_recruiter", False),
                           submitted=app_info.get("submitted", False),
                           recruiter_list=recruiter_list, app_recruiter=app_info.get("recruiter"),
                           associated_old_keys=associated_old_keys)