Blame view

app/commands/commands.py 20.9 KB
e0778a0d   hitier   New fake_lesia_na...
1
2
import csv
import os
335db4c0   hitier   Allow randoming c...
3
import sys
f1bb8c76   hitier   Move auth tests t...
4

a17327bf   hitier   New db feeding co...
5
6
7
import click
import random

21724174   hitier   Fix mysql_lesia_u...
8
from flask import current_app
f1bb8c76   hitier   Move auth tests t...
9
from sqlalchemy.exc import IntegrityError
e817ff5e   hitier   Random Charge Age...
10
from sqlalchemy.sql import func
a17327bf   hitier   New db feeding co...
11

d6b9daca   hitier   Feed categories a...
12
from app.models import db, Agent, Service, Project, Capacity, Period, Charge, AgentStatus, Company, AgentBap, \
a53e2fff   hitier   New category/labe...
13
    AgentGrade, Category, Label, ProjectLabel, CategoryLabel
f1bb8c76   hitier   Move auth tests t...
14
# TODO: rename to methods and add get_roles()
946dda30   hitier   New cli command u...
15
from app.auth.models import User, _nameToRole, _roleToName
a17327bf   hitier   New db feeding co...
16

a17327bf   hitier   New db feeding co...
17
18
from . import bp

335db4c0   hitier   Allow randoming c...
19

946dda30   hitier   New cli command u...
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@bp.cli.command('create_db')
def create_db():
    """
    Create the database structure. Database should be empty.

    configure the proper database uri in the db_config.py file.
    """
    db.create_all()
    admin = User(email='admin@nowhere.org', name='admin', login='admin', role='admin')
    admin.set_password('admin')
    sqlite_uri = db.engine.url.__str__() if 'sqlite' in db.engine.url.__str__() else None
    try:
        db.session.add(admin)
        db.session.commit()
    except IntegrityError:
        current_app.logger.error("User admin already exists, database should be empty at create")
        if sqlite_uri:
            current_app.logger.error("see " + sqlite_uri)
        sys.exit(-1)

    if sqlite_uri:
3262868b   hitier   New Cli tests
41
        print("Created sqlite db: " + sqlite_uri)
946dda30   hitier   New cli command u...
42
43


67814e41   hitier   New cli command f...
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@bp.cli.command("feed_from_irap")
@click.option('--csv-file', '-f', 'csv_file_name', help="the csv file path to feed from")
def feed_from_irap(csv_file_name):
    """
    Use an Irap csv charges files and feed db with

    :param csv_file_name:
    :return:
    """

    rows = []

    with open(csv_file_name, newline='') as csvfile:
        csvreader = csv.DictReader(csvfile, delimiter=',', quotechar='"')
        for row in csvreader:
28a7e0a2   hitier   Strip row values ...
59
60
            # Remove any leading/trailing spaces
            row = {k: v.strip() for k, v in row.items()}
67814e41   hitier   New cli command f...
61
62
            rows.append(row)

28a7e0a2   hitier   Strip row values ...
63
    firstname_key = 'NOM'
2d944bab   hitier   CSV column keys a...
64
    secondname_key = 'PRÉNOM'
0e188a92   hitier   Import more agent...
65
    status_key = 'STATUT'
2d944bab   hitier   CSV column keys a...
66
67
    virtual_key = 'VIRTUEL'
    company_key = 'SOCIÉTÉ'
0e188a92   hitier   Import more agent...
68
69
    bap_key = 'BAP'
    grade_key = 'GRADE CORPS'
28a7e0a2   hitier   Strip row values ...
70
    project_key = 'PROJETS'
2d944bab   hitier   CSV column keys a...
71
    service_key = 'GROUPE MÉTIER'
d6b9daca   hitier   Feed categories a...
72
    categorie_keys = ['TYPOLOGIE', 'THÉMATIQUE']
67814e41   hitier   New cli command f...
73

28a7e0a2   hitier   Strip row values ...
74
75
    # Get the columns values
    #
0e188a92   hitier   Import more agent...
76
77
78
79
80
    agents = []
    services = []
    baps = []
    grades = []
    companies = []
854e5e73   hitier   Feed statuses, so...
81
    statuses = []
74c7dad5   hitier   Update irap feed ...
82
    labels = []
f1bb8c76   hitier   Move auth tests t...
83

74c7dad5   hitier   Update irap feed ...
84
    # Build a category dict of lists
f1bb8c76   hitier   Move auth tests t...
85
86
    #   key being the category name,
    #   list being filled with corresponding labels
74c7dad5   hitier   Update irap feed ...
87
    categorie_labels = {k: [] for k in categorie_keys}
f1bb8c76   hitier   Move auth tests t...
88

74c7dad5   hitier   Update irap feed ...
89
90
91
    # Projects' labels is a dict of lists
    #   indexed by project name
    #   containing labels for that project
f1bb8c76   hitier   Move auth tests t...
92
    #
74c7dad5   hitier   Update irap feed ...
93
    project_labels = {}
f1bb8c76   hitier   Move auth tests t...
94

74c7dad5   hitier   Update irap feed ...
95
96
97
    #
    # Parse the rows and fill in various lists
    #
0e188a92   hitier   Import more agent...
98
    for r in rows:
0e188a92   hitier   Import more agent...
99
100
101
102
        services.append(r[service_key])
        baps.append(r[bap_key])
        grades.append(r[grade_key])
        companies.append(r[company_key])
854e5e73   hitier   Feed statuses, so...
103
        statuses.append(r[status_key])
f1bb8c76   hitier   Move auth tests t...
104

74c7dad5   hitier   Update irap feed ...
105
106
107
        # the projet and its labels
        project_name = r[project_key]
        project_labels[project_name] = []
f1bb8c76   hitier   Move auth tests t...
108

74c7dad5   hitier   Update irap feed ...
109
110
111
112
        # now fill in both
        #   the labels list,
        #   the category-labels dict,
        #   and the project-labels dict
d6b9daca   hitier   Feed categories a...
113
        for k in categorie_keys:
74c7dad5   hitier   Update irap feed ...
114
115
116
            labels.append(r[k])
            categorie_labels[k].append(r[k])
            project_labels[project_name].append(r[k])
f1bb8c76   hitier   Move auth tests t...
117

74c7dad5   hitier   Update irap feed ...
118
        # create the agents list of dicts
d6b9daca   hitier   Feed categories a...
119
        agents.append({
0e188a92   hitier   Import more agent...
120
121
122
123
124
125
            'firstname': r[firstname_key],
            'secondname': r[secondname_key],
            'status': r[status_key],
            'virtual': r[virtual_key],
            'company': r[company_key],
            'bap': r[bap_key],
d6b9daca   hitier   Feed categories a...
126
            'grade': r[grade_key]})
0e188a92   hitier   Import more agent...
127

ed453065   hitier   Remove empty valu...
128
129
130
131
132
133
134
135
136
137
    # Uppercase the small tables
    #
    baps = [x.upper() for x in baps]
    grades = [x.upper() for x in grades]
    statuses = [x.upper() for x in statuses]

    # Now, sort the lists
    #
    #  1- first remove empty string with filter()
    #  2- then keep only uniq item with set()
74c7dad5   hitier   Update irap feed ...
138
    #  3- at last alpha sort with sorted()
0e188a92   hitier   Import more agent...
139
    #
ed453065   hitier   Remove empty valu...
140
141
142
143
144
    services = sorted(set(filter(None, services)))
    baps = sorted(set(filter(None, baps)))
    grades = sorted(set(filter(None, grades)))
    companies = sorted(set(filter(None, companies)))
    statuses = sorted(set(filter(None, statuses)))
74c7dad5   hitier   Update irap feed ...
145
    labels = sorted(set(filter(None, labels)))
67814e41   hitier   New cli command f...
146

74c7dad5   hitier   Update irap feed ...
147
    # Do the same for the projects, that are keys of project_labels
f1bb8c76   hitier   Move auth tests t...
148
    #
74c7dad5   hitier   Update irap feed ...
149
    projects = sorted(set(project_labels.keys()))
f1bb8c76   hitier   Move auth tests t...
150

74c7dad5   hitier   Update irap feed ...
151
152
    # Do the same for the labels inside each category
    #  c is the category name containing the labels list
