Example #1
0
def is_authorized(engineer_id=None, token=None, admin=False, phone=None):
    if token and engineer_id and admin:
        engineer_obj = engineer_collection.find_one(
            {
                "id": user_id,
                "is_active": True,
                "secret_hash": token
            }, {"_id": 0})

        if engineer_obj:
            return True
        else:
            return False
    elif phone:
        engineer_obj = engineer_collection.find_one(
            {
                "phone": phone,
                "is_active": True
            }, {"_id": 0})

        if engineer_obj:
            return True
        else:
            return False
    else:
        engineer_obj = engineer_collection.find_one(
            {
                "id": user_id,
                "is_active": True
            }, {"_id": 0})

        if engineer_obj:
            return True
        else:
            return False
def admin_engineer():
    params = request.json
    engineer_id = params["engineer_id"]
    name = params["name"]
    phone = str(params["phone"])

    if engineer_id == 0:
        # it means that we need to create enginneer
        # now we will check for duplicate phone number in the list
        existing_phone = engineer_collection.find_one({"phone": phone},
                                                      {"_id": 0})
        print(existing_phone)

        if existing_phone:
            resp = {"message": "Phone number already exists"}
            return jsonify(resp), 404
        else:
            result = engineer_collection.insert_one({
                "id":
                generate_unique_id(engineer_collection),
                "name":
                name,
                "phone":
                phone,
                "is_admin":
                True,
                "is_active":
                True,
                "created_at":
                str(datetime.datetime.now())
            })
            resp = {"message": "enginner inserted sucessfully"}
            return jsonify(resp), 200

    else:
        engineer_obj = engineer_collection.find_one({'id': engineer_id},
                                                    {"_id": 0})
        if engineer_obj:
            result_obj = engineer_collection.update_one({'id': engineer_id}, {
                "$set": {
                    "name": name,
                    "phone": phone,
                    "updated_at": str(datetime.datetime.now()),
                    "audit_log": engineer_obj
                }
            })

            resp = {"message": "engineer updated sucessfully"}
            return jsonify(resp), 200

        else:
            resp = {"message": "engineer not found"}
            return jsonify(resp), 404
Example #3
0
def verify_user_name(phone):
	
	# user_name_result = is_authorized(phone=phone)

	# print(user_name_result)
	user_name_result = engineer_collection.find_one({"phone": phone,"is_active":True},{"_id": 0})
	print(user_name_result)	
	if user_name_result:
		# this means that the email has been found and now the otp can be generated
		otp = otp_generator()
		result_obj = engineer_collection.update_one({'phone' : phone},
												 {"$set"  : 
												 			{"otp" : otp, "updated_at":str(datetime.datetime.now()) }})
		phone_no = str(phone)
		if phone_no[0] == "+":
		    phone_no=phone_no[3:]
		phone_no=str(phone_no)
		otp=str(otp)
	    # url += str(phone_no)
	    # url += "&message=" + msg + "&priority=1&dnd=1&unicode=0"
		
		
		# url1="http://kit19.com/ComposeSMS.aspx?username=raghav643283&password=7924&sender=SNAPOW&to="+phone_no+"&message=Welcome%20to%20OMS%20SERVICE%20Your%20OTP%20is%20"+otp+"&priority=1&dnd=1&unicode=0"
		# req = urllib2.urlopen(url1)

		resp = {"message":"phone number found","otp": otp }
		return jsonify(resp), 200 
	else:
		resp = {"message":"phone number not found: please contact administrator"}
		return jsonify(resp), 404
def verify_username():
	params 		    = request.json
	phone_param = params.get('phone')
	if phone_param:
		phone_number 	= str(phone_param)
	
	else:
		user_data = params.get("user_data")
		phone_number 	= str(user_data.get('phone'))
	
	user_type = params.get("type")
	
	print("----------------------")
	print(params)
	

	if user_type == 'admin':
		engineer_obj = engineer_collection.find_one({"phone":phone_number,"is_admin":True},{"_id":0})

		print("inside admin")
		print(engineer_obj)

		if engineer_obj:
			resp = verify_user_name(phone_number)
			return resp
		else:

			resp = {"message":'Unauthorized access : Engineers are not allowed to log-in from admin panel'}
			return jsonify(resp), 404

	else:

		user_type = "engineer"
		resp = verify_user_name(phone_number)
		return resp
