Skip to content

Commit

Permalink
OM-189 Implemented online worker query
Browse files Browse the repository at this point in the history
  • Loading branch information
malinowskikam committed Aug 28, 2024
1 parent e32c985 commit 6fa3114
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 47 deletions.
4 changes: 3 additions & 1 deletion worker_voucher/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"voucher_expiry_period": {
"months": 1
},
"yearly_worker_voucher_limit": 120
"yearly_worker_voucher_limit": 120,
"validate_created_worker_online": True
}


Expand All @@ -44,6 +45,7 @@ class WorkerVoucherConfig(AppConfig, ConfigUtilMixin):
voucher_bill_due_period = None
voucher_expiry_period = None
yearly_worker_voucher_limit = None
validate_created_worker_online = None

def ready(self):
from core.models import ModuleConfiguration
Expand Down
15 changes: 7 additions & 8 deletions worker_voucher/gql_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
from django.utils.translation import gettext as _
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from uuid import uuid4

from core import datetime
from core.gql.gql_mutations.base_mutation import BaseMutation
from core.models import MutationLog
from core.schema import OpenIMISMutation
Expand All @@ -18,7 +16,7 @@
from worker_voucher.models import WorkerVoucher
from worker_voucher.services import WorkerVoucherService, validate_acquire_unassigned_vouchers, \
validate_acquire_assigned_vouchers, validate_assign_vouchers, create_assigned_voucher, create_voucher_bill, \
create_unassigned_voucher, assign_voucher, policyholder_user_filter
create_unassigned_voucher, assign_voucher, economic_unit_user_filter


class CreateWorkerMutation(CreateInsureeMutation):
Expand All @@ -34,7 +32,7 @@ class Input(CreateInsureeInputType):
@classmethod
def async_mutate(cls, user, **data):
user_policyholders = PolicyHolder.objects.filter(
policyholder_user_filter(user)).values_list('id', flat=True)
economic_unit_user_filter(user)).values_list('id', flat=True)
economic_unit_code = data.pop('economic_unit_code', None)
chf_id = data.get('chf_id', None)
ph = PolicyHolder.objects.filter(
Expand Down Expand Up @@ -102,7 +100,7 @@ def _mutate(cls, user, uuid=None, uuids=None, economic_unit_code=None, **data):
return [{"message": _("workers.validation.no_workers_to_delete")}]

eu_uuid = (PolicyHolder.objects
.filter(policyholder_user_filter(user), code=economic_unit_code)
.filter(economic_unit_user_filter(user), code=economic_unit_code)
.values_list('uuid', flat=True)
.first())

Expand All @@ -115,8 +113,8 @@ def _mutate(cls, user, uuid=None, uuids=None, economic_unit_code=None, **data):
for worker_uuid in uuids_to_delete:
errors += cls._delete_worker_for_eu(user, worker_uuid, eu_uuid)
if errors:
raise ValidationError("Errors during mutation")
except ValidationError:
raise ValueError("Errors during mutation")
except ValueError:
pass

return errors
Expand All @@ -127,7 +125,8 @@ def _delete_worker_for_eu(cls, user, worker_uuid, eu_uuid):
insuree__uuid=worker_uuid,
insuree__validity_to__isnull=True,
policy_holder__uuid=eu_uuid,
policy_holder__is_deleted=False
policy_holder__is_deleted=False,
is_deleted=False,
).first()

if not phi:
Expand Down
7 changes: 6 additions & 1 deletion worker_voucher/gql_queries.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import graphene
from graphene_django import DjangoObjectType

from core import datetime, ExtendedConnection, prefix_filterset
from core import ExtendedConnection, prefix_filterset
from insuree.gql_queries import InsureeGQLType, PhotoGQLType, GenderGQLType
from insuree.models import Insuree
from invoice.models import Bill
Expand Down Expand Up @@ -83,3 +83,8 @@ class AcquireVouchersValidationSummaryGQLType(graphene.ObjectType):
price = graphene.Decimal()
count = graphene.Int()
price_per_voucher = graphene.Decimal()


class OnlineWorkerDataGQLType(graphene.ObjectType):
other_names = graphene.String()
last_name = graphene.String()
68 changes: 50 additions & 18 deletions worker_voucher/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@
from insuree.apps import InsureeConfig
from insuree.gql_queries import InsureeGQLType
from insuree.models import Insuree
from insuree.services import custom_insuree_number_validation
from msystems.services.mconnect_worker_service import MConnectWorkerService
from policyholder.models import PolicyHolder
from worker_voucher.apps import WorkerVoucherConfig
from worker_voucher.gql_queries import WorkerVoucherGQLType, AcquireVouchersValidationSummaryGQLType, WorkerGQLType
from worker_voucher.gql_queries import WorkerVoucherGQLType, AcquireVouchersValidationSummaryGQLType, WorkerGQLType, \
OnlineWorkerDataGQLType
from worker_voucher.gql_mutations import CreateWorkerVoucherMutation, UpdateWorkerVoucherMutation, \
DeleteWorkerVoucherMutation, AcquireUnassignedVouchersMutation, AcquireAssignedVouchersMutation, \
DateRangeInclusiveInputType, AssignVouchersMutation, CreateWorkerMutation, DeleteWorkerMutation
from worker_voucher.models import WorkerVoucher
from worker_voucher.services import get_voucher_worker_enquire_filters, validate_acquire_unassigned_vouchers, \
validate_acquire_assigned_vouchers, validate_assign_vouchers, policyholder_user_filter
validate_acquire_assigned_vouchers, validate_assign_vouchers, economic_unit_user_filter, worker_user_filter