d6b9daca   hitier   Feed categories a...
153
    #
74c7dad5   hitier   Update irap feed ...
154
155
156
    for c in categorie_keys:
        c_labels = sorted(set(filter(None, categorie_labels[c])))
        categorie_labels[c] = c_labels
d6b9daca   hitier   Feed categories a...
157
158

    # At least, as agents is a list of dicts, sorting is a bit tricky
854e5e73   hitier   Feed statuses, so...
159
160
161
162
163
    #
    # the first one liner will store the last agent's line only
    # then we alpha sort  on the name
    # on both, the discrimination is based on the name couple: (firstname, secondname)
    #
0e188a92   hitier   Import more agent...
164
    agents = list({(a['firstname'], a['secondname']): a for a in agents}.values())
854e5e73   hitier   Feed statuses, so...
165
    agents = sorted(agents, key=lambda a: (a['firstname'], a['secondname']))
28a7e0a2   hitier   Strip row values ...
166

74c7dad5   hitier   Update irap feed ...
167
168
169
170
171
172
    #
    # We are done with collecting data
    #
    # Now we write to database
    #

0e188a92   hitier   Import more agent...
173
    # Feed baps from column
28a7e0a2   hitier   Strip row values ...
174
    #
0e188a92   hitier   Import more agent...
175
176
177
178
179
    for b in baps:
        n_b = AgentBap(name=b)
        db.session.add(n_b)
    db.session.commit()

f1bb8c76   hitier   Move auth tests t...
180
    # Feed grades from column
0e188a92   hitier   Import more agent...
181
182
183
184
185
186
    #
    for g in grades:
        n_g = AgentGrade(name=g)
        db.session.add(n_g)
    db.session.commit()

f1bb8c76   hitier   Move auth tests t...
187
    # Feed companies from column
0e188a92   hitier   Import more agent...
188
189
190
191
    #
    for c in companies:
        n_c = Company(name=c)
        db.session.add(n_c)
67814e41   hitier   New cli command f...
192
    db.session.commit()
67814e41   hitier   New cli command f...
193

854e5e73   hitier   Feed statuses, so...
194
195
196
197
198
199
200
    # Feed statuses from column
    #
    for s in statuses:
        n_s = AgentStatus(name=s)
        db.session.add(n_s)
    db.session.commit()

28a7e0a2   hitier   Strip row values ...
201
202
    # Feed projects from column
    #
67814e41   hitier   New cli command f...
203
204
205
206
207
    for p in projects:
        n_p = Project(name=p)
        db.session.add(n_p)
    db.session.commit()

74c7dad5   hitier   Update irap feed ...
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    # Feed labels from column
    #
    for _l in labels:
        n_l = Label(name=_l)
        db.session.add(n_l)
    db.session.commit()

    # Feed categories from initial list
    #
    for _c in categorie_keys:
        n_c = Category(name=_c)
        db.session.add(n_c)
    db.session.commit()

28a7e0a2   hitier   Strip row values ...
222
223
    # Feed services from column
    #
67814e41   hitier   New cli command f...
224
225
226
227
228
    for s in services:
        n_s = Service(name=s)
        db.session.add(n_s)
    db.session.commit()

770d2129   hitier   Now add only non-...
229
    # Feed periods names
61e60a1f   hitier   Now add default c...
230
    # Todo: are statically built,
ed453065   hitier   Remove empty valu...
231
232
    #      should come from year column name.
    #      also see later
770d2129   hitier   Now add only non-...
233
    #
67814e41   hitier   New cli command f...
234
235
236
237
238
    for p in range(2011, 2030):
        n_p = Period(name=f"{p}")
        db.session.add(n_p)
    db.session.commit()

61e60a1f   hitier   Now add default c...
239
    # Add one default capacity
f1bb8c76   hitier   Move auth tests t...
240
    #
0e188a92   hitier   Import more agent...
241
242
243
    db.session.add(Capacity(name="Agent"))
    db.session.commit()

d6b9daca   hitier   Feed categories a...
244
245
    # Feed categories and labels
    #