def admin_new_comment():
	params  	 = request.json
	# user_id 	 = params['user_id']
	# secret_hash  = params['secret_hash']
	print("--------params-----------")
	print(params)

	engineer_id  = params.get('enginneer_id')

	update_date_time = str(datetime.datetime.now())
	get_last_read_datetime  = engineer_collection.find_one({"id": engineer_id},{'_id':0})
	print("----------------- get_last_read_datetime ------------------")
	print(get_last_read_datetime)
	
	last_read_datetime = update_date_time
	if "last_notification_datetetime" in get_last_read_datetime:

		last_read_datetime = get_last_read_datetime['last_notification_datetetime']
	
	abc = engineer_collection.update({"id": engineer_id},{"$set":{"last_notification_datetetime": update_date_time}})

	print("-------- abc admin -----------")
	print(abc)

	notificaion_list_to_show = []
	notification_to_show = notification_list.find({"time":{"$gte": last_read_datetime}},{'_id':0})
	for notificaionList in notification_to_show:
		notificaion_list_to_show.append(notificaionList)

	tasks_cursor     =  task_collection.find({"updated_at":{"$gte":last_read_datetime}},{"_id":0})
	update_date_time =  datetime.datetime.now()
	tasks            = []
	result = {}
	if tasks_cursor.count()!=0:
		for task in tasks_cursor:
			total_comment = comment_collection.find({"task_id": task['id']}).count()
			get_last_read_datetime   = last_read_comments.find_one({"id": engineer_id, "task_id": task['id']})
			if get_last_read_datetime is not None:
				unread_comment = comment_collection.find({"created_at":{"$gte": get_last_read_datetime['last_read_datetetime']},'task_id': task['id']}).count()
				task['unread_comment'] = unread_comment

			else:
				task['unread_comment'] = total_comment

			task['total_comments'] = total_comment
			tasks.append(task)

		result['tasks'] = tasks
		

		result['notification'] = notificaion_list_to_show
		return jsonify(result), 200
	else :
		return jsonify(result), 200
def verify_cookie(user_id, secret_hash):
    user = engineer_collection.find_one(
        {
            "id": user_id,
            "secret_hash": secret_hash,
            "is_admin": True
        }, {"_id": 0})

    if user:
        return True
    else:
        return False
def verify_otp():
	params 		   = request.json

	user_type = params.get('user_type')

	phone_params = params.get('phone')
	user_otp = params.get('otp')

	print("=========== otp params =========")
	print(params)
	
	if phone_params and user_otp:
		phone = str(phone_params)
		user_type = 'non_admin'
	else:
		user_data = params.get("user_data")
		phone 	= str(user_data.get('phone'))

	
		user_otp 	   = user_data.get('otp')
		

	if user_otp:
		if user_type == 'admin':
			engineer_obj = engineer_collection.find_one({"phone":phone,"is_admin":True},{"_id":0})
			if engineer_obj:
				resp = verify_user_name_otp(user_otp,phone)
	
				return resp
			else:
				resp = {"message":'Unauthorized access'}
				return jsonify(resp), 404

		else:
			user_type = "engineer"	
			print("---------- engineer -------------")	
			resp = verify_user_name_otp(user_otp,phone)
	
			return resp
	else:

		resp = {"message":'OTP is mandatory'}
		return jsonify(resp), 404
Example #8
0
def verify_user_name_otp(user_otp,phone):
	
	user_name_result = engineer_collection.find_one({"phone": phone},{"_id": 0})
	# "is_active":True
	if user_name_result:
		otp       = user_name_result.get("otp")
		user_id   = user_name_result.get("id")
		user_name = user_name_result.get("name") 
		
		if int(user_otp) == otp :
			print("otp is correct")
			user_id,secret_hash = make_cookie(user_id)
			resp = {"message": "user is authorized","phone": phone,"token": secret_hash,"user_id" : user_id,"user_name":user_name} 
			
			return jsonify(resp), 200

		else:
			resp = {"message": "incorrect otp"}
			return jsonify(resp), 404
	else:
		resp = {"message": "Phone number not found: please contact administrator "}
		return jsonify(resp), 404

	print(user_otp)
