Beispiel #1
0
    def get(self, request, pk, user_id, member_name):

        if Entity_Role.delete(request, pk=pk, user_id=user_id):

            entity = get_object_or_404(Entity, pk=pk)
            entity_admin_ids = list(Entity_Role.objects.values_list("user_id", flat=True).filter(role=settings.SOCION_ENTITY_ADMIN, entity_id=pk, deleted=False).distinct())
            admin_user_ids = [user_id, entity.created_by, ]
            net_admin_ids = list(set().union(entity_admin_ids, admin_user_ids))
            if net_admin_ids:
                title = 'Remove Entity Admin.'
                for entity_admin_id in net_admin_ids:
                    if entity_admin_id == user_id:
                        description = f"You have been withdrawn as Entity admin to entity {entity.name}."
                    else:
                        description = f"{member_name} has been withdrawn as Entity admin to entity {entity.name}."
                    Notifications.notification_save(title=title,
                                                    description=description,
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=settings.SOCION_ENTITY_ADMIN, user_id=entity_admin_id, session_id=None)
            entity_logger.info('Successfully Deactivated an Entity Admin from an Entity with ID : %s.' % entity.id)
            return HttpResponseRedirect(reverse('entity-profile', kwargs={'pk': pk}))
        else:
            entity_logger.error('Could not Deactivate an Entity Admin from an Entity with ID : %s.' % pk)
            return HttpResponseForbidden
Beispiel #2
0
def pop_add_entity(template_name, request, **kwargs):
    data = dict()
    context = None
    qr_value = kwargs.get('qr_value', None)
    if qr_value is not None:
        context = {'qr_value': qr_value}
    if request.method == 'POST':
        created_by = request.user.user_id
        user_id = request.POST.get('socionEntityAdminUser')
        entity_name = request.POST.get('socionEntityName')
        entity = Entity.objects.create(name=entity_name, created_by=created_by)
        Entity_Role.objects.create(entity_id=entity.id, role=settings.SOCION_ENTITY_ADMIN, user_id=user_id, created_at=datetime.now(),
                                   updated_at=datetime.now(), deleted=bool(False), created_by=created_by)
        Notifications.notification_save(title='Invite Entity',
                                        description=f"Entity {entity_name} has been invited to register.",
                                        notification_type=settings.NOTIFICATION_TYPE["USER"],
                                        date_time=datetime.now(), is_deleted=False, is_read=False,
                                        role=settings.SOCION_SUPER_ADMIN, user_id=created_by, session_id=None)
        Notifications.notification_save(title='Receive Invitation',
                                        description=f"Congratulations! You have been invited to register your entity. Please complete the registration process.",
                                        notification_type=settings.NOTIFICATION_TYPE["USER"],
                                        date_time=datetime.now(), is_deleted=False, is_read=False,
                                        role=settings.SOCION_ENTITY_ADMIN, user_id=user_id, session_id=None)
        data['form_is_valid'] = True
        entity_logger.info('Successfully Invited an Entity %s.' % entity_name)
    else:
        entity_logger.error('Could not Invite an Entity')
    data['html_form'] = render_to_string(template_name, context=context, request=request)
    return JsonResponse(data)