74c7dad5   hitier   Update irap feed ...
246
247
248
249
250
251
252
253
254
    for category, labels in categorie_labels.items():
        print(category)
        n_c = Category.query.filter_by(name=category).one()
        for label in labels:
            print(label)
            n_l = Label.query.filter(Label.name == label).one()
            current_app.logger.debug(f"Adding label {label} to category {category}")
            n_cl = CategoryLabel(label=n_l, category=n_c)
            db.session.add(n_cl)
d6b9daca   hitier   Feed categories a...
255
256
    db.session.commit()

f1bb8c76   hitier   Move auth tests t...
257
258
    # Feed project's labels
    #
74c7dad5   hitier   Update irap feed ...
259
260
261
262
263
264
    for project, labels in project_labels.items():
        print(f"Project {project}")
        n_p = Project.query.filter(Project.name == project).one()
        for label in labels:
            n_l = Label.query.filter(Label.name == label).one()
            n_pl = ProjectLabel(project=n_p, label=n_l)
f1bb8c76   hitier   Move auth tests t...
265
266
267
268
            db.session.add(n_pl)
    db.session.commit()

    # Feed agents from agents list previously filled
0e188a92   hitier   Import more agent...
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    #
    for a in agents:
        status = AgentStatus.query.filter(AgentStatus.name == a['status']).one_or_none()
        if status is None and a['status']:
            status = AgentStatus(name=a['status'])
        company = Company.query.filter(Company.name == a['company']).one_or_none()
        if company is None and a['company']:
            company = Company(name=a['company'])
        bap = AgentBap.query.filter(AgentBap.name == a['bap']).one_or_none()
        if bap is None and a['bap']:
            bap = AgentBap(name=a['bap'])
        grade = AgentGrade.query.filter(AgentGrade.name == a['grade']).one_or_none()
        if grade is None and a['grade']:
            grade = AgentBap(name=a['grade'])
        virtual = 1 if a['virtual'] else 0
2d277715   hitier   Set permanent fie...
284
        permanent = 1 if a['status'] == 'PERM' else 0
0e188a92   hitier   Import more agent...
285
286
287
        n_a = Agent(firstname=a['firstname'],
                    secondname=a['secondname'],
                    status_id=status.id if status else None,
854e5e73   hitier   Feed statuses, so...
288
                    company_id=company.id if company else None,
0e188a92   hitier   Import more agent...
289
                    bap_id=bap.id if bap else None,
ed453065   hitier   Remove empty valu...
290
                    grade_id=grade.id if grade else None,
2d277715   hitier   Set permanent fie...
291
292
                    virtual=virtual,
                    permanent=permanent)
0e188a92   hitier   Import more agent...
293
        db.session.add(n_a)
61e60a1f   hitier   Now add default c...
294
295
    db.session.commit()

f1bb8c76   hitier   Move auth tests t...
296
297
298
    # Feed agents from agents list previously filled
    #

770d2129   hitier   Now add only non-...
299
300
301
302
303
    # Now feed the charges.
    #
    # At least one for each csv row
    # At most one for each year
    #
67814e41   hitier   New cli command f...
304
    for r in rows:
28a7e0a2   hitier   Strip row values ...
305
306
307
        p = Project.query.filter(Project.name == r[project_key]).one()
        a = Agent.query.filter(Agent.firstname == r[firstname_key], Agent.secondname == r[secondname_key]).one()
        s = Service.query.filter(Service.name == r[service_key]).one()
61e60a1f   hitier   Now add default c...
308
        c = Capacity.query.first()
ed453065   hitier   Remove empty valu...
309
        # TODO: period names should come from db request
67814e41   hitier   New cli command f...
310
311
312
        for period_name in range(2011, 2030):
            t = Period.query.filter(Period.name == period_name).one()
            charge = r[f"{period_name}"]
796a5688   hitier   Add % sign in cha...
313
314
            # Charge are stored as percent in db, but as fraction of ETP in irap csv
            # we make the conversion here.
67814e41   hitier   New cli command f...
315
            try:
28a7e0a2   hitier   Strip row values ...
316
                charge = int(100 * float(charge))
67814e41   hitier   New cli command f...
317
            except ValueError:
67814e41   hitier   New cli command f...
318
                charge = 0
