Skip to content

Commit

Permalink
Merge pull request #148 from openimis/feature/op-1976
Browse files Browse the repository at this point in the history
update to cope with bad FE
  • Loading branch information
delcroip authored Sep 19, 2024
2 parents 5db878c + 7876cbf commit 08e3799
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 41 deletions.
1 change: 1 addition & 0 deletions insuree/gql_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class InsureeBase:
status = graphene.String(required=False)
status_reason = graphene.String(required=False)
status_date = graphene.Date(required=False)
add_on_existing_policy = graphene.Boolean(required=False)


class CreateInsureeInputType(InsureeBase, OpenIMISMutation.Input):
Expand Down
79 changes: 58 additions & 21 deletions insuree/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,25 @@ def handle_insuree_photo(user, now, insuree, data):
data['audit_user_id'] = user.id_for_audit
data['validity_from'] = now
data['insuree_id'] = insuree.id
if 'uuid' not in data or (existing_insuree_photo and data['uuid'] == existing_insuree_photo.uuid):
data['uuid'] = str(uuid.uuid4())
photo_bin = data.get('photo', None)
# no photo changes
if (
'uuid' in data and existing_insuree_photo and
uuid.UUID(data['uuid']) == uuid.UUID(existing_insuree_photo.uuid)
):
existing_insuree_photo_bin = load_photo_file(
existing_insuree_photo.folder,
existing_insuree_photo.filename
)
if photo_bin == existing_insuree_photo_bin:
return existing_insuree_photo
else:
# we ignore the uuid, FE must have messup
data['uuid'] = str(uuid.uuid4())
if 'uuid' not in data:
data['uuid'] = str(uuid.uuid4())


if photo_bin and InsureeConfig.insuree_photos_root_path \
and (existing_insuree_photo is None or existing_insuree_photo.photo != photo_bin):
(file_dir, file_name) = create_file(now, insuree.id, photo_bin, data['uuid'])
Expand Down Expand Up @@ -234,11 +250,9 @@ def _create_dir(file_dir):
.mkdir(parents=True, exist_ok=True)


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

_create_dir(file_dir)
with open(_photo_dir(file_dir, file_name), "xb") as f:
f.write(base64.b64decode(photo_bin))
Expand Down Expand Up @@ -306,7 +320,7 @@ def __init__(self, user):
self.user = user

@register_service_signal('insuree_service.create_or_update')
def create_or_update(self, data):
def create_or_update(self, data, create_only=False):
photo_data = data.pop('photo', None)
from core import datetime
now = datetime.datetime.now()
Expand All @@ -317,47 +331,51 @@ def create_or_update(self, data):
raise ValidationError(_("mutation.insuree.wrong_status"))
if InsureeConfig.is_insuree_photo_required and photo_data is None:
raise ValidationError(_("mutation.insuree.no_required_photo"))
insuree = None
if "uuid" in data:
insuree = Insuree.objects.filter(uuid=data["uuid"]).first()
elif 'chf_id' in data and not create_only:
insuree = Insuree.objects.filter(chf_id=data["chf_id"], *filter_validity()).first()
if status in [InsureeStatus.INACTIVE, InsureeStatus.DEAD]:
status_reason = InsureeStatusReason.objects.get(code=data.get('status_reason', None),
validity_to__isnull=True)
if status_reason is None or status_reason.status_type != status:
raise ValidationError(_("mutation.insuree.wrong_status"))
data['status_reason'] = status_reason
if "uuid" in data:
insuree = Insuree.objects.get(uuid=data["uuid"])
if insuree:
self.disable_policies_of_insuree(insuree=insuree, status_date=data['status_date'])
elif "uuid" in data:
insuree = Insuree.objects.filter(uuid=data["uuid"]).first()
if not insuree:
insuree = Insuree.objects.create(**data)
self.activate_policies_of_insuree(insuree, audit_user_id=data['audit_user_id'])
if InsureeConfig.insuree_fsp_mandatory and 'health_facility_id' not in data:
raise ValidationError("mutation.insuree.fsp_required")
if not insuree:
insuree = Insuree(**data)

insuree = Insuree(**data)
return self._create_or_update(insuree, photo_data)
return self._create_or_update(
insuree, photo_data,
add_on_existing_policy=data.get('add_on_existing_policy', False)
)

def disable_policies_of_insuree(self, insuree, status_date):
policies_to_cancel = InsureePolicy.objects.filter(insuree=insuree.id, validity_to__isnull=True).all()
for policy in policies_to_cancel:
policy.expiry_date = status_date
policy.save()