class Query(ExportableQueryMixin, graphene.ObjectType):
Expand All @@ -29,7 +33,7 @@ class Query(ExportableQueryMixin, graphene.ObjectType):
WorkerGQLType,
orderBy=graphene.List(of_type=graphene.String),
client_mutation_id=graphene.String(),
policy_holder_code=graphene.String()
economic_unit_code=graphene.String()
)

worker_voucher = OrderedDjangoFilterConnectionField(
Expand Down Expand Up @@ -70,22 +74,29 @@ class Query(ExportableQueryMixin, graphene.ObjectType):
date_ranges=graphene.List(DateRangeInclusiveInputType)
)

def resolve_worker(self, info, client_mutation_id=None, policy_holder_code=None, **kwargs):
online_worker_data = graphene.Field(
OnlineWorkerDataGQLType,
national_id=graphene.String(),
economic_unit_code=graphene.ID(),
)

def resolve_worker(self, info, client_mutation_id=None, economic_unit_code=None, **kwargs):
Query._check_permissions(info.context.user, InsureeConfig.gql_query_insurees_perms)
filters = filter_validity(**kwargs)

if client_mutation_id:
filters.append(Q(mutations__mutation__client_mutation_id=client_mutation_id))

if policy_holder_code:
workers_filters = [
Q(policyholderinsuree__policy_holder__code=policy_holder_code),
Q(policyholderinsuree__policy_holder__is_deleted=False),
Q(policyholderinsuree__is_deleted=False),
]
filters += workers_filters
eu = PolicyHolder.objects.filter(economic_unit_user_filter(info.context.user)).first()
if not eu:
raise AttributeError("workers.validation.economic_unit_not_exist")

query = Insuree.get_queryset(None, info.context.user).distinct('id').filter(
worker_user_filter(info.context.user),
policyholderinsuree__policy_holder__code=economic_unit_code,
)

return gql_optimizer.query(Insuree.objects.filter(*filters).distinct(), info)
return gql_optimizer.query(query.filter(*filters).distinct(), info)

def resolve_worker_voucher(self, info, client_mutation_id=None, **kwargs):
Query._check_permissions(info.context.user, WorkerVoucherConfig.gql_worker_voucher_search_perms)
Expand All @@ -94,24 +105,24 @@ def resolve_worker_voucher(self, info, client_mutation_id=None, **kwargs):
if client_mutation_id:
filters.append(Q(mutations__mutation__client_mutation_id=client_mutation_id))

