aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_repr.py
blob: b09f37ecb63c09519faa9b0cda2a176d0ce54f62 (plain)
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
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas Touhey <thomas@touhey.fr>
# This file is part of the sgdfi project, which is MIT-licensed.
#******************************************************************************
""" Main object to interact with SGDF's intranet. """

import regex as _re

from ._util import IID, Enum as _Enum, \
	Base, Property as _Property, \
	IIDProperty as _IIDProperty, DateProperty as _DateProperty, \
	BoolProperty as _BoolProperty, EnumProperty as _EnumProperty, \
	ArrayProperty as _ArrayProperty, TextProperty as _TextProperty, \
	ObjectProperty as _ObjectProperty, ValueProperty as _ValueProperty
from ._dbs import Department, DepartmentData as _DepartmentData, \
	OperationType, OperationTypeData as _OperationTypeData, \
	Function, FunctionRawData, FunctionData as _FunctionData, StructureType, \
	StructureTypeData as _StructureTypeData, StructureStatus, \
	StructureStatusData as _StructureStatusData, StructureSpeciality, \
	StructureSpecialityData as _StructureSpecialityData, \
	AllocationsRegime, EventTypeData as _EventTypeData, Code as _Code

__all__ = ["Base", "IID", "Title", "Structure", "Adherent",
	"RallyRegistration", "Camp", "Place", "Operation", "OperationType",
	"Function", "Event", "StructureType", "StructureStatus",
	"StructureSpeciality", "AllocationsRegime", "Department"]

_Base = Base

# ---
# Internal classes.
# ---

class Title(_Enum):
	""" Unknown. """
	UNKNOWN = 0

	""" Mister (monsieur). """
	MISTER = 1

	""" Miss (madame / mademoiselle). """
	MISS = 2

class _Name:
	""" A person's name. """

	def __init__(self, value = None):
		self.__title  = None
		self.__first  = None
		self.__common = None
		self.__last   = None

		if value is None:
			return
		if type(value) != str:
			raise ValueError("Expected a string.")

		value = value.split()
		if not value:
			return

		# Try to decode the title (if there is one).

		fst = value.pop(0)
		title = fst.upper().replace('.', '')
		if   title == 'M':
			self.__title = Title.MISTER
		elif title == 'MME':
			self.__title = Title.MISS
		else:
			self.__title = Title.UNKNOWN
			value.insert(0, fst)

		# Get the common name.

		self.__common = ' '.join(value[:-1])
		self.__first = value[-1]

	def __repr__(self):
		p = []
		ful = str(self)
		if ful:
			p.append(f"full = {repr(ful)}")
		if self.__common is not None and self.__last is not None and \
			self.__last != self.__common:
			p.append(f"last = {repr(self.__last)}")

		return f"{self.__class__.__name__}({', '.join(p)})"

	def __bool__(self):
		return bool(str(self))

	def __str__(self):
		ops = []

		titl = {Title.MISTER: "M.", Title.MISS: "Mme"}.get(self.__title, None)
		if titl is not None:
			ops.append(titl)

		if self.__common is not None:
			ops.append(self.__common)
		if self.__first is not None:
			ops.append(self.__first)

		return ' '.join(ops)

	@property
	def title(self):
		""" Title. """

		return self.__title

	@title.setter
	def title(self, value):
		try:
			self.__title = Title(value)
		except ValueError:
			self.__title = Title.UNKNOWN

	@property
	def first(self):
		""" First name (prénom). """

		return self.__first

	@property
	def common(self):
		""" Common name (nom de famille). """

		return self.__common

	@property
	def last(self):
		""" Last name (nom de jeune fille). """

		return self.__last

	@last.setter
	def last(self, value):
		if value is None:
			self.__last = None
			return
		if type(value) != str:
			raise ValueError("Expected a string.")

		self.__last = value

# ---
# Specific properties.
# ---

class _FunctionProperty(_Property):
	""" Function. """

	def init(self):
		self.__data = None

	def get(self):
		return self.__data

	def set(self, value):
		if value is None:
			self.__data = None
			return

		self.__data = _FunctionData(value)

	def delete(self):
		self.__data = None

class _OperationFields:
	""" Operation fields. """

	def __init__(self, value, sep = ','):
		if type(value) != str:
			raise ValueError("fields should be string")

		pattern = f'([^{sep}\(]*(?P<par>\(([^\(\)]*(?&par)*)*\))*)*'
		reg = _re.compile(pattern, _re.S)

		fields = {}
		lastfield = None
		for k in reg.finditer(value):
			ma = k.group(0)
			if not ma:
				continue

			# From here, we have a valid group.
			# If we have reached the last field already, just append it to
			# the last key. Otherwise, check if it is a new group or not.

			if lastfield and lastkey == lastfield:
				fields[lastkey] += sep + ma
				continue

			g = ma.split(':')
			if len(g) < 2:
				if not lastkey:
					continue

				fields[lastkey] += sep + ma
				continue

			# New group!

			lastkey = g[0].strip()
			fields[lastkey] = ':'.join(g[1:]).lstrip()

		self.__fields = fields

	def __repr__(self):
		return f"OperationFields({repr(self.__fields)})"

	def __iter__(self):
		return iter(self.__fields)

	def __getitem__(self, key):
		return self.__fields[key]