def change_status():
	params = request.json

	cookies = request.cookies

	if cookies:
		requestee_user_id = cookies.get('user_id')
		requestee_user_secret_hash = cookies.get('token')
		
	else:
		requestee_user_id = params['engineer_id']
		params.pop("engineer_id")

	requestee_user_obj = engineer_collection.find_one({"id":requestee_user_id},{"_id":0})

	task_status = params['task_status']
	task_id     = params['task_id']

	if task_status in STATUS :
		task_obj = task_collection.find_one({"id": task_id },{"_id":0})
		if task_obj :

			audit_log_obj = create_audit_log(old= task_obj, new = params, user_name = requestee_user_obj )

			if audit_log_obj:
				pass
			else:
				audit_log_obj = task_obj.get("audit_log")

			if task_status == "completed":

				task_collection.update_one({'id': task_id },
	                                      { '$set':
	                                      	{
	                                      		"task_status": task_status,
	                                      		"updated_at": str(datetime.datetime.now()),
	                                      		"audit_log": audit_log_obj,
	                                      		"completed_at": str(datetime.datetime.now())
	                                      	}
	                                          
	                                       }
	                                      )
				resp = {"message": "task status completed sucessfully"}
				return jsonify(resp), 200
			elif task_status == 'verified':
				task_collection.update_one({'id': task_id },
	                                      { '$set':
	                                      	{
	                                      		"task_status": task_status,
	                                      		"updated_at": str(datetime.datetime.now()),
	                                      		"audit_log": audit_log_obj,
	                                      		"verified_at": str(datetime.datetime.now())
	                                      	}
	                                          
	                                       }
	                                      )
				resp = {"message": "task status verified sucessfully"}
				return jsonify(resp), 200
			else:
				task_collection.update_one({'id': task_id },
	                                      { '$set':
	                                      	{
	                                      		"task_status": task_status,
	                                      		"updated_at": str(datetime.datetime.now()),
	                                      		"audit_log": audit_log_obj
	                                      	}
	                                          
	                                       }
	                                      )
				resp = {"message": "task status updated sucessfully"}
				return jsonify(resp), 200

		else :
			resp = {"message":"task not found"}
			return jsonify(resp), 404


	else :
		resp = {"message": "Invalid task status"}
		return jsonify(resp), 404
