class Answer(BaseModel): question = models.ForeignKey('questionnaire.Question', on_delete=models.CASCADE) answer = models.CharField(max_length=128) order = models.IntegerField(default=0) ignore = models.BooleanField(default=False) score = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __str__(self): return self.answer
class Collateral(BaseModel): name = models.CharField(max_length=256) thumbnail = models.URLField(null=True, blank=True) category = models.ForeignKey('product.Category', null=True, blank=True, on_delete=models.PROTECT) url = models.URLField() collateral_type = models.CharField(max_length=16, choices=get_choices( Constants.COLLATERALS_TYPE)) collateral_file_type = models.CharField(max_length=32, choices=get_choices( Constants.COLLATERALS_CHOICES)) promocode = models.ForeignKey('users.PromoCode', on_delete=models.PROTECT) short_descripton = models.CharField(max_length=256, null=True, blank=True) long_descripton = models.TextField(null=True, blank=True) order = models.IntegerField(default=0) def __str__(self): return '%s | %s: %s' % (self.name, self.collateral_type, self.collateral_file_type) class Meta: ordering = ('order', )
class HealthPremium(BaseModel): product_variant = models.ForeignKey('product.ProductVariant', null=True, blank=True, on_delete=models.CASCADE) deductible = models.ForeignKey('product.DeductibleMaster', null=True, blank=True, on_delete=models.CASCADE) sum_insured = models.IntegerField(default=0.0) suminsured_range = IntegerRangeField(db_index=True) age_range = IntegerRangeField(db_index=True) adults = models.IntegerField(null=True, blank=True, db_index=True) childrens = models.IntegerField(null=True, blank=True, db_index=True) citytier = models.CharField(max_length=256, null=True, blank=True) base_premium = models.FloatField(default=Constants.DEFAULT_BASE_PREMIUM) gst = models.FloatField(default=Constants.DEFAULT_GST) commission = models.FloatField(default=0.0) premium = GenericRelation('sales.quote', related_query_name='healthinsurance', object_id_field='premium_id') online_process = models.BooleanField(default=True) is_active = models.BooleanField(default=True) ignore = models.BooleanField(default=False) def get_details(self): return dict(sum_insured=self.sum_insured, amount=self.amount, commision=self.commission_amount) @cached_property def commission_amount(self): company = self.product_variant.company_category.company category = self.product_variant.company_category.category return self.amount * (self.commission + company.commission + category.commission) @cached_property def amount(self): return round((self.gst * self.base_premium) + self.base_premium, 2) def __str__(self): return '%s | %s | %s' % (self.sum_insured, self.product_variant.name, self.age_range)
class Question(BaseModel): category = models.ForeignKey('product.Category', on_delete=models.CASCADE) title = models.CharField(max_length=32) question_type = models.CharField(max_length=10, choices=get_choices( constants.QUESTION_COICES), default="single") question = models.TextField() order = models.IntegerField(default=0) ignore = models.BooleanField(default=False) class Meta: ordering = ('order', ) def __str__(self): return self.title
class FeatureMaster(BaseModel): category = models.ForeignKey('product.Category', null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=127, default="") order = models.IntegerField(default=1) feature_type = models.CharField(max_length=32, default='Others', choices=get_choices( Constants.FEATURE_TYPES)) short_description = models.CharField(max_length=128, null=True, blank=True) long_description = models.TextField(null=True, blank=True) def __str__(self): return "%s - %s" % (self.name, self.category.name) class Meta: ordering = ('order', )
class HealthInsurance(Insurance): gastrointestinal_disease = JSONField( default=list, help_text=Constants.GASTROINTESTINAL_DISEASE) neuronal_diseases = JSONField(default=list, help_text=Constants.NEURONAL_DISEASES) oncology_disease = JSONField(default=list, help_text=Constants.ONCOLOGY_DISEASE) respiratory_diseases = JSONField(default=list, help_text=Constants.RESPIRATORY_DISEASES) cardiovascular_disease = JSONField( default=list, help_text=Constants.CARDIOVASCULAR_DISEASE) ent_diseases = JSONField(default=list, help_text=Constants.ENT_DISEASE) blood_diseases = JSONField(default=list, help_text=Constants.BLOOD_DISODER) alcohol_consumption = models.IntegerField( default=0.0, help_text=Constants.ALCOHOL_CONSUMPTION, null=True, blank=True) tobacco_consumption = models.IntegerField( default=0.0, help_text=Constants.TABBACO_CONSUMPTION, null=True, blank=True) cigarette_consumption = models.IntegerField( default=0.0, help_text=Constants.CIGARETTE_CONSUMPTION, null=True, blank=True) previous_claim = models.BooleanField(default=False, help_text=Constants.PREVIOUS_CLAIM, null=True, blank=True) proposal_terms = models.BooleanField(default=False, help_text=Constants.PROPOSAL_TERMS, null=True, blank=True) def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) def update_default_fields(self, kw): for field in Constants.HEALTHINSURANCE_FIELDS: setattr(self, field, kw) self.save() def switch_premium(self, adults, childrens): opportunity = self.application.quote.opportunity data = dict( effective_age=(now().year - self.application.active_members.aggregate( s=models.Min('dob'))['s'].year), adults=adults, product_variant_id=self.application.quote.premium. product_variant_id, # noqa childrens=childrens) for member in Constants.RELATION_CHOICES: members = self.application.active_members.filter(relation=member) if members.exists() and member not in ['son', 'daughter']: data['%s_age' % (member)] = members.get().age data[ 'customer_segment_id'] = opportunity.category_opportunity.get_customer_segment( **data).id # noqa opportunity.refresh_quote_data(**data) quote = opportunity.get_quotes().first() if not quote: raise RecommendationException('No quote found for this creteria') previous_quote = self.application.quote if quote.id != previous_quote.id: previous_quote.status = 'rejected' previous_quote.save() quote.status = 'accepted' quote.save() self.application.quote_id = quote.id self.application.premium = quote.premium.amount self.application.suminsured = quote.premium.sum_insured self.application.save() def get_summary(self): response = dict() for field in self._meta.fields: if field.name in Constants.INSURANCE_EXCLUDE_FIELDS: continue field_value = getattr(self, field.name) if isinstance(field_value, list): values = list() for row in field_value: if row['value']: values.append( Member.objects.get(id=row['id']).relation) field_value = None if values: field_value = ", ".join(values) if not field_value: continue response[field.name] = field_value return response def get_insurance_fields(self): field_data = list() from sales.serializers import (MemberSerializer, GetInsuranceFieldsSerializer) members = self.application.active_members or Member.objects.filter( application_id=self.application_id) for field in self._meta.fields: if field.name in Constants.INSURANCE_EXCLUDE_FIELDS: continue if field.__class__.__name__ not in [ 'BooleanField', 'IntegerField' ]: members_data = list() for member in getattr(self, field.name): row = MemberSerializer(members.get(id=member['id'])).data row['value'] = member['value'] members_data.append(row) if field.__class__.__name__ == 'BooleanField': data = dict(text=field.help_text, field_name=field.name, field_requirements=[{ 'relation': 'None', 'value': getattr(self, field.name) }]) elif field.__class__.__name__ == 'IntegerField': data = dict(text=field.help_text, field_name=field.name, field_requirements=[{ 'relation': 'None', 'consumption': getattr(self, field.name) }]) else: data = dict(text=field.help_text, field_name=field.name, field_requirements=members_data) serializer = GetInsuranceFieldsSerializer(data=data) serializer.is_valid(raise_exception=True) field_data.append(serializer.data) return field_data
class DeductibleMaster(BaseModel): text = models.CharField(max_length=100) number = models.IntegerField() def __str__(self): return self.text
class SumInsuredMaster(models.Model): text = models.CharField(max_length=64) number = models.IntegerField() def __str__(self): return self.text
class User(BaseModel): account = models.ForeignKey('users.Account', on_delete=models.CASCADE) user_type = models.CharField( choices=get_choices(Constants.USER_TYPE), max_length=16, default=Constants.DEFAULT_USER_TYPE) campaign = models.ForeignKey( 'users.Campaign', null=True, blank=True, on_delete=models.CASCADE) rating = models.IntegerField(default=5) enterprise = models.ForeignKey( 'users.Enterprise', on_delete=models.PROTECT) flag = JSONField(default=Constants.USER_FLAG) is_active = models.BooleanField(default=False) manager_id = models.CharField(max_length=48, null=True, blank=True) def save(self, *args, **kwargs): cache.delete('USER_DETAIL:%s' % self.id) super(self.__class__, self).save(*args, **kwargs) class Meta: unique_together = ('user_type', 'account') def __str__(self): return self.account.get_full_name() def get_authorization_key(self): return jwt.encode( {'user_id': str(self.id)}, JWT_SECRET, algorithm='HS256') def get_full_name(self): return self.account.get_full_name() @classmethod def get_authenticated_user(cls, token): try: payload = jwt.decode(token, JWT_SECRET) return cls.objects.get(id=payload.get('user_id')) except Exception: pass return None def get_accounts(self): return self.bankaccount_set.filter(is_active=True) def generate_referral(self, referral_reference=None): import random code = ('%s%s' % ( self.account.first_name.lower()[:3], self.account.phone_no[-5:]) ).upper() if Referral.objects.filter(code=code).exists(): while Referral.objects.filter(code=code).exists(): code = ('%s%s' % ( self.account.first_name.lower()[:3], random.randint(11111, 99999))).upper() return Referral.objects.create( code=code, reference_code=referral_reference, user_id=self.id) def get_categories(self): categories = list() from product.models import Category for category in Category.objects.only( 'name', 'id', 'hexa_code', 'logo', 'is_active'): is_active = False categorys = self.enterprise.categories.filter(id=category.id) if categorys.exists(): is_active = categorys.get().is_active categories.append(dict( id=category.id, hexa_code=category.hexa_code, name=category.name.split(' ')[0], is_active=is_active, logo=( Constants.DEBUG_HOST if DEBUG else '') + category.logo.url )) categories = sorted( categories, key=lambda category: Constants.CATEGORY_ORDER.get( category['name'], 1)) return categories def get_companies(self): return self.enterprise.companies.filter(is_active=True) def get_applications(self, status=None): from sales.models import Application query = dict(quote__opportunity__lead__user_id=self.id) if status and isinstance(status, list): query['status__in'] = status elif status: query['status'] = status return Application.objects.filter(**query) def get_policies(self): from sales.models import Policy return Policy.objects.filter( application__quote__opportunity__lead__user_id=self.id) def get_earnings(self, earning_type=None): from earnings.models import Earning return Earning.get_user_earnings(self.id, earning_type) def get_rules(self): rules = dict.fromkeys(Constants.PROMO_RULES_KEYS, False) rules['button_text'] = dict( recommendation='View plan details', product_detail='Save Plan') promo_code = self.enterprise.promocode.code.split('-')[1:] for rule_code in promo_code: if not rule_code.isdigit(): rule_code = 1 rules.update(Constants.PROMO_RULES[int(rule_code)]) if self.enterprise.enterprise_type != 'subscriber': rules['kyc_allowed'] = True rules['button_text']['recommendation'] = 'Buy Now' rules['button_text']['product_detail'] = 'Buy Now' return rules def get_collaterals(self): from content.models import Collateral return Collateral.objects.filter( promocode_id=self.enterprise.promocode_id) @staticmethod def validate_referral_code(code): return Referral.objects.filter(code=code).exists() @staticmethod def validate_promo_code(code): return PromoCode.objects.filter(code=code).exists() @staticmethod def get_referral_details(code): # To Dos: Remove this referrals = Referral.objects.filter(code=code) if not referrals.exists(): return { 'user_type': Constants.DEFAULT_USER_TYPE, 'enterprise_id': SubcriberEnterprise.objects.get( name=Constants.DEFAULT_ENTERPRISE).id } referral = referrals.get() from earnings.models import Earning Earning.objects.create( user_id=referral.user.id, earning_type='referral', amount=100) return dict( enterprise_id=( referral.enterprise or SubcriberEnterprise.objects.get( name=Constants.DEFAULT_ENTERPRISE)).id) @staticmethod def get_promo_code_details(code, name): promo_code = PromoCode.objects.get(code=code) enterprises = Enterprise.objects.filter( promocode=promo_code, enterprise_type='enterprise') if enterprises.exists(): return dict( user_type='enterprise', enterprise_id=enterprises.get().id) enterprise = Enterprise.objects.create(name=name, promocode=promo_code) from product.models import Category, Company for category_id in Category.objects.values_list('id', flat=True): enterprise.categories.add(category_id) for company_id in Company.objects.values_list('id', flat=True): enterprise.companies.add(company_id) enterprise.save() return dict( user_type=enterprise.enterprise_type, enterprise_id=enterprise.id) @property def account_no(self): return self.bankaccount_set.get(default=True).account_no @property def ifsc(self): return self.bankaccount_set.get(default=True).branch.ifsc @property def bank_name(self): return self.bankaccount_set.get(default=True).branch.bank.name