-
Notifications
You must be signed in to change notification settings - Fork 196
/
entity.py
3178 lines (2704 loc) · 119 KB
/
entity.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
"""
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>.
Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
Contributions to this module:
* Miguel Sanda <msanda@arrobalytics.com>
* Pranav P Tulshyan ptulshyan77@gmail.com<>
The EntityModel represents the Company, Corporation, Legal Entity, Enterprise or Person that engage and operate as a
business. EntityModels can be created as part of a parent/child model structure to accommodate complex corporate
structures where certain entities may be owned by other entities and may also generate consolidated financial statements.
Another use case of parent/child model structures is the coordination and authorization of inter-company transactions
across multiple related entities. The EntityModel encapsulates all LedgerModel, JournalEntryModel and TransactionModel which is the core structure of
Django Ledger in order to track and produce all financials.
The EntityModel must be assigned an Administrator at creation, and may have optional Managers that will have the ability
to operate on such EntityModel.
EntityModels may also have different financial reporting periods, (also known as fiscal year), which start month is
specified at the time of creation. All key functionality around the Fiscal Year is encapsulated in the
EntityReportMixIn.
"""
from calendar import monthrange
from collections import defaultdict
from datetime import date, datetime, timedelta
from decimal import Decimal
from itertools import zip_longest
from random import choices
from string import ascii_lowercase, digits
from typing import Tuple, Union, Optional, List, Dict, Set
from uuid import uuid4, UUID
from django.contrib.auth import get_user_model
from django.core import serializers
from django.core.cache import caches
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Q
from django.db.models.signals import pre_save
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from treebeard.mp_tree import MP_Node, MP_NodeManager, MP_NodeQuerySet
from django_ledger.io import roles as roles_module, validate_roles, IODigestContextManager
from django_ledger.io.io_core import IOMixIn, get_localtime, get_localdate
from django_ledger.models.accounts import AccountModel, AccountModelQuerySet, DEBIT, CREDIT
from django_ledger.models.bank_account import BankAccountModelQuerySet, BankAccountModel
from django_ledger.models.coa import ChartOfAccountModel, ChartOfAccountModelQuerySet
from django_ledger.models.coa_default import CHART_OF_ACCOUNTS_ROOT_MAP
from django_ledger.models.customer import CustomerModelQueryset, CustomerModel
from django_ledger.models.items import (ItemModelQuerySet, ItemTransactionModelQuerySet,
UnitOfMeasureModel, UnitOfMeasureModelQuerySet, ItemModel)
from django_ledger.models.ledger import LedgerModel
from django_ledger.models.mixins import CreateUpdateMixIn, SlugNameMixIn, ContactInfoMixIn, LoggingMixIn
from django_ledger.models.unit import EntityUnitModel
from django_ledger.models.utils import lazy_loader
from django_ledger.models.vendor import VendorModelQuerySet, VendorModel
from django_ledger.settings import DJANGO_LEDGER_DEFAULT_CLOSING_ENTRY_CACHE_TIMEOUT
UserModel = get_user_model()
ENTITY_RANDOM_SLUG_SUFFIX = ascii_lowercase + digits
class EntityModelValidationError(ValidationError):
pass
class EntityModelQuerySet(MP_NodeQuerySet):
"""
A custom defined EntityModel QuerySet.
Inherits from the Materialized Path Node QuerySet Class from Django Treebeard.
"""
def hidden(self):
"""
A QuerySet of all hidden EntityModel.
Returns
-------
EntityModelQuerySet
A filtered QuerySet of hidden EntityModels only.
"""
return self.filter(hidden=True)
def visible(self):
"""
A Queryset of all visible EntityModel.
Returns
-------
EntityModelQuerySet
A filtered QuerySet of visible EntityModels only.
"""
return self.filter(hidden=False)
class EntityModelManager(MP_NodeManager):
"""
A custom defined EntityModel Manager. This ModelManager uses the custom defined EntityModelQuerySet as default.
Inherits from the Materialized Path Node Manager to include the necessary methods to manage tree-like models.
This Model Manager keeps track and maintains a root/parent/child relationship between Entities for the purposes of
producing consolidated financial statements.
Examples
________
>>> user = request.user
>>> entity_model_qs = EntityModel.objects.for_user(user_model=user)
"""
def get_queryset(self):
"""Sets the custom queryset as the default."""
qs = EntityModelQuerySet(self.model).order_by('path')
return qs.order_by('path').select_related('admin', 'default_coa')
def for_user(self, user_model):
"""
This QuerySet guarantees that Users do not access or operate on EntityModels that don't have access to.
This is the recommended initial QuerySet.
Parameters
----------
user_model
The Django User Model making the request.
Returns
-------
EntityModelQuerySet
A filtered QuerySet of EntityModels that the user has access. The user has access to an Entity if:
1. Is the Administrator.
2. Is a manager.
"""
qs = self.get_queryset()
if user_model.is_superuser:
return qs
return qs.filter(
Q(admin=user_model) |
Q(managers__in=[user_model])
)
class EntityModelFiscalPeriodMixIn:
"""
This class encapsulates the functionality needed to determine the start and end of all financial periods of an
EntityModel. At the moment of creation, an EntityModel must be assigned a calendar month which is going to
determine the start of the Fiscal Year.
"""
VALID_QUARTERS = list(range(1, 5))
VALID_MONTHS = list(range(1, 13))
def get_fy_start_month(self) -> int:
"""
The fiscal year start month represents the month (as an integer) when the assigned fiscal year of the
EntityModel starts.
Returns
-------
int
An integer representing the month that the fiscal year starts.
Examples
________
* 1 -> January.
* 4 -> April.
* 9 -> September.
"""
try:
fy: int = getattr(self, 'fy_start_month')
except AttributeError:
# current object is not an entity, get current entity and fetch its fy_start_month value
# if current object is a detail view with an object...
obj = getattr(self, 'object')
if isinstance(obj, EntityModel):
entity = obj
elif isinstance(obj, LedgerModel):
entity = obj.entity
elif isinstance(obj, EntityUnitModel):
entity = obj.entity
elif isinstance(obj, AccountModel):
entity = obj.coa_model.entity
fy: int = getattr(entity, 'fy_start_month')
return fy
def validate_quarter(self, quarter: int):
"""
Validates the quarter as a valid parameter for other functions.
Makes sure that only integers 1,2,3, or 4 are used to refer to a particular Quarter.
Prevents injection of invalid values from views into the IOMixIn.
Parameters
----------
quarter: int
The quarter number to validate.
Raises
------
ValidationError
If quarter is not valid.
"""
if quarter not in self.VALID_QUARTERS:
raise ValidationError(f'Specified quarter is not valid: {quarter}')
def validate_month(self, month: int):
"""
Validates the month as a valid parameter for other functions.
Makes sure that only integers between 1 and 12 are used to refer to a particular month.
Prevents injection of invalid values from views into the IOMixIn.
Parameters
----------
month: int
The month number to validate.
Raises
------
ValidationError
If month is not valid.
"""
if month not in self.VALID_MONTHS:
raise ValidationError(f'Specified month is not valid: {month}')
def get_fy_start(self, year: int, fy_start_month: Optional[int] = None) -> date:
"""
The fiscal year start date of the EntityModel, according to its settings.
Parameters
----------
year: int
The fiscal year associated with the requested start date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
date
The date when the requested EntityModel fiscal year starts.
"""
if fy_start_month:
self.validate_month(fy_start_month)
fy_start_month = self.get_fy_start_month() if not fy_start_month else fy_start_month
return date(year, fy_start_month, 1)
def get_fy_end(self, year: int, fy_start_month: int = None) -> date:
"""
The fiscal year ending date of the EntityModel, according to its settings.
Parameters
----------
year: int
The fiscal year associated with the requested end date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
date
The date when the requested EntityModel fiscal year ends.
"""
if fy_start_month:
self.validate_month(fy_start_month)
fy_start_month = self.get_fy_start_month() if not fy_start_month else fy_start_month
ye = year if fy_start_month == 1 else year + 1
me = 12 if fy_start_month == 1 else fy_start_month - 1
return date(ye, me, monthrange(ye, me)[1])
def get_quarter_start(self, year: int, quarter: int, fy_start_month: int = None) -> date:
"""
The fiscal year quarter starting date of the EntityModel, according to its settings.
Parameters
----------
year: int
The fiscal year associated with the requested start date.
quarter: int
The quarter number associated with the requested start date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
date
The date when the requested EntityModel quarter starts.
"""
if fy_start_month:
self.validate_month(fy_start_month)
fy_start_month = self.get_fy_start_month() if not fy_start_month else fy_start_month
self.validate_quarter(quarter)
quarter_month_start = (quarter - 1) * 3 + fy_start_month
year_start = year
if quarter_month_start > 12:
quarter_month_start -= 12
year_start = year + 1
return date(year_start, quarter_month_start, 1)
def get_quarter_end(self, year: int, quarter: int, fy_start_month: int = None) -> date:
"""
The fiscal year quarter ending date of the EntityModel, according to its settings.
Parameters
----------
year: int
The fiscal year associated with the requested end date.
quarter: int
The quarter number associated with the requested end date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
date
The date when the requested EntityModel quarter ends.
"""
if fy_start_month:
self.validate_month(fy_start_month)
fy_start_month = self.get_fy_start_month() if not fy_start_month else fy_start_month
self.validate_quarter(quarter)
quarter_month_end = quarter * 3 + fy_start_month - 1
year_end = year
if quarter_month_end > 12:
quarter_month_end -= 12
year_end += 1
return date(year_end, quarter_month_end, monthrange(year_end, quarter_month_end)[1])
def get_fiscal_year_dates(self, year: int, fy_start_month: int = None) -> Tuple[date, date]:
"""
Convenience method to get in one shot both, fiscal year start and end dates.
Parameters
----------
year: int
The fiscal year associated with the requested start and end date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
tuple
Both, the date when the requested EntityModel fiscal year start and end date as a tuple.
The start date will be first.
"""
if fy_start_month:
self.validate_month(fy_start_month)
sd = self.get_fy_start(year, fy_start_month)
ed = self.get_fy_end(year, fy_start_month)
return sd, ed
def get_fiscal_quarter_dates(self, year: int, quarter: int, fy_start_month: int = None) -> Tuple[date, date]:
"""
Convenience method to get in one shot both, fiscal year quarter start and end dates.
Parameters
----------
year: int
The fiscal year associated with the requested start and end date.
quarter: int
The quarter number associated with the requested start and end date.
fy_start_month: int
Optional fiscal year month start. If passed, it will override the EntityModel setting.
Returns
-------
tuple
Both, the date when the requested EntityModel fiscal year quarter start and end date as a tuple.
The start date will be first.
"""
if fy_start_month:
self.validate_month(fy_start_month)
self.validate_quarter(quarter)
qs = self.get_quarter_start(year, quarter, fy_start_month)
qe = self.get_quarter_end(year, quarter, fy_start_month)
return qs, qe
def get_fy_for_date(self, dt: Union[date, datetime], as_str: bool = False) -> Union[str, int]:
"""
Given a known date, returns the EntityModel fiscal year associated with the given date.
Parameters
__________
dt: date
Date to evaluate.
as_str: bool
If True, return date as a string.
Returns
_______
str or date
Fiscal year as an integer or string, depending on as_str parameter.
"""
fy_start_month = self.get_fy_start_month()
if dt.month >= fy_start_month:
y = dt.year
else:
y = dt.year - 1
if as_str:
return str(y)
return y
class EntityModelClosingEntryMixIn:
def validate_closing_entry_model(self, closing_entry_model, closing_date: Optional[date] = None):
if isinstance(self, EntityModel):
if self.uuid != closing_entry_model.entity_model_id:
raise EntityModelValidationError(
message=_(f'The Closing Entry Model {closing_entry_model} does not belong to Entity {self.name}')
)
if closing_date and closing_entry_model.closing_date != closing_date:
raise EntityModelValidationError(
message=_(f'The Closing Entry Model date {closing_entry_model.closing_date} '
f'does not match explicitly provided closing_date {closing_date}')
)
# ---> Closing Entry IO Digest <---
def get_closing_entry_digest(self,
to_date: date,
from_date: Optional[date] = None,
user_model: Optional[UserModel] = None,
closing_entry_model=None,
**kwargs: Dict) -> Tuple:
ClosingEntryModel = lazy_loader.get_closing_entry_model()
ClosingEntryTransactionModel = lazy_loader.get_closing_entry_transaction_model()
if not closing_entry_model:
closing_entry_model = ClosingEntryModel(
entity_model=self,
closing_date=to_date
)
closing_entry_model.clean()
else:
self.validate_closing_entry_model(closing_entry_model, closing_date=to_date)
io_digest: IODigestContextManager = self.digest(
user_model=user_model,
to_date=to_date,
from_date=from_date,
by_unit=True,
by_activity=True,
signs=False,
**kwargs
)
ce_data = io_digest.get_closing_entry_data()
ce_txs_list = [
ClosingEntryTransactionModel(
closing_entry_model=closing_entry_model,
account_model_id=ce['account_uuid'],
unit_model_id=ce['unit_uuid'],
tx_type=ce['balance_type'],
activity=ce['activity'],
balance=ce['balance']
) for ce in ce_data
]
for ce in ce_txs_list:
ce.clean()
return closing_entry_model, ce_txs_list
def get_closing_entry_digest_for_date(self,
closing_date: date,
closing_entry_model=None,
**kwargs) -> Tuple:
return self.get_closing_entry_digest(
to_date=closing_date,
closing_entry_model=closing_entry_model,
**kwargs
)
def get_closing_entry_digest_for_month(self,
year: int,
month: int,
**kwargs: Dict) -> Tuple:
_, day_end = monthrange(year, month)
closing_date = date(year=year, month=month, day=day_end)
return self.get_closing_entry_digest_for_date(closing_date=closing_date, **kwargs)
def get_closing_entry_digest_for_fiscal_year(self, fiscal_year: int, **kwargs: Dict) -> Tuple:
closing_date = getattr(self, 'get_fy_end')(year=fiscal_year)
return self.get_closing_entry_digest_for_date(to_date=closing_date, **kwargs)
# ---> Closing Entry QuerySet <---
def get_closing_entry_queryset_for_date(self, closing_date: date):
ClosingEntryTransactionModel = lazy_loader.get_closing_entry_transaction_model()
return ClosingEntryTransactionModel.objects.for_entity(
entity_slug=self,
).filter(closing_entry_model__closing_date__exact=closing_date)
def get_closing_entry_queryset_for_month(self, year: int, month: int):
_, end_day = monthrange(year, month)
closing_date = date(year, month, end_day)
return self.get_closing_entry_queryset_for_date(closing_date=closing_date)
def get_closing_entry_queryset_for_fiscal_year(self, fiscal_year: int):
closing_date: date = getattr(self, 'get_fy_end')(year=fiscal_year)
return self.get_closing_entry_queryset_for_date(closing_date=closing_date)
# ----> Create Closing Entries <----
def create_closing_entry_for_date(self,
closing_date: date,
closing_entry_model=None,
closing_entry_exists=True):
if closing_entry_model:
self.validate_closing_entry_model(closing_entry_model, closing_date=closing_date)
if closing_date > get_localdate():
raise EntityModelValidationError(
message=_(f'Cannot create closing entry with a future date {closing_date}.')
)
if closing_entry_model is None or closing_entry_exists:
self.closingentrymodel_set.filter(closing_date__exact=closing_date).delete()
else:
closing_entry_model.closingentrytransactionmodel_set.all().delete()
closing_entry_model, ce_txs_list = self.get_closing_entry_digest_for_date(
closing_date=closing_date,
closing_entry_model=closing_entry_model
)
if closing_entry_model is not None:
closing_entry_model.save()
ClosingEntryTransactionModel = lazy_loader.get_closing_entry_transaction_model()
return closing_entry_model, ClosingEntryTransactionModel.objects.bulk_create(
objs=ce_txs_list,
batch_size=100
)
def create_closing_entry_for_month(self, year: int, month: int):
_, day = monthrange(year, month)
closing_date = date(year, month, day)
return self.create_closing_entry_for_date(closing_date=closing_date)
def create_closing_entry_for_fiscal_year(self, fiscal_year: int):
closing_date: date = getattr(self, 'get_fy_end')(year=fiscal_year)
return self.create_closing_entry_for_date(closing_date=closing_date)
# ---> Closing Entry Cache Keys <----
def get_closing_entry_cache_key_for_date(self, closing_date: date) -> str:
closing_date = closing_date.strftime('%Y%m%d')
entity_uuid = getattr(self, 'uuid')
return f'closing_entry_{closing_date}_{entity_uuid}'
def get_closing_entry_cache_key_for_month(self, year: int, month: int) -> str:
_, day = monthrange(year, month)
end_dt = date(year=year, month=month, day=day)
return self.get_closing_entry_cache_key_for_date(closing_date=end_dt)
def get_closing_entry_cache_key_for_fiscal_year(self, fiscal_year: int) -> str:
end_dt: date = getattr(self, 'get_fy_end')(year=fiscal_year)
end_dt_str = end_dt.strftime('%Y%m%d')
return f'closing_entry_{end_dt_str}_{self.uuid}'
# ----> Closing Entry Caching Month < -----
def get_closing_entry_cache_for_date(self,
closing_date: date,
cache_name: str = 'default',
force_cache_update: bool = False,
cache_timeout: Optional[int] = None,
**kwargs):
if not force_cache_update:
cache_system = caches[cache_name]
ce_cache_key = self.get_closing_entry_cache_key_for_date(closing_date=closing_date)
ce_ser = cache_system.get(ce_cache_key)
# if closing entry is in cache...
if ce_ser:
ce_qs_serde_gen = serializers.deserialize(format='json', stream_or_string=ce_ser)
return list(ce.object for ce in ce_qs_serde_gen)
return
return self.save_closing_entry_cache_for_date(
closing_date=closing_date,
cache_name=cache_name,
cache_timeout=cache_timeout,
**kwargs)
def get_closing_entry_cache_for_month(self,
year: int,
month: int,
cache_name: str = 'default',
force_cache_update: bool = False,
cache_timeout: Optional[int] = None,
**kwargs):
_, day = monthrange(year, month)
closing_date = date(year, month, day)
return self.get_closing_entry_cache_for_date(
closing_date=closing_date,
cache_name=cache_name,
force_cache_update=force_cache_update,
cache_timeout=cache_timeout,
**kwargs
)
def get_closing_entry_cache_for_fiscal_year(self,
fiscal_year: int,
cache_name: str = 'default',
force_cache_update: bool = False,
cache_timeout: Optional[int] = None,
**kwargs):
closing_date: date = getattr(self, 'get_fy_end')(year=fiscal_year)
return self.get_closing_entry_cache_for_date(
closing_date=closing_date,
cache_name=cache_name,
force_cache_update=force_cache_update,
cache_timeout=cache_timeout,
**kwargs
)
# ---> SAVE CLOSING ENTRY <---
def save_closing_entry_cache_for_date(self,
closing_date: date,
cache_name: str = 'default',
cache_timeout: Optional[int] = None,
**kwargs):
cache_system = caches[cache_name]
ce_qs = self.get_closing_entry_queryset_for_date(closing_date=closing_date)
ce_cache_key = self.get_closing_entry_cache_key_for_date(closing_date=closing_date)
ce_ser = serializers.serialize(format='json', queryset=ce_qs)
if not cache_timeout:
cache_timeout = DJANGO_LEDGER_DEFAULT_CLOSING_ENTRY_CACHE_TIMEOUT
cache_system.set(ce_cache_key, ce_ser, cache_timeout, **kwargs)
return list(ce_qs)
def save_closing_entry_cache_for_month(self,
year: int,
month: int,
cache_name: str = 'default',
cache_timeout: Optional[int] = None,
**kwargs):
_, day = monthrange(year, month)
closing_date = date(year, month, day)
return self.save_closing_entry_cache_for_date(
closing_date=closing_date,
cache_name=cache_name,
cache_timeout=cache_timeout,
**kwargs
)
def save_closing_entry_cache_for_fiscal_year(self,
fiscal_year: int,
cache_name: str = 'default',
cache_timeout: Optional[int] = None,
**kwargs):
closing_date: date = getattr(self, 'get_fy_end')(year=fiscal_year)
return self.save_closing_entry_cache_for_date(
closing_date=closing_date,
cache_name=cache_name,
cache_timeout=cache_timeout,
**kwargs
)
class EntityModelAbstract(MP_Node,
SlugNameMixIn,
CreateUpdateMixIn,
ContactInfoMixIn,
IOMixIn,
LoggingMixIn,
EntityModelFiscalPeriodMixIn,
EntityModelClosingEntryMixIn):
"""
The base implementation of the EntityModel. The EntityModel represents the Company, Corporation, Legal Entity,
Enterprise or Person that engage and operate as a business. The base model inherit from the Materialized Path Node
of the Django Treebeard library. This allows for complex parent/child relationships between Entities to be tracked
and managed properly.
The EntityModel also inherits functionality from the following MixIns:
1. :func:`SlugNameMixIn <django_ledger.models.mixins.SlugNameMixIn>`
2. :func:`PaymentTermsMixIn <django_ledger.models.mixins.PaymentTermsMixIn>`
3. :func:`ContactInfoMixIn <django_ledger.models.mixins.ContactInfoMixIn>`
4. :func:`CreateUpdateMixIn <django_ledger.models.mixins.CreateUpdateMixIn>`
5. :func:`EntityReportMixIn <django_ledger.models.mixins.EntityReportMixIn>`
6. :func:`IOMixIn <django_ledger.io.io_mixin.IOMixIn>`
Attributes
__________
uuid : UUID
This is a unique primary key generated for the table. The default value of this field is uuid4().
name: str
The name of the Company, Enterprise, Person, etc. used to identify the Entity.
admin: UserModel
The Django UserModel that will be assigned as the administrator of the EntityModel.
default_coa: ChartOfAccounts
The default Chart of Accounts Model of the Entity. EntityModel can have multiple Chart of Accounts but only one
can be assigned as default.
managers: UserModel
The Django UserModels that will be assigned as the managers of the EntityModel by the admin.
hidden: bool
A flag used to hide the EntityModel from QuerySets. Defaults to False.
accrual_method: bool
A flag used to define which method of accounting will be used to produce financial statements.
* If False, Cash Method of Accounting will be used.
* If True, Accrual Method of Accounting will be used.
fy_start_month: int
An integer that specifies the month that the Fiscal Year starts.
picture
The image or logo used to identify the company on reports or UI/UX.
"""
CASH_METHOD = 'cash'
ACCRUAL_METHOD = 'accrual'
FY_MONTHS = [
(1, _('January')),
(2, _('February')),
(3, _('March')),
(4, _('April')),
(5, _('May')),
(6, _('June')),
(7, _('July')),
(8, _('August')),
(9, _('September')),
(10, _('October')),
(11, _('November')),
(12, _('December')),
]
LOGGER_NAME_ATTRIBUTE = 'slug'
META_KEY_CLOSING_ENTRY_DATES = 'closing_entries'
uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True)
name = models.CharField(max_length=150, verbose_name=_('Entity Name'))
default_coa = models.OneToOneField('django_ledger.ChartOfAccountModel',
verbose_name=_('Default Chart of Accounts'),
blank=True,
null=True,
on_delete=models.PROTECT)
admin = models.ForeignKey(UserModel,
on_delete=models.CASCADE,
related_name='admin_of',
verbose_name=_('Admin'))
managers = models.ManyToManyField(UserModel,
through='EntityManagementModel',
related_name='managed_by',
verbose_name=_('Managers'))
hidden = models.BooleanField(default=False)
accrual_method = models.BooleanField(default=False, verbose_name=_('Use Accrual Method'))
fy_start_month = models.IntegerField(choices=FY_MONTHS, default=1, verbose_name=_('Fiscal Year Start'))
last_closing_date = models.DateField(null=True, blank=True, verbose_name=_('Last Closing Entry Date'))
picture = models.ImageField(blank=True, null=True)
meta = models.JSONField(default=dict, null=True, blank=True)
objects = EntityModelManager.from_queryset(queryset_class=EntityModelQuerySet)()
node_order_by = ['uuid']
class Meta:
abstract = True
ordering = ['-created']
verbose_name = _('Entity')
verbose_name_plural = _('Entities')
indexes = [
models.Index(fields=['admin'])
]
def __str__(self):
return f'EntityModel {self.slug}: {self.name}'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._CLOSING_ENTRY_DATES: Optional[List[date]] = None
# ## Logging ###
def get_logger_name(self):
return f'EntityModel {self.uuid}'
# ## ENTITY CREATION ###
@classmethod
def create_entity(cls,
name: str,
use_accrual_method: bool,
admin: UserModel,
fy_start_month: int,
parent_entity=None):
"""
Convenience Method to Create a new Entity Model. This is the preferred method to create new Entities in order
to properly handle potential parent/child relationships between EntityModels.
Parameters
----------
name: str
The name of the new Entity.
use_accrual_method: bool
If True, accrual method of accounting will be used, otherwise Cash Method of accounting will be used.
fy_start_month: int
The month which represents the start of a new fiscal year. 1 represents January, 12 represents December.
admin: UserModel
The administrator of the new EntityModel.
parent_entity: EntityModel
The parent Entity Model of the newly created Entity. If provided, the admin user must also be admin of the
parent company.
Returns
-------
"""
entity_model = cls(
name=name,
accrual_method=use_accrual_method,
fy_start_month=fy_start_month,
admin=admin
)
entity_model.clean()
entity_model = cls.add_root(instance=entity_model)
if parent_entity:
if isinstance(parent_entity, str):
# get by slug...
try:
parent_entity_model = EntityModel.objects.get(slug__exact=parent_entity, admin=admin)
except ObjectDoesNotExist:
raise EntityModelValidationError(
message=_(
f'Invalid Parent Entity. '
f'Entity with slug {parent_entity} is not administered by {admin.username}')
)
elif isinstance(parent_entity, UUID):
# get by uuid...
try:
parent_entity_model = EntityModel.objects.get(uuid__exact=parent_entity, admin=admin)
except ObjectDoesNotExist:
raise EntityModelValidationError(
message=_(
f'Invalid Parent Entity. '
f'Entity with UUID {parent_entity} is not administered by {admin.username}')
)
elif isinstance(parent_entity, cls):
# EntityModel instance provided...
if parent_entity.admin != admin:
raise EntityModelValidationError(
message=_(
f'Invalid Parent Entity. '
f'Entity {parent_entity} is not administered by {admin.username}')
)
parent_entity_model = parent_entity
else:
raise EntityModelValidationError(
_('Only slug, UUID or EntityModel allowed.')
)
parent_entity.add_child(instance=entity_model)
return entity_model
# ### ACCRUAL METHODS ######
def get_accrual_method(self) -> str:
if self.is_cash_method():
return self.CASH_METHOD
return self.ACCRUAL_METHOD
def is_cash_method(self) -> bool:
return self.accrual_method is False
def is_accrual_method(self) -> bool:
return self.accrual_method is True
def is_admin_user(self, user_model):
return user_model.id == self.admin_id
# #### LEDGER MANAGEMENT....
def create_ledger(self, name: str, ledger_xid: Optional[str] = None, posted: bool = False, commit: bool = True):
if commit:
return self.ledgermodel_set.create(name=name, ledger_xid=ledger_xid, posted=posted)
return LedgerModel(
entity=self,
posted=posted,
name=name,
ledger_xid=ledger_xid
)
# #### SLUG GENERATION ###
@staticmethod
def generate_slug_from_name(name: str) -> str:
"""
Uses Django's slugify function to create a valid slug from any given string.
Parameters
----------
name: str
The name or string to slugify.
Returns
-------
The slug as a String.
"""
slug = slugify(name)
suffix = ''.join(choices(ENTITY_RANDOM_SLUG_SUFFIX, k=8))
entity_slug = f'{slug}-{suffix}'
return entity_slug
def generate_slug(self,
commit: bool = False,
raise_exception: bool = True,
force_update: bool = False) -> str:
"""
Convenience method to create the EntityModel slug.
Parameters
----------
force_update: bool
If True, will update the EntityModel slug.
raise_exception: bool
Raises ValidationError if EntityModel already has a slug.
commit: bool
If True,
"""
if not force_update and self.slug:
if raise_exception:
raise ValidationError(
message=_(f'Cannot replace existing slug {self.slug}. Use force_update=True if needed.')
)
self.slug = self.generate_slug_from_name(self.name)
if commit:
self.save(update_fields=[
'slug',
'updated'
])
return self.slug
# #### CHART OF ACCOUNTS ####
def has_default_coa(self) -> bool:
"""
Determines if the EntityModel instance has a Default CoA.
Returns
-------
bool
True if EntityModel instance has a Default CoA.
"""
return self.default_coa_id is not None
def get_default_coa(self, raise_exception: bool = True) -> Optional[ChartOfAccountModel]:
"""
Fetches the EntityModel default Chart of Account.
Parameters
----------
raise_exception: bool
Raises exception if no default CoA has been assigned.
Returns
-------
ChartOfAccountModel
The EntityModel default ChartOfAccount.
"""
if not self.default_coa_id:
if raise_exception:
raise EntityModelValidationError(f'EntityModel {self.slug} does not have a default CoA')
return self.default_coa
def set_default_coa(self, coa_model: Optional[Union[ChartOfAccountModel, str]], commit: bool = False):
# if str, will look up CoA Model by slug...
if isinstance(coa_model, str):
coa_model = self.chartofaccountmodel_set.get(slug=coa_model)
else:
self.validate_chart_of_accounts_for_entity(coa_model)