def update():
	
	#validation userid and secrethash
	#task title
	#task description
	#lattitude 
	#longitude
	#schedule_date
	#assigned to

	params 		= request.json

	cookies = request.cookies
	requestee_user_id = cookies.get('user_id')
	requestee_user_secret_hash = cookies.get('token')
	requestee_user_obj = engineer_collection.find_one({"id":requestee_user_id,"secret_hash":requestee_user_secret_hash},{"_id":0})

	task_id 		    = params["task_id"]
	title 			    = params.get("title") 
	description 	    = params.get("description")
	lattitude	        = params.get("lattitude") 
	longitude           = params.get("longitude")
	schedule_date_param	   = params.get("schedule_date")
	reverse_geocode	   = params.get("reverse_geocode")
	# converting datetime object and in indian format
	datetime_array = schedule_date_param.split("-")
	datetime_obj = datetime.datetime(int(datetime_array[2]),int(datetime_array[1]),int(datetime_array[0]))
	schedule_date = datetime_obj.strftime('%d-%m-%Y')

	schedule_date_operation = datetime.datetime(int(datetime_array[2]), int(datetime_array[1]), int(datetime_array[0]), 0 , 0)

	assigned_user_id   = params.get("assigned_user_id")
	task_status        = "unassigned"

	assigned_user_name = None


	if assigned_user_id:
		assigned_user_obj = engineer_collection.find_one({"id":assigned_user_id})
		if assigned_user_obj :
			assigned_user_name = assigned_user_obj.get('name') 
		else :
			assigned_user_name = None

	if assigned_user_id  and assigned_user_name:
		task_status = "assigned"



	if task_id == 0:
		# that means it is a new entry
		task_id = generate_unique_id(task_collection)

		
		result = task_collection.insert_one({
			"id"                 	 : task_id,
			"title"              	 : title,
			"description"        	 : description,
			"lattitude"	         	 : lattitude,
			"longitude"		     	 : longitude,
			"schedule_date"      	 : schedule_date,
			"assigned_user_name" 	 : assigned_user_name,
			"assigned_user_id"   	 : assigned_user_id,
			"task_status"		 	 : task_status,
			"schedule_date_operation": schedule_date_operation,
			"created_at"             : str(datetime.datetime.now()),
			"audit_log"			     : list(),
			"reverse_geocode"        : reverse_geocode
			},{"_id":0})

		if task_status == "assigned":

			send_notification(assigned_user_id, title, task_id)
			
			phone_no = str(assigned_user_obj.get('phone'))

			url1="http://kit19.com/ComposeSMS.aspx?username=raghav643283&password=7924&sender=SNAPOW&to="+phone_no+"&message=you%20have%20a%20new%20task,title:%20"+result.title+"&priority=1&dnd=1&unicode=0"
			req = urllib2.urlopen(url1)
			print("--------------------sending message to monty-----------------------")
			
			print(req.read().decode(req.headers.get_content_charset()))

		result = task_collection.find_one({"id": task_id},{"_id":0})

		resp = {"message" : "task inserted sucessfully","task_added":result}
		return jsonify(resp), 200

	

	else:
		# this means that the user already exist and we need to update it
		task_obj = task_collection.find_one({"id": task_id },{"_id":0,"id":0})
		
		if task_obj:
			audit_log_obj = create_audit_log(old= task_obj, new = params,user_name=requestee_user_obj, assigned_user_name=assigned_user_name )
			# task_audit_log = task_obj.get('audit_log')
			if audit_log_obj:
				pass
			else:
				audit_log_obj = task_obj.get("audit_log")


			if(reverse_geocode):
				task_collection.update_one({'id': task_id },
                                      { '$set':
                                      	{
                                      		"title"      : title,
											"description" : description,
											"lattitude"	  : lattitude,
											"longitude"	  : longitude,
											"schedule_date": schedule_date,
											"assigned_user_name" : assigned_user_name,
											"assigned_user_id": assigned_user_id,
											"task_status": task_status,
											"updated_at"  : str(datetime.datetime.now()),
											"audit_log"   : audit_log_obj,
											"schedule_date_operation": schedule_date_operation,
											"reverse_geocode"        : reverse_geocode
                                      	}
                                           
                                       }
                                      )
			else:
				task_collection.update_one({'id': task_id },
	              { '$set':
	              	{
	              		"title"      : title,
						"description" : description,
						"lattitude"	  : lattitude,
						"longitude"	  : longitude,
						"schedule_date": schedule_date,
						"assigned_user_name" : assigned_user_name,
						"assigned_user_id": assigned_user_id,
						"task_status": task_status,
						"updated_at"  : str(datetime.datetime.now()),
						"audit_log"   : audit_log_obj,
						"schedule_date_operation": schedule_date_operation
	              	}
	                   
	               }
	              )

			if task_status == "assigned":
				send_notification(assigned_user_id, title, task_id)


			result = task_collection.find_one({"id": task_id},{"_id":0})

			resp = {"message" : "task updated sucessfully","task_added":result}
			return jsonify(resp), 200

		else:
			resp = {"message": "task does not exist"}
			return jsonify(resp), 404
