Example #1
0
def add_specification(record_id=None):
    _model = SpecSectionKpi
    _form = AddSpecForm
    _func_name = "section_kpi_mgt.add_specification"
    _template = "default/add-form.html"
    _form_seq = [["spec_date", "file"]]

    if record_id is None:
        record = _model()
        form = _form()
    else:
        record = _model.query.filter_by(id=record_id).first_or_404()
        form = _form(obj=record)

    if request.method == "POST" and form.validate():
        form.populate_obj(record)
        record.filename = record.spec_date.strftime("%Y-%m")
        # Check if File already Exist while it is new entry, skip this if it is edit mode
        if _model.query.filter(_model.filename == record.filename).all() and record_id is None:
            flash("Specification for <strong>{}</strong> Already Exist.".format(record.filename))
        else:
            upload(files=form.file, filename=record.filename, path=kpidir)

            kpi_calc = KpiCalculator(kpi_file=record.filename)
            kpi_calc.kpi_xl_to_spec()
            record.doc = kpi_calc._all_specs

            db.session.add(record)
            db.session.commit()

            flash("<strong>Success!</strong> Database Updated.")

        return form.redirect(url_for("{}".format(_func_name)))
    return render_template(
        _template,
        form=form,
        form_seq=_form_seq
        # form_seq_capex = _form_capex,
        #                           form_seq_opex = _form_opex,
        #                           form_seq_initiative = _form_initiative,
    )
Example #2
0
def add_kpi(filename=None, section_id=None):
    year = int(filename.split("-")[0])
    month = int(filename.split("-")[1])
    if filename is None or section_id is None:
        return render_template("errors/404.html"), 404

    _func_name = "section_kpi_mgt.add_kpi"
    specs = SpecSectionKpi.query.filter(SpecSectionKpi.filename == filename).first()
    section_name = User.query.filter(User.id == section_id).first().full_name
    if specs is None:
        return render_template(
            "section_kpi_mgt/coming-soon.html", msg="Record for {} doesn't exist yet".format(filename)
        )

    try:
        description = specs.doc[section_name]["_classes_description"]
    except KeyError:
        return render_template(
            "section_kpi_mgt/coming-soon.html",
            msg="Specification for {}:{} doesn't exist yet".format(section_name, filename),
        )

    # START Creates Form According to Specifications
    _form = ScoreCardForm
    for key, value in description.items():
        _form.append_integer_field(name=key, label=value)
    # END Creates Form According to Specifications

    _form_capex = sorted([x for x in description if x[0] == "a"])  # ['a11', 'a12'....]
    _form_opex = sorted([x for x in description if x[0] == "b"])  # gets list from description
    _form_initiative = sorted([x for x in description if x[0] == "c"])  #

    _template = "section_kpi_mgt/add-kpi-score.html"

    # Check if record already exist for /<filename>/<section_name>
    # so that we can select modes, add or edit
    records = SectionRawScore.query.filter(
        and_(
            SectionRawScore.section_id == section_id,
            extract("month", SectionRawScore.score_date) == month,
            extract("year", SectionRawScore.score_date) == year,
        )
    ).all()

    if records is None:
        form = _form()
        flash("new")
    else:
        # populate the form if record is exist
        temp_dict = dict()
        for i in records:
            temp_dict[i.score_class] = i.raw_score
            # delete existing records to avoid duplication of data
            db.session.delete(i)
        db.session.commit()

        Record = namedtuple("Record", ", ".join(temp_dict.keys()))
        records = Record(**temp_dict)
        form = _form(obj=records)

    if request.method == "POST" and form.validate():
        data = form.data.copy()
        data.pop("next", None)
        score_date = dt(year=year, month=month, day=1)

        for k, v in data.items():
            record = SectionRawScore(score_class=k, raw_score=v, score_date=score_date, section_id=section_id)
            db.session.add(record)

        # Calculate Raw Score
        kpi_calculator = KpiCalculator(raw_score=data)
        kpi_calculator.set_spec(specs.doc[section_name])
        kpi_calculator.run()
        # Store Calculated Score
        record = SectionWeightedScore.query.filter(
            and_(
                SectionWeightedScore.section_id == section_id,
                extract("month", SectionWeightedScore.weighted_score_date) == month,
                extract("year", SectionWeightedScore.weighted_score_date) == year,
            )
        ).all()

        # if record in weighted score exist, delete all, and just add new once
        if record is not None:
            for i in record:
                db.session.delete(i)
            db.session.commit()

        for k, v in kpi_calculator._weighted_category_scores.items():
            record = SectionWeightedScore(
                section_id=section_id, weighted_score_date=score_date, weighted_score=v, category=k
            )
            db.session.add(record)

        db.session.commit()
        flash("<strong>Success!</strong> Database Updated.")

        return form.redirect(url_for(_func_name))

    return render_template(
        _template, form=form, form_seq_capex=_form_capex, form_seq_opex=_form_opex, form_seq_initiative=_form_initiative
    )