Blame view

app/commands/commands.py 5.15 KB
335db4c0   hitier   Allow randoming c...
1
import sys
a17327bf   hitier   New db feeding co...
2
3
4
import click
import random

d8a6b942   hitier   More install doc
5
from sqlalchemy.exc import OperationalError
e817ff5e   hitier   Random Charge Age...
6
from sqlalchemy.sql import func
a17327bf   hitier   New db feeding co...
7
8
9
10
11
12
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

from app.models import db, User, Agent, Service, Project, Capacity, Period, Charge

d8a6b942   hitier   More install doc
13
from db_config import mysql_lesia_uri
a17327bf   hitier   New db feeding co...
14
15
16

from . import bp

335db4c0   hitier   Allow randoming c...
17

a17327bf   hitier   New db feeding co...
18
19
@bp.cli.command("feed_from_lesia")
def feed_from_lesia():
d8a6b942   hitier   More install doc
20
21
22
23
    """ Feed db with agents from a lesia like mysql database.

    configure that database uri in the db_config.py file.
    """
a17327bf   hitier   New db feeding co...
24
25
    Base = automap_base()

d8a6b942   hitier   More install doc
26
    engine = create_engine(mysql_lesia_uri)
a17327bf   hitier   New db feeding co...
27
28

    # reflect the tables
d8a6b942   hitier   More install doc
29
30
31
32
33
34
35
    try:
        Base.prepare(engine, reflect=True)
    except OperationalError:
        # TODO: use logging facility instead
        print("Please, configure the mysql database (see db_config.py)")
        sys.exit(-1)

a17327bf   hitier   New db feeding co...
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

    # mapped classes are now created with names by default
    # matching that of the table name.
    LesiaAgent = Base.classes.agent
    LesiaService = Base.classes.gestit_services
    LesiaProject = Base.classes.gestit_projets
    LesiaFonction = Base.classes.gestit_fonctions

    lesia_session = Session(engine)
    agents = lesia_session.query(LesiaAgent).all()
    for a in agents:
        n_a = Agent(firstname=a.nom, secondname=a.prenom)
        db.session.add(n_a)
    db.session.commit()

    services = lesia_session.query(LesiaService).all()
    for s in services:
        n_s = Service(name=s.nom)
        db.session.add(n_s)
    db.session.commit()

    projects = lesia_session.query(LesiaProject).all()
    for p in projects:
        n_p = Project(name=p.nom)
        db.session.add(n_p)
    db.session.commit()

    fonctions = lesia_session.query(LesiaFonction).all()
    for f in fonctions:
        n_c = Capacity(name=f.nom)
        db.session.add(n_c)
    db.session.commit()

335db4c0   hitier   Allow randoming c...
69

a17327bf   hitier   New db feeding co...
70
71
@bp.cli.command("feed_periods")
def feed_periods():
d8a6b942   hitier   More install doc
72
    """ Fill in the periods name in the database. """
e817ff5e   hitier   Random Charge Age...
73
    for y in range(2014, 2023):
a17327bf   hitier   New db feeding co...
74
75
76
77
78
79
80
        for s in ['S1', 'S2']:
            period_name = "{}_{}".format(y, s)
            p = Period(name=period_name)
            db.session.add(p)
    db.session.commit()


d8a6b942   hitier   More install doc
81
82
83
84
@bp.cli.command("feed_random_charges")
@click.option('--agent', '-a', 'agent', default=None, help="the agent id you want to charge")
def feed_random_charges(agent):
    """ Randomly fill in the agents charges. """
a17327bf   hitier   New db feeding co...
85
    for i in range(0, 100):
335db4c0   hitier   Allow randoming c...
86
87
88
89
        if agent is None:
            agent_id = random.choice([i for (i,) in db.session.query(Agent.id).all()])
        else:
            agent_id = int(agent)
a17327bf   hitier   New db feeding co...
90
91
92
93
94
        project_id = random.choice([i for (i,) in db.session.query(Project.id).all()])
        service_id = random.choice([i for (i,) in db.session.query(Service.id).all()])
        capacity_id = random.choice([i for (i,) in db.session.query(Capacity.id).all()])
        period_id = random.choice([i for (i,) in db.session.query(Period.id).all()])
        percent = random.choice(range(10, 110, 10))
e817ff5e   hitier   Random Charge Age...
95
96
97
98
99
100
101
102
        # check max agent charge for the period
        total_charge = db.session.query(func.sum(Charge.charge_rate).label("total_charge")) \
            .filter(Charge.agent_id == agent_id,
                    Charge.period_id == period_id
                    ).scalar()
        if total_charge is not None and (total_charge + percent)>= 100:
            print("Skipping agent {} for period {}".format(agent_id, period_id))
            continue
335db4c0   hitier   Allow randoming c...
103
        charge = Charge(agent_id=agent_id,
a17327bf   hitier   New db feeding co...
104
105
106
107
108
109
110
111
112
113
                        project_id=project_id,
                        service_id=service_id,
                        capacity_id=capacity_id,
                        period_id=period_id,
                        charge_rate=percent)
        print("adding {}_{}_{}_{}_{}_{}".format(agent_id, project_id, service_id, capacity_id, period_id, percent))
        db.session.add(charge)
        db.session.commit()


d8a6b942   hitier   More install doc
114
@bp.cli.command('user_delete')
a17327bf   hitier   New db feeding co...
115
@click.argument('user_id')
d8a6b942   hitier   More install doc
116
117
def user_delete(user_id):
    """Delete the user by given id (see user_show_all")."""
a17327bf   hitier   New db feeding co...
118
119
120
121
122
123
124
    user = User.query.get(user_id)
    db.session.delete(user)
    db.session.commit()


@bp.cli.command('create_db')
def create_db():
d8a6b942   hitier   More install doc
125
    """ Create the database structure."""
a17327bf   hitier   New db feeding co...
126
127
128
129
130
131
    db.create_all()
    admin = User(email='admin@nowhere.org', name='admin', login='admin', password='admin')
    db.session.add(admin)
    db.session.commit()


d8a6b942   hitier   More install doc
132
@bp.cli.command('user_add')
a17327bf   hitier   New db feeding co...
133
134
@click.argument('email')
@click.argument('name')
3ed62121   hitier   Add login to user
135
@click.argument('login')
a17327bf   hitier   New db feeding co...
136
@click.argument('password')
d8a6b942   hitier   More install doc
137
138
def user_add(email, name, login, password):
    """ Add a new user in db."""
3ed62121   hitier   Add login to user
139
    user = User(email=email, name=name, login=login, password=password)
a17327bf   hitier   New db feeding co...
140
141
142
143
144
    db.session.add(user)
    db.session.commit()
    print("added ", name)


d8a6b942   hitier   More install doc
145
146
147
@bp.cli.command('user_show_all')
def user_show_all():
    """ Show all users in db."""
a17327bf   hitier   New db feeding co...
148
149
150
151
152
153
154
155
156
157
158
    print("{:<5} {:<15} {:<15} {:<15} {:<15}".format('id', 'name', 'login', 'passwd', 'email'))
    print("{:<5} {:<15} {:<15} {:<15} {:<15}".format('-' * 5, '-' * 15, '-' * 15, '-' * 15, '-' * 15))
    for user in User.query.all():
        print(user.login)
        print("{:<5} {:<15} {:<15} {:<15} {:<15}".format(
            user.id,
            user.name,
            user.login,
            user.password,
            user.email
        ))