Example #1
0
 def assign_handwerker(request):
     response = {}
     try:
         component_id = request.POST.get('component_id')
         user_id = request.POST.get('user_id')
         BuildingComponents.objects.filter(id=component_id).update(assign_to_id=user_id, assigned_by=request.user)
         component = BuildingComponents.objects.get(id=component_id)
         # handworker = Users.objects.get(id=user_id)
         if component.flat:
             task = Tasks.objects.filter(building_component__component__parent_id=component.component_id).first()
         else:
             task = Tasks.objects.filter(building_component__building_id=component.building_id,
                                         building_component__flat__isnull=True).filter(Q(
                 Q(building_component__component__parent_id=component.component_id) | Q(
                     building_component__component_id=component.component_id))).first()
         task.save()
         handworker = HandWorker.objects.get(user_id=user_id)
         # Send Notification
         message = NotificationText.get_assign_worker_notification_text(request.user.get_full_name(), handworker.company_name,
                                                                        component.component.name)
         NotificationsView.create_notfication(request, 'assign_worker', message, task.id, request.user.id)
         handworker_info = {
             "fullname": handworker.company_name,
             "avatar": handworker.user.avatar.url if handworker.user.avatar else ''
         }
         response['success'] = True
         response['handworker'] = handworker_info
     except Exception as e:
         LogHelper.efail(e)
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
     return HttpResponse(json.dumps(response), content_type='application/json')