def activate_policies_of_insuree(self, insuree, audit_user_id):
def activate_policies_of_insuree(self, insuree):
from core import datetime
now = datetime.date.today()
from policy.models import Policy
policies_to_activate = Policy.objects.filter(family=insuree.family, validity_to__isnull=True)
for policy in policies_to_activate:
if policy.expiry_date >= now:
current_policy_dict = {"effective_date": now, "expiry_date": policy.expiry_date,
"audit_user_id": audit_user_id, "offline": policy.offline,
"audit_user_id": self.user.audit_user_id, "offline": policy.offline,
"start_date": policy.start_date, "policy": policy, "insuree": insuree,
"enrollment_date": policy.enroll_date}
current_policy = InsureePolicy(**current_policy_dict)
current_policy.save()

def _create_or_update(self, insuree, photo_data=None):

def _create_or_update(self, insuree, photo_data=None, add_on_existing_policy=False):
validate_insuree(insuree)
if insuree.id:
filters = Q(id=insuree.id)
Expand All @@ -372,13 +390,15 @@ def _create_or_update(self, insuree, photo_data=None):
if existing_insuree:
existing_insuree.save_history()
insuree.id = existing_insuree.id
insuree.save()

if photo_data:
photo = handle_insuree_photo(self.user, insuree.validity_from, insuree, photo_data)
if photo:
insuree.photo = photo
insuree.photo_date = photo.date
insuree.save()
insuree.save()
if insuree and add_on_existing_policy:
self.activate_policies_of_insuree(insuree=insuree)
return insuree

def remove(self, insuree):
Expand All @@ -395,7 +415,24 @@ def remove(self, insuree):
'message': _("insuree.mutation.failed_to_remove_insuree") % {'chfid': insuree.chfid},
'detail': insuree.uuid}]
}


def change_family(self, insuree, family, user_audit_id=None):
if insuree.family != family:
if (
insuree.family and
insuree.family.head_insuree == insuree
):
raise ValueError(F"Insuree {insuree} already assigned as head to a family")
if user_audit_id:
insuree.save_history()
insuree.family = family
if user_audit_id:
insuree.user_audit_id = user_audit_id
insuree.save()
return True
return False


@register_service_signal('insuree_service.delete')
def set_deleted(self, insuree):
try:
Expand Down
12 changes: 8 additions & 4 deletions insuree/tests/test_graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ def setUpClass(cls):
cls.admin_dist_token = get_token(cls.admin_dist_user, DummyContext(user=cls.admin_dist_user))
cls.photo_base64 = "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=="

cls.photo_base64_2 = "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbrAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=="