770d2129   hitier   Now add only non-...
319
320
            if charge == 0:
                continue
67814e41   hitier   New cli command f...
321
322
323
            n_c = Charge(agent_id=a.id,
                         project_id=p.id,
                         service_id=s.id,
61e60a1f   hitier   Now add default c...
324
                         capacity_id=c.id,
67814e41   hitier   New cli command f...
325
326
327
328
329
330
                         period_id=t.id,
                         charge_rate=charge)
            db.session.add(n_c)
    db.session.commit()


946dda30   hitier   New cli command u...
331
332
333
334
335
336
337
338
@bp.cli.command("feed_from_lesia")
def feed_from_lesia():
    """
    Feed db with agents from a lesia like mysql database.

    Remember to configure the proper database uri in the db_config.py file.
    """
    from .lesia_db import lesia_agent, lesia_session, lesia_service, lesia_project, \
90fdccc7   hitier   Now feed projects...
339
340
341
342
343
344
345
346
        lesia_fonction, lesia_periods, lesia_affectation, lesia_domains, lesia_poles, \
        lesia_domainprojects

    # Feed all lesia 'domaine' names and link to new category "Domaine"
    #
    domain_category = Category(name="Domaine")
    domains = lesia_session.query(lesia_domains)
    for d in domains:
a53e2fff   hitier   New category/labe...
347
        n_l = Label(name=d.nom)
74c7dad5   hitier   Update irap feed ...
348
        n_cl = CategoryLabel(category=domain_category, label=n_l)
a53e2fff   hitier   New category/labe...
349
        db.session.add(n_cl)
90fdccc7   hitier   Now feed projects...
350
351
352
353
354
355
356
    db.session.commit()

    # Feed all lesia 'pôle' names and link to new category  "Pôle"
    #
    pole_category = Category(name="Pôle")
    poles = lesia_session.query(lesia_poles)
    for p in poles:
a53e2fff   hitier   New category/labe...
357
358
359
        n_l = Label(name=p.nom)
        n_cl = CategoryLabel(category=pole_category, label=n_l)
        db.session.add(n_cl)
90fdccc7   hitier   Now feed projects...
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    db.session.commit()

    # Feed lesia project with proper "pôle"
    #  (as this information is stored in gestit_projets)
    #
    projects = lesia_session.query(lesia_project).all()
    for p in projects:
        # add project
        n_p = Project(id=p.id, name=p.nom)
        db.session.add(n_p)
        # get corresponding lesia pole name
        pole_name = lesia_session.query(lesia_poles).filter(lesia_poles.id == p.pole_id).one().nom
        # search corresponding Label and store in ProjectLabel table
        n_l = Label.query.filter(Label.name == pole_name).one()
a53e2fff   hitier   New category/labe...
374
        n_pl = ProjectLabel(project=n_p, label=n_l)
90fdccc7   hitier   Now feed projects...
375
376
377
378
379
380
381
382
383
384
385
        db.session.add(n_pl)
        db.session.commit()

    # Get projects domain information and store in ProjectLabel
    #
    domain_projects = lesia_session.query(lesia_domainprojects)
    for dp in domain_projects:
        project_name = lesia_session.query(lesia_project).filter(lesia_project.id == dp.projet_id).one().nom
        domain_name = lesia_session.query(lesia_domains).filter(lesia_domains.id == dp.domaine_id).one().nom
        n_p = Project.query.filter(Project.name == project_name).one()
        n_l = Label.query.filter(Label.name == domain_name).one()
a53e2fff   hitier   New category/labe...
386
        n_pl = ProjectLabel(project=n_p, label=n_l)
90fdccc7   hitier   Now feed projects...
387
388
389
390
391
392
393
394
395
396
397
        db.session.add(n_pl)
        # Some projects have 2 domain labels in lesia db
        # That is not allowed any more in the new model.
        #
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            current_app.logger.error(
                "Error adding project to category/label: {} {} {}".format(n_p.name, n_l.category.name, n_l.name))
            continue
