Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OTC-868: modular IMIS: the function of moving a member from one family to another one seems buggy #65

Merged
merged 1 commit into from
Jul 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 25 additions & 11 deletions insuree/gql_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import base64
import graphene

from insuree.services import validate_insuree_number, InsureeService, FamilyService
from insuree.services import validate_insuree_number, InsureeService, FamilyService, InsureePolicyService

from .apps import InsureeConfig
from core.schema import OpenIMISMutation
Expand Down Expand Up @@ -33,7 +33,8 @@ class InsureeBase:
chf_id = graphene.String(max_length=12, required=False)
last_name = graphene.String(max_length=100, required=True)
other_names = graphene.String(max_length=100, required=True)
gender_id = graphene.String(max_length=1, required=True, description="Was mandatory in Legacy but not in modular")
gender_id = graphene.String(max_length=1, required=True,
description="Was mandatory in Legacy but not in modular")
dob = graphene.Date(required=True)
head = graphene.Boolean(required=False)
marital = graphene.String(max_length=1, required=False)
Expand Down Expand Up @@ -152,7 +153,8 @@ def async_mutate(cls, user, **data):
data['validity_from'] = TimeUtils.now()
client_mutation_id = data.get("client_mutation_id")
family = update_or_create_family(data, user)
FamilyMutation.object_mutated(user, client_mutation_id=client_mutation_id, family=family)
FamilyMutation.object_mutated(
user, client_mutation_id=client_mutation_id, family=family)
return None
except Exception as exc:
logger.exception("insuree.mutation.failed_to_create_family")
Expand Down Expand Up @@ -183,7 +185,8 @@ def async_mutate(cls, user, **data):
data['audit_user_id'] = user.id_for_audit
client_mutation_id = data.get("client_mutation_id")
family = update_or_create_family(data, user)
FamilyMutation.object_mutated(user, client_mutation_id=client_mutation_id, family=family)
FamilyMutation.object_mutated(
user, client_mutation_id=client_mutation_id, family=family)
return None
except Exception as exc:
logger.exception("insuree.mutation.failed_to_update_family")
Expand Down Expand Up @@ -220,7 +223,8 @@ def async_mutate(cls, user, **data):
'list': [{'message': _("insuree.mutation.failed_to_delete_family") % {'uuid': family_uuid}}]
})
continue
errors += FamilyService(user).set_deleted(family, data["delete_members"])
errors += FamilyService(user).set_deleted(family,
data["delete_members"])
if len(errors) == 1:
errors = errors[0]['list']
return errors
Expand Down Expand Up @@ -249,7 +253,8 @@ def async_mutate(cls, user, **data):
data['validity_from'] = TimeUtils.now()
client_mutation_id = data.get("client_mutation_id")
insuree = update_or_create_insuree(data, user)
InsureeMutation.object_mutated(user, client_mutation_id=client_mutation_id, insuree=insuree)
InsureeMutation.object_mutated(
user, client_mutation_id=client_mutation_id, insuree=insuree)
return None
except Exception as exc:
logger.exception("insuree.mutation.failed_to_create_insuree")
Expand Down Expand Up @@ -278,11 +283,13 @@ def async_mutate(cls, user, **data):
if not user.has_perms(InsureeConfig.gql_mutation_create_insurees_perms):
raise PermissionDenied(_("unauthorized"))
if 'uuid' not in data:
raise ValidationError("There is no uuid in updateMutation input!")
raise ValidationError(
"There is no uuid in updateMutation input!")
data['audit_user_id'] = user.id_for_audit
client_mutation_id = data.get("client_mutation_id")
insuree = update_or_create_insuree(data, user)
InsureeMutation.object_mutated(user, client_mutation_id=client_mutation_id, insuree=insuree)
InsureeMutation.object_mutated(
user, client_mutation_id=client_mutation_id, insuree=insuree)
return None
except Exception as exc:
logger.exception("insuree.mutation.failed_to_update_insuree")
Expand All @@ -300,7 +307,8 @@ class DeleteInsureesMutation(OpenIMISMutation):
_mutation_class = "DeleteInsureesMutation"

class Input(OpenIMISMutation.Input):
uuid = graphene.String(required=False) # family uuid, to 'lock' family while mutation is processed
# family uuid, to 'lock' family while mutation is processed
uuid = graphene.String(required=False)
uuids = graphene.List(graphene.String)

@classmethod
Expand Down Expand Up @@ -439,11 +447,17 @@ def async_mutate(cls, user, **data):
insuree.save_history()
insuree.family = family
insuree.save()

if data['cancel_policies']:
return InsureeService(user).cancel_policies(insuree)
InsureeService(user).cancel_policies(insuree)

# Assign all the valid policies from the new family
InsureePolicyService(user).add_insuree_policy(insuree)