def deactivate_engineer_task():
    params = request.json
    engineer_id = params.get('engineer_id')
    deactivate_status = params.get('deactivate_status')
    cookies = request.cookies
    user_id = cookies.get('user_id')
    token = cookies.get('token')

    admin_obj = engineer_collection.find_one(
        {
            "id": user_id,
            "secret_hash": token,
            "is_admin": True
        }, {"_id": 0})

    if admin_obj:
        if deactivate_status:
            task_obj = task_collection.find(
                {
                    "assigned_user_id": engineer_id,
                    "task_status": {
                        "$in": ['completed', 'assigned']
                    }
                }, {"_id": 0})
            if task_obj.count() > 0:

                for task in task_obj:
                    task_collection.update_one({'id': task.get('id')}, {
                        "$set": {
                            "task_status": "unassigned",
                            "updated_at": str(datetime.datetime.now())
                        }
                    })

                result_obj = engineer_collection.update_one(
                    {'id': engineer_id}, {
                        "$set": {
                            "is_active": False,
                            "updated_at": str(datetime.datetime.now())
                        }
                    })
                resp = {
                    "message":
                    "Engineer deaactivated, {} marked as unassigned .. ".
                    format(task_obj.count())
                }
                return jsonify(resp), 200

            else:
                result_obj = engineer_collection.update_one(
                    {'id': engineer_id}, {
                        "$set": {
                            "is_active": False,
                            "updated_at": str(datetime.datetime.now())
                        }
                    })
                resp = {"message": "Engineer deactivated"}
                return jsonify(resp), 200

        else:
            task_obj = task_collection.find(
                {
                    "assigned_user_id": engineer_id,
                    "task_status": {
                        "$in": ['completed', 'assigned']
                    }
                }, {"_id": 0})
            print("----- tasks found ----{}".format(task_obj.count()))
            if task_obj:

                tasks = [t for t in task_obj]
                resp = {
                    "message": "tasks found",
                    "tasks": tasks,
                    "tasks_found": True
                }
                return jsonify(resp), 200
            else:
                resp = {"message": "tasks found", "tasks_found": False}
                return jsonify(resp), 200

    else:
        resp = {"message": "Invalid request"}
        return jsonify(resp), 404
Example #12
0
def update():

    params = request.json

    comment_id = params.get('comment_id')
    comment_text = params.get('comment_text')
    image_id = params.get('image_id')  #sincce its optional
    comment_by_id = params['comment_by_id']

    engineer_data = engineer_collection.find_one({"id": comment_by_id},
                                                 {"name": 1})

    comment_by_name = engineer_data['name']
    task_id = params['task_id']

    if comment_id == 0:
        comments_json = {
            "id": generate_unique_id(comment_collection),  #"test_id"
            "comment_text": comment_text,
            "image_id": image_id,
            "comment_by_id": comment_by_id,
            "comment_by_name": comment_by_name,
            "task_id": task_id,
            "created_at": str(datetime.datetime.now()),
            "updated_at": None
        }

        result = comment_collection.insert_one(comments_json)
        del comments_json['_id']

        update_date_time = str(datetime.datetime.now())
        get_last_read_datetime = last_read_comments.find_one({
            "id": comment_by_id,
            "task_id": task_id
        })
        if get_last_read_datetime is not None:
            last_read_comments.update({
                "id": comment_by_id,
                "task_id": task_id
            }, {"$set": {
                "last_read_datetetime": update_date_time
            }})
        else:
            last_read_comments.insert({
                "id": comment_by_id,
                "task_id": task_id,
                "last_read_datetetime": update_date_time
            })

        task_assigned_to = task_collection.find_one({"id": task_id})
        if task_assigned_to is not None:
            if task_assigned_to[
                    'assigned_user_id'] != comment_by_id and task_assigned_to[
                        "task_status"] == "assigned":
                send_notification(task_assigned_to['assigned_user_id'],
                                  comment_by_name, comment_text, task_id)

        audit = {}
        audit['time'] = str(datetime.datetime.now())
        audit['user_name'] = comment_by_name
        audit["changed_key"] = "comment"
        audit["comments"] = 1
        audit[
            "comment_text"] = comment_by_name + " has added a new comment on task" + task_assigned_to[
                'title']

        auditLos = notification_list.insert(audit)

        task_collection.update(
            {"id": task_id},
            {"$set": {
                "updated_at": str(datetime.datetime.now())
            }})
        resp = {
            "message": "task inserted sucessfully",
            "comment_list": comments_json
        }
        return jsonify(resp), 200

    elif comment_id == None:
        resp = {"message": "No comment_id found "}
        return jsonify(resp), 404
    else:
        comment_obj = comment_collection.find_one({"id": comment_id}, {
            "audit_log": 0,
            "_id": 0,
            "id": 0
        })
        if comment_obj:

            result_obj = comment_collection.update_one({'id': comment_id}, {
                "$set": {
                    "comment_text": comment_text,
                    "image_id": image_id,
                    "updated_at": str(datetime.datetime.now()),
                    "audit_log": comment_obj
                }
            })

            resp = {"message": " comment updated sucessfully"}
            return jsonify(resp), 200

        else:
            resp = {"message": "comment not found"}
            return jsonify(resp), 404