946dda30   hitier   New cli command u...
398
399
400
401
402
403
404
405
406
407
408
409
410

    agents = lesia_session.query(lesia_agent).all()
    for a in agents:
        n_a = Agent(id=a.IDagent, firstname=a.nom, secondname=a.prenom)
        db.session.add(n_a)
    db.session.commit()

    services = lesia_session.query(lesia_service).all()
    for s in services:
        n_s = Service(id=s.id, name=s.nom, abbr=s.abbreviation)
        db.session.add(n_s)
    db.session.commit()

946dda30   hitier   New cli command u...
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    fonctions = lesia_session.query(lesia_fonction).all()
    for f in fonctions:
        n_c = Capacity(id=f.id, name=f.nom)
        db.session.add(n_c)
    db.session.commit()

    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()


e0778a0d   hitier   New fake_lesia_na...
436
437
@bp.cli.command("fake_lesia_names")
def fake_lesia_names():
14f36f55   hitier   Move lesia init c...
438
    """
e0778a0d   hitier   New fake_lesia_na...
439
440
441
442
443
    Extract fake name from resources files to change names in db.
    Mainly after a lesia import, for confidential reasons

    Changes nams in tables:

14f36f55   hitier   Move lesia init c...
444
445
446
447
448
449
        - services
        - capacities
        - projects
    :return:
    """