return None
except Exception as exc:
logger.exception("insuree.mutation.failed_to_change_insuree_family")
logger.exception(
"insuree.mutation.failed_to_change_insuree_family")
return [{
'message': _("insuree.mutation.failed_to_change_insuree_family"),
'detail': str(exc)}
Expand Down
57 changes: 46 additions & 11 deletions insuree/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@
from insuree.apps import InsureeConfig
from insuree.models import InsureePhoto, PolicyRenewalDetail, Insuree, Family, InsureePolicy


logger = logging.getLogger(__name__)


def create_insuree_renewal_detail(policy_renewal):
from core import datetime, datetimedelta
now = datetime.datetime.now()
adult_birth_date = now - datetimedelta(years=CoreConfig.age_of_majority)
photo_renewal_date_adult = now - datetimedelta(months=InsureeConfig.renewal_photo_age_adult) # 60
photo_renewal_date_child = now - datetimedelta(months=InsureeConfig.renewal_photo_age_child) # 12
photo_renewal_date_adult = now - \
datetimedelta(months=InsureeConfig.renewal_photo_age_adult) # 60
photo_renewal_date_child = now - \
datetimedelta(months=InsureeConfig.renewal_photo_age_child) # 12
photos_to_renew = InsureePhoto.objects.filter(insuree__family=policy_renewal.insuree.family) \
.filter(insuree__validity_to__isnull=True) \
.filter(Q(insuree__photo_date__isnull=True)
Expand All @@ -42,7 +45,8 @@ def create_insuree_renewal_detail(policy_renewal):


def validate_insuree_number(insuree_number, uuid=None):
query = Insuree.objects.filter(chf_id=insuree_number, validity_to__isnull=True)
query = Insuree.objects.filter(
chf_id=insuree_number, validity_to__isnull=True)
insuree = query.first()
if insuree and insuree.uuid != uuid:
return [{"errorCode": InsureeConfig.validation_code_taken_insuree_number,
Expand All @@ -64,7 +68,8 @@ def validate_insuree_number(insuree_number, uuid=None):
{
"errorCode": InsureeConfig.validation_code_invalid_insuree_number_len,
"message": "Invalid insuree number length %s, should be %s" %
(len(insuree_number), InsureeConfig.get_insuree_number_length())
(len(insuree_number),
InsureeConfig.get_insuree_number_length())
}
]
config_modulo = InsureeConfig.get_insuree_number_modulo_root()
Expand Down Expand Up @@ -189,7 +194,8 @@ def _create_dir(file_dir):


def create_file(date, insuree_id, photo_bin):
file_dir = path.join(str(date.year), str(date.month), str(date.day), str(insuree_id))
file_dir = path.join(str(date.year), str(date.month),
str(date.day), str(insuree_id))
file_name = str(uuid.uuid4())

_create_dir(file_dir)
Expand All @@ -200,7 +206,8 @@ def create_file(date, insuree_id, photo_bin):


def copy_file(date, insuree_id, original_file):
file_dir = path.join(str(date.year), str(date.month), str(date.day), str(insuree_id))
file_dir = path.join(str(date.year), str(date.month),
str(date.day), str(insuree_id))
file_name = str(uuid.uuid4())

_create_dir(file_dir)
Expand Down Expand Up @@ -230,7 +237,8 @@ def create_or_update(self, data):
if errors:
raise Exception("Invalid insuree number")
if insuree_uuid:
insuree = Insuree.objects.prefetch_related("photo").get(uuid=insuree_uuid)
insuree = Insuree.objects.prefetch_related(
"photo").get(uuid=insuree_uuid)
insuree.save_history()
# reset the non required fields
# (each update is 'complete', necessary to be able to set 'null')
Expand Down Expand Up @@ -265,7 +273,8 @@ def remove(self, insuree):
def set_deleted(self, insuree):
try:
insuree.delete_history()
[ip.delete_history() for ip in insuree.insuree_policies.filter(validity_to__isnull=True)]
[ip.delete_history()
for ip in insuree.insuree_policies.filter(validity_to__isnull=True)]
return []
except Exception as exc:
logger.exception("insuree.mutation.failed_to_delete_insuree")
Expand All @@ -280,13 +289,15 @@ def cancel_policies(self, insuree):
try:
from core import datetime
now = datetime.datetime.now()
ips = insuree.insuree_policies.filter(Q(expiry_date__isnull=True) | Q(expiry_date__gt=now))
ips = insuree.insuree_policies.filter(
Q(expiry_date__isnull=True) | Q(expiry_date__gt=now))
for ip in ips:
ip.expiry_date = now
InsureePolicy.objects.bulk_update(ips, ['expiry_date'])
return []
except Exception as exc:
logger.exception("insuree.mutation.failed_to_cancel_insuree_policies")
logger.exception(
"insuree.mutation.failed_to_cancel_insuree_policies")
return {
'title': insuree.chf_id,
'list': [{
Expand All @@ -295,14 +306,38 @@ def cancel_policies(self, insuree):
}


class InsureePolicyService:
def __init__(self, user):
self.user = user

def add_insuree_policy(self, insuree):
from policy.models import Policy
policies = Policy.objects.filter(family_id=insuree.family_id)
for policy in policies:
if policy.can_add_insuree():
ip = InsureePolicy(
insuree=insuree,
policy=policy,
enrollment_date=policy.enroll_date,
start_date=policy.start_date,
effective_date=policy.effective_date,
expiry_date=policy.expiry_date,
offline=False,
audit_user_id=self.user.i_user.id
)
print(ip.__dict__)
ip.save()


class FamilyService:
def __init__(self, user):
self.user = user

def create_or_update(self, data):
head_insuree_data = data.pop('head_insuree')
head_insuree_data["head"] = True
head_insuree = InsureeService(self.user).create_or_update(head_insuree_data)
head_insuree = InsureeService(
self.user).create_or_update(head_insuree_data)
data["head_insuree"] = head_insuree
family_uuid = data.pop('uuid', None)
if family_uuid:
Expand Down