Beispiel #3
0
 def get(self, request, pk=None):
     entity = get_object_or_404(Entity, pk=pk)
     entity_admin_ids = list(Entity_Role.objects.values_list("user_id", flat=True).filter(role=settings.SOCION_ENTITY_ADMIN, entity_id=pk, deleted=False).distinct())
     user_detail_url = f"{settings.BASE_URL}user/private/details/{request.user.user_id}"
     response = requests.get(user_detail_url)
     if response.status_code == 200:
         member = response.json()
         member_name = member['name']
         entity_logger.info('Successfully Fetched Details of member from an Entity with ID : %s.' % entity.id)
     if Entity.reactivate(request, pk=pk):
         for entity_admin_id in entity_admin_ids:
             Notifications.notification_save(title='Remove Entity Admin.',
                                             description=f"Entity {entity.name} has been reactivated by {member_name}.",
                                             notification_type=settings.NOTIFICATION_TYPE["USER"],
                                             date_time=datetime.now(), is_deleted=False, is_read=False,
                                             role=settings.SOCION_ENTITY_ADMIN, user_id=entity_admin_id, session_id=None)
         Notifications.notification_save(title='Remove Entity Admin.',
                                         description=f"Entity {entity.name} has been reactivated by {member_name}.",
                                         notification_type=settings.NOTIFICATION_TYPE["USER"],
                                         date_time=datetime.now(), is_deleted=False, is_read=False,
                                         role=settings.SOCION_SUPER_ADMIN, user_id=entity.created_by, session_id=None)
         entity_logger.info('Successfully Reactivated an Entity with ID : %s.' % entity.id)
         return HttpResponseRedirect(reverse('index'))
     else:
         entity_logger.error('Could not Reactivate an Entity with ID : %s.' % entity.id)
         return HttpResponseRedirect(reverse('entity_profile', kwargs={'pk': pk}))
Beispiel #4
0
    def get(self, request, pk=None):

        if Entity.delete(request, pk=pk):
            entity = Entity.objects.get(pk=pk)
            entity_admin_ids = list(
                Entity_Role.objects.values_list("user_id", flat=True).filter(entity_id=pk,
                                                                             deleted=False).distinct())
            programs = Program.objects.filter(entity_id=pk)
            programs_ids = Program.objects.values_list("id", flat=True).filter(entity_id=pk)
            topics = Topic.objects.filter(program_id__in=programs_ids)
            roles = Program_Roles.objects.values_list("role", flat=True).filter(program_id__in=programs_ids)
            programs.update(deleted=True)
            topics.update(deleted=True)
            roles.update(deleted=True)
            if entity_admin_ids:
                for admin_user_id in entity_admin_ids:
                    Notifications.notification_save(title="Deactivate Entity",
                                                    description=f"Entity {entity.name} has been deactivated by {request.user.username}",
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=None, user_id=admin_user_id, session_id=None)
            entity_logger.info('Successfully Deactivated an Entity with ID : %s.' % entity.id)
            return HttpResponseRedirect(reverse('index'))
        else:
            entity_logger.error('Could not Deactivate an Entity with ID : %s.' % pk)
            return HttpResponseRedirect(reverse('entity_profile', kwargs={'pk': pk}))
Beispiel #5
0
def save_all(request, form, template_name, content=None):
    data = dict()
    if request.method == 'POST' or 'GET':
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            entity_logger.info('Successfully Edited an Entity with ID : %s.' % form.instance.id)
        else:
            data['form_is_valid'] = False
        context = {'form': form, 'data': content}
        data['html_form'] = render_to_string(template_name, context, request=request)
        return JsonResponse(data)
    else:
        entity_logger.error('Could not Edit an Entity with Id : %s.' % form.instance.id)
        return False
