Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding=utf-8 -*-
- from django.db import models
- from django.core.validators import RegexValidator
- from django.contrib.auth.models import User
- from django.conf import settings
- from django.db.models.signals import post_save
- from datetime import timedelta, datetime
- from django.urls import reverse
- from registration.date import *
- from django.db.models.signals import post_save
- from django.dispatch import receiver
- from django.core.exceptions import ValidationError
- from django.forms.models import model_to_dict
- from registration.models import Patient, CriticalParametrs,Entity,Attachment
- from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
- from django.contrib.contenttypes.models import ContentType
- from django.db import models
- from registration.date import get_time_to_city, get_week, cheked_set_write, tz
- from django.utils import timezone
- class Apps(models.Model):
- name = models.CharField('Название приложение', max_length=35)
- version = models.CharField('Версия приложение', max_length=35, default='')
- comment = models.CharField('Коммент', max_length=35)
- is_last = models.BooleanField('Является ли последней', unique=True, default=True)
- app = models.FileField('Приложение')
- def __str__(self):
- return f'{self.name} {self.version} {"Last version" if self.is_last else ""}'
- def get_last_app():
- return Apps.objects.get(is_last=True)
- def to_json(self):
- return model_to_dict(self)
- class Meta:
- verbose_name = 'Приложение'
- verbose_name_plural = 'Приложения'
- db_table = 'app'
- class DeviceTypes(models.Model):
- type = models.CharField('Тип устройства', max_length=30)
- def __str__(self):
- return f'{self.type}'
- class Meta:
- verbose_name = "Тип устройства"
- verbose_name_plural = "Типы устройств"
- class DeviceSpecies(models.Model):
- species = models.CharField('Вид устройства', max_length=10)
- type = models.ForeignKey(DeviceTypes,on_delete=models.CASCADE, default=30)
- def __str__(self):
- return f'{self.species} {self.type}'
- class Meta:
- verbose_name = "Вид устройства"
- verbose_name_plural = "Виды устройств"
- class Sertificate_Device(models.Model):
- name_sertificate = models.CharField('Название сетиификата', max_length=255)
- sertificate = models.FileField('Сертификат', blank=True)
- def __str__(self):
- return 'Сертификат на устройство(Браслет): ' + str(self.name_sertificate)
- class Meta:
- verbose_name = "Сертификат устройства"
- verbose_name_plural = "Сертификаты устройств"
- class HealthDevice(models.Model):
- name = models.CharField('Название браслета', max_length=255, null=False, default = 'Anonymous')
- mac_adress = models.CharField('Мак адрес измерительного устройства', unique=True, max_length=17)
- last_connect = models.DateTimeField('Последнее соединение')
- battery_charge = models.SmallIntegerField('Уровень заряда')
- last_user = models.ForeignKey(Patient, related_name="health_device",on_delete=models.CASCADE,default=0)
- is_active = models.BooleanField(default=True)
- now_measure = models.BooleanField(default=False)
- device_species = models.ForeignKey(DeviceSpecies,on_delete=models.CASCADE, default=0)
- device_type = models.ForeignKey(DeviceTypes,on_delete=models.CASCADE, default=0)
- def __str__(self):
- return f'{self.mac_adress} {self.last_user} {self.last_connect} {"Active" if self.is_active else "NoN"}'
- class Meta:
- verbose_name = "Параметры состояния устройства"
- verbose_name_plural = "Параметры состояния устройств"
- # таблица андроид устройств пользователя
- class Android(models.Model):
- mac_adress = models.CharField('Мак адрес телефона', primary_key=True, max_length=17)
- last_connect = models.DateTimeField('Последнее соединение')
- battery_charge = models.SmallIntegerField('Уровень заряда')
- last_user = models.ForeignKey(Patient, on_delete=models.CASCADE,default=0)
- is_active = models.BooleanField(default=True)
- def __str__(self):
- return f'{self.mac_adress} {self.last_user} {"Active" if self.is_active else "NoN active"}'
- class Meta:
- verbose_name = "Android устройство"
- verbose_name_plural = "Android устройства"
- class BaseDevicesClass(models.Model):
- datetime = models.DateTimeField('Время измерения', db_index=True)
- sync_datetime = models.DateTimeField('Время получения измерения')
- tags = GenericRelation('CriticalValue')
- lat = models.FloatField('Широта', blank=True, null=True)
- lon = models.FloatField('Долгота', blank=True, null=True)
- class Meta:
- abstract = True
- # Теперь ты можешь получить из этого поля user.health_device.get().field_name , попробуй так
- class Tonometer(BaseDevicesClass):
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- HR = models.IntegerField('Пульс')
- HP = models.IntegerField('Систолическое давление')
- LP = models.IntegerField('Диастолическое давление')
- AFTER_MED = models.BooleanField('Прием лекарств')
- def __str__(self):
- return f'{self.user} пульс: {self.HR} давление: {self.HP}/{self.LP}'
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Давление',
- 'values' : str(self.HP) + '/' + str(self.LP),
- 'pacient' : self.user,
- 'only_values':{
- 'HP': self.HP,
- 'LP': self.LP
- }
- }
- else:
- return {
- 'only_values':{
- 'HP': None,
- 'LP': None
- }
- }
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- class Meta:
- verbose_name = "Тонометр"
- verbose_name_plural = "Тонометр"
- class Oximeter(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- HR = models.IntegerField('Пульс')
- BO = models.IntegerField('Уровень кислорода')
- def __str__(self):
- return f'{self.user} пульс: {self.HR} oxi:{self.BO}'
- def get_params(self):
- return {
- 'id' : self.id,
- 'name': 'Пульс',
- 'values' : self.HR,
- 'pacient' : self.user
- }
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- class Meta:
- verbose_name = "Оксиметр"
- verbose_name_plural = "Оксиметр"
- class Glucometer(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- BG = models.DecimalField('Уровень сахара', max_digits=3, decimal_places=1)
- AFTER_EAT = models.BooleanField(default=True)
- def __str__(self):
- return f'{self.user} sugar:{self.BG} { "После" if self.AFTER_EAT else "До"}'
- def get_params(self):
- return {
- 'id' : self.id,
- 'name': 'Уровень сахара',
- 'values' : self.BG,
- 'pacient' : self.user
- }
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- class Meta:
- verbose_name = "Глюкометр"
- verbose_name_plural = "Глюкометр"
- class Thermometer(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- TM = models.DecimalField('Температура', max_digits=3, decimal_places=1)
- def __str__(self):
- return f'{self.user} {self.TM}'
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Температура',
- 'values' : self.TM,
- 'pacient' : self.user
- }
- else:
- return {
- 'only_values':{
- 'TM': None,
- }
- }
- class Meta:
- verbose_name = "Термометр"
- verbose_name_plural = "Термометр"
- class Wristband(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- HP = models.IntegerField('Систолическое давление', default=0)
- LP = models.IntegerField('Диастолическое давление', default=0)
- def __str__(self):
- return f'{self.user} {self.HP}/{self.LP}'
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Давление',
- 'values' : str(self.HP) + '/' + str(self.LP),
- 'pacient' : self.user,
- 'only_values':{
- 'HP': self.HP,
- 'LP': self.LP
- }
- }
- else:
- return {
- 'only_values':{
- 'HP': None,
- 'LP': None
- }
- }
- class Meta:
- verbose_name = "Давление"
- verbose_name_plural = "Давление"
- class Calories(BaseDevicesClass):
- datetime = models.DateTimeField('Время измерения', db_index=True)
- sync_datetime = models.DateTimeField('Время получения измерения')
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- kilocalories = models.FloatField('Калории', default=0)
- def __str__(self):
- return f'{self.user} {self.kilocalories}'
- def create_or_update_model(sync_datetime, android_mac, user, kilocalories):
- try:
- сalories = Calories.objects.get(user = user,sync_datetime = sync_datetime)
- сalories.kilocalories = kilocalories
- сalories.save()
- return сalories
- except:
- сalories = Calories.objects.create(
- user=user,
- datetime=datetime.now(),
- sync_datetime=sync_datetime,
- android_mac = android_mac,
- kilocalories=kilocalories,
- )
- return сalories
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Калории',
- 'values' : str(self.kilocalories),
- 'pacient' : self.user,
- 'only_values':{
- 'kilocalories': self.kilocalories,
- }
- }
- else:
- return {
- 'only_values':{
- 'kilocalories': None
- }
- }
- class Meta:
- verbose_name = "Калории"
- verbose_name_plural = "Калории"
- class Distance(BaseDevicesClass):
- datetime = models.DateTimeField('Время измерения', db_index=True)
- sync_datetime = models.DateTimeField('Время получения измерения')
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE, null=True)
- count_of_steps = models.IntegerField('Дистанция (шаг(и))', null=True)
- meters = models.IntegerField('Дистанция (метр)', null=True)
- def __str__(self):
- return f'{self.user} {self.count_of_steps} {self.meters}метров'
- def create_or_update_model(sync_datetime, android_mac, user, count_of_steps, meters):
- try:
- distance = Distance.objects.get(user = user,sync_datetime = sync_datetime)
- distance.count_of_steps = count_of_steps
- distance.meters = meters
- distance.save()
- return distance
- except:
- distance = Distance.objects.create(
- user=user,
- datetime=datetime.now(),
- sync_datetime=sync_datetime,
- android_mac = android_mac,
- meters=meters,
- count_of_steps=count_of_steps
- )
- return distance
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- def get_params(self = None):
- if self:
- return {
- 'only_values':{
- 'count_of_steps': self.count_of_steps,
- 'meters': self.meters
- }
- }
- else:
- return {
- 'only_values':{
- 'count_of_steps': None,
- 'meters': None
- }
- }
- class Meta:
- verbose_name = "Дистанция"
- verbose_name_plural = "Дистанция"
- class WristbandHR(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='pacient_hr', null=True)
- HR = models.IntegerField('Пульс')
- def __str__(self):
- return f'{self.user} {self.HR}'
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Пульс',
- 'values' : self.HR,
- 'pacient' : self.user
- }
- else:
- return {
- 'only_values':{
- 'HR': None
- }
- }
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- class Meta:
- verbose_name = "Пульс браслета"
- verbose_name_plural = "Пульс браслета"
- class WristbandBO(BaseDevicesClass):
- android_mac = models.ForeignKey(Android,on_delete=models.CASCADE, null=True)
- user = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='pacient_bo', null=True)
- BO = models.IntegerField('Уровень кислорода', default=0)
- def __str__(self):
- return f'{self.user} {self.BO}'
- def get_params(self = None):
- if self:
- return {
- 'id' : self.id,
- 'name': 'Уровень кислорода',
- 'values' : self.BO,
- 'pacient' : self.user
- }
- else:
- return {
- 'only_values':{
- 'BO': None
- }
- }
- @property
- def get_time(self):
- time_shifting = self.user.residence_address.town.time_shifting if self.user.residence_address.town else 0
- return (self.datetime + timedelta(hours=time_shifting)).strftime("%Y-%m-%d %H:%M")
- class Meta:
- verbose_name = "Оксигенация браслета"
- verbose_name_plural = "Оксигенация браслета"
- class Device(models.Model):
- COLOR_CHOICES = (
- ('Красный', 'Красный'),
- ('Синий', 'Синий'),
- ('Чёрный', 'Чёрный'),
- )
- name = models.CharField('Название', max_length=64)
- title = models.CharField('Заголовок', max_length=256, blank=True, default='')
- cost = models.FloatField('Цена')
- color = models.CharField('Цвет',choices=COLOR_CHOICES, max_length=32)
- foto_1 = models.ImageField('Фото браслета', blank=True)
- foto_2 = models.ImageField('Фото браслета', blank=True)
- foto_3 = models.ImageField('Фото браслета', blank=True)
- sertificate = models.ManyToManyField(Sertificate_Device, verbose_name='Сетритикат', blank=True, null=True)
- description = models.TextField('Описание', blank=True, default='')
- basic_specific = models.TextField('Основные спецификации')
- battery = models.CharField('Батарея', max_length=128)
- strap_size = models.CharField('Размер ремешка', max_length=128)
- weight = models.CharField('Вес', max_length=128)
- type_material = models.CharField('Тип материала', max_length=128)
- bluetooth = models.BooleanField('Bluetooth', default = True)
- wi_fi = models.BooleanField('Wi-fi', default = True)
- water_resistance = models.BooleanField('Водостойкость', default = True)
- pedometer = models.BooleanField('Шагомер', default = True)
- heart_rate_monitor = models.BooleanField('Пульсометр',default=True)
- thermometer = models.BooleanField('Термометр',default=True)
- bo_sensor = models.BooleanField('Датчик кислорода в крови',default=True)
- def to_json(self):
- return model_to_dict(self)
- def __str__(self):
- return f'{self.id} {self.name} {self.color} {self.cost}'
- class Meta:
- verbose_name = "Устройство"
- verbose_name_plural = "Устройства"
- class Order(models.Model):
- status = models.CharField('Статус заказа', max_length=128)
- pacient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null = True)
- type_devise = models.ForeignKey(Device, on_delete=models.SET_NULL, null = True)
- color = models.CharField(verbose_name="Цвет",null=True, blank=True,max_length=150)
- region = models.CharField(verbose_name="Регион",null=True, blank=True,max_length=150)
- town = models.CharField(verbose_name="Город",null=True, blank=True,max_length=150)
- district = models.CharField('Район',null=True,blank=True, max_length=150)
- postal_code = models.CharField('Индекс почтовый', blank=True,null=True,max_length=6)
- building = models.CharField('Дом №', max_length=100, blank=True, null=True, default='')
- street = models.CharField(max_length=100, null=True, blank=True, verbose_name='Улица',)
- flat = models.CharField('Квартира №', blank=True,null=True, max_length=10)
- phone_number = models.CharField('Номер телефона', max_length=12, default=None)
- email = models.CharField('Почта', max_length=170, default=None)
- paid = models.BooleanField('Оплачен?', default=False)
- submitted = models.DateTimeField(blank=True, null=True)
- created = models.DateTimeField(auto_now_add=True)
- updated = models.DateTimeField(auto_now=True)
- class Meta:
- verbose_name = "Заказ"
- verbose_name_plural = "Заказы"
- ordering = ('-created',)
- def __str__(self):
- return f'{self.id} {self.pacient} { "PAID" if self.paid else "NO paid"}'
- def to_json(self):
- return model_to_dict(self)
- class Meta:
- verbose_name = "Заказ через сайт"
- verbose_name_plural = "Заказ через сайт"
- db_table = 'order'
- class Orders_Operations(models.Model):
- status = models.CharField('Статус заказа', max_length=128)
- surname = models.CharField('Фамилия', max_length=32, db_index=True)
- name = models.CharField('Имя', max_length=32)
- patronymic = models.CharField('Отчество', max_length=32)
- type_devise = models.ForeignKey(Device, on_delete=models.SET_NULL, null = True)
- color = models.CharField(verbose_name="Цвет",null=True, blank=True,max_length=150)
- region = models.CharField(verbose_name="Регион",null=True, blank=True,max_length=150)
- town = models.CharField(verbose_name="Город",null=True, blank=True,max_length=150)
- district = models.CharField('Район',null=True,blank=True, max_length=150)
- postal_code = models.CharField('Индекс почтовый', blank=True,null=True,max_length=6)
- building = models.CharField('Дом №', max_length=100, blank=True, null=True, default='')
- street = models.CharField(max_length=100, null=True, blank=True, verbose_name='Улица',)
- flat = models.CharField('Квартира №', blank=True,null=True, max_length=10)
- phone_number = models.CharField('Номер телефона', max_length=12, default=None)
- email = models.CharField('Почта', max_length=170, default=None)
- paid = models.BooleanField('Оплачен', default=False)
- sent = models.BooleanField('Отправлен', default=False)
- сonfirmed = models.BooleanField('Подтверждён', default=False)
- submitted = models.DateTimeField(blank=True, null=True)
- created = models.DateTimeField(auto_now_add=True)
- updated = models.DateTimeField(auto_now=True)
- def to_json(self):
- return model_to_dict(self)
- def __str__(self):
- return f'{self.phone_number if self.phone_number else self.email} { "PAID" if self.paid else "NO paid"}'
- def sent_order(id_order, id_device):
- order = Orders_Operations.objects.get(id = id_order)
- order.sent = True
- order.save()
- device = Device.objects.get(id = id_device)
- Leftovers_Devices.decrement(device)
- def paid_product_user(id_order):
- order = Orders_Operations.objects.get(id = id_order)
- order.paid = True
- order.save()
- @property
- def get_address_person(self):
- str_addr = ''
- if self.region:
- str_addr += str(self.region) + ', '
- if self.town:
- str_addr += str(self.town) + ', '
- if self.street:
- str_addr += str(self.street) + ', '
- if self.building:
- str_addr += 'дом' +str(self.building) + ', '
- if self.flat:
- str_addr += 'кв №' + str(self.flat) + ' '
- return str_addr
- class Meta:
- ordering = ('-created',)
- verbose_name = "Заказ через оператора"
- verbose_name_plural = "Заказ через оператора"
- db_table = 'orders_operations'
- class Permissions_Patient(models.Model):
- name = models.CharField('Название', max_length=64)
- def __str__(self):
- return self.name
- class Meta:
- verbose_name = "Права на сайте"
- verbose_name_plural = "Права на сайте"
- db_table = 'permissions_patient'
- class Tarifs(models.Model):
- name = models.CharField('Название тарифа', max_length=64)
- cost = models.PositiveIntegerField('Цена')
- permission = models.ManyToManyField(Permissions_Patient, verbose_name="Права по тарифу")
- slug = models.SlugField(max_length=150, null = True, default='')
- title = models.CharField('Заголовок', max_length=356, default='')
- description = models.TextField('Описание', null = True, default='')
- def __str__(self):
- return self.name
- def get_absolute_url(self):
- return reverse('tarif_set', args=[str(self.slug)])
- class Meta:
- verbose_name = "Тарифы"
- verbose_name_plural = "Тариф"
- db_table = 'tarifs'
- class Subscription(models.Model):
- CHOICES_MOUNTH = (
- ('1', '1'),
- ('6', '6'),
- ('12', '12'),
- )
- user = models.ForeignKey(Patient, related_name='subscription', verbose_name='Пациент', on_delete=models.SET_NULL, null = True)
- tarif = models.ForeignKey(Tarifs, verbose_name='Тариф', on_delete=models.SET_NULL, null = True)
- subscription_date = models.DateTimeField("Дата оформления подписки", default=timezone.now, db_index=True)
- subscription_end_date = models.DateTimeField("Конец подписки", default=datetime.today() + timedelta(1*365/12), db_index=True)
- duration = models.CharField(max_length=12, choices=CHOICES_MOUNTH , default="1")
- status = models.BooleanField("Статуc подписки: ", default = False)
- def create_subscription(user, tarif):
- sub_user = Subscription.objects.create(
- user = user,
- tarif = tarif,
- status = True
- )
- bil_account = BillingAccount.objects.get(user = user)
- bil_account.paymant_operation(tarif.cost)
- def __str__(self):
- return f"{self.user} {self.tarif}"
- class Meta:
- verbose_name = "Подписка"
- verbose_name_plural = "Подписки"
- class HistoryBalance(models.Model):
- amount = models.FloatField('Сумма операции')
- current_amount = models.FloatField('Сумма текущего счёта')
- write_off = models.BooleanField('Снята ли блокировка с текущей суммы', default=False)
- billing_account = models.ForeignKey('BillingAccount', verbose_name= 'Пользователь', on_delete=models.CASCADE)
- datetime_create = models.DateTimeField('Дата создания операции',default=timezone.now, db_index=True)
- def __str__(self):
- return f"{self.billing_account} {self.amount}"
- class Meta:
- verbose_name = "История счёта"
- verbose_name_plural = "История счёта"
- db_table = 'historybalance'
- class BillingAccount(models.Model):
- user = models.ForeignKey(Patient,related_name='bil_pacient_account', on_delete=models.SET_NULL, null = True)
- datetime_create = models.DateTimeField('Дата создания аккаунта',default=timezone.now, db_index=True)
- amount = models.FloatField('Cумма на счету', default=0, null=False)
- def __str__(self):
- return f"{self.user} {self.amount}"
- def paymant_operation(self, amount):
- history = HistoryBalance.objects.create(
- current_amount = self.amount,
- amount = amount,
- write_off = True,
- billing_account = self
- )
- self.amount = self.amount - amount
- self.save()
- def check_status_amount(pacient_id):
- """Проверка суммы для списания со счёта !"""
- count = 0
- block_amount = Block_amount.objects.filter(write_off = False, billing_account__user = pacient_id)
- for amount in block_amount:
- count += amount.amount
- total_amount = BillingAccount.objects.get(user__id = pacient_id).amount- count > 0
- return total_amount
- def block_amount(self, amount):
- """Блокирование суммы для дальнейшего списания"""
- Block_amount.objects.create(billing_account = self, amount = amount, write_off = False)
- def take_away_block_amount(self):
- """отмена заблокированной суммы !"""
- block_amount = Block_amount.objects.get(id = self.id)
- block_amount.write_off = True
- block_amount.save()
- def get_summ_in_account(self):
- return self.amount
- class Meta:
- verbose_name = "Счёт пациентнов"
- verbose_name_plural = "Счёт пациента"
- db_table = 'billingaccount'
- class Block_amount(models.Model):
- amount = models.FloatField('Сумма для блокировки аккаунта')
- write_off = models.BooleanField('Снята ли блокировка с текущей суммы', default=False)
- billing_account = models.ForeignKey(BillingAccount, verbose_name= 'Пользователь с заблокированной суммой', on_delete=models.CASCADE)
- datetime_block = models.DateTimeField('Дата блокировки',default=timezone.now, db_index=True)
- def __str__(self):
- return f"{self.billing_account} {self.amount}"
- class Meta:
- verbose_name = "Блокировка счёта"
- verbose_name_plural = "Блокировка счёта"
- db_table = 'block_amount'
- @receiver(post_save, sender=Patient)
- def save_or_create_account(sender, instance, created, **kwargs):
- if created:
- BillingAccount.objects.create(user=instance, amount = 290)
- else:
- try:
- bl_acc = BillingAccount.objects.get(user=instance)
- bl_acc.save()
- except ObjectDoesNotExist:
- BillingAccount.objects.create(user=instance)
- class Attachment_phys(models.Model):
- """Прикрепление физ.лиц"""
- recording_time = models.DateTimeField('Время записи', blank=False, null=True)
- pacient = models.ForeignKey(Patient, related_name='pacient', verbose_name='Пациент', on_delete=models.CASCADE)
- connected_pacients = models.ForeignKey(Patient, related_name='connected', verbose_name='Физ.лица', on_delete=models.CASCADE)
- confirmation_connected = models.BooleanField('Подтверждение Физ.лица', default=False)
- confirmation_pacient = models.BooleanField('Подтверждение пациента', default=False)
- refusal = models.BooleanField('Отказ', default=False)
- def __str__(self):
- return str(self.pacient) + ' - ' + str(self.connected_pacients)
- def save(self, *args, **kwargs):
- super(Attachment_phys, self).save(*args, **kwargs)
- class Meta:
- verbose_name = "Прикрепление физ.лиц"
- verbose_name_plural = "Прикрепление физ.лиц"
- class Attachment_entity(models.Model):
- """Прикрепление физ.лиц"""
- recording_time = models.DateTimeField('Время записи', blank=False, null=True)
- pacient_entity = models.ForeignKey(Patient, related_name='pacient_entity', verbose_name='Пациент', on_delete=models.CASCADE)
- connected_pacients_entity = models.ForeignKey(Entity, related_name='connected_entity', verbose_name='Юр.лица', on_delete=models.CASCADE)
- confirmation_connected = models.BooleanField('Подтверждение Юр.лица', default=False)
- confirmation_pacient = models.BooleanField('Подтверждение пациента', default=False)
- refusal = models.BooleanField('Отказ', default=False)
- def __str__(self):
- return str(self.pacient) + ' - ' + str(self.connected_pacients)
- def save(self, *args, **kwargs):
- super(Attachment_entity, self).save(*args, **kwargs)
- class Meta:
- db_table= 'attachment_entity'
- verbose_name = 'Запрос на прикрепление к пациенту'
- verbose_name_plural = 'Запросы на прикрепления к пациентам'
- class Trusted_persons(models.Model):
- phone_regex = RegexValidator(regex=r'^\+7\d{11}$')
- user = models.ForeignKey(Patient, on_delete=models.SET_NULL, null = True)
- surname = models.CharField('Фамилия', max_length=32,null = True, db_index=True)
- name = models.CharField('Имя', max_length=32,null = True)
- patronymic = models.CharField('Отчество', max_length=32,null = True)
- comments = models.CharField('Комментарий', max_length=250, null = True)
- relatives_phone_number = models.CharField('Номер телефона доверенного лица', validators=[phone_regex], max_length=12, blank=True)
- hidden = models.BooleanField('Скрыть запись', default=False)
- def __str__(self):
- return f'{self.user}'
- class Meta:
- verbose_name = "Доверенные лица"
- verbose_name_plural = "Доверенное лицо"
- db_table = 'trusted_persons'
- class CriticalValue(models.Model):
- content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
- object_id = models.PositiveIntegerField()
- content_object = GenericForeignKey('content_type', 'object_id')
- connect = models.DateTimeField('Дата формирования записи', default=timezone.now)
- user = models.ForeignKey(Patient, on_delete=models.SET_NULL, null = True)
- measures = models.BooleanField('Обработан', default=False)
- def __str__(self):
- return f'{self.user} {self.content_type} {self.user}'
- def get_measures_filter(id_pacien):
- if ArchiveCriticalValue.objects.filter(critical_values__user = id_pacien).exists():
- list_cr = ArchiveCriticalValue.objects.filter(critical_values__user = id_pacien).last()
- block_time = datetime.strftime(list_cr.date_time_create + timedelta(minutes = 2),'%Y-%m-%d %H:%M:%S')
- now = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
- if datetime.strptime(str(block_time),'%Y-%m-%d %H:%M:%S') < datetime.strptime(str(now),'%Y-%m-%d %H:%M:%S'):
- return False
- else:
- return True
- return False
- def get_values():
- critical_list = []
- cr_v = CriticalValue.objects.filter(connect__date = datetime.today().date())
- for cr in cr_v:
- get_list = cr.content_object.get_params()
- get_list['id_cr_values'] = cr.id
- get_list['connect'] = cr.connect
- critical_list.append(get_list)
- return critical_list
- def get_values_for_pacient(user, o_time=None):
- critical_list = []
- for cr in CriticalValue.objects.filter(connect__date = datetime.today().date(), user = user,measures=False):
- now = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
- if o_time:
- if datetime.strptime(str(o_time),'%Y-%m-%d %H:%M:%S') < datetime.strptime(str(now),'%Y-%m-%d %H:%M:%S'):
- cr.measures = True
- cr.save()
- get_list = cr.content_object.get_params()
- get_list['id_cr_values'] = cr.id
- get_list['connect'] = cr.connect
- critical_list.append(get_list)
- return critical_list
- class Meta:
- verbose_name = "Критическое значение"
- verbose_name_plural = "Критические значения"
- class ArchiveCriticalValue(models.Model):
- date_time_create = models.DateTimeField('Время формирования записи')
- critical_values = models.ForeignKey(CriticalValue,related_name='archive_values', verbose_name='Критический показатель', on_delete=models.CASCADE)
- subject_of_communication = models.CharField('Предмет общения', blank=True, max_length=255)
- action_taken = models.CharField('Cовершённое действие', blank=True, max_length=255)
- date_time_communication = models.DateTimeField('Дата и время обращения оператора к пациенту')
- talk_time_start = models.DateTimeField('Начало разговора')
- talk_time_end = models.DateTimeField('Конец разговора')
- def __str__(self):
- return f'Архив {self.critical_values.user.name} {self.critical_values.user.surname} {self.critical_values.user.patronymic} {self.date_time_create}'
- def to_json(self):
- return model_to_dict(self)
- def create_values(id_critical_value, talk_time_start, talk_time_end):
- cr_v = CriticalValue.objects.get(id = id_critical_value)
- archive = ArchiveCriticalValue.objects.create(
- date_time_create=get_time_to_city(cr_v.user.residence_address.town.time_shifting),
- critical_values=cr_v,
- talk_time_start = talk_time_start,
- talk_time_end = talk_time_end,
- date_time_communication = get_time_to_city(cr_v.user.residence_address.town.time_shifting)
- )
- cr_v.measures= True
- cr_v.save()
- archive.save()
- json_data = archive.to_json()
- json_data['date_time_create'] = archive.date_time_create.strftime('%Y-%m-%d %H:%M:%s')
- json_data['date_time_communication'] = archive.date_time_communication.strftime('%Y-%m-%d %H:%M:%s')
- # json_data['talk_time_start'] = archive.talk_time_start#.strftime('%Y-%m-%d %H:%M:%S')
- # json_data['talk_time_end'] = archive.talk_time_end#.strftime('%Y-%m-%d %H:%M:%S')
- return json_data
- class Meta:
- db_table = 'archive_critical_values'
- verbose_name = 'Архив критических значений'
- verbose_name_plural = 'Архив критических значений'
- class Post(models.Model):
- title = models.CharField('Заголовок',max_length = 256)
- body = models.TextField('Статья')
- previes = models.TextField('Превью',null=True)
- publish = models.DateTimeField('Дата публикации',default = timezone.now)
- created = models.DateTimeField(auto_now_add = True)
- updated = models.DateTimeField(auto_now = True)
- def __str__(self):
- return self.title
- class Meta:
- verbose_name = 'Новости'
- verbose_name_plural = 'Новости'
- # @receiver(post_save, sender=Patient)
- # def save_or_create_subscription(sender, instance, created, **kwargs):
- # if created:
- # Subscription.objects.create(user=instance)
- # else:
- # try:
- # sub_acc = Subscription.objects.get(user=instance)
- # sub_acc.save()
- # except ObjectDoesNotExist:
- # Subscription.objects.create(user=instance)
- class Leftovers_Devices(models.Model):
- type_device = models.ForeignKey(Device, on_delete=models.SET_NULL, null = True)
- count = models.PositiveIntegerField('Кол-во', default = 0)
- def decrement(type_device):
- leftovers = Leftovers_Devices.objects.get(type_device = type_device)
- leftovers.count -= 1
- leftovers.save()
- def __str__(self):
- return f'{self.type_device} {self.count}шт'
- class Meta:
- verbose_name = 'Таблица остатков'
- verbose_name_plural = 'Таблица остатков'
- class Receipts_Devices(models.Model):
- type_device = models.ForeignKey(Device, on_delete=models.SET_NULL, null = True)
- date = models.DateTimeField('Дата поступления')
- count = models.PositiveIntegerField('Кол-во')
- new = models.BooleanField('Новое поступление', default=True)
- re_take = models.BooleanField('Возврат', default=False)
- comment = models.TextField('Комментарий', default='')
- def save(self, *args, **kwargs):
- leftovers, created = Leftovers_Devices.objects.get_or_create(type_device = self.type_device, defaults = {'type_device': self.type_device, 'count': 0})
- leftovers.count += self.count
- leftovers.save()
- super(Receipts_Devices, self).save(*args, **kwargs)
- def __str__(self):
- return f'{self.date} {self.type_device} {self.count}шт'
- class Meta:
- verbose_name = 'Таблица поступленийй'
- verbose_name_plural = 'Таблица поступлений'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement