-
Notifications
You must be signed in to change notification settings - Fork 9
/
database.py
3242 lines (2824 loc) · 142 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# This file is part of Gertrude.
#
# Gertrude is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Gertrude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gertrude; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import operator
import math
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import *
from sqlalchemy_utils import database_exists
from sqlalchemy.orm.collections import collection, attribute_mapped_collection
from version import VERSION
from helpers import *
from parameters import *
import bcrypt
from config import config
DB_VERSION = 131
Base = declarative_base()
KEY_VERSION = "VERSION"
KEY_RELEASE = "RELEASE"
class DBSettings(Base):
__tablename__ = "data"
key = Column(String, primary_key=True)
value = Column(String)
class Timeslot(object):
def __init__(self, debut, fin, activity, **kwargs):
self.debut = debut
self.fin = fin
self.activity = activity
self.value = None # needed for TrancheCapacite compatibility
if isinstance(activity, int):
raise Exception("Not allowed integer activity")
for key, value in kwargs.items():
setattr(self, key, value)
def is_checkbox(self):
return self.activity.mode == MODE_SANS_HORAIRES
def is_presence(self):
return self.activity.mode == MODE_NORMAL
def get_duration(self, arrondi=SANS_ARRONDI):
# TODO a utiliser partout
return 0 if self.debut is None else 5 * GetDureeArrondie(arrondi, self.debut, self.fin)
def __repr__(self):
return "Timeslot %r %r-%r" % (self.activity.label if self.activity else None, self.debut, self.fin)
class Day(object):
def __init__(self):
self.timeslots = []
def get_state(self):
default = ABSENT
for timeslot in self.timeslots:
mode = timeslot.activity.mode
if mode < 0:
default = mode
elif mode == MODE_SALARIE_RECUP_HEURES_SUPP:
default = CONGES_RECUP_HEURES_SUPP
elif mode == MODE_ABSENCE_NON_PREVENUE:
default = ABSENCE_NON_PREVENUE
elif mode not in (MODE_PLACE_SOUHAITEE, MODE_SANS_HORAIRES, MODE_SYSTEMATIQUE_SANS_HORAIRES):
return PRESENT
return default
def get_activity_timeslots(self):
return [timeslot for timeslot in self.timeslots if timeslot.debut is not None]
def get_timeslots_per_activity_mode(self, activity_mode):
return [timeslot for timeslot in self.timeslots if timeslot.activity.mode == activity_mode]
def get_duration_per_activity_mode(self, activity_mode, mode_arrondi=SANS_ARRONDI):
return sum([timeslot.get_duration(mode_arrondi) for timeslot in self.get_timeslots_per_activity_mode(activity_mode)]) / 60
def get_duration_permanences(self):
return self.get_duration_per_activity_mode(MODE_PERMANENCE)
def get_duration(self, mode_arrondi=SANS_ARRONDI):
return self.get_duration_per_activity_mode(0, mode_arrondi)
def GetPlageHoraire(self):
debut, fin = None, None
for timeslot in self.timeslots:
if timeslot.debut and timeslot.fin and timeslot.activity.mode == MODE_PRESENCE:
if not debut or timeslot.debut < debut:
debut = timeslot.debut / 12
if not fin or timeslot.fin > fin:
fin = timeslot.fin / 12
return debut, fin
def GetHeureArrivee(self):
arrivee, depart = self.GetPlageHoraire()
return "" if arrivee is None else GetHeureString(arrivee)
def GetHeureDepart(self):
arrivee, depart = self.GetPlageHoraire()
return "" if depart is None else GetHeureString(depart)
def GetHeureArriveeDepart(self):
arrivee, depart = self.GetPlageHoraire()
return "" if (arrivee is None and depart is None) else ("de %s à %s" % (GetHeureString(arrivee), GetHeureString(depart)))
def GetActivity(self, heure):
if not isinstance(heure, int):
heure = int(round(heure * 12))
for timeslot in self.timeslots:
if timeslot.debut <= heure < timeslot.fin:
return timeslot
else:
return None
def __str__(self):
return "Day timeslots=%r" % self.timeslots
class DayCollection(dict):
def __init__(self, key):
self.keyfunc = operator.attrgetter(key)
@collection.iterator
def __iter__(self):
for day in self.values():
for timeslot in day.timeslots:
yield timeslot
@collection.appender
def add(self, timeslot):
key = self.keyfunc(timeslot)
if not self.get(key):
dict.__setitem__(self, key, Day())
self[key].timeslots.append(timeslot)
@collection.remover
def remove(self, timeslot):
key = self.keyfunc(timeslot)
timeslots = self[key].timeslots
timeslots.remove(timeslot)
if not timeslots:
dict.__delitem__(self, key)
class PeriodeReference(object):
def get_days_per_week(self):
days = len(self.days)
if self.duree_reference > 7:
days //= (self.duree_reference // 7)
return days
def get_duration_per_week(self, mode_arrondi=SANS_ARRONDI):
duration = 0
for day in self.days.values():
duration += day.get_duration(mode_arrondi)
if self.duree_reference > 7:
duration /= (self.duree_reference // 7)
return duration
def get_day_from_index(self, index):
return self.days.get(index, Day())
def get_day_from_date(self, date):
if self.duree_reference > 7:
weekday = ((date - self.debut).days + self.debut.weekday()) % self.duree_reference
else:
weekday = date.weekday()
return self.days.get(weekday, Day())
def GetFin(self):
return self.fin if self.fin else datetime.date.max
class Creche(Base):
__tablename__ = "creche"
idx = Column(Integer, primary_key=True)
nom = Column(String)
adresse = Column(String)
code_postal = Column(Integer)
ville = Column(String)
telephone = Column(String)
ouverture = Column(Float, default=7.5)
fermeture = Column(Float, default=18.5)
affichage_min = Column(Float, default=7)
affichage_max = Column(Float, default=19)
granularite = Column(Integer, default=15)
preinscriptions = Column(Boolean, default=False)
presences_supplementaires = Column(Boolean, default=True)
modes_inscription = Column(Integer, default=TOUS_MODES_ACCUEIL)
minimum_maladie = Column(Integer, default=3)
email = Column(String)
email_changements_planning = Column(String)
type = Column(Integer, default=TYPE_PARENTAL)
mode_saisie_planning = Column(Integer, default=SAISIE_HORAIRE)
periode_revenus = Column(Integer, default=REVENUS_YM2)
mode_facturation = Column(Integer, default=FACTURATION_PSU)
temps_facturation = Column(Integer, default=FACTURATION_FIN_MOIS)
repartition = Column(Integer, default=REPARTITION_MENSUALISATION_12MOIS)
prorata = Column(Integer, default=PRORATA_JOURS_OUVRES)
conges_inscription = Column(Integer, default=0)
tarification_activites = Column(Integer, default=0)
traitement_maladie = Column(Integer, default=DEDUCTION_MALADIE_AVEC_CARENCE_JOURS_OUVRES)
facturation_jours_feries = Column(Integer, default=ABSENCES_DEDUITES_EN_SEMAINES)
facturation_periode_adaptation = Column(Integer, default=PERIODE_ADAPTATION_FACTUREE_NORMALEMENT)
_formule_taux_effort = Column(String, name="formule_taux_effort", default="None")
masque_alertes = Column(Integer, default=0)
age_maximum = Column(Integer, default=3)
seuil_alerte_inscription = Column(Integer, default=3)
cloture_facturation = Column(Integer, default=0)
arrondi_heures = Column(Integer, default=SANS_ARRONDI)
arrondi_facturation = Column(Integer, default=SANS_ARRONDI)
arrondi_facturation_periode_adaptation = Column(Integer, default=SANS_ARRONDI)
arrondi_mensualisation = Column(Integer, default=ARRONDI_HEURE_PLUS_PROCHE)
arrondi_heures_salaries = Column(Integer, default=SANS_ARRONDI)
arrondi_mensualisation_euros = Column(Integer, default=SANS_ARRONDI)
arrondi_semaines = Column(Integer, default=ARRONDI_SEMAINE_SUPERIEURE)
gestion_maladie_hospitalisation = Column(Boolean, default=False)
gestion_conges_sans_solde = Column(Boolean, default=False)
tri_inscriptions = Column(Integer, default=TRI_NOM)
tri_planning = Column(Integer, default=TRI_NOM)
tri_factures = Column(Integer, default=TRI_NOM)
smtp_server = Column(String)
caf_email = Column(String)
numero_caf = Column(String)
numero_dossier_afc = Column(String)
mode_accueil_defaut = Column(Integer, default=MODE_TEMPS_PARTIEL)
gestion_absences_non_prevenues = Column(Boolean, default=False)
gestion_maladie_sans_justificatif = Column(Boolean, default=False)
gestion_preavis_conges = Column(Boolean, default=False)
gestion_depart_anticipe = Column(Boolean)
alerte_depassement_planning = Column(Boolean, default=False)
last_tablette_synchro = Column(String)
changement_groupe_auto = Column(Boolean, default=False)
allergies = Column(String)
regularisation_fin_contrat = Column(Boolean, default=True)
regularisation_conges_non_pris = Column(Boolean, default=True)
date_raz_permanences = Column(Date)
conges_payes_salaries = Column(Integer, default=25)
conges_supplementaires_salaries = Column(Integer, default=0)
cout_journalier = Column(Float, default=0)
iban = Column(String)
bic = Column(String)
creditor_id = Column(String)
societe = Column(String)
siret = Column(String)
gestion_plannings_salaries = Column(Integer, default=0)
delai_paiement_familles = Column(Integer)
users = relationship("User", cascade="all, delete-orphan")
sites = relationship("Site", cascade="all, delete-orphan")
bureaux = relationship("Bureau", cascade="all, delete-orphan")
professeurs = relationship("Professeur", cascade="all, delete-orphan")
categories = relationship("Categorie", cascade="all, delete-orphan")
groupes = relationship("Groupe", cascade="all, delete-orphan")
reservataires = relationship("Reservataire", cascade="all, delete-orphan")
tarifs_horaires = relationship("TarifHoraire", cascade="all, delete-orphan")
tarifs_speciaux = relationship("TarifSpecial", cascade="all, delete-orphan")
familles = relationship("Famille", cascade="all, delete-orphan")
inscrits = relationship("Inscrit", cascade="all, delete-orphan")
salaries = relationship("Salarie", cascade="all, delete-orphan")
_activites = relationship("Activite", cascade="all, delete-orphan")
plages_horaires = relationship("PlageHoraire", cascade="all, delete-orphan")
_conges = relationship("CongeStructure", cascade="all, delete-orphan")
baremes_caf = relationship("BaremeCAF", cascade="all, delete-orphan")
numeros_facture = relationship("NumeroFacture", collection_class=attribute_mapped_collection("date"), cascade="all, delete-orphan")
tranches_capacite = relationship("TrancheCapacite", collection_class=lambda: DayCollection("jour"), cascade="all, delete-orphan")
charges = relationship("Charge", collection_class=attribute_mapped_collection("date"), cascade="all, delete-orphan")
alertes = relationship("Alerte", collection_class=attribute_mapped_collection("texte"), cascade="all, delete-orphan")
food_needs = relationship("FoodNeed", cascade="all, delete-orphan")
def __init__(self, **kwargs):
Base.__init__(self, **kwargs)
self.update()
def update(self):
self.periodes_fermeture = {}
self.jours_fermeture = {}
self.jours_fete = set()
self.jours_weekend = []
self.mois_sans_facture = {}
self.mois_facture_uniquement_heures_supp = {}
self.liste_conges = []
self.conges = []
self.feries = {}
self.states = {}
self.activites = []
self.formule_taux_effort = None
@reconstructor
def init_on_load(self):
self.update()
# TODO split conges / feries
self.formule_taux_effort = eval(self._formule_taux_effort)
self.UpdateFormuleTauxEffort(changed=False)
for activity in self._activites:
if activity.mode <= 0:
self.states[activity.mode] = activity
else:
self.activites.append(activity)
for conge in self._conges:
if conge.debut in [tmp[0] for tmp in jours_fermeture]:
self.feries[conge.debut] = conge
else:
self.conges.append(conge)
self.calcule_jours_conges()
def get_activite_by_id(self, id):
for activite in self._activites:
if activite.idx == id:
return activite
else:
return None
def select_inscriptions(self, start, end):
for inscrit in self.inscrits:
for inscription in inscrit.get_inscriptions(start, end):
yield inscription
def select_inscrits(self, start, end, site=None, handicap=None, reservataire=None):
for inscrit in self.inscrits:
if inscrit.is_present(start, end, site, handicap, reservataire):
yield inscrit
def select_reservataires(self, start, end):
for reservataire in self.reservataires:
if ((reservataire.fin is None or reservataire.fin >= start) and
reservataire.debut is not None and (not end or reservataire.debut <= end)):
yield reservataire
def get_next_activity_value(self):
values = self.activites.keys()
return max(values) + 1
def add_activite(self, activity):
self._activites.append(activity)
if activity.mode < 0:
self.states[activity.mode] = activity
else:
self.activites.append(activity)
def delete_activite(self, activity):
self._activites.remove(activity)
self.activites.remove(activity)
def add_ferie(self, conge):
self._conges.append(conge)
self.feries[conge.debut] = conge
self.calcule_jours_conges()
def delete_ferie(self, conge):
self._conges.remove(conge)
del self.feries[conge.debut]
self.calcule_jours_conges()
def add_conge(self, conge):
self._conges.append(conge)
self.conges.append(conge)
self.calcule_jours_conges()
def delete_conge(self, conge):
self._conges.remove(conge)
self.conges.remove(conge)
self.calcule_jours_conges()
def calcule_jours_conges(self):
self.periodes_fermeture = {}
self.jours_fermeture = {}
self.jours_fete = set()
self.jours_weekend = []
self.jours_fermeture_non_prevus = {}
self.mois_sans_facture = {}
self.mois_facture_uniquement_heures_supp = {}
for year in range(config.first_date.year, config.last_date.year + 1):
self.mois_sans_facture[year] = set()
self.mois_facture_uniquement_heures_supp[year] = set()
for label, func, enable in jours_fermeture:
if label in self.feries:
tmp = func(year)
if isinstance(tmp, list):
for j in tmp:
self.jours_fermeture[j] = self.feries[label]
if label == "Week-end":
self.jours_weekend.append(j)
else:
self.jours_fermeture[tmp] = self.feries[label]
self.jours_feries = self.jours_fermeture.keys()
self.jours_fete = set(self.jours_feries) - set(self.jours_weekend)
self.jours_conges = set()
self.liste_conges = []
def AddPeriode(debut, fin, conge):
date = debut
while date <= fin:
if conge.options == FERMETURE_NON_PRISE_EN_COMPTE_MENSUALISATION:
if date not in self.jours_feries:
self.jours_fermeture_non_prevus[date] = conge
else:
self.periodes_fermeture[date] = conge
self.jours_fermeture[date] = conge
if date not in self.jours_feries:
self.jours_conges.add(date)
date += datetime.timedelta(1)
self.liste_conges.append((debut, fin))
for conge in self.conges:
if conge.options == MOIS_SANS_FACTURE:
date = str2date(conge.debut, day=1)
if date and date.year in self.mois_sans_facture.keys():
self.mois_sans_facture[date.year].add(date.month)
elif conge.debut in months:
mois = months.index(conge.debut) + 1
for key in self.mois_sans_facture:
self.mois_sans_facture[key].add(mois)
else:
try:
mois = int(conge.debut)
for key in self.mois_sans_facture:
self.mois_sans_facture[key].add(mois)
except:
pass
elif conge.options == MOIS_FACTURE_UNIQUEMENT_HEURES_SUPP:
date = str2date(conge.debut, day=1)
if date and date.year in self.mois_facture_uniquement_heures_supp.keys():
self.mois_facture_uniquement_heures_supp[date.year].add(date.month)
elif conge.debut in months:
mois = months.index(conge.debut) + 1
for key in self.mois_facture_uniquement_heures_supp:
self.mois_facture_uniquement_heures_supp[key].add(mois)
else:
try:
mois = int(conge.debut)
for key in self.mois_facture_uniquement_heures_supp:
self.mois_facture_uniquement_heures_supp[key].add(mois)
except:
pass
else:
try:
count = conge.debut.count('/')
if count == 2:
debut = str2date(conge.debut)
if conge.fin.strip() == "":
fin = debut
else:
fin = str2date(conge.fin)
AddPeriode(debut, fin, conge)
elif count == 1:
for year in range(config.first_date.year, config.last_date.year + 1):
debut = str2date(conge.debut, year)
if conge.fin.strip() == "":
fin = debut
else:
fin = str2date(conge.fin, year)
AddPeriode(debut, fin, conge)
except:
pass
self.jours_fete = list(self.jours_fete)
self.jours_feries = list(self.jours_feries)
self.jours_conges = list(self.jours_conges)
def GetDateRevenus(self, date):
if self.periode_revenus == REVENUS_CAFPRO:
return date
elif date >= datetime.date(2008, 9, 1):
return IncrDate(date, years=-2)
elif date < datetime.date(date.year, 9, 1):
return datetime.date(date.year - 2, 1, 1)
else:
return datetime.date(date.year - 1, 1, 1)
def GetHeuresAccueil(self, jour):
result = 0
for timeslot in self.tranches_capacite.get(jour, Day()).timeslots:
result += timeslot.value * (timeslot.fin - timeslot.debut)
return result / 12
def get_factures_list(self):
result = []
date = config.get_first_monday()
while date <= datetime.date.today():
result.append(date)
date = GetNextMonthStart(date)
return result
def get_capacite(self, jour=None, tranche=None):
if jour is None:
jours, result = 0, 0.0
for jour in range(7):
if self.is_jour_semaine_travaille(jour):
jours += 1
result += self.get_capacite(jour)
return result / jours
elif tranche is None:
return self.GetHeuresAccueil(jour) / self.get_amplitude_horaire()
else:
for start, end, value in self.tranches_capacite[jour].activites:
if start <= tranche < end:
return value
else:
return 0
def is_jour_semaine_travaille(self, day):
day %= 7
if days[day] in self.feries:
return False
elif day == 5 or day == 6:
return "Week-end" not in self.feries
else:
return True
def get_nombre_jours_semaine_travailles(self):
result = 0
for day in range(7):
if self.is_jour_semaine_travaille(day):
result += 1
return result
def get_amplitude_horaire(self):
return self.fermeture - self.ouverture
def get_allergies(self):
return [allergie.strip() for allergie in self.allergies.split(",") if allergie.strip()]
def are_revenus_needed(self):
if self.mode_facturation in (FACTURATION_FORFAIT_10H, FACTURATION_PSU, FACTURATION_PSU_TAUX_PERSONNALISES):
return True
elif self.mode_facturation == FACTURATION_FORFAIT_MENSUEL:
return False
for tarif in self.tarifs_horaires:
if tarif.formule:
for cas in tarif.formule:
if "revenus" in cas[0] or "paje" in cas[0]:
return True
return False
def GetPlagesOuvertureArray(self, affichage=False, conversion=True):
if affichage:
result = [(self.affichage_min, self.affichage_max)]
else:
result = [(self.ouverture, self.fermeture)]
for plage in self.plages_horaires:
if plage.flags == PLAGE_FERMETURE and plage.debut and plage.fin > plage.debut:
for i, (debut, fin) in enumerate(result):
if plage.debut > debut and plage.fin < fin:
result[i] = (debut, plage.debut)
result.insert(i + 1, (plage.fin, fin))
break
if conversion:
result = [(int(debut * (60 // BASE_GRANULARITY)), int(fin * (60 // BASE_GRANULARITY))) for debut, fin in
result]
return result
def GetPlagesArray(self, plage_type, conversion=True):
result = []
for plage in self.plages_horaires:
if plage.flags == plage_type and plage.debut and plage.fin > plage.debut:
result.append((plage.debut, plage.fin))
if conversion:
result = [(int(debut * (60 // BASE_GRANULARITY)), int(fin * (60 // BASE_GRANULARITY))) for debut, fin in
result]
return result
def get_activites_avec_horaires(self):
return [activite for activite in self.activites if activite.has_horaires()]
def get_activites_sans_horaires(self):
return [activite for activite in self.activites if activite.mode == MODE_SANS_HORAIRES]
def has_activites_avec_horaires(self):
for activite in self.activites:
if activite.has_horaires():
return True
return False
def eval_formule_tarif(self, formule, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs, site, debut):
# print 'eval_formule_tarif', 'mode=%d' % mode, handicap, 'revenus=%f' % revenus, 'enfants=%d' % enfants, 'jours=%d' % jours, 'heures=%f' % heures, reservataire, nom, 'parents=%d' % parents, chomage, conge_parental, 'heures_mois=%f' % heures_mois, heure_mois
hg = MODE_HALTE_GARDERIE
creche = MODE_CRECHE
forfait = MODE_FORFAIT_MENSUEL
urgence = MODE_ACCUEIL_URGENCE
site = site.lower()
debut = str(debut) if isinstance(debut, datetime.date) else ""
for tarif in self.tarifs_speciaux:
try:
exec("%s = %r" % (tarif.label.lower().replace(" ", "_"), tarifs & (1 << tarif.idx)))
except:
pass
try:
for cas in formule:
if heure_mois is None and "heure_mois" in cas[0]:
return None, None
elif eval(cas[0]):
# print cas[0], cas[1]
return cas[1], cas[2]
else:
raise Exception("Aucune condition ne matche")
except:
raise Exception("Erreur dans la formule")
def eval_formule_taux_effort(self, formule, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs):
# print 'eval_formule_taux_effort', 'mode=%d' % mode, handicap, 'revenus=%f' % revenus, 'enfants=%d' % enfants, 'jours=%d' % jours, 'heures=%f' % heures, reservataire, nom, 'parents=%d' % parents, chomage, conge_parental, 'heures_mois=%f' % heures_mois, heure_mois
hg = MODE_HALTE_GARDERIE
creche = MODE_CRECHE
forfait = MODE_FORFAIT_MENSUEL
urgence = MODE_ACCUEIL_URGENCE
for tarif in self.tarifs_speciaux:
try:
exec("%s = %r" % (tarif.label.lower().replace(" ", "_"), tarifs & (1 << tarif.idx)))
except:
pass
try:
for cas in formule:
if heure_mois is None and "heure_mois" in cas[0]:
return None
elif eval(cas[0]):
return cas[1]
else:
raise Exception("Aucune condition ne matche")
except:
raise Exception("Erreur dans la formule")
def CheckFormule(self, formule, index):
hg = MODE_HALTE_GARDERIE
creche = MODE_CRECHE
forfait = MODE_FORFAIT_MENSUEL
urgence = MODE_ACCUEIL_URGENCE
handicap = False
chomage = 0
conge_parental = 0
mode = hg
revenus = 20000
jours = 5
heures = 60
heures_mois = 60 * 4.33
heure_mois = heures_mois
parents = 2
enfants = 1
reservataire = False
nom = "gertrude"
site = ""
paje = paje1
for tarif in self.tarifs_speciaux:
try:
exec("%s = False" % tarif.label.lower().replace(" ", "_"))
except:
pass
try:
test = eval(formule[index][0])
return True
except Exception as e:
print(e)
return False
def get_formule_conversion_taux_effort(self, formule):
if formule:
result = []
for cas in formule:
condition = cas[0].strip()
if condition == "":
condition = "True"
else:
condition = condition.lower(). \
replace(" et ", " and "). \
replace(" ou ", " or "). \
replace("!=", "__<>"). \
replace("<=", "__<eq"). \
replace(">=", "__>eq"). \
replace("=", "=="). \
replace("__<>", "!="). \
replace("__<eq", "<="). \
replace("__>eq", ">=")
result.append([condition, cas[1], cas[0]])
return result
else:
return None
def UpdateFormuleTauxEffort(self, changed=True):
if changed:
print('update formule_taux_effort', self.formule_taux_effort)
self._formule_taux_effort = str(self.formule_taux_effort)
self.conversion_formule_taux_effort = self.get_formule_conversion_taux_effort(self.formule_taux_effort)
def EvalTauxEffort(self, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs):
return self.eval_formule_taux_effort(self.conversion_formule_taux_effort, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs)
def eval_tarif(self, date, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs, site, debut):
conversion_formule = Select(self.tarifs_horaires, date).conversion_formule
return self.eval_formule_tarif(conversion_formule, mode, handicap, revenus, enfants, jours, heures, reservataire, nom, parents, chomage, conge_parental, heures_mois, heure_mois, paje, tarifs, site, debut)
def GetAllergies(self):
return [allergie.strip() for allergie in self.allergies.split(",") if allergie.strip()]
def GetObject(self, objects, idx):
try:
idx = int(idx)
for o in objects:
if o.idx == idx:
return o
except:
pass
return None
def GetSite(self, idx):
return self.GetObject(self.sites, idx)
def GetInscrit(self, idx):
return self.GetObject(self.inscrits, idx)
def GetReservataire(self, idx):
return self.GetObject(self.reservataires, idx)
def GetSalarie(self, idx):
return self.GetObject(self.salaries, idx)
class Site(Base):
__tablename__ = "sites"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
nom = Column(String)
adresse = Column(String)
code_postal = Column(Integer)
ville = Column(String)
telephone = Column(String)
email = Column(String)
societe = Column(String)
siret = Column(String)
capacite = Column(Integer)
groupe = Column(Integer)
def get_name(self):
return self.nom if self.nom else "<sans nom>"
def get_factures_list(self):
return self.creche.get_factures_list()
class FoodNeed(Base):
__tablename__ = "food_needs"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
label = Column(String)
tranche_4_6 = Column(Integer)
tranche_6_12 = Column(Integer)
tranche_12_18 = Column(Integer)
tranche_18_24 = Column(Integer)
tranche_24_ = Column(Integer)
class Bureau(Base):
__tablename__ = "bureaux"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
debut = Column(Date)
fin = Column(Date)
president = Column(String)
vice_president = Column(String)
tresorier = Column(String)
secretaire = Column(String)
directeur = Column(String)
gerant = Column(String)
directeur_adjoint = Column(String)
comptable = Column(String)
class BaremeCAF(Base):
__tablename__ = "baremescaf"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
debut = Column(Date)
fin = Column(Date)
plancher = Column(Integer)
plafond = Column(Integer)
def __init__(self, creche, **kwargs):
Base.__init__(self, creche=creche, **kwargs)
class TarifHoraire(Base):
__tablename__ = "tarifs_horaires"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
debut = Column(Date)
fin = Column(Date)
_formule = Column(String, name="formule")
def __init__(self, creche, formule=[], **kwargs):
Base.__init__(self, creche=creche, **kwargs)
self.formule = formule
self.UpdateFormule(changed=True)
@reconstructor
def init_on_load(self):
self.formule = eval(self._formule)
self.conversion_formule = self.get_formule_conversion(self.formule)
def UpdateFormule(self, changed=True):
if changed:
# print('update formule_taux_horaire', self.formule)
self._formule = str(self.formule)
self.conversion_formule = self.get_formule_conversion(self.formule)
def get_formule_conversion(self, formule):
if formule:
result = []
for cas in formule:
condition = cas[0].strip()
if condition == "":
condition = "True"
else:
condition = condition.lower(). \
replace(" et ", " and "). \
replace(" ou ", " or "). \
replace("!=", "__<>"). \
replace("<=", "__<eq"). \
replace(">=", "__>eq"). \
replace("=", "=="). \
replace("__<>", "!="). \
replace("__<eq", "<="). \
replace("__>eq", ">=")
result.append([condition, cas[1], cas[2], cas[0]])
return result
else:
return None
def CheckFormule(self, index):
return self.creche.CheckFormule(self.conversion_formule, index)
class Reservataire(Base):
__tablename__ = "reservataires"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
debut = Column(Date)
fin = Column(Date)
nom = Column(String, default="")
adresse = Column(String)
code_postal = Column(Integer)
ville = Column(String)
telephone = Column(String)
email = Column(String)
places = Column(Integer)
heures_jour = Column(Float)
heures_semaine = Column(Float)
options = Column(Integer)
periode_facturation = Column(Integer)
delai_paiement = Column(Integer)
tarif = Column(Float)
encaissements = relationship("EncaissementReservataire", cascade="all, delete-orphan")
corrections = [] # fake
def __init__(self, creche, nom="", **kwargs):
Base.__init__(self, creche=creche, nom=nom)
@reconstructor
def init_on_load(self):
if self.nom is None:
self.nom = ""
def slug(self):
return "reservataire-%d" % self.idx
def get_delai_paiement(self):
return self.delai_paiement
def has_facture(self, date, site=None):
return date in self.get_factures_list()
def get_facture_cloturee(self, date):
return None
def get_factures_list(self):
result = []
if self.debut and self.periode_facturation:
date = datetime.date(self.debut.year, 9, 1) if self.debut.month >= 9 else datetime.date(self.debut.year - 1, 9, 1)
while date <= datetime.date.today() and (not self.fin or date < self.fin):
next_date = date
for i in range(self.periode_facturation):
next_date = GetNextMonthStart(next_date)
if self.debut < next_date:
result.append(date)
date = next_date
return result
class Activite(Base):
__tablename__ = "activities"
idx = Column(Integer, primary_key=True)
creche_id = Column(Integer, ForeignKey("creche.idx"))
creche = relationship(Creche)
label = Column(String)
# value = Column(Integer)
mode = Column(Integer)
_couleur = Column(String, name="couleur")
_couleur_supplement = Column(String, name="couleur_supplement", default="")
formule_tarif = Column(String)
owner = Column(Integer)
flags = Column(Integer)
timeslots_plannings_enfants = relationship("TimeslotInscription", cascade="all, delete-orphan")
timeslots_enfants = relationship("TimeslotInscrit", cascade="all, delete-orphan")
timeslots_plannings_salaries = relationship("TimeslotPlanningSalarie", cascade="all, delete-orphan")
timeslots_salaries = relationship("TimeslotSalarie", cascade="all, delete-orphan")
def __init__(self, creche, **kwargs):
Base.__init__(self, creche=creche, **kwargs)
self.couleur = self.get_color(self._couleur)
self.couleur_supplement = self.get_color(self._couleur_supplement)
@reconstructor
def init_on_load(self):
self.couleur = self.get_color(self._couleur)
self.couleur_supplement = self.get_color(self._couleur_supplement)
@staticmethod
def get_color(color, default=[0, 0, 0, 255, 100]):
if color:
try:
return eval(color)
except Exception as e:
print("Exception couleur '%s'" % color, e)
return default
else:
return default
def set_color(self, key, value):
if key in ("couleur", "couleur_supplement"):
setattr(self, key, value)
setattr(self, "_%s" % key, str(value))
def has_summary(self):
return self.mode >= 0 and self.mode not in (MODE_CONGES, MODE_PLACE_SOUHAITEE, MODE_SYSTEMATIQUE_SANS_HORAIRES, MODE_SYSTEMATIQUE_SANS_HORAIRES_MENSUALISE, MODE_ABSENCE_NON_PREVENUE, MODE_SALARIE_HEURES_SUPP, MODE_SALARIE_RECUP_HEURES_SUPP)
def has_horaires(self):
return self.mode in (MODE_PRESENCE, MODE_NORMAL, MODE_LIBERE_PLACE, MODE_PLACE_SOUHAITEE, MODE_PRESENCE_NON_FACTUREE, MODE_ABSENCE_NON_PREVENUE, MODE_PRESENCE_SUPPLEMENTAIRE, MODE_PERMANENCE, MODE_CONGES)
def EvalTarif(self, inscrit, date, montant_heure_garde=0.0, reservataire=False):
if self.formule_tarif and self.formule_tarif.strip():
enfants, enfants_inscrits = inscrit.famille.GetEnfantsCount(date)[0:2]
for tarif in self.creche.tarifs_speciaux:
try:
exec("%s = %r" % (tarif.label.lower().replace(" ", "_"), inscrit.famille.tarifs & (1 << tarif.idx)))
except Exception as e:
print("Exception tarif special", e)
try:
return eval(self.formule_tarif)
except Exception as e:
print("Exception tarif activite", e)
return 0.0
else:
return 0.0
class ContratSalarie(Base):
__tablename__ = "contrats_salaries"
idx = Column(Integer, primary_key=True)
salarie_id = Column(Integer, ForeignKey("employes.idx"))
salarie = relationship("Salarie")
site_id = Column(Integer, ForeignKey("sites.idx"))
site = relationship("Site")
debut = Column(Date)
fin = Column(Date)
fonction = Column(String)
plannings = relationship("PlanningSalarie", cascade="all, delete-orphan")
def __init__(self, salarie, site=None, debut=None, fin=None, fonction=None):
Base.__init__(self, salarie=salarie, site=site, debut=debut, fin=fin, fonction=fonction)
self.plannings.append(PlanningSalarie(self))
def __getattribute__(self, item):
if item == "duree_reference":
if not self.plannings: