nsarchive 1.3.0__py3-none-any.whl → 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nsarchive/__init__.py CHANGED
@@ -1,814 +1,28 @@
1
- import time
1
+ """
2
+ nsarchive - API-wrapper pour récupérer des données liées à Nation.
2
3
 
3
- import deta
4
+ Version: 2.0.0
5
+ License: GPL-3.0
6
+ Auteur : happex <110610727+okayhappex@users.noreply.github.com>
4
7
 
5
- from .cls.base import *
6
- from .cls.entities import *
8
+ Dependencies:
9
+ - Python ^3.10
10
+ - supabase ^2.9.1
11
+ - pillow ^10.4
12
+
13
+ Le fichier README.md fournit des détails supplémentaires pour l'utilisation.
14
+ """
15
+
16
+ # Import des types et des exceptions
17
+ from .cls.base import NSID
7
18
  from .cls.archives import *
19
+ from .cls.entities import *
8
20
  from .cls.republic import *
9
21
  from .cls.economy import *
10
22
 
11
23
  from .cls.exceptions import *
12
24
 
13
- class EntityInstance:
14
- """
15
- Instance qui vous permettra d'interagir avec les profils des membres ainsi que les différents métiers et secteurs d'activité.
16
-
17
- ## Informations disponibles
18
- - Profil des membres et des entreprises: `.User | .Organization | .Entity`
19
- - Participation d'un membre à différent votes: `.User | .Organization | .Entity`
20
- - Appartenance et permissions d'un membre dans un groupe: `.GroupMember.MemberPermissions`
21
- - Position légale et permissions d'une entité: `.Position.Permissions`
22
- - Sanctions et modifications d'une entité: `.Action[ .AdminAction | .Sanction ]`
23
- """
24
-
25
- def __init__(self, token: str) -> None:
26
- self.db = deta.Deta(token)
27
- self.base = self.db.Base('entities')
28
- self.electors = self.db.Base('electors')
29
- self.archives = self.db.Base('archives')
30
- self.avatars = self.db.Drive('avatars')
31
- self.positions = self.db.Base('positions') # Liste des métiers
32
-
33
- def get_entity(self, id: str | NSID) -> User | Organization | Entity:
34
- """
35
- Fonction permettant de récupérer le profil public d'une entité.\n
36
-
37
- ## Paramètres
38
- id: `NSID`\n
39
- ID héxadécimal de l'entité à récupérer
40
-
41
- ## Renvoie
42
- - `.User` dans le cas où l'entité choisie est un membre
43
- - `.Organization` dans le cas où c'est un groupe
44
- - `.Entity` dans le cas où c'est indéterminé
45
- """
46
-
47
- id = NSID(id)
48
- _data = self.base.get(id)
49
- _votes = self.electors.get(id)
50
-
51
- if _data is None:
52
- return None
53
-
54
- if _data['_type'] == 'user':
55
- entity = User(id)
56
-
57
- entity.xp = _data['xp']
58
- entity.boosts = _data['boosts']
59
-
60
- if _votes is None:
61
- entity.votes = []
62
- else:
63
- entity.votes = [ NSID(vote) for vote in _votes['votes'] ]
64
- elif _data['_type'] == 'organization':
65
- entity = Organization(id)
66
-
67
- entity.owner = self.get_entity(NSID(_data['owner_id']))
68
-
69
- for _member in _data['members']:
70
- member = GroupMember(_member['id'])
71
- member.group_permissions.__dict__ = _member['permissions']
72
-
73
- _member_profile = self.get_entity(member.id)
74
-
75
- member.set_name(_member_profile.name)
76
- member.legalPosition = _member_profile.legalPosition
77
- member.registerDate = _member_profile.registerDate
78
-
79
- member.xp = _member_profile.xp
80
- member.boosts = _member_profile.boosts
81
-
82
- member.permissions = _member_profile.permissions
83
- member.votes = _member_profile.votes
84
-
85
- entity.append(member)
86
-
87
- try:
88
- entity.avatar = self.avatars.get(id).read()
89
- except:
90
- entity.avatar = None
91
-
92
- entity.certifications = _data['certifications']
93
- else:
94
- entity = Entity(id)
95
-
96
- entity.name = _data['name']
97
- entity.legalPosition = _data['legalPosition'] # Métier si c'est un utilisateur, domaine professionnel si c'est un collectif
98
- entity.registerDate = _data['registerDate']
99
-
100
- return entity
101
-
102
- def save_entity(self, entity: Entity) -> None:
103
- """
104
- Fonction permettant de créer ou modifier une entité.
105
-
106
- ## Paramètres
107
- entity: `.Entity` ( `.User | .Organization` )
108
- L'entité à sauvegarder
109
- """
110
-
111
- entity.id = NSID(entity.id)
112
-
113
- _base = self.base
114
- _data = {
115
- '_type': 'user' if type(entity) == User else 'organization' if type(entity) == Organization else 'unknown',
116
- 'name': entity.name,
117
- 'legalPosition': entity.legalPosition,
118
- 'registerDate': entity.registerDate
119
- }
120
-
121
- if type(entity) == Organization:
122
- _data['owner_id'] = NSID(entity.owner.id) if entity.owner else NSID("0")
123
- _data['members'] = []
124
- _data['certifications'] = entity.certifications
125
-
126
- for member in entity.members:
127
- _member = {
128
- 'id': NSID(member.id),
129
- 'permissions': member.group_permissions.__dict__.copy()
130
- }
131
-
132
- _data['members'] += [_member]
133
-
134
- self.avatars.put(name = entity.id, data = entity.avatar)
135
- elif type(entity) == User:
136
- _data['xp'] = entity.xp
137
- _data['boosts'] = entity.boosts
138
-
139
- _votes = []
140
- for vote in entity.votes:
141
- _votes.append(NSID(vote))
142
-
143
- self.electors.put({ "votes": _votes }, entity.id, expire_in = 112 * 84600) # Données supprimées après 16 semaines d'inactivité
144
-
145
- _base.put(_data, entity.id, expire_in = 3 * 31536000) # Pareil après 3 ans
146
-
147
- def delete_entity(self, entity: Entity) -> None:
148
- """
149
- Fonction permettant de supprimer le profil d'une entité
150
-
151
- ## Paramètres
152
- entity: `.Entity` ( `.User | .Organization` )
153
- L'entité à supprimer
154
- """
155
-
156
- self.base.delete(NSID(entity.id))
157
-
158
- if type(entity) == Organization:
159
- self.avatars.delete(NSID(entity.id))
160
-
161
- def fetch_entities(self, query: dict = None, listquery: dict | None = None) -> list[ Entity | User | Organization ]:
162
- """
163
- Récupère une liste d'entités en fonction d'une requête.
164
-
165
- ## Paramètres
166
- query: `dict`
167
- La requête pour filtrer les entités.
168
- listquery: `dict | None`
169
- OBSOLÈTE
170
-
171
- ## Renvoie
172
- - `list[Entity | User | Organization]`
173
- """
174
-
175
- _res = self.base.fetch(query).items
176
-
177
- if listquery:
178
- print("\033[1;33mAvertissement\033[0m Listquery n'est plus pris en charge et sera retiré en version 1.3.0")
179
-
180
- return [ self.get_entity(NSID(entity['key'])) for entity in _res if entity is not None ]
181
-
182
- def get_entity_groups(self, id: str | NSID) -> list[Organization]:
183
- """
184
- Récupère les groupes auxquels appartient une entité.
185
-
186
- ## Paramètres
187
- id: `str | NSID`
188
- ID de l'entité.
189
-
190
- ## Renvoie
191
- - `list[Organization]`
192
- """
193
-
194
- id = NSID(id)
195
- groups = self.fetch_entities({'_type': 'organization'})
196
- groups.extend(self.fetch_entities({'_type': 'organization', 'owner_id': id}))
197
-
198
- for group in groups:
199
- if group is None:
200
- groups.remove(group)
201
- continue
202
-
203
- if group.owner.id == id:
204
- continue
205
-
206
- for member in group.members:
207
- if member.id == id:
208
- break
209
- else:
210
- groups.remove(group)
211
-
212
- return [ group for group in groups if group is not None ]
213
-
214
- def get_position(self, id: str) -> Position:
215
- """
216
- Récupère une position légale (métier, domaine professionnel).
217
-
218
- ## Paramètres
219
- id: `str`
220
- ID de la position (SENSIBLE À LA CASSE !)
221
-
222
- ## Renvoie
223
- - `.Position`
224
- """
225
-
226
- _data = self.positions.get(id)
227
-
228
- if _data is None:
229
- return None
230
-
231
- position = Position(id)
232
- position.name = _data['name']
233
-
234
- for _permission in _data['permissions']:
235
- position.permissions.__setattr__(_permission, True)
236
-
237
- return position
238
-
239
- def _add_archive(self, archive: Action) -> None:
240
- """
241
- Ajoute une archive d'une action (modification au sein d'un groupe ou sanction) dans la base de données.
242
- """
243
-
244
- archive.id = NSID(archive.id)
245
- archive.author = NSID(archive.author)
246
- archive.target = NSID(archive.target)
247
-
248
- _data = archive.__dict__.copy()
249
-
250
- if type(archive) == Sanction:
251
- _data['type'] = "sanction"
252
- elif type(archive) == AdminAction:
253
- _data['type'] = "adminaction"
254
- elif type(archive) == Report:
255
- _data['type'] = "report"
256
- else:
257
- _data['type'] = "unknown"
258
-
259
- self.archives.put(key = archive.id, data = _data)
260
-
261
- def _get_archive(self, id: str | NSID) -> Action | Sanction | AdminAction:
262
- """
263
- Récupère une archive spécifique.
264
-
265
- ## Paramètres
266
- id: `str | NSID`
267
- ID de l'archive.
268
-
269
- ## Renvoie
270
- - `.Action | .Sanction | .AdminAction`
271
- """
272
-
273
- id = NSID(id)
274
- _data = self.archives.get(id)
275
-
276
- if _data is None:
277
- return None
278
-
279
- if _data['type'] == "sanction": # Mute, ban, GAV, kick, détention, prune (xp seulement)
280
- archive = Sanction(_data['author'], _data['target'])
281
-
282
- archive.details = _data['details']
283
- archive.major = _data['major']
284
- archive.duration = _data['duration']
285
- elif _data['type'] == "adminaction": # Renommage, promotion, démotion (au niveau de l'état)
286
- archive = AdminAction(_data['author'], _data['target'])
287
-
288
- archive.details = _data['details']
289
- archive.new_state = _data['new_state']
290
- elif _data['type'] == "report": # Plainte
291
- archive = Report(_data['author'], _data['target'])
292
-
293
- archive.details = _data['details']
294
- else:
295
- archive = Action(_data['author'], _data['target'])
296
-
297
- archive.id = id
298
- archive.action = _data['action']
299
- archive.date = _data['date']
300
-
301
- return archive
302
-
303
- def _fetch_archives(self, **query) -> list[ Action | Sanction | AdminAction ]:
304
- """
305
- Récupère une liste d'archives correspondant à la requête.
306
-
307
- ## Paramètres
308
- query: `dict`
309
- Requête pour filtrer les archives.
310
-
311
- ## Renvoie
312
- - `list[Action | Sanction | AdminAction]`
313
- """
314
-
315
- _res = self.archives.fetch(query).items
316
-
317
- return [ self._get_archive(archive['key']) for archive in _res ]
318
-
319
- class RepublicInstance:
320
- """
321
- Gère les interactions avec les votes, les archives de la république, et les fonctionnaires.
322
-
323
- ## Informations
324
- - Résultats des votes: `.Vote | .ClosedVote`
325
- - Différentes institutions: `.Institutions | .Administration | .Government | .Assembly | .Court | .PoliceForces`
326
- - Occupants des différents rôles et historique de leurs actions: `.Official`
327
- """
328
-
329
- def __init__(self, token: str) -> None:
330
- """Initialise une nouvelle RepublicInstance avec un token Deta."""
331
-
332
- self.db = deta.Deta(token)
333
- self.votes = self.db.Base('votes')
334
- self.archives = self.db.Base('archives')
335
- self.mandate = self.db.Base('mandate')
336
- self.functions = self.db.Base('functions') # Liste des fonctionnaires
337
-
338
- def get_vote(self, id: str | NSID) -> Vote | ClosedVote | Lawsuit:
339
- """
340
- Récupère un vote spécifique.
341
-
342
- ## Paramètres
343
- id: `str | NSID`
344
- ID du vote.
345
-
346
- ## Renvoie
347
- - `.Vote | .ClosedVote`
348
- """
349
-
350
- id = NSID(id)
351
- _data = self.votes.get(id)
352
-
353
- if _data is None:
354
- return None
355
-
356
- if _data['_type'] == 'open':
357
- vote = Vote(id, _data['title'], tuple(_data['choices'].keys()))
358
- elif _data['_type'] == 'closed':
359
- vote = ClosedVote(id, _data['title'])
360
- elif _data['_type'] == 'lawsuit':
361
- vote = Lawsuit(id, _data['title'])
362
- else:
363
- vote = Vote('0', 'Unknown Vote', ())
364
-
365
- vote.author = _data['author']
366
- vote.startDate = _data['startDate']
367
- vote.endDate = _data['endDate']
368
- vote.choices = _data['choices']
369
-
370
- return vote
371
-
372
- def save_vote(self, vote: Vote | ClosedVote) -> None:
373
- """Sauvegarde un vote dans la base de données."""
374
-
375
- vote.id = NSID(vote.id)
376
-
377
- _data = {
378
- '_type':'open' if type(vote) == Vote else\
379
- 'closed' if type(vote) == ClosedVote else\
380
- 'lawsuit' if type(vote) == Lawsuit else\
381
- 'unknown',
382
- 'title': vote.title,
383
- 'author': NSID(vote.author),
384
- 'startDate': vote.startDate,
385
- 'endDate': vote.endDate,
386
- 'choices': vote.choices
387
- }
388
-
389
- self.votes.put(_data, vote.id)
390
-
391
- def get_official(self, id: str | NSID, current_mandate: bool = True) -> Official:
392
- """
393
- Récupère les informations d'un fonctionnaire (mandats, contributions).
394
-
395
- ## Paramètres
396
- id: `str | NSID`
397
- ID du fonctionnaire.
398
- current_mandate: `bool`
399
- Indique si l'on doit récupérer le mandat actuel ou les anciens mandats.
400
-
401
- ## Renvoie
402
- - `.Official`
403
- """
404
-
405
- id = NSID(id)
406
-
407
- archives = self.mandate if current_mandate else self.archives
408
-
409
- _contributions = archives.fetch({'author': id, 'type': 'contrib'}).items
410
- _mandates = archives.fetch({'target': id, 'type': 'election'}).items\
411
- + archives.fetch({'target': id, 'type': 'promotion'}).items
412
-
413
- user = Official(id)
414
- for mandate in _mandates:
415
- if mandate['position'].startswith('MIN'):
416
- mandate['position'] = 'MIN'
417
-
418
- try:
419
- user.mandates[mandate['position']] += 1
420
- except KeyError:
421
- user.mandates[mandate['position']] = 1
422
-
423
- for contrib in _contributions:
424
- try:
425
- user.contributions[contrib['action']] += 1
426
- except KeyError:
427
- user.contributions[contrib['action']] = 1
428
-
429
- return user
430
-
431
- def get_institutions(self) -> Organization:
432
- """Récupère l'état actuel des institutions de la république."""
433
-
434
- admin = Administration()
435
- gov = Government(Official('0'))
436
- assembly = Assembly()
437
- court = Court()
438
- police_forces = PoliceForces()
439
-
440
- _admins = self.functions.get('ADMIN')
441
- admin.members = [ self.get_official(user) for user in _admins['users'] ]
442
- admin.president = self.get_official('F7DB60DD1C4300A') # happex (remplace Kheops pour l'instant)
443
-
444
- gov.president = self.get_official(self.functions.get('PRE_REP')['users'][0])
445
-
446
- minister = lambda code : self.get_official(self.functions.get(f'MIN_{code}')['users'][0])
447
- gov.prime_minister = minister('PRIM')
448
- gov.economy_minister = minister('ECO')
449
- gov.inner_minister = minister('INN')
450
- gov.press_minister = minister('AUD')
451
- gov.justice_minister = minister('JUS')
452
- gov.outer_minister = minister('OUT')
453
-
454
- assembly.president = self.get_official(self.functions.get('PRE_AS')['users'][0])
455
- assembly.members = [ self.get_official(id) for id in self.functions.get('REPR')['users'] ]
456
-
457
- court.president = gov.justice_minister
458
- court.members = [ self.get_official(id) for id in self.functions.get('JUDGE')['users'] ]
459
-
460
- police_forces.president = gov.inner_minister
461
- police_forces.members = [ self.get_official(id) for id in self.functions.get('POLICE')['users'] ]
462
-
463
- instits = Institutions()
464
- instits.administration = admin
465
- instits.government = gov
466
- instits.court = court
467
- instits.assembly = assembly
468
- instits.police = police_forces
469
-
470
- return instits
471
-
472
- def update_institutions(self, institutions: Institutions):
473
- """
474
- Fonction communément appelée après un vote législatif ou une nomination.\n
475
- Celle-ci met à jour: Le gouvernement (président, ministres), les différents députés et leur président, les différents juges, les différents policiers.\n
476
-
477
- ## Paramètres
478
- institutions: `.Institutions`\n
479
- Le nouvel état des institutions, à sauvegarder.
480
- """
481
-
482
- get_ids = lambda institution : [ member.id for member in institutions.__getattribute__(institution).members ]
483
-
484
- self.functions.put(key = 'ADMIN', data = { 'users': get_ids('administration') })
485
- self.functions.put(key = 'REPR', data = { 'users': get_ids('assembly') })
486
- self.functions.put(key = 'JUDGE', data = { 'users': get_ids('court') })
487
- self.functions.put(key = 'POLICE', data = { 'users': get_ids('police') })
488
-
489
- self.functions.put(key = 'PRE_AS', data = { 'users': [ institutions.assembly.president.id ] })
490
- self.functions.put(key = 'PRE_REP', data = { 'users': [ institutions.government.president.id ] })
491
-
492
- self.functions.put(key = 'MIN_PRIM', data = { 'users': [ institutions.government.prime_minister.id ] })
493
- self.functions.put(key = 'MIN_INN', data = { 'users': [ institutions.government.inner_minister.id ] })
494
- self.functions.put(key = 'MIN_JUS', data = { 'users': [ institutions.government.justice_minister.id ] })
495
- self.functions.put(key = 'MIN_ECO', data = { 'users': [ institutions.government.economy_minister.id ] })
496
- self.functions.put(key = 'MIN_AUD', data = { 'users': [ institutions.government.press_minister.id ] })
497
- self.functions.put(key = 'MIN_OUT', data = { 'users': [ institutions.government.outer_minister.id ] })
498
-
499
- def new_mandate(self, institutions: Institutions, weeks: int = 4) -> None:
500
- """
501
- Fonction qui amène à supprimer toutes les archives du mandat précédent
502
- """
503
-
504
- for item in self.mandate.fetch().items:
505
- if item['date'] >= round(time.time()) - weeks * 604800: # On évite de supprimer les informations écrites lors de la période définie
506
- self.mandate.delete(item['id'])
507
-
508
- self.update_institutions(institutions)
509
-
510
- def _add_archive(self, archive: Action) -> None:
511
- """Ajoute une archive d'une action (élection, promotion, ou rétrogradation) dans la base de données."""
512
-
513
- archive.id = NSID(archive.id)
514
- _data = archive.__dict__.copy()
515
-
516
- if type(archive) == Election:
517
- _data['type'] = "election"
518
- elif type(archive) == Promotion:
519
- _data['type'] = "promotion"
520
- elif type(archive) == Demotion:
521
- _data['type'] = "demotion"
522
- else:
523
- _data['type'] = "unknown"
524
-
525
- self.archives.put(key = archive.id, data = _data)
526
- self.mandate.put(key = archive.id, data = _data) # Ajouter les archives à celle du mandat actuel
527
-
528
- def _get_archive(self, id: str | NSID) -> Action | Election | Promotion | Demotion:
529
- """
530
- Récupère une archive spécifique.
531
-
532
- ## Paramètres
533
- id: `str | NSID`
534
- ID de l'archive.
535
-
536
- ## Renvoie
537
- - `.Action | .Election | .Promotion | .Demotion`
538
- """
539
-
540
- id = NSID(id)
541
- _data = self.archives.get(id)
542
-
543
- if _data is None:
544
- return None
545
-
546
- if _data['type'] == "election":
547
- archive = Election(_data['author'], _data['target'], _data['position'])
548
-
549
- archive.positive_votes = _data['positive_votes']
550
- archive.total_votes = _data['total_votes']
551
- elif _data['type'] == "promotion":
552
- archive = Promotion(_data['author'], _data['target'], _data['position'])
553
- elif _data['type'] == "demotion":
554
- archive = Demotion(_data['author'], _data['target'])
555
-
556
- archive.reason = _data['reason']
557
- else:
558
- archive = Action(_data['author'], _data['target'])
559
-
560
- archive.id = id
561
- archive.action = _data['action']
562
- archive.date = _data['date']
563
-
564
- return archive
565
-
566
- def _fetch_archives(self, **query) -> list[ Action | Election | Promotion | Demotion ]:
567
- """
568
- Récupère une liste d'archives correspondant à la requête.
569
-
570
- ## Paramètres
571
- query: `dict`
572
- Requête pour filtrer les archives.
573
-
574
- ## Renvoie
575
- - `list[Action | Election | Promotion | Demotion]`
576
- """
577
-
578
- _res = self.archives.fetch(query).items
579
-
580
- return [ self._get_archive(archive['key']) for archive in _res ]
581
-
582
- class BankInstance:
583
- """Gère les interactions avec les comptes bancaires, les transactions, et le marché."""
584
-
585
- def __init__(self, token: str) -> None:
586
- self.db = deta.Deta(token)
587
- self.archives = self.db.Base('archives')
588
- self.accounts = self.db.Base('accounts')
589
- self.registry = self.db.Base('banks')
590
- self.marketplace = self.db.Base('shop')
591
- self.inventories = self.db.Base('inventories')
592
-
593
- def get_account(self, id: str | NSID) -> BankAccount:
594
- """
595
- Récupère les informations d'un compte bancaire.
596
-
597
- ## Paramètres
598
- id: `str | NSID`
599
- ID du compte.
600
-
601
- ## Renvoie
602
- - `.BankAccount`
603
- """
604
-
605
- id = NSID(id)
606
- _data = self.accounts.get(id)
607
-
608
- if _data is None:
609
- return None
610
-
611
- account = BankAccount(id)
612
- account.amount = _data['amount']
613
- account.locked = _data['locked']
614
- account.owner = _data['owner_id']
615
- account.bank = _data['bank']
616
-
617
- return account
618
-
619
- def save_account(self, account: BankAccount):
620
- """Sauvegarde un compte bancaire dans la base de données."""
621
-
622
- _data = {
623
- 'amount': account.amount,
624
- 'locked': account.locked,
625
- 'owner_id': account.owner,
626
- 'bank': account.bank
627
- }
628
-
629
- self.accounts.put(_data, NSID(account.id))
630
-
631
- def lock_account(self, account: BankAccount):
632
- """Verrouille un compte bancaire pour empêcher toute transaction."""
633
-
634
- account.id = account.id.upper()
635
- account.locked = True
636
-
637
- self.save_account(account)
638
-
639
- def get_sale(self, id: str | NSID) -> Sale | None:
640
- """
641
- Récupère une vente disponible sur le marketplace.
642
-
643
- ## Paramètres
644
- id: `str | NSID`
645
- ID de l'item.
646
-
647
- ## Renvoie
648
- - `.Item | None`
649
- """
650
-
651
- id = NSID(id)
652
-
653
- _data = self.marketplace.get(id)
654
-
655
- if _data is None:
656
- return None
657
-
658
- sale = Sale(NSID(id))
659
-
660
- del _data['key']
661
- sale.__dict__ = _data
662
-
663
- return sale
664
-
665
- def sell_item(self, item: Item, quantity: int, price: int, seller: NSID) -> None:
666
- """
667
- Vend un item sur le marché.
668
-
669
- ## Paramètres
670
- item: `.Item`
671
- Item à vendre
672
- quantity: `int`
673
- Nombre d'items à vendre
674
- price: `int`
675
- Prix à l'unité de chaque objet
676
- seller: `NSID`
677
- ID de l'auteur de la vente
678
- """
679
-
680
- sale = Sale(NSID(round(time.time()) * 16 ** 3), item)
681
- sale.quantity = quantity
682
- sale.price = price
683
- sale.seller_id = seller
684
-
685
- _data = sale.__dict__.copy()
686
- del _data['id']
687
-
688
- self.marketplace.put(key = sale.id, data = _data)
689
-
690
- def delete_sale(self, sale: Sale) -> None:
691
- """Annule une vente sur le marketplace."""
692
-
693
- sale.id = NSID(sale.id)
694
- self.marketplace.delete(sale.id)
695
-
696
- def get_inventory(self, id: NSID) -> Inventory | None:
697
- """
698
- Récupérer un inventaire dans la base des inventaires.
699
-
700
- ## Paramètres
701
- id: `NSID`
702
- ID du propriétaire de l'inventaire
703
-
704
- ## Retourne
705
- - `.Inventory | None`
706
- """
707
- _data = self.inventories.get(id)
708
-
709
- if _data is None:
710
- return None
711
-
712
- inventory = Inventory(id)
713
-
714
- del _data['key']
715
-
716
- for _item in _data['objects']:
717
- item = Item(_item['id'])
718
- item.__dict__ = _item
719
-
720
- inventory.objects.append(item)
721
-
722
- return inventory
723
-
724
- def save_inventory(self, inventory: Inventory) -> None:
725
- """
726
- Sauvegarder un inventaire
727
-
728
- ## Paramètres
729
- inventory: `.Inventory`
730
- Inventaire à sauvegarder
731
- """
732
-
733
- _data = {
734
- "owner_id": inventory.owner_id,
735
- "objects": [ object.__dict__ for object in inventory.objects ]
736
- }
737
-
738
- self.inventories.put(key = inventory.owner_id, data = _data)
739
-
740
- def delete_inventory(self, inventory: Inventory) -> None:
741
- """
742
- Supprime un inventaire
743
-
744
- ## Paramètres
745
- inventory: `.Inventory`
746
- Inventaire à supprimer
747
- """
748
-
749
- self.inventories.delete(inventory.id)
750
-
751
- def _add_archive(self, archive: Action):
752
- """Ajoute une archive d'une transaction ou d'une vente dans la base de données."""
753
-
754
- archive.id = NSID(archive.id)
755
- archive.author = NSID(archive.author)
756
- archive.target = NSID(archive.target)
757
-
758
- _data = archive.__dict__.copy()
759
-
760
- if type(archive) == Transaction:
761
- _data['type'] = "transaction"
762
- archive.currency = archive.currency.upper()
763
- else:
764
- _data['type'] = "unknown"
765
-
766
- self.archives.put(key = archive.id, data = _data)
767
-
768
- def _get_archive(self, id: str | NSID) -> Action | Transaction:
769
- """
770
- Récupère une archive spécifique.
771
-
772
- ## Paramètres
773
- id: `str | NSID`
774
- ID de l'archive.
775
-
776
- ## Renvoie
777
- - `.Action | .Transaction`
778
- """
779
-
780
- id = NSID(id)
781
- _data = self.archives.get(id)
782
-
783
- if _data is None:
784
- return None
785
-
786
- if _data['type'] == "transaction":
787
- archive = Transaction(_data['author'], _data['target'], _data['amount'])
788
-
789
- archive.reason = _data['reason']
790
- archive.currency = _data['currency']
791
- else:
792
- archive = Action(_data['author'], _data['target'])
793
-
794
- archive.id = id
795
- archive.action = _data['action']
796
- archive.date = _data['date']
797
-
798
- return archive
799
-
800
- def _fetch_archives(self, **query) -> list[ Action | Transaction ]:
801
- """
802
- Récupère une liste d'archives correspondant à la requête.
803
-
804
- ## Paramètres
805
- query: `dict`
806
- Requête pour filtrer les archives.
807
-
808
- ## Renvoie
809
- - `list[Action | Transaction]`
810
- """
811
-
812
- _res = self.archives.fetch(query).items
813
-
814
- return [ self._get_archive(archive['key']) for archive in _res ]
25
+ # Import des instances
26
+ from .instances._economy import EconomyInstance
27
+ from .instances._entities import EntityInstance
28
+ from .instances._republic import RepublicInstance