Beispiel #6
0
def pop_add_entity_admin(template_name, request, **kwargs):
    data = dict()
    context = None
    qr_value = kwargs.get('qr_value', None)
    if qr_value is not None:
        context = {'qr_value': qr_value}
    if request.method == 'POST':
        user_id = request.POST.get('userId')
        role = request.POST.get('entityRole')
        entity_id = request.POST.get('entityId')
        member_name = request.POST.get('entityName')
        entity = get_object_or_404(Entity, pk=entity_id)
        entity_admin_ids = list(Entity_Role.objects.values_list("user_id", flat=True).filter(role=settings.SOCION_ENTITY_ADMIN, entity_id=entity_id, deleted=False).distinct())
        query = '''INSERT INTO Entity_Role (entity_id, role, user_id, created_at, updated_at, created_by, deleted) VALUES (%s,%s,%s,%s,%s,%s,%s)'''
        try:
            query_data = (entity_id, role, user_id, datetime.now(), datetime.now(), request.user.user_id, False)
            cursor.execute(query, query_data)
            transaction.commit()
            for entity_admin_id in entity_admin_ids:
                Notifications.notification_save(title='Add Entity Admin.',
                                                description=f"{member_name} has onboarded as Entity Admin to entity {entity.name}.",
                                                notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                date_time=datetime.now(), is_deleted=False, is_read=False,
                                                role=settings.SOCION_ENTITY_ADMIN, user_id=entity_admin_id, session_id=None)
            Notifications.notification_save(title='Add Entity Admin.',
                                            description=f"{member_name} has onboarded as Entity Admin to entity {entity.name}.",
                                            notification_type=settings.NOTIFICATION_TYPE["USER"],
                                            date_time=datetime.now(), is_deleted=False, is_read=False,
                                            role=settings.SOCION_SUPER_ADMIN, user_id=entity.created_by, session_id=None)
            Notifications.notification_save(title='Add Entity Admin.',
                                            description=f"You have been onboarded as Entity admin to entity {entity.name}.",
                                            notification_type=settings.NOTIFICATION_TYPE["USER"],
                                            date_time=datetime.now(), is_deleted=False, is_read=False,
                                            role=settings.SOCION_ENTITY_ADMIN, user_id=user_id, session_id=None)
            data['form_is_valid'] = True
            entity_logger.info('Successfully Added an Entity Admin to Entity with ID : %s.' % entity_id)
        except (Exception, ValueError):
            data['form_is_valid'] = False
            entity_logger.error('Could not Add an Entity Admin.')
    else:
        entity_logger.error('Could not Add an Entity Admin as the Method was not allowed.')
        data['form_is_valid'] = False

    data['html_form'] = render_to_string(template_name, context=context, request=request)
    return JsonResponse(data)
Beispiel #7
0
    def get(self, request, pk, user_id, admin_username):

        if Entity_Role.reactivate(request, pk=pk, user_id=user_id):
            entity = Entity.objects.get(pk=pk)
            entity_admin_ids = list(Entity_Role.objects.values_list("user_id", flat=True).filter(entity_id=pk, deleted=False).distinct())
            admin_user_ids = [user_id, entity.created_by, ]
            net_admin_ids = list(set().union(entity_admin_ids, admin_user_ids))
            if net_admin_ids:
                title = "Reactivate Entity Admin"
                description = f"Entity Administrator, {admin_username}, has been reinstated to Entity {entity.name}"
                for admin_user_id in net_admin_ids:
                    Notifications.notification_save(title=title,
                                                    description=description,
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=None, user_id=admin_user_id, session_id=None)
            entity_logger.info('Successfully Reactivated an Entity Admin from an Entity with ID : %s.' % entity.id)
            return HttpResponseRedirect(reverse('entity-profile', kwargs={'pk': pk}))
        else:
            entity_logger.error('Could not Reactivate an Entity Admin from an Entity with ID : %s.' % pk)
            return HttpResponseForbidden
