Vypis a automaticke prirazovani okresu dle PSC k uzivateli

This commit is contained in:
Jarmil 2019-11-13 10:59:34 +01:00
parent 2b8ca1ad45
commit d9b5570d90
7 changed files with 124 additions and 81 deletions

View File

@ -0,0 +1,18 @@
[
{
"model": "nalodeni.county",
"pk": 1,
"fields": {
"name": "Vsetín",
"zip_prefix": "756"
}
},
{
"model": "nalodeni.county",
"pk": 2,
"fields": {
"name": "Praha 4",
"zip_prefix": "149"
}
}
]

View File

@ -8,6 +8,7 @@ from django.core.exceptions import ValidationError
from . import models
class AppUserForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AppUserForm, self).__init__(*args, **kwargs)
@ -129,7 +130,6 @@ class AppRegFollowEmailForm(ModelForm):
return data
class UserFormForm(ModelForm):
def __init__(self, *args, **kwargs):
super(UserFormForm, self).__init__(*args, **kwargs)
@ -153,6 +153,7 @@ class UserFormForm(ModelForm):
model = models.UserForm
fields = ['skills','skills_note', 'topics','regions']
class UserFollowFormForm(ModelForm):
def __init__(self, *args, **kwargs):
super(UserFollowFormForm, self).__init__(*args, **kwargs)
@ -172,7 +173,6 @@ class UserFollowFormForm(ModelForm):
fields = ['topics','regions']
class EmailVizitkaForm(forms.Form):
name = forms.CharField(label=_('Jméno'), max_length=50)
email = forms.CharField(label=_('E-mail'), max_length=50, required=False)
@ -182,32 +182,21 @@ class EmailVizitkaForm(forms.Form):
phone = forms.CharField(label=_('Telefon'), max_length=50, required=False)
##
# Newsletters
##
class NewsletterForm(ModelForm):
#def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
class Meta:
model = models.Newsletter
exclude = []
class NewsMsgForm(ModelForm):
#def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
class NewsMsgForm(ModelForm):
class Meta:
model = models.NewsMsg
fields = ['title', 'headerText', 'footerText',
'delivery_ts', 'sent_ts',
'testMailRecipients']
class NewsMsgBlockForm(ModelForm):
#def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
class NewsMsgBlockForm(ModelForm):
class Meta:
model = models.NewsMsgBlock
exclude = ['newsmsg']
@ -231,5 +220,6 @@ class Euro2019InterestForm(ModelForm):
raise ValidationError(_('Prosím, potvrďte souhlas se zpracováním osobních údajů.'), code='invalid')
return data
class CustomRecipientsForm(forms.Form):
recipients = forms.CharField(widget=forms.Textarea)

View File

@ -0,0 +1,28 @@
# Generated by Django 2.0.3 on 2019-11-13 09:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nalodeni', '0054_auto_20190412_1852'),
]
operations = [
migrations.CreateModel(
name='County',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Název')),
('zip_prefix', models.CharField(max_length=3, verbose_name='Předčíslí PSČ')),
],
options={
'ordering': ['name'],
},
),
migrations.AlterUniqueTogether(
name='county',
unique_together={('zip_prefix',)},
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 2.0.3 on 2019-11-13 09:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('nalodeni', '0055_auto_20191113_0942'),
]
operations = [
migrations.AddField(
model_name='appuser',
name='county',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='nalodeni.County', verbose_name='dotazník'),
),
]

View File