Example #2
0
    def change_task_status(request, task_id):
        try:
            with transaction.atomic():
                response = {}
                task_status = request.data.pop("status", '')
                task = Tasks.objects.get(id=task_id)
                task.status = task_status
                task.save()
                # Send Notification
                if request.user.is_staff:
                    user_name = request.user.get_full_name()
                else:
                    user_name = request.user.handworker.company_name
                message = NotificationText.get_change_task_status_notification_text(
                    user_name, task.building_component.component.name,
                    task.status)
                task_thread = threading.Thread(
                    target=NotificationsView.create_notfication,
                    args=(request, 'change_task_status', message, task_id,
                          request.user.id))
                task_thread.start()

                response['success'] = True
                response['message'] = "Task status changed successfully"
                return Response(response, status=status.HTTP_200_OK)
        except Exception as e:
            LogHelper.efail(e)
            return Response(
                {
                    'status': False,
                    'message': "Something went wrong."
                },
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #3
0
 def change_task_due_date(request, task_id):
     try:
         with transaction.atomic():
             response = {}
             if not request.user.is_staff:
                 raise ModuleNotFoundError
             due_date = request.data.pop("due_date", '')
             task = Tasks.objects.get(id=task_id)
             task.due_date = due_date
             task.save()
             # Send Notification
             message = NotificationText.get_change_due_date_notification_text(
                 request.user.get_full_name(),
                 task.building_component.component.name, due_date)
             task_thread = threading.Thread(
                 target=NotificationsView.create_notfication,
                 args=(request, 'change_due_date', message, task_id,
                       request.user.id))
             task_thread.start()
             response['success'] = True
             response['message'] = "Deadline Update successfully"
             return Response(response, status=status.HTTP_200_OK)
     except Exception as e:
         LogHelper.efail(e)
         return Response(
             {
                 'status': False,
                 'message': "Something went wrong."
             },
             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Example #4
0
 def get(self, request, *args, **kwargs):
     try:
         response = {}
         task_id = kwargs['task_id']
         task = Tasks.objects.get(id=task_id)
         if task.building_component.component.parent:
             assign_to_user = BuildingComponents.objects.filter(component_id=task.building_component.component.parent_id, building_id=task.building_component.building_id, flat_id=task.building_component.flat_id).first()
         else:
             assign_to_user = task.building_component
         if assign_to_user.assign_to:
             assign_to = {
                 "fullname": assign_to_user.assign_to.handworker.company_name,
                 "avatar": assign_to_user.assign_to.avatar.url if assign_to_user.assign_to.avatar else ''
             }
         else:
             assign_to = None
         response['task'] = task
         response['assign_to'] = assign_to
         comments = Comments.objects.filter(task_id=task_id).order_by('-created_at')
         response['more_comments'] = False
         if comments.count() > 5:
             response['more_comments'] = True
         comments_list = comments[:5]
         response['comments_list'] = comments_list
         response['today'] = datetime.today().strftime('%Y-%m-%d')
         followers_response = TaskDetailsView.get_task_followers(request, task, assign_to_user.assign_to)
         response.update(followers_response)
         NotificationsView.read_notification(request,task_id)
         return render(request, 'tasks/task_details.html', response)
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
 def read_notification(request, task_id):
     try:
         NotificationStatus.objects.filter(
             user_id=request.user.id,
             notification__task_id=task_id).update(status=True)
     except Exception as e:
         LogHelper.efail(e)
Example #6
0
 def get_done_components(request):
     response = {}
     try:
         if 'building_id' in request.POST:
             building_id = request.POST.get('building_id')
             components = BuildingComponents.objects.filter(building_id=building_id, flat__isnull=True,
                                                            component__parent__isnull=True)
             for component in components:
                 component.total_tasks = Tasks.objects.filter(building_component__building_id=building_id,
                                              building_component__flat__isnull=True, status='done').filter(Q(
                     Q(building_component__component__parent_id=component.component_id) | Q(
                         building_component__component_id=component.component_id))).count()
         elif 'flat_id' in request.POST:
             flat_id = request.POST.get('flat_id')
             components = BuildingComponents.objects.filter(flat_id=flat_id, component__parent__isnull=True)
             for component in components:
                 component.total_tasks = Tasks.objects.filter(building_component__flat_id=flat_id, status='done').filter(Q(
                     Q(building_component__component__parent_id=component.component_id) | Q(
                         building_component__component_id=component.component_id))).count()
         components_list = render_to_string('tasks/done_components.html', {"components": components, "request": request})
         response['success'] = True
         response['components_list'] = components_list
     except Exception as e:
         LogHelper.efail(e)
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
     return HttpResponse(json.dumps(response), content_type='application/json')
Example #7
0
 def change_active_flat(request, flat_id):
     try:
         flat = Flats.objects.get(id=flat_id)
         request.session['active_project']['id'] = str(
             flat.building.project_id)
         request.session['active_project'][
             'name'] = flat.building.project.name
         request.session["active_building"]['id'] = str(flat.building_id)
         request.session["active_building"][
             'number'] = flat.building.display_number
         request.session["active_flat"]['id'] = str(flat_id)
         request.session["active_flat"]['number'] = flat.number
         request.session.modified = True
         current_activity = {
             'project_id': flat.building.project.id,
             'project_name': flat.building.project.name,
             'building_id': flat.building.id,
             'building_number': flat.building.display_number,
             'flat_id': flat.id,
             'flat_number': flat.number
         }
         request.user.current_activity = json.dumps(current_activity)
         request.user.save()
     except Exception as e:
         LogHelper.efail(e)
     return True
Example #8
0
 def handle_uploaded_file(request, f):
     random_number = CommonView.randomString(10)
     file = str(f.name).rsplit('.', 1)
     filename = file[0] + "_" + random_number + "." + file[1]
     thumb_filename = file[0] + "_" + random_number + "_thumb." + file[1]
     full_filename = os.path.join(settings.MEDIA_ROOT, "comments", filename)
     thumb_full_filename = os.path.join(settings.MEDIA_ROOT, "comments",
                                        thumb_filename)
     fout = open(full_filename, 'wb+')
     # host_url = "http://"+request.get_host()
     host_url = ""
     try:
         for chunk in f.chunks():
             fout.write(chunk)
         fout.close()
         with open(full_filename, 'r+b') as f:
             with Image.open(f) as image:
                 cover = resizeimage.resize_cover(image, [150, 150])
                 cover.save(thumb_full_filename, image.format)
                 if os.stat(full_filename).st_size > 1200000:
                     resized_image = resizeimage.resize_cover(
                         image, [1700, 1500])
                     resized_image.save(full_filename, image.format)
         file_info = {
             "path": host_url + "/media/comments/" + filename,
             "thumb_path": host_url + "/media/comments/" + thumb_filename,
             "ext": file[1]
         }
         return file_info
     except Exception as e:
         LogHelper.efail(e)
         return ""
 def preview_qr(request, pk):
     try:
         context = {}
         qr_info = QrCode.objects.filter(building_id=pk, flat__isnull=True).select_related('building').first()
         context['qr_info'] = qr_info
         return render(request, 'buildings/preview_qr.html', context)
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
Example #10
0
 def get_all_flat_tasks(request, *args, **kwargs):
     try:
         flat_id = kwargs['flat_id']
         flat = Flats.objects.get(id=flat_id)
         if str(flat.building_id) == str(request.session['active_building']['id']):
             CurrentProjects.change_active_flat(request, flat_id)
         return render(request, 'tasks/task_list.html', {'flat': flat})
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
Example #11
0
 def get_all_building_tasks(request, *args, **kwargs):
     try:
         building_id = kwargs['building_id']
         building = Buildings.objects.get(id=building_id)
         if str(building.project_id) == str(request.session['active_project']['id']):
             CurrentProjects.change_active_building(request, building_id)
         return render(request, 'tasks/task_list.html', {'building': building})
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
    def create_notification_user(request, notification):
        try:
            # notification_users = []
            super_admin = Users.objects.filter(is_superuser=True).first()
            notification_user_form = {
                "user_id": super_admin.id,
                "notification_id": notification.id
            }
            # notification_users.append(NotificationStatus(**notification_user_form))
            notification_user = NotificationStatus(**notification_user_form)
            notification_user.save()

            assigned_user = BuildingComponents.objects.filter(
                component_id=notification.task.building_component.component.
                parent_id,
                building_id=notification.task.building_component.building_id,
                flat_id=notification.task.building_component.flat_id).first()
            if assigned_user.assign_to:
                notification_user_form = {
                    "user_id": assigned_user.assign_to.id,
                    "notification_id": notification.id
                }
                # notification_users.append(NotificationStatus(**notification_user_form))
                notification_user = NotificationStatus(
                    **notification_user_form)
                notification_user.save()
            staffs = ProjectStuff.objects.filter(
                project_id=notification.task.building_component.building.
                project_id,
                user__is_active=True)
            for staff in staffs:
                notification_user_form = {
                    "user_id": staff.user_id,
                    "notification_id": notification.id
                }
                # notification_users.append(NotificationStatus(**notification_user_form))
                notification_user = NotificationStatus(
                    **notification_user_form)
                notification_user.save()
            followers = notification.task.followers
            if followers:
                for follower in followers:
                    notification_user_form = {
                        "user_id": follower['id'],
                        "notification_id": notification.id
                    }
                    # notification_users.append(NotificationStatus(**notification_user_form))
                    notification_user = NotificationStatus(
                        **notification_user_form)
                    notification_user.save()
            # NotificationStatus.objects.bulk_create(notification_users)
        except Exception as e:
            LogHelper.efail(e)
        return
Example #13
0
 def get(self, request, *args, **kwargs):
     try:
         building_id = kwargs['building_id']
         context = CommonView.common_datatable_context(self)
         context['building_id'] = building_id
         building = Buildings.objects.get(id=building_id)
         context['building'] = building
         return render(request, 'flats/flat.html', context)
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
Example #14
0
 def update_worker(request, data, user_id):
     try:
         form_data = {
             'company_name': data['company_name'],
             'telephone_office': data['telephone_office'],
             'telephone_mobile': data['telephone_mobile'],
             'working_type': data['working_type'],
         }
         HandWorker.objects.filter(user_id=user_id).update(**form_data)
     except Exception as e:
         LogHelper.efail(e)
 def get(self, request, *args, **kwargs):
     try:
         project_id = kwargs['project_id']
         context = CommonView.common_datatable_context(self)
         context['project_id'] = project_id
         project = Projects.objects.get(id=project_id)
         context['project'] = project
         return render(request, 'buildings/building.html', context)
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
Example #16
0
 def post(self, request, *args, **kwargs):
     if CommonView.superuser_login(request):
         form = self.form_class(request.POST)
         try:
             if form.is_valid():
                 form.save(request=request)
                 return HttpResponseRedirect('/projects/')
         except Exception as e:
             LogHelper.efail(e)
         return render(request, self.template_name, {'form': form})
     else:
         return redirect('index')
Example #17
0
 def change_active_project(request, project_id):
     try:
         project = Projects.objects.get(id=project_id)
         current_activity = {
             'project_id': project.id,
             'project_name': project.name
         }
         request.user.current_activity = json.dumps(current_activity)
         request.user.save()
     except Exception as e:
         LogHelper.efail(e)
     return True
Example #18
0
 def forget_password(request):
     try:
         response = {}
         email = request.data.pop("email", '')
         users = Users.objects.filter(email=email, is_active=1)
         if users.exists():
             user = users[0]
             current_time = datetime.now()
             expired_date = current_time + timedelta(hours=1)
             reset_code = user.resetpassword_set.filter(
                 already_used=0, expired_at__gt=current_time)
             if reset_code.exists():
                 hash_code = reset_code[0].hash_code
                 ResetPassword.objects.filter(id=reset_code[0].id).update(
                     expired_at=expired_date)
             else:
                 # generate hash code and store
                 key = ''.join(
                     random.choice(string.ascii_letters + string.digits +
                                   string.ascii_letters)
                     for _ in range(10)) + str(datetime.now())
                 key = key.encode('utf-8')
                 hash_code = hashlib.sha224(key).hexdigest()
                 ResetPassword(user=user,
                               hash_code=hash_code,
                               expired_at=expired_date).save()
             # base_url = settings.SITE_URL
             base_url = "http://" + request.get_host()
             mail_template = "mails/reset_password.html"
             context = {'base_url': base_url, 'key': hash_code}
             subject = "Supplementer ::Password Reset"
             to = user.email
             CommonView.sendEmail(request, mail_template, context, subject,
                                  to, user.id)
             response['success'] = True
             response[
                 'message'] = "A reset password email is sent to you with confirmation link"
             return Response(response, status=status.HTTP_200_OK)
         else:
             return Response(
                 {
                     'success': False,
                     'message': "Email doesn't found"
                 },
                 status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         LogHelper.efail(e)
         return Response(
             {
                 'success': False,
                 'message': "Something went wrong."
             },
             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 def read_all_notification(request):
     response = {}
     try:
         NotificationStatus.objects.filter(user_id=request.user.id).update(
             status=True)
         response['success'] = True
         response['message'] = "All notifications read successfully"
     except Exception as e:
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
         LogHelper.efail(e)
     return HttpResponse(json.dumps(response),
                         content_type='application/json')
Example #20
0
 def add_task_followers(request):
     response = {}
     try:
         task_id = request.POST.get('task_id')
         followers = json.loads(request.POST.get('followers'))
         Tasks.objects.filter(id=task_id).update(followers=followers)
         response['success'] = True
         response['message'] = "Followers added successfully"
     except Exception as e:
         LogHelper.efail(e)
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
     return HttpResponse(json.dumps(response), content_type='application/json')
 def create_notfication(request, type, text, task_id, sending_by_id):
     try:
         notification_form = {
             "type": type,
             "text": text,
             "task_id": task_id,
             "sending_by_id": sending_by_id
         }
         notification = Notification(**notification_form)
         notification.save()
         NotificationsView.create_notification_user(request, notification)
     except Exception as e:
         LogHelper.efail(e)
     return
Example #22
0
 def change_active_building(request, building_id):
     try:
         building = Buildings.objects.get(id=building_id)
         current_activity = {
             'project_id': building.project.id,
             'project_name': building.project.name,
             'building_id': building.id,
             'building_number': building.display_number
         }
         request.user.current_activity = json.dumps(current_activity)
         request.user.save()
     except Exception as e:
         LogHelper.efail(e)
     return True
 def get(self, request, *args, **kwargs):
     response = {}
     try:
         notifications = NotificationStatus.objects.filter(
             user_id=request.user.id).order_by('-sending_at')
         response['more_notifications'] = False
         if notifications.count() > 20:
             response['more_notifications'] = True
         notifications_list = notifications[:20]
         response['notifications_list'] = notifications_list
         response['today'] = datetime.today().strftime('%Y-%m-%d')
         return render(request, 'profiles/notifications.html', response)
     except Exception as e:
         LogHelper.efail(e)
         return redirect('index')
Example #24
0
 def get_all_plans_by_active_flat(request):
     response = {}
     try:
         flat_id = request.session['active_flat']['id']
         if 'flat_id' in request.POST:
             flat_id = request.POST.get('flat_id')
         plans = FlatPlans.objects.filter(flat_id=flat_id)
         plan_list_tab = render_to_string('flats/plan.html', {"plans": plans, "flat_id": flat_id})
         response['plan_list_tab'] = plan_list_tab
         response['success'] = True
     except Exception as e:
         LogHelper.efail(e)
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
     return HttpResponse(json.dumps(response), content_type='application/json')
 def post(self, request, *args, **kwargs):
     form = self.form_class(request.POST)
     project_id = kwargs['project_id']
     try:
         if form.is_valid():
             request.project_id = project_id
             obj = form.save(request=request)
             default_components = CommonView.create_default_building_components(request, obj)
             qr = CommonView.generate_qr_code(request, obj)
             if default_components:
                 building_components = BuildingComponents.objects.filter(building_id=obj.id, flat__isnull=True)
                 default_tasks = CommonView.create_default_tasks(request, building_components)
             return HttpResponseRedirect('/projects/'+str(obj.project_id)+'/buildings/')
     except Exception as e:
         LogHelper.efail(e)
     return render(request, self.template_name, {'form': form, 'project_id': project_id})
Example #26
0
 def post(self, request, *args, **kwargs):
     response = {}
     form = self.form_class(request.POST, request.FILES)
     form.created_by = request.user
     response['form'] = form
     flat_id = kwargs['flat_id']
     request.flat_id = flat_id
     response['flat_id'] = flat_id
     try:
         if form.is_valid():
             form.save(request=request)
             return HttpResponseRedirect('/flats/'+str(flat_id)+'/tasks/#plans')
         else:
             return render(request, self.template_name, response)
     except Exception as e:
         LogHelper.efail(e)
         return render(request, self.template_name, response)
Example #27
0
 def post(self, request, *args, **kwargs):
     response = {}
     form = self.form_class(request.POST, request.FILES)
     response['form'] = form
     project_id = kwargs['project_id']
     request.project_id = project_id
     response['project_id'] = project_id
     try:
         if form.is_valid():
             form.save(request=request)
             return HttpResponseRedirect(
                 '/current-project-buildings/#plans')
         else:
             return render(request, self.template_name, response)
     except Exception as e:
         LogHelper.efail(e)
         return render(request, self.template_name, response)
Example #28
0
 def get(self, request):
     try:
         unique_key = request.GET.get("unique_key")
         scan_obj = QrCode.objects.filter(unique_key=unique_key).first()
         if scan_obj.flat:
             if request.user.is_staff:
                 components = BuildingComponents.objects.annotate(name=F('component__name')).filter(flat_id=scan_obj.flat_id, component__parent__isnull=True)
             else:
                 components = BuildingComponents.objects.annotate(name=F('component__name')).filter(
                     flat_id=scan_obj.flat_id, component__parent__isnull=True, assign_to_id=request.user.id)
         else:
             if request.user.is_staff:
                 components = BuildingComponents.objects.annotate(name=F('component__name')).filter(building_id=scan_obj.building_id, flat__isnull=True, component__parent__isnull=True)
             else:
                 components = BuildingComponents.objects.annotate(name=F('component__name')).filter(
                     building_id=scan_obj.building_id, flat__isnull=True, component__parent__isnull=True, assign_to_id=request.user.id)
         if len(components) < 1:
             return Response({'success': False, "message": "Not Found"}, status=status.HTTP_404_NOT_FOUND)
         if scan_obj.flat:
             ActivityView.change_active_flat(request, scan_obj.flat_id)
         else:
             ActivityView.change_active_building(request, scan_obj.building_id)
         paginator = CustomPagination()
         paginator.page_size = 10
         result_page = paginator.paginate_queryset(components, request)
         serializer = ComponentSerializer(result_page, many=True)
         if scan_obj.flat:
             flat_info = {
                 "id": scan_obj.flat.id,
                 "number": scan_obj.flat.number
             }
         else:
             flat_info = None
         building_info = {
             "id": scan_obj.building.id,
             "display_number": scan_obj.building.display_number
         }
         project_info = {
             "id": scan_obj.building.project.id,
             "name": scan_obj.building.project.name
         }
         return paginator.get_paginated_response(data=serializer.data, flat=flat_info, building=building_info, project=project_info)
     except Exception as e:
         LogHelper.efail(e)
         return Response({'status': False, 'message': "Something went wrong."},
                         status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 def post(self, request, *args, **kwargs):
     if CommonView.superuser_login(request):
         response = {}
         form = self.form_class(request.POST)
         form.created_by = request.user
         parents = Components.objects.filter(
             Q(parent__isnull=True) | Q(parent_id=0))
         response['parents'] = parents
         response['form'] = form
         try:
             if form.is_valid():
                 form.save(request=request)
                 return HttpResponseRedirect('/components/')
         except Exception as e:
             LogHelper.efail(e)
             return render(request, self.template_name, response)
     else:
         return redirect('index')
Example #30
0
 def get_component_tasks(request):
     response = {}
     try:
         type = request.POST.get('type')
         component_id = request.POST.get('id')
         if 'building_id' in request.POST:
             building_id = request.POST.get('building_id')
             if type == 'pending':
                 tasks = Tasks.objects.filter(building_component__building_id=building_id, building_component__flat__isnull=True).filter(Q(Q(building_component__component__parent_id=component_id) | Q(building_component__component_id=component_id))).exclude(status='done')
             elif type == 'done':
                 tasks = Tasks.objects.filter(building_component__building_id=building_id,
                                              building_component__flat__isnull=True, status='done').filter(Q(
                     Q(building_component__component__parent_id=component_id) | Q(
                         building_component__component_id=component_id)))
             else:
                 tasks = Tasks.objects.filter(building_component__building_id=building_id,
                                              building_component__flat__isnull=True).filter(Q(
                     Q(building_component__component__parent_id=component_id) | Q(
                         building_component__component_id=component_id)))
         elif 'flat_id' in request.POST:
             flat_id = request.POST.get('flat_id')
             if type == 'pending':
                 tasks = Tasks.objects.filter(building_component__flat_id=flat_id).filter(Q(Q(building_component__component__parent_id=component_id) | Q(building_component__component_id=component_id))).exclude(status='done')
             elif type == 'done':
                 tasks = Tasks.objects.filter(building_component__flat_id=flat_id, status='done').filter(Q(
                     Q(building_component__component__parent_id=component_id) | Q(
                         building_component__component_id=component_id)))
             else:
                 tasks = Tasks.objects.filter(building_component__flat_id=flat_id).filter(Q(
                     Q(building_component__component__parent_id=component_id) | Q(
                         building_component__component_id=component_id)))
         for task in tasks:
             try:
                 task.comment = Comments.objects.filter(task_id=task.id, text__isnull=False).last()
             except Exception as e:
                 task.comment = None
         tasks_list = render_to_string('tasks/task.html', {"tasks": tasks, "request": request})
         response['success'] = True
         response['tasks_list'] = tasks_list
     except Exception as e:
         LogHelper.efail(e)
         response['success'] = False
         response['message'] = "Something went wrong. Please try again"
     return HttpResponse(json.dumps(response), content_type='application/json')