Beispiel #8
0
    def post(self, request, pk):

        entity = get_object_or_404(Entity, pk=pk)
        entity_admin_ids = list(Entity_Role.objects.values_list("user_id", flat=True).filter(role=settings.SOCION_ENTITY_ADMIN, entity_id=pk, deleted=False).distinct())
        for file in request.FILES.getlist('inline[]'):
            print(file.size)
            ext = file.name.split(".")[-1]
            if ext in settings.SOCION_VIDEO_FORMAT:
                v = vimeo.VimeoClient(token=config('VIMEO_ACCESS_TOKEN'))
                path = file.temporary_file_path()
                try:
                    # Upload the file and include the video title and description.
                    uri = v.upload(path, data={
                        'name': file.name,
                        'chunk_size': 128 * 1024 * 1024
                        })

                    # Get the metadata response from the upload and log out the Vimeo.com url
                    video_data = v.get(uri + '?fields=link').json()
                    vimeo_url = video_data['link']
                    file_key = s3_file_upload(request, bucket_name="entity-docs/Entity Videos/")
                    if file_key is not None:
                        url = "%s%s" % (URL, file_key)
                        attachment = EntityDocument(entity=entity, name=file, content_url=url, vimeo_url=vimeo_url,
                                                    created_by=request.user.user_id, content_type='Video')
                        attachment.save()
                        entity_logger.info('Successfully Added a Video to an Entity with ID : %s.' % entity.id)
                except vimeo.exceptions.VideoUploadFailure as e:
                    # We may have had an error. We can't resolve it here necessarily, so
                    # report it to the user.
                    # print('Error uploading %s' % file.name)
                    # print('Server reported: %s' % e.message)
                    entity_logger.error('Could not Add Video to an Entity with ID : %s.' % entity.id)
                    pass

            elif ext in settings.SOCION_IMAGE_FORMAT:
                file_key = s3_file_upload(request, bucket_name="entity-docs/image/")
                if file_key is not None:
                    url = "%s%s" % (URL, file_key)
                    attachment = EntityDocument(entity=entity, name=file, content_type='Image',
                                                created_by=request.user.user_id, content_url=url)
                    attachment.save()
                    entity_logger.info('Successfully Added an Image to an Entity with ID : %s.' % entity.id)
            elif ext in settings.SOCION_DOC_FORMAT:
                file_key = s3_file_upload(request, bucket_name="entity-docs/document/")
                if file_key is not None:
                    url = "%s%s" % (URL, file_key)
                    attachment = EntityDocument(name=file, entity=entity, content_url=url,
                                                created_by=request.user.user_id, content_type='Document')
                    attachment.save()
                    entity_logger.info('Successfully Added a Document to an Entity with ID : %s.' % entity.id)

        for entity_admin_id in entity_admin_ids:
            Notifications.notification_save(title='Entity upload document.',
                                            description=f"Document(s) have been uploaded to entity {entity.name} profile.",
                                            notification_type=settings.NOTIFICATION_TYPE["USER"],
                                            date_time=datetime.now(), is_deleted=False, is_read=False,
                                            role=settings.SOCION_ENTITY_ADMIN, user_id=entity_admin_id, session_id=None)
        Notifications.notification_save(title='Entity upload document.',
                                        description=f"Document(s) have been uploaded to entity {entity.name} profile.",
                                        notification_type=settings.NOTIFICATION_TYPE["USER"],
                                        date_time=datetime.now(), is_deleted=False, is_read=False,
                                        role=settings.SOCION_SUPER_ADMIN, user_id=entity.created_by, session_id=None)
        return HttpResponseRedirect(reverse('entity-profile', kwargs={'pk': pk}))
