Ejemplo n.º 1
0
 def renew(self, contract):
     try:
         # check rights for renew contract
         if not self.user.has_perms(
                 ContractConfig.gql_mutation_renew_contract_perms):
             raise PermissionError("Unauthorized")
         from core import datetime, datetimedelta
         contract_to_renew = ContractModel.objects.filter(
             id=contract["id"]).first()
         contract_id = contract["id"]
         # block renewing contract not in Updateable or Approvable state
         state_right = self.__check_rights_by_status(
             contract_to_renew.state)
         # check if we can renew
         if state_right is not "cannot_update" and contract_to_renew.state is not ContractModel.STATE_TERMINATED:
             raise ContractUpdateError("You cannot renew this contract!")
         # create copy of the contract - later we also copy contract detail
         renewed_contract = copy(contract_to_renew)
         # TO DO : if a policyholder is set, the contract details must be removed and PHinsuree imported again
         renewed_contract.id = None
         # Date to (the previous contract) became date From of the new contract (TBC if we need to add 1 day)
         # Date To of the new contract is calculated by DateFrom new contract + “Duration in month of previous contract“
         length_contract = (contract_to_renew.date_valid_to.year - contract_to_renew.date_valid_from.year) * 12 \
                           + (contract_to_renew.date_valid_to.month - contract_to_renew.date_valid_from.month)
         renewed_contract.date_valid_from = contract_to_renew.date_valid_to + datetimedelta(
             days=1)
         renewed_contract.date_valid_to = contract_to_renew.date_valid_to + datetimedelta(
             months=length_contract)
         renewed_contract.state, renewed_contract.version = (
             ContractModel.STATE_DRAFT, 1)
         renewed_contract.amount_rectified, renewed_contract.amount_due = (
             0, 0)
         renewed_contract.save(username=self.user.username)
         historical_record = renewed_contract.history.all().first()
         renewed_contract.json_ext = json.dumps(_save_json_external(
             user_id=historical_record.user_updated.id,
             datetime=historical_record.date_updated,
             message=f"contract renewed - state "
             f"{historical_record.state}"),
                                                cls=DjangoJSONEncoder)
         renewed_contract.save(username=self.user.username)
         # copy also contract details
         self.__copy_details(contract_id=contract_id,
                             modified_contract=renewed_contract)
         renewed_contract_dict = model_to_dict(renewed_contract)
         id_new_renewed = f"{renewed_contract.id}"
         renewed_contract_dict["id"], renewed_contract_dict["uuid"] = (
             id_new_renewed, id_new_renewed)
         return _output_result_success(
             dict_representation=renewed_contract_dict)
     except Exception as exc:
         return _output_exception(model_name="Contract",
                                  method="renew",
                                  exception=exc)
Ejemplo n.º 2
0
 def resolve_claims(self, info, **kwargs):
     if not info.context.user.has_perms(ClaimConfig.gql_query_claims_perms):
         raise PermissionDenied(_("unauthorized"))
     query = Claim.objects
     code_is_not = kwargs.get('codeIsNot', None)
     if code_is_not:
         query = query.exclude(code=code_is_not)
     variance = kwargs.get('diagnosisVariance', None)
     if variance:
         from core import datetime, datetimedelta
         last_year = datetime.date.today() + datetimedelta(years=-1)
         diag_avg = Claim.objects \
                         .filter(*filter_validity(**kwargs)) \
                         .filter(date_claimed__gt=last_year) \
                         .values('icd__code') \
                         .filter(icd__code=OuterRef('icd__code')) \
                         .annotate(diag_avg=Avg('approved')).values('diag_avg')
         variance_filter = Q(claimed__gt=(1 + variance / 100) *
                             Subquery(diag_avg))
         if not ClaimConfig.gql_query_claim_diagnosis_variance_only_on_existing:
             diags = Claim.objects \
                 .filter(*filter_validity(**kwargs)) \
                 .filter(date_claimed__gt=last_year).values('icd__code').distinct()
             variance_filter = (variance_filter | ~Q(icd__code__in=diags))
         query = query.filter(variance_filter)
     return gql_optimizer.query(query.all(), info)
Ejemplo n.º 3
0
    def test_t_user_active_status(self):
        always_valid = User(username='******',
                            t_user=TechnicalUser(username='******'))
        self.assertTrue(always_valid.is_active)

        from core import datetime, datetimedelta
        not_yet_active = User(
            username='******',
            t_user=TechnicalUser(username='******',
                                 validity_from=datetime.datetime.now() +
                                 datetimedelta(days=1)))
        self.assertFalse(not_yet_active.is_active)

        not_active_anymore = User(
            username='******',
            t_user=TechnicalUser(username='******',
                                 validity_to=datetime.datetime.now() +
                                 datetimedelta(days=-1)))
        self.assertFalse(not_active_anymore.is_active)