@ -7,6 +7,8 @@ from django.db.models import *
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.core.exceptions import ValidationError
@ -21,7 +23,7 @@ from records_audit.utils import DataAudited
class AppUser(AbstractUser, DataAudited):
"""
Prepare an empty User class just in case it will be needed later.
Uzivatel. Nove nalodeni jsou sem prepisovani z AppRegEmail.
"""
### Jiz definovano v predkovi
#first_name = CharField(_('firstName'),max_length=100, default='')
@ -43,9 +45,7 @@ class AppUser(AbstractUser, DataAudited):
etStamp = DateTimeField(_('E-mail token timestamp'), editable=False,
default=None, blank=True, null=True)
##
# Constants
##
DISTRICT_PHA = 0
DISTRICT_JHC = 1
DISTRICT_JHM = 2
@ -201,15 +201,15 @@ class AppUser(AbstractUser, DataAudited):
userform = ForeignKey('UserForm', on_delete=CASCADE, verbose_name=_('dotazník'),
blank=True, null=True, default=None)
##
# Other fields
##
status = IntegerField(_('Stav'), blank=False, null=False,
default = STATUS_NEW, choices=STATUS_CHOICES)
# stav uzivatele - jaky? proc? ceho? boha jeho...
status = IntegerField(_('Stav'), blank=False, null=False, default = STATUS_NEW, choices=STATUS_CHOICES)
# Okres. Prirazuje se automaticky pri zmene postcode (PSC)
county = ForeignKey('County', on_delete=SET_NULL, verbose_name=_('dotazník'), blank=True, null=True, default=None)
##
# pro kompatibilitu kodu a modelu
@property
def firstName(self):
return self.first_name
@ -225,10 +225,8 @@ class AppUser(AbstractUser, DataAudited):
@lastName.setter
def lastName(self, value):
self.last_name = value
#
##
##
# Ukladani a nacitani nastaveni
# consent_gdpr
@ -239,7 +237,6 @@ class AppUser(AbstractUser, DataAudited):
def consent_gdpr(self, value):
writeUserSetting(self, 'consent_gdpr', value, datetime.date)
# consent_cookies
@property
def consent_cookies(self):
@ -248,7 +245,6 @@ class AppUser(AbstractUser, DataAudited):
def consent_cookies(self, value):
writeUserSetting(self, 'consent_cookies', value, datetime.date)
# consent_terms
@property
def consent_terms(self):
@ -257,13 +253,9 @@ class AppUser(AbstractUser, DataAudited):
def consent_terms(self, value):
writeUserSetting(self, 'consent_terms', value, datetime.date)
# Konec
##
# Meta
##
# Meta information
##
def __str__(self):
return self.username
@ -275,6 +267,7 @@ class AppUser(AbstractUser, DataAudited):
_audit_fields = ('postcode', 'district', 'kind', 'password')
_audit_fields_exclude = ('emailToken',)
_audit_fields_private = ('password',)
class Meta:
verbose_name = _('AppUser')
verbose_name_plural = _('AppUsers')
@ -282,31 +275,49 @@ class AppUser(AbstractUser, DataAudited):
ordering = ('username',)
##
# Permission functions
##
def do_site_perms_calc(self, site_perms):
'''Precalculate needed permissions:
- district IDs for the given roles
'''
spc = {}
# Permissions
rslt = []
def do_site_perms_calc(self, site_perms):
""" Precalculate needed permissions - district IDs for the given roles """
spc, rslt = {}, []
for p in self.DISTRICT_ROLES:
if p in site_perms:
# append the ID of the choice
rslt.append(self.DISTRICT_ROLES[p])
spc['dist'] = rslt
return spc
@receiver(pre_save, sender=AppUser)
def UserModel_presave(sender, instance, **kwargs):
""" Pred ulozenim modelu UserModel vyhleda a pripoji podle prefixu PSC prislusny okres """
try:
obj = County.objects.get(zip_prefix=str(instance.postcode)[:3])
except:
obj = None
instance.county = obj
USER_MODEL = AppUser
#USER_MODEL = get_user_model()
class County(Model):
"""
Ciselnik okresu. S vyuzitim zip_prefix je k uzivateli automaticky prirazen
okres, podle psc, ktere zadal pri registraci
"""
name = CharField(_('Název'), max_length=100)
zip_prefix = CharField(_('Předčíslí PSČ'), max_length=3)
def __str__(self):
return self.name
class Meta:
ordering = ['name',]
unique_together = ( ('zip_prefix',),)
class InterestRegion(Model):
"""
Dostupné emailové zdroje informací.
@ -323,6 +334,7 @@ class InterestRegion(Model):
ordering = ['name',]
unique_together = ( ('tag',),)
class UserSkill(Model):
"""
Dovednosti, které může mít daný uživatel.
@ -445,7 +457,6 @@ class Euro2019Interest(Model):
unique_together = (("email",))
def get_user_by_keycloak_email(id):
"""
Funkce pro dohledani uzivatele podle dat ze SSO serveru.
@ -465,11 +476,11 @@ def get_user_by_keycloak_email(id):
'auth_time': 1505657362
'session_state': '73b44047-b86b-429b-b21f-800b2bc0d33f'
'acr': '0'
'name': 'Martin Rejman'
'preferred_username': 'mr'
'given_name': 'Martin'
'family_name': 'Rejman'
'email': 'martin.rejman@centrum.cz'
'name': 'John Doe'
'preferred_username': 'jd'
'given_name': 'John'
'family_name': 'Doe'
'email': 'john.doe@example.com'
}
"""
# check presence of required attributes
@ -660,14 +671,12 @@ class Newsletter(Model):
region_ids = []
skill_ids = []
#print('* ')
for item in group.split(" "):
item = item.strip()
if item == "":
continue
#print(item)
if item[0] == "s":
rslt = UserSkill.objects.filter(tag=item[2:])
if len(rslt) == 1:
@ -681,7 +690,6 @@ class Newsletter(Model):
if len(rslt) == 1:
topic_ids.append(rslt[0].id)
#print(topic_ids, region_ids, skill_ids)
rslt_u = AppUser.objects.all()
if len(topic_ids) > 0:
rslt_u = rslt_u.filter(userform__topics__in = topic_ids)
@ -690,7 +698,6 @@ class Newsletter(Model):
if len(region_ids) > 0:
rslt_u = rslt_u.filter(userform__regions__in = region_ids)
#print(rslt_u)
all_users = all_users | rslt_u
# use distinct because ORM _will_ multiply the results
@ -700,7 +707,6 @@ class Newsletter(Model):
return len(self.get_recip_users())
class NewsCond(Model):
"""
Podmínky pro filtrování uživatelů, kterým se newsletter odesílat.
@ -794,8 +800,6 @@ class NewsMsgBlock(Model):
ordering = ['order', 'heading']
class NewsMsgReply(Model):
"""
Reakce ctenaru na dany informacni blok.
@ -817,12 +821,6 @@ class NewsMsgReply(Model):
default=0, blank=True, null=True)
## .......+++++++......... ##
# User settings #
# #
class UserSetting(Model):
"""
Different settings and values stored for global purpose.
@ -862,6 +860,7 @@ def readUserSetting(user, key, default, dataType):
else:
return dataType(val)
def writeUserSetting(user, key, value, dataType):
"""
Saves a user setting for the current SITE_ID.
@ -881,14 +880,6 @@ def writeUserSetting(user, key, value, dataType):
obj.save()
# #
# End user settings #
## .......+++++++......... ##
## .......+++++++......... ##
# GLOBAL APP SETTINGS #
# #
class AppSetting(Model):
"""
Different settings and values stored for global purpose.
@ -915,6 +906,7 @@ def readAppSetting(key, default=None):
except:
return default
def writeAppSetting(key, value):
obj, created = AppSetting.objects.get_or_create(key=key)
@ -930,9 +922,3 @@ def writeAppSetting(key, value):
obj.value = ''
obj.save()
# #
# END GLOBAL SETTINGS #
## .......+++++++......... ##

View File

@ -44,6 +44,7 @@ $(document).ready(function(){
<th>PSČ</th>
<th>Město</th>
<th>Kraj</th>
<th>Okres</th>
<th>Uživatel chce</th>
<th>Dovednosti</th>
<th>Datum registrace</th>
@ -58,6 +59,7 @@ $(document).ready(function(){
<td>{{p.postcode|default_if_none:'-'}}</td>
<td>{{p.city|default_if_none:'-'}}</td>
<td>{{p.get_district_display}}</td>
<td>{{p.county|default_if_none:''}}</td>
<td>{{p.get_kind_display}}</td>
<td>{{p.interestedIn|default_if_none:'-'}}</td>
<td>{{p.createdStamp}}</td>

View File

@ -20,7 +20,7 @@
<table style="width: auto;">
<tr><th>Uživ. jméno (login)</th><td>{{obj.username}}</td></tr>
<tr><th>Jméno a příjmení</th><td>{{obj.first_name|default_if_none:'-'}} {{obj.last_name|default_if_none:'-'}}</td></tr>
<tr><th>Město, PSČ, Kraj</th><td>{{obj.city|default_if_none:'-'}}, {{obj.postcode|default_if_none:'-'}}, {{obj.get_district_display|default_if_none:'-'}}</td></tr>
<tr><th>Město, PSČ, Kraj, Okres</th><td>{{obj.city|default_if_none:'-'}}, {{obj.postcode|default_if_none:'-'}}, {{obj.get_district_display|default_if_none:'-'}}, {{obj.county|default_if_none:'-'}}</td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><th>Reg. e-mail</th><td>{{obj.email}}</td></tr>
<tr><th>Kontaktní e-mail</th><td{% if not obj.email_contact_verified %} class="red"{%endif%}>{{obj.email_contact|default_if_none:'-'}}{% if not obj.email_contact_verified %} (neověřen){%endif%}</td></tr>