class _OperationFieldsProperty(_Property):
	""" Operation fields. """

	def init(self, sep = ','):
		self.__value = None
		self.__sep = sep

	def get(self):
		return self.__value

	def set(self, value):
		if value is None:
			self.__value = None
			return

		self.__value = _OperationFields(value, self.__sep)

	def delete(self):
		self.__value = None

# ---
# Objects.
# ---

class Structure(_Base):
	""" A structure (unit, group, territory, …). """

	iid = _IIDProperty()
	type = _ValueProperty(cls = _StructureTypeData)
	name = _TextProperty()
	code = _ValueProperty(cls = _Code)
	# TODO: private code thingy?
	description = _TextProperty(not_empty = True)
	status = _ValueProperty(cls = _StructureStatusData)
	hemisphere = _TextProperty()
	address = _TextProperty(not_empty = True)
	postal_code = _TextProperty()
	town = _TextProperty()
	country = _TextProperty(not_empty = True)
	department = _ValueProperty(cls = _DepartmentData)
	phone = _TextProperty(not_empty = True)
	fax = _TextProperty(not_empty = True)
	email = _TextProperty(not_empty = True)
	website = _TextProperty(not_empty = True)
	start = _DateProperty()
	location_info = _TextProperty(not_empty = True)
	gps_latitude = _TextProperty(not_empty = True)
	gps_longitude = _TextProperty(not_empty = True)

class Adherent(_Base):
	""" A person who is part of the organization. """

	iid = _IIDProperty()
	name = _ValueProperty(cls = _Name, default = _Name())
	code = _ValueProperty(cls = _Code)
	function = _ValueProperty(cls = _FunctionData)

	# TODO: inscription (structure, fct 2ndaires,
	# statut, début de mandat, fin de mandat).

	address = _TextProperty()
	postal_code = _TextProperty()
	town = _TextProperty()
	country = _TextProperty()
	npai = _BoolProperty()
	home_phone = _TextProperty()
	work_phone = _TextProperty()
	portable_phone1 = _TextProperty()
	portable_phone2 = _TextProperty()
	home_email = _TextProperty()
	work_email = _TextProperty()
	birth_date = _DateProperty()
	birth_postal_code = _TextProperty()
	birth_insee_code = _TextProperty()
	birth_town = _TextProperty()
	profession = _TextProperty()
	allocations_beneficiary_number = _TextProperty()
	allocations_beneficiary_regime = _EnumProperty(enum = AllocationsRegime)
	image_rights = _BoolProperty()
	medical_surgical_measures = _BoolProperty()
	civil_liability_insurance = _BoolProperty()
	ice_last_name = _TextProperty()
	ice_first_name = _TextProperty()
	ice_phone = _TextProperty()

class RallyRegistration(_Base):
	""" A registration to an event common to several structures. """

	iid = _IIDProperty()
	name = _TextProperty()

class Camp(_Base):
	""" A scout camp. """

	iid = _IIDProperty()
	name = _TextProperty()

class Place(_Base):
	""" A place. """

	iid = _IIDProperty()
	name = _TextProperty()
	description = _TextProperty()
	address = _TextProperty(doc = "Lines for the address of the place.")
	postal_code = _TextProperty()
	town = _TextProperty(doc = "Name of the town to which the " \
		"place is related.")
	country = _TextProperty()
	department = _TextProperty(doc = "Name of the related " \
		"administrative department.")
	out_of_france = _BoolProperty()
	continent = _TextProperty(doc = "Name of the continent the place is in.")
	phone = _TextProperty()
	fax = _TextProperty()
	email = _TextProperty()
	js = _TextProperty(doc = "J&S number for the place.")
	hardwall = _BoolProperty(doc = "Does the place has permanent " \
		"installations? (hébergement en dur)")
	localnumber = _TextProperty()
	owner = _TextProperty()
	owner_address = _TextProperty()
	ign_num = _TextProperty(doc = "Related IGN map number.")
	car_access = _BoolProperty()
	closest_train_station = _TextProperty()
	closest_train_station_distance = _TextProperty()
	closest_bus_stop = _TextProperty()
	closest_bus_stop_distance = _TextProperty()

class Event(_Base):
	""" An event. """

	iid = _IIDProperty()
	type = _ValueProperty(cls = _EventTypeData)
	start = _DateProperty()
	end = _DateProperty()
	# TODO: structure principale ayant proposé l'évènement.
	# TODO: dernier utilisateur ayant mis à jour l'évènement.
	# TODO: visibilité de l'évènement.
	# TODO: fonctions concernées.

	name = _TextProperty()
	description = _TextProperty()

	# TODO: date de rappel de l'évènement.
	# TODO: date de dernier envoi des invitations.

class Operation(_Base):
	""" An event on the website.. """

	time = _DateProperty()
	type = _ValueProperty(cls = _OperationTypeData)
	author = _ObjectProperty(types = (Adherent,),
		default = Adherent())
	fields = _OperationFieldsProperty()
	related = _ArrayProperty(types = (Structure, Adherent,
		RallyRegistration, Camp, Place))

# End of file.