Skip to content

Commit

Permalink
Finish openimis/fixes_from_dev
Browse files Browse the repository at this point in the history
Fixes from dev
  • Loading branch information
dragos-dobre authored Dec 21, 2021
2 parents 31a32e1 + a9ed5e7 commit 3496f9c
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 19 deletions.
15 changes: 15 additions & 0 deletions core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from copy import copy

import core
from django.apps import apps
from django.db import models
from django.db.models import Q, DO_NOTHING, F
from django.conf import settings
Expand Down Expand Up @@ -369,6 +370,13 @@ def rights(self):
def rights_str(self):
return [str(r) for r in self.rights]

@cached_property
def get_health_facility(self):
if self.health_facility_id:
hf_model = apps.get_model("location", "HealthFacility")
if hf_model:
return hf_model.objects.filter(pk=self.health_facility_id).first()

def set_password(self, raw_password):
from hashlib import sha256
from secrets import token_hex
Expand Down Expand Up @@ -495,6 +503,13 @@ def get_session_auth_hash(self):
key_salt = "core.User.get_session_auth_hash"
return salted_hmac(key_salt, self.username).hexdigest()

def get_health_facility(self):
if self.claim_admin:
return self.claim_admin.health_facility
if self.i_user:
return self.i_user.get_health_facility()
return None

def __getattr__(self, name):
if name == '_u':
raise ValueError('wrapper has not been initialised')
Expand Down
20 changes: 10 additions & 10 deletions core/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def mutate_and_get_payload(cls, root, info, **data):
client_mutation_details=json.dumps(data.get(
"client_mutation_details"), cls=OpenIMISJSONEncoder) if data.get("client_mutation_details") else None
)
logging.debug("OpenIMISMutation: saved as %s, label: %s", mutation_log.id, mutation_log.client_mutation_label)
logger.debug("OpenIMISMutation: saved as %s, label: %s", mutation_log.id, mutation_log.client_mutation_label)
if info and info.context and info.context.user and info.context.user.language:
lang = info.context.user.language
if isinstance(lang, Language):
Expand All @@ -164,7 +164,7 @@ def mutate_and_get_payload(cls, root, info, **data):
translation.activate(lang)

try:
logging.debug("[OpenIMISMutation %s] Sending signals", mutation_log.id)
logger.debug("[OpenIMISMutation %s] Sending signals", mutation_log.id)
results = signal_mutation.send(
sender=cls, mutation_log_id=mutation_log.id, data=data, user=info.context.user,
mutation_module=cls._mutation_module, mutation_class=cls._mutation_class)
Expand All @@ -173,7 +173,7 @@ def mutate_and_get_payload(cls, root, info, **data):
mutation_module=cls._mutation_module, mutation_class=cls._mutation_class
))
errors = [err for r in results for err in r[1]]
logging.debug("[OpenIMISMutation %s] signals sent, got errors back: ", mutation_log.id, len(errors))
logger.debug("[OpenIMISMutation %s] signals sent, got errors back: ", mutation_log.id, len(errors))
if errors:
mutation_log.mark_as_failed(json.dumps(errors))
return cls(internal_id=mutation_log.id)
Expand All @@ -182,37 +182,37 @@ def mutate_and_get_payload(cls, root, info, **data):
sender=cls, mutation_log_id=mutation_log.id, data=data, user=info.context.user,
mutation_module=cls._mutation_module, mutation_class=cls._mutation_class
)
logging.debug("[OpenIMISMutation %s] before mutate signal sent", mutation_log.id)
logger.debug("[OpenIMISMutation %s] before mutate signal sent", mutation_log.id)
if core.async_mutations:
logging.debug("[OpenIMISMutation %s] Sending async mutation", mutation_log.id)
logger.debug("[OpenIMISMutation %s] Sending async mutation", mutation_log.id)
openimis_mutation_async.delay(
mutation_log.id, cls._mutation_module, cls._mutation_class)
else:
logging.debug("[OpenIMISMutation %s] mutating...", mutation_log.id)
logger.debug("[OpenIMISMutation %s] mutating...", mutation_log.id)
try:
error_messages = cls.async_mutate(
info.context.user if info.context and info.context.user else None,
**data)
if not error_messages:
logging.debug("[OpenIMISMutation %s] marked as successful", mutation_log.id)
logger.debug("[OpenIMISMutation %s] marked as successful", mutation_log.id)
mutation_log.mark_as_successful()
else:
errors_json = json.dumps(error_messages)
logging.debug("[OpenIMISMutation %s] marked as failed: %s", mutation_log.id, errors_json)
logger.error("[OpenIMISMutation %s] marked as failed: %s", mutation_log.id, errors_json)
mutation_log.mark_as_failed(errors_json)
except BaseException as exc:
error_messages = exc
logger.error("async_mutate threw an exception. It should have gotten this far.", exc_info=exc)
# Record the failure of the mutation but don't include details for security reasons
mutation_log.mark_as_failed(f"The mutation threw a {type(exc)}, check logs for details")
logging.debug("[OpenIMISMutation %s] send post mutation signal", mutation_log.id)
logger.debug("[OpenIMISMutation %s] send post mutation signal", mutation_log.id)
signal_mutation_module_after_mutating[cls._mutation_module].send(
sender=cls, mutation_log_id=mutation_log.id, data=data, user=info.context.user,
mutation_module=cls._mutation_module, mutation_class=cls._mutation_class,
error_messages=error_messages
)
except Exception as exc:
logger.warning(f"Exception while processing mutation id {mutation_log.id}", exc_info=True)
logger.error(f"Exception while processing mutation id {mutation_log.id}", exc_info=exc)
mutation_log.mark_as_failed(exc)

