Blame view

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

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

a5a365e8   hitier   Move User model t...
12
13
from app.models import db, Agent, Service, Project, Capacity, Period, Charge
from app.auth.models import User
a17327bf   hitier   New db feeding co...
14

a17327bf   hitier   New db feeding co...
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()

21724174   hitier   Fix mysql_lesia_u...
26
    engine = create_engine(current_app.config['LESIA_AGENTS_DB_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
    # mapped classes are now created with names by default
    # matching that of the table name.
f1026243   hitier   Feed db periods a...
38
39
40
41
42
43
    lesia_agent = Base.classes.agent
    lesia_service = Base.classes.gestit_services
    lesia_project = Base.classes.gestit_projets
    lesia_fonction = Base.classes.gestit_fonctions
    lesia_affectation = Base.classes.gestit_affectations
    lesia_periods = Base.classes.gestit_semestres
a17327bf   hitier   New db feeding co...
44
45

    lesia_session = Session(engine)
1002c994   hitier   Also feed ids fro...
46

f1026243   hitier   Feed db periods a...
47
    agents = lesia_session.query(lesia_agent).all()
a17327bf   hitier   New db feeding co...
48
    for a in agents:
1002c994   hitier   Also feed ids fro...
49
        n_a = Agent(id=a.IDagent, firstname=a.nom, secondname=a.prenom)
a17327bf   hitier   New db feeding co...
50
51
52
        db.session.add(n_a)
    db.session.commit()

f1026243   hitier   Feed db periods a...
53
    services = lesia_session.query(lesia_service).all()
a17327bf   hitier   New db feeding co...
54
    for s in services:
1002c994   hitier   Also feed ids fro...
55
        n_s = Service(id=s.id, name=s.nom, abbr=s.abbreviation)
a17327bf   hitier   New db feeding co...
56
57
58
        db.session.add(n_s)
    db.session.commit()

f1026243   hitier   Feed db periods a...
59
    projects = lesia_session.query(lesia_project).all()
a17327bf   hitier   New db feeding co...
60
    for p in projects:
1002c994   hitier   Also feed ids fro...
61
        n_p = Project(id=p.id, name=p.nom)
a17327bf   hitier   New db feeding co...
62
63
64
        db.session.add(n_p)
    db.session.commit()

f1026243   hitier   Feed db periods a...
65
    fonctions = lesia_session.query(lesia_fonction).all()
a17327bf   hitier   New db feeding co...
66
    for f in fonctions:
1002c994   hitier   Also feed ids fro...
67
        n_c = Capacity(id=f.id, name=f.nom)
a17327bf   hitier   New db feeding co...
68
69
70
        db.session.add(n_c)
    db.session.commit()

f1026243   hitier   Feed db periods a...
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    periods = lesia_session.query(lesia_periods)
    for p in periods:
        n_p = Period(name=p.id_semestre)
        db.session.add(n_p)
    db.session.commit()

    affectations = lesia_session.query(lesia_affectation)
    for f in affectations:
        p = Period.query.filter(Period.name == f.semestre_id).one()
        n_c = Charge(agent_id=f.agent_id,
                     project_id=f.projet_id,
                     service_id=f.service_id,
                     capacity_id=f.fonction_id,
                     period_id=p.id,
                     charge_rate=f.charge)
        db.session.add(n_c)
    db.session.commit()

335db4c0   hitier   Allow randoming c...
89

a17327bf   hitier   New db feeding co...
90
91
@bp.cli.command("feed_periods")
def feed_periods():
d8a6b942   hitier   More install doc
92
    """ Fill in the periods name in the database. """
e817ff5e   hitier   Random Charge Age...
93
    for y in range(2014, 2023):
a17327bf   hitier   New db feeding co...
94
95
96
97
98
99
100
        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
101
102
103
104
@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...
105
    for i in range(0, 100):
335db4c0   hitier   Allow randoming c...
106
107
108
109
        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...
110
111
112
113
114
        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...
115
116
117
118
119
        # 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()
a5a365e8   hitier   Move User model t...
120
        if total_charge is not None and (total_charge + percent) >= 100:
e817ff5e   hitier   Random Charge Age...
121
122
            print("Skipping agent {} for period {}".format(agent_id, period_id))
            continue
335db4c0   hitier   Allow randoming c...
123
        charge = Charge(agent_id=agent_id,
a17327bf   hitier   New db feeding co...
124
125
126
127
128
129
130
131
132
133
                        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
134
@bp.cli.command('user_delete')
a17327bf   hitier   New db feeding co...
135
@click.argument('user_id')
d8a6b942   hitier   More install doc
136
137
def user_delete(user_id):
    """Delete the user by given id (see user_show_all")."""
a17327bf   hitier   New db feeding co...
138
139
140
141
142
143
144
    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
145
    """ Create the database structure."""
a17327bf   hitier   New db feeding co...
146
    db.create_all()
42c07429   hitier   Default role valu...
147
    admin = User(email='admin@nowhere.org', name='admin', login='admin', password='admin', role='admin')
a17327bf   hitier   New db feeding co...
148
149
150
151
    db.session.add(admin)
    db.session.commit()


d8a6b942   hitier   More install doc
152
@bp.cli.command('user_add')
a17327bf   hitier   New db feeding co...
153
154
@click.argument('email')
@click.argument('name')
3ed62121   hitier   Add login to user
155
@click.argument('login')
a17327bf   hitier   New db feeding co...
156
@click.argument('password')
d8a6b942   hitier   More install doc
157
158
def user_add(email, name, login, password):
    """ Add a new user in db."""
3ed62121   hitier   Add login to user
159
    user = User(email=email, name=name, login=login, password=password)
a17327bf   hitier   New db feeding co...
160
161
162
163
164
    db.session.add(user)
    db.session.commit()
    print("added ", name)


d8a6b942   hitier   More install doc
165
166
167
@bp.cli.command('user_show_all')
def user_show_all():
    """ Show all users in db."""
a17327bf   hitier   New db feeding co...
168
169
170
171
172
173
174
175
176
177
178
    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
        ))