-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollecting_society.py
6569 lines (5781 loc) · 239 KB
/
collecting_society.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
# For copyright and license terms, see COPYRIGHT.rst (top level of repository)
# Repository: https://github.com/C3S/collecting_society
import sys
import os
import uuid
import datetime
import requests
import json
import copy
import math
from decimal import Decimal
from typing import Protocol, Any
from sql import Table
from sql.conditionals import Case
from sql.functions import CharLength
import hurry.filesize
from trytond.model import Model, ModelView, ModelSQL, fields, Unique
from trytond.model.model import ModelMeta
from trytond.model.fields import Field
from trytond.wizard import Wizard, StateView, Button, StateTransition, \
StateAction
from trytond.exceptions import UserError, UserWarning
from trytond.transaction import Transaction
from trytond.pool import Pool
from trytond.pyson import Eval, Bool, Or, And
from .formulas import utils, collection, distribution
__all__ = [
# Mixins
'UUID',
'Code',
'CodeSequence',
'PublicApi',
'CurrentState',
'ClaimState',
'CommitState',
'EntityOrigin',
'CurrencyDigits',
'AccessControlList',
'MixinRight',
'MixinIdentifier',
'MixinIdentifierHelper',
# Collecting Society
'CollectingSociety',
'TariffSystem',
'TariffCategory',
'TariffAdjustmentCategory',
'TariffCategoryTariffAdjustmentCategory',
'TariffAdjustment',
'TariffRelevanceCategory',
'TariffCategoryTariffRelevanceCategory',
'TariffRelevance',
'Tariff',
'Allocation',
'AllocationAccountInvoice',
'CollectStart',
'Collect',
'AllocationInvoice',
'Collection',
'Distribution',
'DistributionAccountMove',
'DistributionPlan',
'DistributeStart',
'Distribute',
'EventIndicators',
'LocationIndicators',
'LocationIndicatorsPeriod',
'LocationSpaceIndicators',
'WebsiteResourceIndicators',
'ReleaseIndicators',
'UtilisationIndicators',
'IndicatorsMeta',
# Licenser
'License',
'Artist',
'ArtistArtist',
'ArtistRelease',
'ArtistPayeeAcceptance',
'ArtistIdentifier',
'ArtistIdentifierSpace',
'ArtistPlaylist',
'ArtistPlaylistItem',
'Creation',
'CreationDerivative',
'CreationRole',
'CreationTariffCategory',
'CreationIdentifier',
'CreationIdentifierSpace',
'CreationRight',
'CreationRightCreationRight',
'Release',
'ReleaseTrack',
'ReleaseGenre',
'ReleaseStyle',
'ReleaseIdentifier',
'ReleaseIdentifierSpace',
'ReleaseRight',
'ReleaseRightReleaseRight',
'MixinIdentifier',
'Instrument',
'CreationRightInstrument',
'Genre',
'Style',
'Label',
'Publisher',
# Licensee
'Event',
'EventPerformance',
'Location',
'LocationCategory',
'LocationSpace',
'LocationSpaceCategory',
'Website',
'WebsiteCategory',
'WebsiteResource',
'WebsiteResourceCreation',
'WebsiteResourceCategory',
'WebsiteCategoryWebsiteResourceCategory',
'Device',
'DeviceMessage',
'DeviceMessageDeviceMessage',
'DeviceAssignment',
'DeviceMessageFingerprint',
'DeviceMessageFingerprintMatch',
'DeviceMessageFingerprintMatchStart',
'DeviceMessageFingerprintMerge',
'DeviceMessageFingerprintMergeStart',
'DeviceMessageFingerprintMergeSelect',
'DeviceMessageFingerprintCreationlist',
'DeviceMessageFingerprintCreationlistItem',
'DeviceMessageUsagereport',
'Declaration',
'DeclarationGroup',
'Utilisation',
'UtilisationCalculate',
'UtilisationConfirm',
'UtilisationFinalize',
'UtilisationCreationlist',
'UtilisationCreationlistItem',
# Archiving
'Storehouse',
'HarddiskLabel',
'Harddisk',
'HarddiskTest',
'FilesystemLabel',
'Filesystem',
'Content',
'Checksum',
'Fingerprintlog',
# Portal
'AccessControlEntry',
'AccessControlEntryRole',
'AccessRole',
'AccessRolePermission',
'AccessPermission',
# Tryton
'STATES',
'DEPENDS',
]
STATES = {
'readonly': ~Eval('active'),
}
DEPENDS = ['active']
SEPARATOR = ' /25B6 '
DEFAULT_ACCESS_ROLES = ['Administrator', 'Stakeholder']
##############################################################################
# Mixins
##############################################################################
class UUID:
'Mixin to add a machine readable uuid field for internal use'
__slots__ = ()
uuid = fields.Char(
'UUID', required=True,
help='The machine readable UUID for the record for internal use.')
@classmethod
def __setup__(cls):
super().__setup__()
table = cls.__table__()
cls._sql_constraints += [
('uuid_uniq', Unique(table, table.uuid),
f'The UUID of the {cls.__name__} must be unique.'),
]
@staticmethod
def default_uuid():
return str(uuid.uuid4())
@classmethod
def create(cls, vlist):
vlist = [x.copy() for x in vlist]
for values in vlist:
if not values.get('code'):
values['uuid'] = cls.default_uuid()
return super().create(vlist)
@classmethod
def copy(cls, vlist, default=None):
if default is None:
default = {}
default = default.copy()
default['uuid'] = None
return super().copy(vlist, default=default)
@classmethod
def search_rec_name(cls, name, clause):
return [('uuid',) + tuple(clause[1:])]
class PublicApiProtocol(Protocol):
def __setup__(self) -> None: ...
def __table__(self) -> Table: ...
_sql_constraints: list[tuple[str, Any, str]]
class Code:
'Mixin to add a free code field for technical use and public reference'
__slots__ = ()
code = fields.Char(
'Code', required=True,
help='The code for technical use and public reference.')
@classmethod
def __setup__(cls):
super().__setup__()
table = cls.__table__()
cls._sql_constraints += [
('code_uniq', Unique(table, table.code),
f'The code of the {cls.__name__} must be unique.'),
]
@staticmethod
def order_code(tables):
table, _ = tables[None]
return [CharLength(table.code), table.code]
@classmethod
def copy(cls, vlist, default=None):
if default is None:
default = {}
default = default.copy()
default['code'] = None
return super().copy(vlist, default=default)
@classmethod
def search_rec_name(cls, name, clause):
return [('code',) + tuple(clause[1:])]
class CodeSequence:
'Mixin to add a human readable sequence code field for public reference'
__slots__ = ()
# name of sequence field in collecting_society.configuration
_code_sequence = ''
code = fields.Char(
'Code', required=True, states={
'readonly': True,
}, help="The official public sequence code of the "
f"{_code_sequence.replace('_', ' ')}")
@classmethod
def __setup__(cls):
super().__setup__()
table = cls.__table__()
cls._sql_constraints = [
('code_uniq', Unique(table, table.code),
f"The code of the {cls._code_sequence.replace('_', ' ')} "
"must be unique."),
]
@staticmethod
def order_code(tables):
table, _ = tables[None]
return [CharLength(table.code), table.code]
@classmethod
def create(cls, vlist):
Configuration = Pool().get('collecting_society.configuration')
vlist = [x.copy() for x in vlist]
for values in vlist:
if not values.get('code'):
config = Configuration(1)
sequence = getattr(config, cls._code_sequence)
values['code'] = sequence.get()
return super().create(vlist)
@classmethod
def copy(cls, vlist, default=None):
if default is None:
default = {}
default = default.copy()
default['code'] = None
return super().copy(vlist, default=default)
@classmethod
def search_rec_name(cls, name, clause):
return [('code',) + tuple(clause[1:])]
class PublicApi:
'Mixin to add a machine readable oid field for public use'
__slots__ = ()
oid = fields.Char(
'OID', required=True,
help='A unique object identifier used in the public web api to avoid'
'exposure of implementation details to the users.')
@classmethod
def __setup__(cls: PublicApiProtocol):
super().__setup__()
table = cls.__table__()
cls._sql_constraints += [
('oid_uniq', Unique(table, table.oid),
f'The OID of the {cls.__name__} must be unique.'),
]
@staticmethod
def default_oid():
return str(uuid.uuid4())
@classmethod
def create(cls, vlist):
vlist = [x.copy() for x in vlist]
for values in vlist:
if not values.get('code'):
values['oid'] = cls.default_oid()
return super().create(vlist)
@classmethod
def copy(cls, vlist, default=None):
if default is None:
default = {}
default = default.copy()
default['oid'] = None
return super().copy(vlist, default=default)
@classmethod
def search_rec_name(cls, name, clause):
return [('oid',) + tuple(clause[1:])]
class CurrentState:
'Mixin for the active state'
__slots__ = ()
active = fields.Boolean('Active')
@staticmethod
def default_active():
return True
class ClaimState:
'Mixin for the claim workflow'
__slots__ = ()
claim_state = fields.Selection(
[
('unclaimed', 'Unclaimed'),
('claimed', 'Claimed'),
('revised', 'Revised'),
], 'Claim', states={'required': True}, sort=False,
help='The state in a claim process.\n\n'
'*Unclaimed*: Object is not yet claimed or a claim was cancelled.\n'
'*Claimed*: Someone claimed this object but it was not revised yet.\n'
'*Revised*: The claim was confirmed by administration')
@staticmethod
def default_claim_state():
return "unclaimed"
class CommitState:
'Mixin for the commit workflow'
__slots__ = ()
commit_state = fields.Selection(
[
('uncommited', 'Uncommited'),
('commited', 'Commited'),
('revised', 'Revised'),
('rejected', 'Rejected'),
('deleted', 'Deleted'),
], 'Commit', states={'required': True}, sort=False,
help='The state in a commit process.\n\n'
'*Uncommited*: The object was freshly created.\n'
'*Commited*: The object was commited by the web user.\n'
'*Revised*: The commit was revised by administration.\n'
'*Rejected*: The commit was rejected by administration.\n'
'*Deleted*: The rejeted object was deleted.\n')
@staticmethod
def default_commit_state():
return 'uncommited'
class CurrencyDigits:
'Mixin to provide the currency digit configuration'
__slots__ = ()
currency_digits = fields.Function(
fields.Integer('Currency Digits'), 'get_currency_digits')
def get_currency_digits(self, name):
Company = Pool().get('company.company')
if Transaction().context.get('company'):
company = Company(Transaction().context['company'])
return company.currency.digits
return 2
class AccessControlList:
'Mixin to add an Access Control List'
__slots__ = ()
acl = fields.One2Many(
'ace', 'entity', 'Access Control List',
states=STATES, depends=DEPENDS,
help='A list of acces control entries with object permissions.')
def permits(self, web_user, code, derive=True):
for ace in self.acl:
if ace.web_user != web_user:
continue
for role in ace.roles:
for permission in role.permissions:
if permission.code == code:
return True
return False
def permissions(self, web_user, valid_codes=[], derive=True):
permissions = set()
for ace in self.acl:
if ace.web_user != web_user:
continue
permissions.update([
permission.code
for role in ace.roles
for permission in role.permissions])
if valid_codes:
permissions = permissions.intersection(valid_codes)
return tuple(permissions)
class EntityOrigin:
'Mixin to track the origin of the entity'
__slots__ = ()
entity_origin = fields.Selection(
[
('direct', 'Direct'),
('indirect', 'Indirect'),
], 'Entity Origin', states={'required': True}, sort=False,
help='Defines, if an object was created as foreign object (indirect) '
'or not.')
entity_creator = fields.Many2One(
'party.party', 'Entity Creator', states={'required': True})
@staticmethod
def default_entity_origin():
return "direct"
class MixinRight:
'Mixin for the right a rightsholder claims on an rights object'
__slots__ = ()
type_of_right = fields.Selection(
[
('copyright', 'Copyright'),
('ancillary', 'Ancillary Copyright'),
], 'Type of Right', required=True, help='Type of right')
valid_from = fields.Date('Valid From Date')
valid_to = fields.Date('Valid To Date')
country = fields.Many2One(
'country.country', 'Territory or Country', states={'required': True})
collecting_society = fields.Many2One(
'collecting_society', 'Collecting Society')
@property
def rightsholder(self):
raise NotImplementedError("Subclasses should implement this")
@property
def rightsobject(self):
raise NotImplementedError("Subclasses should implement this")
@property
def contribution(self):
raise NotImplementedError("Subclasses should implement this")
@property
def predecessor(self):
raise NotImplementedError("Subclasses should implement this")
@property
def successor(self):
raise NotImplementedError("Subclasses should implement this")
class MixinIdentifier:
'Mixin for <Object>Identifier models'
__slots__ = ()
valid_from = fields.Date('Valid From Date')
valid_to = fields.Date('Valid To Date')
id_code = fields.Char('ID Code')
class MixinIdentifierHelper:
'Mixin for Repertoire models that feature identifiers'
__slots__ = ()
# TODO: honor valid-from and -to dates
def get_id_code(self, space):
for identifier in self.cs_identifiers:
if identifier.space.name == space:
return identifier.id_code
return None
def set_id_code(self, space, id_code):
replaced = False
for identifier in self.cs_identifiers:
if identifier.space.name == space:
identifier.id_code = id_code
identifier.save()
replaced = True
if not replaced:
self.cs_identifiers.new(
space=space, id_code=id_code)
##############################################################################
# Collecting Society
##############################################################################
class CollectingSociety(PublicApi, ModelSQL, ModelView, CurrentState):
'Collecting Society'
__name__ = 'collecting_society'
_history = True
name = fields.Char(
'Name', required=True, states=STATES, depends=DEPENDS)
party = fields.Many2One(
'party.party', 'Party', states=STATES, depends=DEPENDS,
help='The legal person or organization acting the collecting society')
represents_copyright = fields.Boolean(
'Represents Copyright', help='The collecting society '
'represents copyrights of authors')
represents_ancillary_copyright = fields.Boolean(
'Represents Ancillary Copyright', help='The collecting society '
'represents ancillary copyights of performers')
# --- Tariffs -----------------------------------------------------------------
class TariffSystem(CodeSequence, ModelSQL, ModelView, CurrentState):
'Tariff System'
__name__ = 'tariff_system'
_history = True
_rec_name = 'version'
_code_sequence = 'tariff_system_sequence'
version = fields.Char(
'Version', required=True, states=STATES, depends=DEPENDS)
valid_from = fields.Date(
'Valid from', help='Date from which the tariff is valid.')
valid_through = fields.Date(
'Valid through', help='Date thorugh which the tariff is valid.')
transitional_through = fields.Date(
'Transitional through',
help='Date of the end of the transitinal phase, through which the '
'tariff might still be used.')
tariffs = fields.One2Many(
'tariff_system.tariff', 'system', 'Tariffs',
help='The tariffs of the tariff system.')
# TODO: attachement
@classmethod
def __setup__(cls):
super().__setup__()
table = cls.__table__()
cls._sql_constraints = [
('version_uniq', Unique(table, table.version),
'The version of the tariff system must be unique.')
]
@classmethod
def search_rec_name(cls, name, clause):
return [
'OR',
('code',) + tuple(clause[1:]),
('version',) + tuple(clause[1:]),
]
def get_rec_name(self, name):
rec_name = f"v{self.version}"
return rec_name
class TariffCategory(Code, PublicApi, ModelSQL, ModelView, CurrentState):
'Tariff Category'
__name__ = 'tariff_system.category'
_history = True
name = fields.Char(
'Name', required=True, states=STATES, depends=DEPENDS)
description = fields.Text(
'Description', states=STATES, depends=DEPENDS,
help='A description of the tariff category.')
tariffs = fields.One2Many(
'tariff_system.tariff', 'category', 'Tariffs',
states=STATES, depends=DEPENDS,
help='The tariffs in this tariff category.')
adjustment_categories = fields.Many2Many(
'tariff_category-tariff_adjustment_category',
'tariff_category', 'tariff_adjustment_category',
'Adjustment Categories',
states=STATES, depends=DEPENDS,
help='The adjustment categories applicable for the tariff category')
relevance_categories = fields.Many2Many(
'tariff_category-tariff_relevance_category',
'tariff_category', 'tariff_relevance_category',
'Relevance Categories',
states=STATES, depends=DEPENDS,
help='The relevance categories applicable for the tariff category')
administration_product = fields.Many2One(
'product.product', 'Administration Product', required=True,
help="The product which represents the administration amount of the "
"tariff.")
distribution_product = fields.Many2One(
'product.product', 'Distribution Product', required=True,
help="The product which represents the distribution amount of the "
"tariff.")
@classmethod
def search_rec_name(cls, name, clause):
return [
'OR',
('name',) + tuple(clause[1:]),
('code',) + tuple(clause[1:]),
]
def get_rec_name(self, name):
rec_name = f"{self.name}"
return rec_name
class TariffAdjustmentCategory(Code, ModelSQL, ModelView, CurrentState):
'Tariff Adjustment Category'
__name__ = 'tariff_system.tariff.adjustment.category'
_history = True
name = fields.Char(
'Name', states={'required': True}, depends=DEPENDS,
help='The name of the category')
value_min = fields.Numeric(
'Minimum', digits=(3, 6), states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS, help='The minimum value')
value_max = fields.Numeric(
'Maximum', digits=(3, 6), states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS, help='The maximum value')
value_default = fields.Numeric(
'Default', digits=(3, 6), states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS, help='The default value')
tariff_categories = fields.Many2Many(
'tariff_category-tariff_adjustment_category',
'tariff_adjustment_category', 'tariff_category', 'Tariff Categories',
states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS,
help='The tariff categories, for which the adjustment category can '
'be applied')
class TariffCategoryTariffAdjustmentCategory(ModelSQL):
'Tariff Category - Tariff Adjustment Category'
__name__ = 'tariff_category-tariff_adjustment_category'
_history = True
tariff_category = fields.Many2One(
'tariff_system.category', 'Tariff Category',
required=True, ondelete='CASCADE')
tariff_adjustment_category = fields.Many2One(
'tariff_system.tariff.adjustment.category',
'Tariff Adjustment Category',
required=True, ondelete='CASCADE')
class TariffAdjustment(PublicApi, ModelSQL, ModelView):
'Tariff Adjustment'
__name__ = 'tariff_system.tariff.adjustment'
_history = True
category = fields.Many2One(
'tariff_system.tariff.adjustment.category', 'Category',
states={'required': True}, help='The category of the adjustment')
status = fields.Selection(
[
('on_approval', 'On Approval'),
('approved', 'Approved'),
('rejected', 'Rejected'),
], 'Status', required=True, sort=False,
help='The approval status of the adjustment')
value = fields.Numeric(
'Value', digits=(3, 6),
required=True,
domain=[
['OR',
('category', '=', None),
('category.value_min', '<=', Eval('value')),],
['OR',
('category', '=', None),
('category.value_max', '>=', Eval('value')),],
],
help='The value of the adjustment')
deviation = fields.Boolean(
'Deviation', help='Does the value deviate from the category standard?')
deviation_reason = fields.Text(
'Deviation Reason', states={
'required': Bool(Eval('deviation')),
'invisible': Bool(~Eval('deviation')),
}, depends=['deviation'],
help='Reason for deviation')
utilisation_indicators = fields.Many2One(
'utilisation.indicators', 'Indicators Utilisation',
help='The set of utilisation indicators of the tariff adjustment')
@fields.depends('category')
def on_change_category(self):
if self.category:
self.value = self.category.value_default
@staticmethod
def default_deviation():
return False
@staticmethod
def default_status():
return 'on_approval'
class TariffRelevanceCategory(PublicApi, ModelSQL, ModelView, CurrentState):
'Tariff Relevance Category'
__name__ = 'tariff_system.tariff.relevance.category'
_history = True
name = fields.Char(
'Name', states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS,
help='The name of the category')
value_min = fields.Numeric(
'Minimum', digits=(3, 6), help='The minimum value', states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS)
value_max = fields.Numeric(
'Maximum', digits=(3, 6), help='The maximum value', states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS)
value_default = fields.Numeric(
'Default', digits=(3, 6), help='The default value', states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS)
tariff_categories = fields.Many2Many(
'tariff_category-tariff_relevance_category',
'tariff_relevance_category', 'tariff_category', 'Tariff Categories',
states={
'required': True,
'readonly': ~Eval('active'),
}, depends=DEPENDS,
help='The tariff categories, for which the relevance category can '
'be applied')
class TariffCategoryTariffRelevanceCategory(ModelSQL):
'Tariff Category - Tariff Relevance Category'
__name__ = 'tariff_category-tariff_relevance_category'
_history = True
tariff_category = fields.Many2One(
'tariff_system.category', 'Tariff Category',
required=True, ondelete='CASCADE')
tariff_relevance_category = fields.Many2One(
'tariff_system.tariff.relevance.category', 'Tariff Relevance Category',
required=True, ondelete='CASCADE')
class TariffRelevance(PublicApi, ModelSQL, ModelView):
'Tariff Relevance'
__name__ = 'tariff_system.tariff.relevance'
_history = True
category = fields.Many2One(
'tariff_system.tariff.relevance.category', 'Category',
states={'required': True},
help='The category of the relevance')
value = fields.Numeric(
'Value', digits=(3, 6),
required=True, help='The value of the relevance')
deviation = fields.Boolean(
'Deviation', help='Does the value deviate from the category standard?')
deviation_reason = fields.Text(
'Deviation Reason', states={
'required': Bool(Eval('deviation')),
'invisible': Bool(~Eval('deviation')),
}, depends=['deviation'],
help='Reason for deviation')
# TODO: Many2One Interface
utilisation_indicators = fields.One2Many(
'utilisation.indicators', 'relevance', 'Indicators Utilisation',
help='The set of utilisation indicators of the tariff relevance')
@staticmethod
def default_deviation():
return False
def get_rec_name(self, name):
rec_name = f"{self.category.name}: {self.value:.2f}"
if self.deviation:
rec_name += " *"
return rec_name
@fields.depends('category')
def on_change_category(self):
if self.category:
self.value = self.category.value_default
class Tariff(PublicApi, ModelSQL, ModelView, CurrentState):
'Tariff'
__name__ = 'tariff_system.tariff'
_history = True
name = fields.Function(
fields.Char('Name'), 'get_name', searcher='search_name')
code = fields.Function(
fields.Char('Code'), 'get_code', searcher='search_code')
system = fields.Many2One(
'tariff_system', 'System', required=True)
category = fields.Many2One(
'tariff_system.category', 'Category', required=True)
def get_name(self, name):
return self.category.name
def get_code(self, name):
return self.category.code + self.system.version
@classmethod
def search_name(cls, name, clause):
return [('tariff_system.tariff.' + clause[0],) + tuple(clause[1:])]
@classmethod
def search_code(cls, name, clause):
return [('tariff_system.tariff.' + clause[0],) + tuple(clause[1:])]
def get_base_formula(self):
version = utils.convert_version(self.code)
return getattr(collection, f"tariff_base__{version}")
def get_relevance_formula(self):
version = utils.convert_version(self.code)
return getattr(collection, f"tariff_relevance__{version}")
def get_share_formula(self):
version = utils.convert_version(self.code)
return getattr(collection, f"tariff_share__{version}")
def get_adjustments_formula(self):
version = utils.convert_version(self.code)
return getattr(collection, f"tariff_adjustments__{version}")
def get_total_formula(self):
version = utils.convert_version(self.system.version)
return getattr(collection, f"tariff_total__{version}")
def get_fee_formula(self):
version = utils.convert_version(self.system.version)
return getattr(collection, f"tariff_fee__{version}")
def get_rec_name(self, name):
rec_name = self.category.code + self.system.version
return rec_name
# --- Collection --------------------------------------------------------------
class Collection(CodeSequence, UUID, ModelSQL, ModelView, CurrencyDigits):
"""
represents a number of allocations on an administrational level
"""
__name__ = 'collection'
_code_sequence = 'collection_sequence'
start = fields.DateTime(
'Start', states={'required': True},
help='Start of the collection')
end = fields.DateTime(
'End', help='End of the collection')
utilisations = fields.One2Many(
'utilisation', 'collection', 'Utilisations',
help='The collected utilisations')
allocations = fields.One2Many(
'allocation', 'collection', 'Total Allocations',
help='The generated allocations')
allocations_processing = fields.Function(
fields.One2Many(
'allocation', None, 'Processing Allocations',
help="Allocations in state 'created' or 'calculated'"),
'get_allocations_with_state')
allocations_unposted = fields.Function(
fields.One2Many(
'allocation', None, 'Unposted Allocations',
help="Allocations with drafted/validated invoices"),
'get_allocations_with_state')
allocations_posted = fields.Function(
fields.One2Many(
'allocation', None, 'Posted Allocations',
help="Allocations with posted invoices"),
'get_allocations_with_state')
allocations_paid = fields.Function(
fields.One2Many(
'allocation', None, 'Paid Allocations',
help="Allocations with paid invoices"),
'get_allocations_with_state')
allocations_distributed = fields.Function(
fields.One2Many(
'allocation', None, 'Distributed Allocations',
help="Allocations in state 'distributed'"),
'get_allocations_with_state')
invoice_amount = fields.Function(
fields.Numeric(
'Invoice Amount', digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits'],
help='The amount to collect'),
'get_invoice_amount')
entity_origin = fields.Selection(
[
('automatic', 'Automatic'),
('manually', 'Manually'),
], 'Entity Origin', states={'required': True}, sort=False,
help='Defines, if an object was created manually (e.g. staff) or '
'automatic (e.g. cronjob).')
entity_creator = fields.Many2One(
'res.user', 'Entity Creator', states={'required': True})
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(1, ('start', 'ASC'))
# TODO:
# - ensure allocations have the same origin (db level & tryton level)
# - ensure allocations have the same licensee (db level & tryton level)
def get_allocations_with_state(self, name):
state = name.split("_")[-1]
if state == 'processing':
return [allocation
for allocation in self.allocations
if allocation.state in ['created', 'calculated']]
elif state == 'unposted':
return [allocation
for allocation in self.allocations
if allocation.invoice.state in ['draft', 'validated']]
elif state == 'posted':
return [allocation
for allocation in self.allocations
if allocation.invoice.state == 'posted']