return cls(internal_id=mutation_log.id)
Expand Down
8 changes: 4 additions & 4 deletions core/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,24 @@ def create_or_update_interactive_user(user_id, data, audit_user_id, connected):
created = True

i_user.save()
create_or_update_user_roles(i_user, data["roles"])
create_or_update_user_roles(i_user, data["roles"], audit_user_id)
if "districts" in data:
create_or_update_user_districts(
i_user, data["districts"], data_subset["audit_user_id"]
)
return i_user, created


def create_or_update_user_roles(i_user, role_ids):
def create_or_update_user_roles(i_user, role_ids, audit_user_id):
from core import datetime

now = datetime.datetime.now()
UserRole.objects.filter(user=i_user, validity_to__isnull=True).update(
validity_to=now
)
for role_id in role_ids:
UserRole.objects.update_or_create(
user=i_user, role_id=role_id, defaults={"validity_to": None}
UserRole.objects.create(
user=i_user, role_id=role_id, audit_user_id=audit_user_id
)


Expand Down
2 changes: 1 addition & 1 deletion core/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def create_test_interactive_user(username, password="Test1234", roles=None, cust
)
i_user.set_password(password)
i_user.save()
create_or_update_user_roles(i_user, roles)
create_or_update_user_roles(i_user, roles, None)
return User.objects.create(
username=username,
i_user=i_user,
Expand Down
9 changes: 6 additions & 3 deletions core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,16 @@ def __ne__(self, other):
return cls


def filter_validity(arg='validity', **kwargs):
def filter_validity(arg="validity", **kwargs):
validity = kwargs.get(arg)
if validity is None:
validity = core.datetime.datetime.now()
return (
Q(validity_from__lte=core.datetime.datetime.now()),
Q(legacy_id__isnull=True),
)
return (
Q(validity_from__lte=validity),
Q(validity_to__isnull=True) | Q(validity_to__gte=validity)
Q(validity_to__isnull=True) | Q(validity_to__gte=validity),
)


Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

setup(
name='openimis-be-core',
version='1.3.0',
version='1.3.1',
packages=find_packages(),
include_package_data=True,
license='GNU AGPL v3',
Expand Down

0 comments on commit 3496f9c

Please sign in to comment.