def test_query_insuree_number_validity(self):
response = self.query(
'''
Expand Down Expand Up @@ -197,7 +199,7 @@ def test_query_ignore_location(self):

# This validates the status code and if you get errors
self.assertResponseNoErrors(response)

def test_create_insuree(self):
muuid = 'ffa465c5-6807-4de0-847e-202b7f42122b'
response = self.query(f'''
Expand Down Expand Up @@ -240,6 +242,8 @@ def test_create_insuree(self):


def test_create_family(self):
hear_number = generate_random_insuree_number()

muuid='50f8f2c9-7685-4cd5-a7d8-b1fa78d46470'
fuuid='50f8f2c9-7685-4cd5-a770-b1fa34d46470'
response = self.query(f'''
Expand All @@ -249,7 +253,7 @@ def test_create_family(self):
clientMutationId: "{muuid}"
clientMutationLabel: "Create Family - test create family (445566778899)"
headInsuree: {{
chfId: "{generate_random_insuree_number()}"
chfId: "{hear_number}"
lastName: "test"
otherNames: "create family"
genderId: "M"
Expand Down Expand Up @@ -293,7 +297,7 @@ def test_create_family(self):
clientMutationId: "{muuid}"
clientMutationLabel: "Update Family - test create family (445566778899)"
headInsuree: {{
chfId: "{generate_random_insuree_number()}"
chfId: "{hear_number}"
uuid: "50f8f2c9-7685-4cd5-a778-b1fa78d46470"
lastName: "test"
otherNames: "create family"
Expand All @@ -303,7 +307,7 @@ def test_create_family(self):
photo:{{
officerId: 1
date: "2023-12-15"
photo: "{self.photo_base64}"
photo: "{self.photo_base64_2}"
}}
cardIssued:false
Expand Down
47 changes: 31 additions & 16 deletions insuree/tests/test_insuree_photo.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,22 @@
from insuree.test_helpers import create_test_insuree
from location.models import UserDistrict
from core.services import create_or_update_interactive_user, create_or_update_core_user

from core.models.openimis_graphql_test_case import openIMISGraphQLTestCase
from insuree.services import validate_insuree_number
from unittest.mock import ANY
from django.conf import settings
from graphql_jwt.shortcuts import get_token


class InsureePhotoTest(TestCase):
class InsureePhotoTest(openIMISGraphQLTestCase):

test_user = None
_TEST_USER_NAME = None
test_user_PASSWORD = None
_TEST_DATA_USER = None
schema = Schema(
query=insuree_schema.Query,
)

photo_base64 = None
test_photo_path, test_photo_uuid = None, None
Expand All @@ -45,16 +49,19 @@ def setUpTestData(cls):
"language": "en",
"roles": [4],
}
cls.test_photo_path=InsureeConfig.insuree_photos_root_path
cls.test_photo_path = InsureeConfig.insuree_photos_root_path
cls.test_photo_uuid = str(uuid.uuid4())
cls.photo_base64 = "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=="
cls.photo_base64_2 = "iVBORw03GgoAAAANSUhEUgAAAQAAAAEAAQMAAABmvDolAAAAA1BMVEW10NBjBBbqAAAAH0lEQVRoge3BAQ0AAADCoPdPbQ43oAAAAAAAAAAAvg0hAAABmmDh1QAAAABJRU5ErkJggg=="
cls.test_user = cls.__create_user_interactive_core()
cls.insuree = create_test_insuree()
cls.test_user_token = get_token(cls.test_user, cls.BaseTestContext(user=cls.test_user))

#Add the disctict on the user
UserDistrict.objects.create(
user = cls.test_user.i_user,
location = cls.insuree.family.location.parent.parent,
audit_user_id = -1
user=cls.test_user.i_user,
location=cls.insuree.family.location.parent.parent,
audit_user_id=-1
)
cls.test_user.i_user
cls.row_sec = settings.ROW_SECURITY
Expand All @@ -76,9 +83,11 @@ def setUpClass(cls):
##insuree_schema.bind_signals()

def test_add_photo_save_db(self):
result = self.__call_photo_mutation()
result = self.__call_photo_mutation(photo_uuid=self.test_photo_uuid)
self.assertEqual(self.insuree.photo.photo, self.photo_base64)

result = self.__call_photo_mutation(self.photo_base64_2, photo_uuid=self.test_photo_uuid)
self.get_mutation_result(result['data']['updateInsuree']['clientMutationId'], self.test_user_token)

def test_pull_photo_db(self):
self.__call_photo_mutation()
query_result = self.__call_photo_query()
Expand All @@ -90,9 +99,10 @@ def test_pull_photo_db(self):


def test_add_photo_save_files(self):
self.__call_photo_mutation()
uuid_photo = uuid.uuid4()
self.__call_photo_mutation(photo_uuid=uuid_photo)
self.assertEqual(self.insuree.photo.filename,
str(self.test_photo_uuid))
str(uuid_photo))


def test_pull_photo_file_path(self):
Expand All @@ -102,8 +112,10 @@ def test_pull_photo_file_path(self):
self.assertEqual(gql_photo['photo'], self.photo_base64)


def __call_photo_mutation(self):
mutation = self.__update_photo_mutation()
def __call_photo_mutation(self, photo=None, photo_uuid=None):
if not photo:
photo = self.photo_base64
mutation = self.__update_photo_mutation(photo, photo_uuid=photo_uuid)
context = self.BaseTestContext(self.test_user)
result = self.insuree_client.execute(mutation, context=context)
self.insuree = Insuree.objects.get(pk=self.insuree.pk)
Expand All @@ -114,8 +126,11 @@ def __call_photo_query(self):
context = self.BaseTestContext(self.test_user)
return self.insuree_client.execute(query, context=context)

def __update_photo_mutation(self):
self.test_photo_uuid = str(uuid.uuid4()).lower()
def __update_photo_mutation(self, photo, photo_uuid=None):
if photo_uuid:
uuid_insert = f'uuid: "{photo_uuid}"'
else:
uuid_insert = ''
return f'''mutation
{{
updateInsuree(input: {{
Expand All @@ -131,10 +146,10 @@ def __update_photo_mutation(self):
marital: "M"
status: "AC"
photo:{{
uuid: "{self.test_photo_uuid}"
{uuid_insert}
officerId: {self.test_user.i_user_id}
date: "2022-06-21"
photo: "{self.photo_base64}"
photo: "{photo}"
}}
cardIssued:false
familyId: {self.insuree.family.id}
Expand Down
Binary file modified locale/en/LC_MESSAGES/django.mo
Binary file not shown.

0 comments on commit 08e3799

Please sign in to comment.