Ejemplo n.º 4
0
def activate_contracted_policies(sender, instance, **kwargs):
    received_amount = instance.received_amount if instance.received_amount else 0
    # check if payment is related to the contract
    payment_detail = PaymentDetail.objects.filter(
        payment__id=int(instance.id)
    ).prefetch_related(
        'premium__contract_contribution_plan_details__contract_details__contract'
    ).prefetch_related(
        'premium__contract_contribution_plan_details'
    ).filter(premium__contract_contribution_plan_details__isnull=False)
    if len(list(payment_detail)) > 0:
        if instance.expected_amount <= received_amount:
            contribution_list_id = [pd.premium.id for pd in payment_detail]
            contract_list = Contract.objects.filter(
                contractdetails__contractcontributionplandetails__contribution__id__in=contribution_list_id
            ).distinct()
            ccpd_number = ContractContributionPlanDetails.objects.prefetch_related('contract_details__contract').filter(
                contract_details__contract__in=list(contract_list)
            ).count()
            # 1- check if the contract have payment attached to each contributions
            # (nbr CCPD of all contract in step 0= Paymentdetails in Steps 0)
            if ccpd_number == len(list(payment_detail)):
                for contract in contract_list:
                    if contract.state == Contract.STATE_EXECUTABLE:
                        # get the ccpd related to the currenttly processing contract
                        ccpd_list = list(
                            ContractContributionPlanDetails.objects.prefetch_related(
                                'contract_details__contract').filter(
                                contract_details__contract=contract
                            )
                        )
                        from core import datetime, datetimedelta
                        # TODO support Splitted payment and check that
                        #  the payment match the value of all contributions
                        for ccpd in ccpd_list:
                            insuree = ccpd.contract_details.insuree
                            pi = InsureePolicy.objects.create(
                                **{
                                    "insuree": insuree,
                                    "policy": ccpd.policy,
                                    "enrollment_date": ccpd.date_valid_from,
                                    "start_date": ccpd.date_valid_from,
                                    "effective_date": ccpd.date_valid_from,
                                    "expiry_date": ccpd.date_valid_to + datetimedelta(
                                        ccpd.contribution_plan.benefit_plan.grace_period
                                    ),
                                    "audit_user_id": -1,
                                }
                            )
                        contract.state = Contract.STATE_EFFECTIVE
                        __save_or_update_contract(contract, contract.user_updated)
Ejemplo n.º 5
0
 def __append_contract_cpd_to_list(self, ccpd, cp, date_valid_from,
                                   insuree_id, total_amount,
                                   calculated_amount, ccpd_list,
                                   ccpd_record):
     """helper private function to gather results to the list
        ccpd - contract contribution plan details
        cp - contribution plan
        return ccpd list and total amount
     """
     from core import datetime, datetimedelta
     # TODO - catch grace period from calculation rule if is defined
     #  grace_period = cp.calculation_rule etc
     #  length = cp.get_contribution_length(grace_period)
     length = cp.get_contribution_length()
     ccpd.date_valid_from = date_valid_from
     ccpd.date_valid_to = date_valid_from + datetimedelta(months=length)
     # TODO: calculate the number of CCPD to create in order to cover the contract lenght
     ccpd_results = self.create_ccpd(ccpd, insuree_id)
     ccpd_record = model_to_dict(ccpd)
     ccpd_record["calculated_amount"] = calculated_amount
     # TODO: support more that 2 CCPD
     # case 1 - single contribution
     if len(ccpd_results) == 1:
         uuid_string = f"{ccpd_results[0].id}"
         ccpd_record['id'], ccpd_record['uuid'] = (uuid_string, uuid_string)
         ccpd_list.append(ccpd_record)
     # case 2 - 2 contributions with 2 policies
     else:
         # there is additional contribution - we have to calculate/recalculate
         total_amount = total_amount - calculated_amount
         for ccpd_result in ccpd_results:
             length_ccpd = float((ccpd_result.date_valid_to.year - ccpd_result.date_valid_from.year) * 12 \
                           + (ccpd_result.date_valid_to.month - ccpd_result.date_valid_from.month))
             periodicity = float(ccpd_result.contribution_plan.periodicity)
             # time part of splited as a fraction to count contribution value for that splited period properly
             part_time_period = length_ccpd / periodicity
             # rc - result calculation
             rc = run_calculation_rules(ccpd, "update", self.user)
             if rc:
                 calculated_amount = rc[0][1] * part_time_period if rc[0][
                     1] not in [None, False] else 0
                 total_amount += calculated_amount
             ccpd_record = model_to_dict(ccpd_result)
             ccpd_record["calculated_amount"] = calculated_amount
             uuid_string = f"{ccpd_result.id}"
             ccpd_record['id'], ccpd_record['uuid'] = (uuid_string,
                                                       uuid_string)
             ccpd_list.append(ccpd_record)
     return ccpd_list, total_amount, ccpd_record
Ejemplo n.º 6
0
    def resolve_claims(self, info, **kwargs):
        if (not info.context.user.has_perms(ClaimConfig.gql_query_claims_perms)
                and settings.ROW_SECURITY):
            raise PermissionDenied(_("unauthorized"))
        query = Claim.objects
        code_is_not = kwargs.get("code_is_not", None)
        if code_is_not:
            query = query.exclude(code=code_is_not)
        variance = kwargs.get("diagnosisVariance", None)

        items = kwargs.get("items", None)
        services = kwargs.get("services", None)

        if items:
            query = query.filter(items__item__code__in=items)

        if services:
            query = query.filter(services__service__code__in=services)

        json_ext = kwargs.get("json_ext", None)

        if json_ext:
            query = query.filter(json_ext__jsoncontains=json_ext)

        if variance:
            from core import datetime, datetimedelta

            last_year = datetime.date.today() + datetimedelta(years=-1)
            diag_avg = (Claim.objects.filter(*filter_validity(
                **kwargs)).filter(
                    date_claimed__gt=last_year).values("icd__code").filter(
                        icd__code=OuterRef("icd__code")).annotate(
                            diag_avg=Avg("approved")).values("diag_avg"))
            variance_filter = Q(claimed__gt=(1 + variance / 100) *
                                Subquery(diag_avg))
            if not ClaimConfig.gql_query_claim_diagnosis_variance_only_on_existing:
                diags = (Claim.objects.filter(*filter_validity(
                    **kwargs)).filter(date_claimed__gt=last_year).values(
                        "icd__code").distinct())
                variance_filter = variance_filter | ~Q(icd__code__in=diags)
            query = query.filter(variance_filter)
        return gql_optimizer.query(query.all(), info)