query = (WorkerVoucher.objects.filter(policyholder_user_filter(info.context.user, prefix='policyholder__'))
query = (WorkerVoucher.objects.filter(economic_unit_user_filter(info.context.user, prefix='policyholder__'))
.filter(*filters))
return gql_optimizer.query(query, info)

def resolve_previous_workers(self, info, economic_unit_code=None, date_range=None, **kwargs):
Query._check_permissions(info.context.user, InsureeConfig.gql_query_insuree_perms)
filters = append_validity_filter(**kwargs)

# This query inner joins workervoucher and duplicates insuree for every voucher for some reason
# distinct added to fix that
eu = PolicyHolder.objects.filter(economic_unit_user_filter(info.context.user), code=economic_unit_code).first()
if not eu:
return [{"message": _("workers.validation.economic_unit_not_exist")}]

query = Insuree.get_queryset(None, info.context.user).distinct('id').filter(
validity_to__isnull=True,
worker_user_filter(info.context.user),
workervoucher__is_deleted=False,
workervoucher__policyholder__is_deleted=False,
workervoucher__policyholder__code=economic_unit_code,
policyholderinsuree__policy_holder__code=economic_unit_code,
policyholderinsuree__is_deleted=False,
policyholderinsuree__policy_holder__is_deleted=False,
)

if date_range:
Expand Down Expand Up @@ -177,6 +188,27 @@ def resolve_assign_vouchers_validation(self, info, economic_unit_code=None, work
validation_summary.pop("unassigned_vouchers")
return AcquireVouchersValidationSummaryGQLType(**validation_summary)

def resolve_online_worker_data(self, info, national_id=None, economic_unit_code=None, **kwargs):
Query._check_permissions(info.context.user, InsureeConfig.gql_query_insuree_perms)

eu = PolicyHolder.objects.filter(economic_unit_user_filter(info.context.user), code=economic_unit_code).first()
if not eu:
return [{"message": _("workers.validation.economic_unit_not_exist")}]

if InsureeConfig.get_insuree_number_validator():
errors = custom_insuree_number_validation(national_id)
if errors:
return errors

online_result = MConnectWorkerService().fetch_worker_data(national_id, info.context.user, eu)
if not online_result.get("success", False):
raise AttributeError(online_result.get("error", _("Unknown Error")))

return OnlineWorkerDataGQLType(
other_names=online_result.get("data", {}).get("GivenName"),
last_name=online_result.get("data", {}).get("FamilyName")
)

@staticmethod
def _check_permissions(user, perms):
if type(user) is AnonymousUser or not user.id or not user.has_perms(perms):
Expand Down
16 changes: 14 additions & 2 deletions worker_voucher/services.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
from decimal import Decimal
from sys import prefix
from typing import Iterable, Dict, Union, List
from uuid import uuid4

Expand Down Expand Up @@ -315,7 +316,7 @@ def create_voucher_bill(user, voucher_ids, policyholder_id):
return BillService.bill_create(convert_results=bill_create_payload)


def policyholder_user_filter(user: User, prefix='') -> Q:
def economic_unit_user_filter(user: User, prefix='') -> Q:
if user.is_imis_admin or user.has_perms(WorkerVoucherConfig.gql_worker_voucher_search_all_perms):
return Q()

Expand All @@ -329,13 +330,24 @@ def policyholder_user_filter(user: User, prefix='') -> Q:

return Q(**filters)

def worker_user_filter(user: User, prefix='') -> Q:
if user.is_imis_admin or user.has_perms(WorkerVoucherConfig.gql_worker_voucher_search_all_perms):
return Q()

filters = {
f"{prefix}policyholderinsuree__is_deleted": False,
f'{prefix}validity_to__isnull': True
}

return Q(**filters) & economic_unit_user_filter(user, prefix="policyholderinsuree__policy_holder__")


def worker_voucher_bill_user_filter(qs: QuerySet, user: User) -> QuerySet:
if user.is_imis_admin:
return qs

user_policyholders = PolicyHolder.objects.filter(
policyholder_user_filter(user)).values_list('id', flat=True)
economic_unit_user_filter(user)).values_list('id', flat=True)

return qs.annotate(subject_uuid=Cast('subject_id', UUIDField())) \
.filter(subject_uuid__in=user_policyholders)
22 changes: 5 additions & 17 deletions worker_voucher/tests/test_gql_worker_delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from core.test_helpers import create_test_interactive_user
from insuree.models import Insuree
from worker_voucher.schema import Query, Mutation
from worker_voucher.services import policyholder_user_filter
from worker_voucher.services import worker_user_filter
from worker_voucher.tests.data.gql_payloads import gql_mutation_worker_delete
from worker_voucher.tests.util import create_test_eu_for_user, create_test_worker_for_user_and_eu

Expand Down Expand Up @@ -41,10 +41,7 @@ def setUpClass(cls):
cls.gql_context2 = cls.GQLContext(cls.user2)

def test_delete_worker_success(self):
workers_before = Insuree.objects.filter(
policyholder_user_filter(self.user, prefix='policyholderinsuree__policy_holder__'),
policyholderinsuree__is_deleted=False,
).count()
workers_before = Insuree.objects.filter(worker_user_filter(self.user)).count()
self.assertEquals(workers_before, 1)

mutation_id = uuid4()
Expand All @@ -58,17 +55,11 @@ def test_delete_worker_success(self):
self.assertFalse(res.get("errors", None))
self._assert_mutation_success(mutation_id)

workers_after = Insuree.objects.filter(
policyholder_user_filter(self.user, prefix='policyholderinsuree__policy_holder__'),
policyholderinsuree__is_deleted=False,
).count()
workers_after = Insuree.objects.filter(worker_user_filter(self.user)).count()
self.assertEquals(workers_after, 0)

def test_delete_worker_failed_no_worker(self):
workers_before = Insuree.objects.filter(
policyholder_user_filter(self.user, prefix='policyholderinsuree__policy_holder__'),
policyholderinsuree__is_deleted=False,
).count()
workers_before = Insuree.objects.filter(worker_user_filter(self.user)).count()
self.assertEquals(workers_before, 1)

mutation_id = uuid4()
Expand All @@ -82,10 +73,7 @@ def test_delete_worker_failed_no_worker(self):
self.assertFalse(res.get("errors", None))
self._assert_mutation_failed(mutation_id)

workers_after = Insuree.objects.filter(
policyholder_user_filter(self.user, prefix='policyholderinsuree__policy_holder__'),
policyholderinsuree__is_deleted=False,
).count()
workers_after = Insuree.objects.filter(worker_user_filter(self.user)).count()
self.assertEquals(workers_after, 1)

def _assert_mutation_success(self, mutation_id):
Expand Down

0 comments on commit 6fa3114

Please sign in to comment.