e0778a0d   hitier   New fake_lesia_na...
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    current_app.logger.info("Faking names from resources files")
    # get  resources files
    #
    # 1- projects
    #
    fake_projects_file = os.path.join(current_app.config['PDC_RESOURCES_DIR'], 'fake-db-names', 'fake-projects.txt')
    with open(fake_projects_file, newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
        fake_projects_names = [', '.join(row) for row in spamreader]
    fake_projects_names_iterator = iter(fake_projects_names)

    # 2- functions/capacities
    #
    fake_capacities_file = os.path.join(current_app.config['PDC_RESOURCES_DIR'], 'fake-db-names',
                                        'fake-capacities.txt')
    with open(fake_capacities_file, newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
        fake_capacities_names = [row for [row] in spamreader]
    fake_capacities_names_iterator = iter(fake_capacities_names)

    # 3- services
    #
    fake_services_file = os.path.join(current_app.config['PDC_RESOURCES_DIR'], 'fake-db-names',
                                      'fake-services.txt')
    with open(fake_services_file, newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
        fake_services_names = [row for row in spamreader]
    fake_services_names_iterator = iter(fake_services_names)

    # Skip columns names
    #
    next(fake_projects_names_iterator)
    next(fake_capacities_names_iterator)
    next(fake_services_names_iterator)

    for s in Service.query.all():
        next_service = next(fake_services_names_iterator)
        s.name = next_service[0]
        s.abbr = next_service[1]

    for p in Project.query.all():
        p.name = next(fake_projects_names_iterator)

    for c in Capacity.query.all():
        c.name = next(fake_capacities_names_iterator)

    db.session.commit()

14f36f55   hitier   Move lesia init c...
498

a17327bf   hitier   New db feeding co...
499
@bp.cli.command("feed_periods")
fa86be39   hitier   Enhance error cat...
500
501
502
503
504
@click.option('--begin-year', '-b', 'begin_year', default=2005, help="the start year to begin periods with")
@click.option('--end-year', '-e', 'end_year', default=2025, help="the last year to end periods with")
def feed_periods(begin_year, end_year):
    """ Fill in the periods names in the database. """
    for y in range(begin_year, end_year):
a17327bf   hitier   New db feeding co...
505
506
507
508
        for s in ['S1', 'S2']:
            period_name = "{}_{}".format(y, s)
            p = Period(name=period_name)
            db.session.add(p)
fa86be39   hitier   Enhance error cat...
509
510
511
512
    try:
        db.session.commit()
    except IntegrityError:
        current_app.logger.error("Periods already exist")
a17327bf   hitier   New db feeding co...
513
514


d8a6b942   hitier   More install doc
515
516
517
518
@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. """
65b2833e   hitier   Fix some sonar co...
519
    for _ in range(0, 100):
335db4c0   hitier   Allow randoming c...
520
521
522
523
        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...
524
525
526
527
528
        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...
529
530
531
532
533
        # 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...
534
        if total_charge is not None and (total_charge + percent) >= 100:
e817ff5e   hitier   Random Charge Age...
535
536
            print("Skipping agent {} for period {}".format(agent_id, period_id))
            continue
335db4c0   hitier   Allow randoming c...
537
        charge = Charge(agent_id=agent_id,
a17327bf   hitier   New db feeding co...
538
539
540
541
542
543
544
545
546
547
                        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
548
@bp.cli.command('user_add')
a17327bf   hitier   New db feeding co...
549
550
@click.argument('email')
@click.argument('name')
3ed62121   hitier   Add login to user
551
@click.argument('login')
a17327bf   hitier   New db feeding co...
552
@click.argument('password')
149f7875   hitier   Now user_add acce...
553
554
@click.argument('role')
def user_add(email, name, login, password, role):
d8a6b942   hitier   More install doc
555
    """ Add a new user in db."""
149f7875   hitier   Now user_add acce...
556
    user = User.query.filter(User.name == name).one_or_none()
f1bb8c76   hitier   Move auth tests t...
557
558
    if user:
        current_app.logger.warn(f"user already exists {name}")
82642adb   hitier   Update routes and...
559
        return
149f7875   hitier   Now user_add acce...
560
    user = User(email=email, name=name, login=login, password=password, role=role)
a17327bf   hitier   New db feeding co...
561
562
    db.session.add(user)
    db.session.commit()
82642adb   hitier   Update routes and...
563
    current_app.logger.info(f"added {name}")
a17327bf   hitier   New db feeding co...
564
565


946dda30   hitier   New cli command u...
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@bp.cli.command('user_update')
@click.option('--name', '-n', 'name', default=None, help="the name to set for that user")
@click.option('--role', '-r', 'role', default=None, help="the role to set for that user")
@click.option('--email', '-e', 'email', default=None, help="the email to set for that user")
@click.option('--password', '-p', 'password', default=None, help="the password to set for that user")
@click.argument('user_id')
def user_update(user_id, name, role, email, password):
    """Update the user by given id and given parameters."""
    user = User.query.get(user_id)
    if not user:
        current_app.logger.error(f"such user_id doesnt exists {user_id}")
        return
    if name:
        user.name = name
        print(f"User --{user.name}-- name updated to {user.name}")
    if role:
        user.set_role(role)
        print(f"User --{user.name}-- role updated to {_roleToName[user.role]}")
    if email:
0e188a92   hitier   Import more agent...
585
        user.email = email
946dda30   hitier   New cli command u...
586
587
588
589
        print(f"User --{user.name}-- email updated to {user.email}")
    if password:
        print(f"User --{user.name}-- password updated")
        user.set_password(password)
0e188a92   hitier   Import more agent...
590
    if not (name or role or email or password):
946dda30   hitier   New cli command u...
591
592
593
594
595
596
597
598
599
600
601
602
603
        print(f"No update for user --{user.name}--")
    db.session.commit()


@bp.cli.command('user_delete')
@click.argument('user_id')
def user_delete(user_id):
    """Delete the user by given id (see user_show_all")."""
    user = User.query.get(user_id)
    db.session.delete(user)
    db.session.commit()


149f7875   hitier   Now user_add acce...
604
605
606
607
608
609
@bp.cli.command('show_roles')
def show_roles():
    """ List all available roles for a user"""
    print("\n".join(list(_nameToRole)))


d8a6b942   hitier   More install doc
610
611
612
@bp.cli.command('user_show_all')
def user_show_all():
    """ Show all users in db."""
4113c4f3   hitier   Fix user_show_all
613
614
    print("{:<5} {:<15} {:<15} {:<15}".format('id', 'name', 'login', 'email'))
    print("{:<5} {:<15} {:<15} {:<15}".format('-' * 5, '-' * 15, '-' * 15, '-' * 15))
a17327bf   hitier   New db feeding co...
615
616
    for user in User.query.all():
        print(user.login)
4113c4f3   hitier   Fix user_show_all
617
        print("{:<5} {:<15} {:<15} {:<15}".format(
a17327bf   hitier   New db feeding co...
618
619
620
            user.id,
            user.name,
            user.login,
a17327bf   hitier   New db feeding co...
621
622
            user.email
        ))