Beispiel #9
0
    def post(self, request, pk):
        entity = get_object_or_404(Entity, pk=pk)
        entity_user_id = list(Entity_Role.objects.values_list("user_id", flat=True).filter(entity_id=entity.id))

        try:
            form = EntityForm(request.POST, request.FILES, instance=entity)
            template = 'entity/register-entity.html'
            if request.FILES:
                aws_session = boto3.Session(aws_access_key_id=config('AWS_ACCESS_KEY_ID'), aws_secret_access_key=config('AWS_SECRET_ACCESS_KEY'))
                s3 = aws_session.resource('s3')
                for file in request.FILES.getlist('inline[]'):
                    ext = file.name.split(".")[-1]
                    mimetype = mimetypes.MimeTypes().guess_type(file.name)[0]
                    uuId = uuid.uuid1()
                    if ext in settings.SOCION_VIDEO_FORMAT:
                        v = vimeo.VimeoClient(token=config('VIMEO_ACCESS_TOKEN'))
                        path = file.temporary_file_path()
                        try:
                            # Upload the file and include the video title and description.
                            uri = v.upload(path, data={
                                'name': file.name,
                                'chunk_size': 128 * 1024 * 1024
                                })

                            # Get the metadata response from the upload and log out the Vimeo.com url
                            video_data = v.get(uri + '?fields=link').json()
                            vimeo_url = video_data['link']
                            file_key = "%s%s%s%s" % ("entity-docs/Entity Videos/", uuId, ".", ext)
                            s3.Bucket(config('AWS_STORAGE_BUCKET_NAME')).put_object(Key=file_key, Body=file, ContentType=mimetype)
                            url = "%s%s" % (URL, file_key)
                            attachment = EntityDocument(entity=entity, name=file, content_url=url, vimeo_url=vimeo_url,
                                                        created_by=request.user.user_id, content_type='Video')
                            attachment.save()
                            entity_logger.info('Successfully Added a Video to an Entity with ID : %s.' % entity.id)
                        except vimeo.exceptions.VideoUploadFailure or botocore.exceptions.ClientError as e:
                            # We may have had an error. We can't resolve it here necessarily, so
                            # report it to the user.
                            # print('Error uploading %s' % file.name)
                            # print('Server reported: %s' % e.message)
                            entity_logger.error('Could not Add Video to an Entity with ID : %s.' % entity.id)
                            pass

                    elif ext in settings.SOCION_IMAGE_FORMAT:
                        file_key = "%s%s%s%s" % ("entity-docs/image/", uuId, ".", ext)
                        s3.Bucket(config('AWS_STORAGE_BUCKET_NAME')).put_object(Key=file_key, Body=file, ContentType=mimetype)
                        url = "%s%s" % (URL, file_key)
                        attachment = EntityDocument(entity=entity, name=file, content_type='Image',
                                                    created_by=request.user.user_id, content_url=url)
                        attachment.save()
                        entity_logger.info('Successfully Added an Image to an Entity with ID : %s.' % entity.id)

                    elif ext in settings.SOCION_DOC_FORMAT:
                        file_key = "%s%s%s%s" % ("entity-docs/document/", uuId, ".", ext)
                        s3.Bucket(config('AWS_STORAGE_BUCKET_NAME')).put_object(Key=file_key, Body=file, ContentType=mimetype)
                        url = "%s%s" % (URL, file_key)
                        attachment = EntityDocument(name=file, entity=entity, content_url=url,
                                                    created_by=request.user.user_id, content_type='Document')
                        attachment.save()
                        entity_logger.info('Successfully Added a Document to an Entity with ID : %s.' % entity.id)

                if entity_user_id:
                    userId = entity_user_id[0]
                    Notifications.notification_save(title='Entity upload document.',
                                                    description=f"Document(s) have been uploaded to entity {entity.name} profile.",
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=settings.SOCION_SUPER_ADMIN, user_id=entity.created_by, session_id=None)
                    Notifications.notification_save(title='Entity upload document.',
                                                    description=f"Document(s) have been uploaded to entity {entity.name} profile.",
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=settings.SOCION_ENTITY_ADMIN, user_id=userId, session_id=None)
            if form.is_valid():
                if entity_user_id:
                    userId = entity_user_id[0]
                    Notifications.notification_save(title='Invite Entity',
                                                    description=f"Entity {entity.name} has been registered.",
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=settings.SOCION_SUPER_ADMIN, user_id=entity.created_by, session_id=None)
                    Notifications.notification_save(title='Invite Entity',
                                                    description=f"Entity {entity.name} has been registered.",
                                                    notification_type=settings.NOTIFICATION_TYPE["USER"],
                                                    date_time=datetime.now(), is_deleted=False, is_read=False,
                                                    role=settings.SOCION_ENTITY_ADMIN, user_id=userId, session_id=None)
                    entity.register()
                entity_logger.info('Successfully Registered an Entity with ID : %s.' % entity.id)
            return save_all(request, form=form, template_name=template)
        except ValueError:
            entity_logger.error('Could not Register an Entity with ID : %s.' % entity.id)
            return HttpResponseRedirect(reverse('entities'))