85 lines
3.5 KiB
Python
85 lines
3.5 KiB
Python
from account.models import OldRole, Role
|
|
from main.models import SiteSettings
|
|
from django.core.management.base import BaseCommand
|
|
from django.db import connections
|
|
from establishment.management.commands.add_position import namedtuplefetchall
|
|
from tqdm import tqdm
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = '''Add site affilations from old db to new db.
|
|
Run after migrate {}!!!'''
|
|
|
|
def map_role_sql(self):
|
|
with connections['legacy'].cursor() as cursor:
|
|
cursor.execute('''
|
|
select distinct
|
|
case when role = 'news_editor' then 'CONTENT_PAGE_MANAGER'
|
|
when role in ('reviewer', 'reviwer', 'reviewer_manager') then 'REVIEWER_MANGER'
|
|
when role = 'admin' then 'SUPERUSER'
|
|
when role ='community_manager' then 'COUNTRY_ADMIN'
|
|
when role = 'site_admin' then 'COUNTRY_ADMIN'
|
|
when role = 'wine_reviewer' then 'WINERY_REVIEWER'
|
|
when role in ('salesman', 'sales_man') then 'SALES_MAN'
|
|
when role = 'seller' then 'SELLER'
|
|
else role
|
|
end as new_role,
|
|
case when role = 'GUEST' then null else role end as role
|
|
from
|
|
(
|
|
SELECT
|
|
DISTINCT
|
|
COALESCE(role, 'GUEST') as role
|
|
FROM site_affiliations AS sa
|
|
) t
|
|
''')
|
|
return namedtuplefetchall(cursor)
|
|
|
|
def add_old_roles(self):
|
|
objects = []
|
|
OldRole.objects.all().delete()
|
|
for s in tqdm(self.map_role_sql(), desc='Add permissions old'):
|
|
objects.append(
|
|
OldRole(new_role=s.new_role, old_role=s.role)
|
|
)
|
|
OldRole.objects.bulk_create(objects)
|
|
self.stdout.write(self.style.WARNING(f'Migrated old roles.'))
|
|
|
|
def site_role_sql(self):
|
|
with connections['legacy'].cursor() as cursor:
|
|
cursor.execute('''
|
|
select site_id,
|
|
role
|
|
from
|
|
(
|
|
SELECT
|
|
DISTINCT
|
|
site_id,
|
|
COALESCE(role, 'GUEST') as role
|
|
FROM site_affiliations AS sa
|
|
) t
|
|
where t.role not in ('admin', 'GUEST')
|
|
''')
|
|
return namedtuplefetchall(cursor)
|
|
|
|
def add_site_role(self):
|
|
objects = []
|
|
for s in tqdm(self.site_role_sql(), desc='Add site role'):
|
|
old_role = OldRole.objects.get(old_role=s.role)
|
|
role_choice = getattr(Role, old_role.new_role)
|
|
sites = SiteSettings.objects.filter(old_id=s.site_id)
|
|
for site in sites:
|
|
role = Role.objects.filter(site=site, role=role_choice)
|
|
if not role.exists():
|
|
objects.append(
|
|
Role(site=site, role=role_choice)
|
|
)
|
|
|
|
Role.objects.bulk_create(objects)
|
|
self.stdout.write(self.style.WARNING(f'Added site roles.'))
|
|
|
|
|
|
|
|
def handle(self, *args, **kwargs):
|
|
# self.add_old_roles()
|
|
self.add_site_role() |