Example #1
0
def display_scheduler(request, practice_id, callgroup_id):
    if not user_is_mgr_of_practice_id(request.user, practice_id):
        return err403(request)

    context = get_context(request)
    context['raw_callgroup_id'] = callgroup_id
    callgroup_old_id = None
    if not callgroup_id or callgroup_id in [0, '0'] and \
      SessionHelper.CURRENT_CALLGROUP_ID in request.session.keys():
        callgroup_id = request.session[SessionHelper.CURRENT_CALLGROUP_ID]

    if SessionHelper.CURRENT_CALLGROUP_ID in request.session.keys():
        callgroup_old_id = request.session[SessionHelper.CURRENT_CALLGROUP_ID]
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    request.session[SessionHelper.CURRENT_CALLGROUP_ID] = callgroup_id

    if callgroup_old_id != callgroup_id:
        SessionHelper.clearAllSessionStack(request)

    if (not callgroup_id):
        current_practice = context['current_practice']
        context['error'] = _('There is no call group associated with your ' +
                             get_org_type_name(current_practice) + '.')
        return render_to_response("error_multicallgroup.html", context)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    specialties = Specialty.objects.filter(
        practice_location__pk=practice_id).order_by('name')
    call_groups = []
    i = 256
    for specialty in specialties:
        for call_group in specialty.call_groups.all().order_by('team'):
            if i:
                description = '%s > %s ' % (specialty.name, call_group.team)
                description = (description[:80] +
                               '..') if len(description) > 80 else description
                call_groups.append({
                    'id': call_group.id,
                    'description': description
                })
                i -= 1
            else:
                context['error'] = _(
                    'For security reason, we only display 256 call groups here. '
                    'Sorry about inconvenience.')
                return render_to_response("error_multicallgroup.html", context)

    context['call_groups'] = call_groups
    context['current_callgroup_id'] = callgroup_id

    return render_to_response("schedule_multicallgroup.html", context)
Example #2
0
def display_scheduler(request, practice_id, callgroup_id):
	if not user_is_mgr_of_practice_id(request.user, practice_id):
		return err403(request)

	context = get_context(request)
	context['raw_callgroup_id'] = callgroup_id
	callgroup_old_id = None
	if not callgroup_id or callgroup_id in [0, '0'] and \
			SessionHelper.CURRENT_CALLGROUP_ID in request.session.keys():
		callgroup_id = request.session[SessionHelper.CURRENT_CALLGROUP_ID]

	if SessionHelper.CURRENT_CALLGROUP_ID in request.session.keys():
		callgroup_old_id = request.session[SessionHelper.CURRENT_CALLGROUP_ID]
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	request.session[SessionHelper.CURRENT_CALLGROUP_ID] = callgroup_id

	if callgroup_old_id != callgroup_id:
		SessionHelper.clearAllSessionStack(request)

	if (not callgroup_id):
		current_practice = context['current_practice']
		context['error'] = _('There is no call group associated with your ' + 
			get_org_type_name(current_practice) + '.')
		return render_to_response("error_multicallgroup.html", context)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	specialties = Specialty.objects.filter(practice_location__pk=practice_id).order_by('name')
	call_groups = []
	i = 256
	for specialty in specialties:
		for call_group in specialty.call_groups.all().order_by('team'):
			if i:
				description = '%s > %s ' % (specialty.name, call_group.team)
				description = (description[:80] + '..') if len(description) > 80 else description
				call_groups.append({'id': call_group.id, 'description': description})
				i -= 1
			else:
				context['error'] = _('For security reason, we only display 256 call groups here. '
									'Sorry about inconvenience.')
				return render_to_response("error_multicallgroup.html", context)

	context['call_groups'] = call_groups
	context['current_callgroup_id'] = callgroup_id

	return render_to_response("schedule_multicallgroup.html", context)
Example #3
0
def changeCurrentPractice(request):
	id = request.POST['id']
	user = request.session['MHL_UserIDs']['MHLUser']
	try:
		current_practice = changeCurrentPracticeForStaff(id, user)
		view = '{"name":"month"}'
		request.session[SessionHelper.SCHEDULE_LASTVIEW] = view
		SessionHelper.clearSessionStack(request, SessionHelper.CURRENT_CALLGROUP_ID)
		callgroup_id = 0
		if current_practice.uses_original_answering_serice():
			callgroup_id = current_practice.call_group.id

		return HttpResponse(json.dumps({'view': view, 'status': 'ok', 
				'callgroup_id': callgroup_id, 
				'uses_original_answering_serice': 
					current_practice.uses_original_answering_serice()}))
	except PracticeLocation.DoesNotExist, MHLUser.DoesNotExist:
		return HttpResponse(json.dumps('err'))
Example #4
0
def undoOrRedo(request, practice_id, callgroup_id, srcStackName, targetStackName):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	user = request.user
	if request.method == 'POST':
		operateList = SessionHelper.popSessionStack(request, srcStackName)
		if (operateList is not None and len(operateList) > 0):
			operateList_n = []
			operateList_r = []
			for operateItem in operateList:
				type = operateItem["type"]
				data = operateItem["data"]
				view = operateItem["view"]
				pk = operateItem["pk"]	
				eventObj = serializers.deserialize("json", data).next()
				if ("0" == type):
					# set defaults
					eventObj.object.callGroup_id = int(callgroup_id)
					eventObj.object.notifyState = 2
					eventObj.object.whoCanModify = 1
					eventObj.object.eventStatus = 1
					if validateNewEvent(eventObj):
						# we are ok to save this new object
						eventObj.object.creator = user
						eventObj.object.creationdate = datetime.datetime.now()
						eventObj.object.lastupdate = datetime.datetime.now()
						eventObj.object.title = 'scheduled_event'
						eventObj.save()
						newOperate = {
							'type': "2",
							'view': view,
							"pk": eventObj.object.pk, 									
							'data': serializers.serialize("json", [eventObj.object], 
								fields=('oncallPerson', 'eventType', 'startDate', 
									'endDate', 'checkString'))}

						SessionHelper.checkSessionStack(request, 
							SessionHelper.SCHEDULE_UNDOSTACK_NAME, pk, eventObj.object.pk)
						SessionHelper.checkSessionStack(request, 
							SessionHelper.SCHEDULE_REDOSTACK_NAME, pk, eventObj.object.pk)

						operateList_n.append(newOperate)							
						operateList_r.append(newOperate)
				elif ("1" == type or "2" == type):
					# check checkString and fill in creationdate and lastupdate date
					oldEvent = EventEntry.objects.get(id=eventObj.object.pk)
					if (oldEvent.checkString == eventObj.object.checkString):
						newType = ("1" == type and "1" or "0") 

						eventObj.object.callGroup_id = int(callgroup_id)
						# necessary for easier access in the admin
						eventObj.object.title = 'scheduled_event-%i' % (eventObj.object.pk,)
						eventObj.object.notifyState = 2
						eventObj.object.whoCanModify = 1
						eventObj.object.creator = user
						eventObj.object.creationdate = oldEvent.creationdate
						eventObj.object.lastupdate = datetime.datetime.now()
						eventObj.object.eventStatus = newType

						eventObj.save()

						operateList_n.append({
							'type': newType,
							'view': view, 	
							"pk": eventObj.object.pk, 								
							'data': serializers.serialize("json", [oldEvent], 
								fields=('oncallPerson', 'eventType', 
									'startDate', 'endDate', 'checkString'))})	
						operateList_r.append({
							'type': newType,
							'view': view, 	
							'pk': pk, 							
							'data': serializers.serialize("json", [eventObj.object], 
								fields=('oncallPerson', 'eventType', 
									'startDate', 'endDate', 'checkString'))})
				request.session[SessionHelper.SCHEDULE_LASTVIEW] = view
			SessionHelper.pushSessionStack(request, targetStackName, operateList_n)
			response = {'operateList': operateList_r, 'error': '', 'undoSize': 
				SessionHelper.getSessionStackSize(request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
					'redoSize': SessionHelper.getSessionStackSize(
						request, SessionHelper.SCHEDULE_REDOSTACK_NAME)}
		else:
			response = {'operateList': [], 'error': '', 'count': 0,
				'undoSize': SessionHelper.getSessionStackSize(
					request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
				'redoSize': SessionHelper.getSessionStackSize(
					request, SessionHelper.SCHEDULE_REDOSTACK_NAME)}
		return HttpResponse(content=json.dumps(response), mimetype='application/json')
Example #5
0
def bulkUpdateEvents(request, practice_id, callgroup_id=None):
	"""
		bulk update eventEntry returns result of eventEntries updated and any 
		errors/warnings if there is a mismatch with checkString
	"""
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	user = request.user
	if request.method == 'POST':
		# form = BulkEventForm(request.POST) # never used.
		errorlist = []
		savelist = []
		operateList = []
		count = 0
		data = request.POST['data']
		view = request.POST['view']

		if checkSchedulerView(view):
			logger.debug('data from request is %s' % (data))
			for eventObj in serializers.deserialize("json", data):
				count = count + 1
				eventObj.object.callGroup_id = int(callgroup_id)
				# necessary for easier access in the admin
				eventObj.object.title = 'scheduled_event-%i' % (eventObj.object.pk,)
				eventObj.object.notifyState = 2
				eventObj.object.whoCanModify = 1
				# we check for pk presence first
				if (eventObj.object.pk == None):
					errorlist.append("0, error updating object - no key present %s %s" %
						(eventObj.object.checkString, eventObj))
				elif checkDSEventConsistency(eventObj):
					# check checkString and fill in creationdate and lastupdate date
					oldEvent = EventEntry.objects.get(id=eventObj.object.pk)
					if (oldEvent.checkString == eventObj.object.checkString):
						# we are ok
						eventObj.object.creator = user
						eventObj.object.creationdate = oldEvent.creationdate
						eventObj.object.lastupdate = datetime.datetime.now()

						try:
							# validate the updated EventEntry 
							eventObj.object.clean_fields()	
							eventObj.save()
							operateList.append({
								'type': eventObj.object.eventStatus,
								"view": view,
								"pk": eventObj.object.pk, 								
								'data': serializers.serialize("json", [oldEvent], 
									fields=('oncallPerson', 'eventType', 'startDate', 
										'endDate', 'checkString'))})							
							savelist.append('%s, %s' % (eventObj.object.id, 
									eventObj.object.checkString))
						except ValidationError:
							errorlist.append("%d, update failed - validate error %s obj %s" %
								(eventObj.object.pk, eventObj.object.checkString, eventObj))	
					else:
						errorlist.append("%d, update failed - invalid checkString %s obj %s" %
							(eventObj.object.pk, eventObj.object.checkString, eventObj))
				else:
					errorlist.append("%d, error updating object %s obj %s" %
						(eventObj.object.pk, eventObj.object.checkString, eventObj))
		else:
			errorlist.append("invalid view")

		SessionHelper.pushSessionStack(request, SessionHelper.SCHEDULE_UNDOSTACK_NAME, operateList)	
		SessionHelper.clearSessionStack(request, SessionHelper.SCHEDULE_REDOSTACK_NAME)	
		response = {'data': savelist, 'error': errorlist, 'count': count,
			'undoSize': SessionHelper.getSessionStackSize(request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
			'redoSize': SessionHelper.getSessionStackSize(request, SessionHelper.SCHEDULE_REDOSTACK_NAME)}
		logger.debug('returned result %s' % (response))
		return HttpResponse(content=json.dumps(response), mimetype='application/json')
	else:
		form = BulkEventForm()
		return render_to_response("bulkOperation.html", {'form': form, })
Example #6
0
def bulkNewEvents(request, practice_id, callgroup_id=None):
	"""
		bulk add eventEntry
		returns result of eventEntries saved and any errors/warnings
	"""
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	user = request.user
	if request.method == 'POST':
		form = BulkEventForm(request.POST)
		data = request.POST['data']
		view = request.POST['view']
		errorlist = []  # this contains errors/warnings 
		operateList = []		
		count = 0  # count how many events we got
		newPks = dict()
		logger.debug('data from request is %s' % (data))

		if checkSchedulerView(view):
			for newdsEventObj in serializers.deserialize("json", data):
				count = count + 1
				# set defaults
				newdsEventObj.object.callGroup_id = int(callgroup_id)
				newdsEventObj.object.notifyState = 2
				newdsEventObj.object.whoCanModify = 1
				newdsEventObj.object.eventStatus = 1
				if validateNewEvent(newdsEventObj):
					# we are ok to save this new object
					newdsEventObj.object.creator = user
					newdsEventObj.object.creationdate = datetime.datetime.now()
					newdsEventObj.object.lastupdate = datetime.datetime.now()
					newdsEventObj.object.title = 'scheduled_event'  
					try:
						# validate the EventEntry 
						newdsEventObj.object.clean_fields()	
						newdsEventObj.save()
						newPks[newdsEventObj.object.checkString] = newdsEventObj.object.pk

						operateList.append({
								'type': "2",
								"view": view,
								"pk": newdsEventObj.object.pk,
								'data': serializers.serialize("json", [newdsEventObj.object], 
									fields=('oncallPerson', 'eventType', 
										'startDate', 'endDate', 'checkString'))})	
					except ValidationError:
						errorlist.append('Validate error saving new object: %s' % 
							(serializers.serialize("json", [newdsEventObj.object], 
								fields=('oncallPerson', 'eventType', 'startDate', 
									'endDate', 'checkString'))))
				else:
					errorlist.append('%s, error saving new object' % (newdsEventObj.object.checkString))
		else:
			errorlist.append("invalid view")

		SessionHelper.pushSessionStack(request, SessionHelper.SCHEDULE_UNDOSTACK_NAME, operateList)		
		SessionHelper.clearSessionStack(request, SessionHelper.SCHEDULE_REDOSTACK_NAME)					
		response = {'data': newPks, 'error': errorlist, 'count': count,
			'undoSize': SessionHelper.getSessionStackSize(request, 
					SessionHelper.SCHEDULE_UNDOSTACK_NAME),
			'redoSize': SessionHelper.getSessionStackSize(request, 
					SessionHelper.SCHEDULE_REDOSTACK_NAME)}
		logger.debug('returned result %s' % (response))
		return HttpResponse(content=json.dumps(response), mimetype='application/json')
	else:
		form = BulkEventForm()
		return render_to_response("bulkOperation.html", {'form': form, })
Example #7
0
def getEvents(request, practice_id, callgroup_id=None):
	"""
		gets events associated with a callgroup
		retuns eventList serialized in json format
	"""
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	fromDateTmp = datetime.date.today() - datetime.timedelta(days=15)  # defaults
	toDateTmp = datetime.date.today() + datetime.timedelta(days=30)
	eventList = []
	if request.method == 'POST':
		form = DateEntryForm(request.POST)
		# ok - checking for is_valid() on the form is buggy with DateTime - it seems?!
		if form.is_valid():
			# get fromDate and toDate and fetch the events
			fromDateTmp = form.cleaned_data['fromDate']
			logger.debug('fromDate from request is %s' % 
				(fromDateTmp))
			toDateTmp = form.cleaned_data['toDate']
			logger.debug('toDate from request is %s' % 
				(toDateTmp))

			callGroupId = callgroup_id

			logger.debug('callGroupId from request is %d' % 
				int(callGroupId))

			user = MHLUser.objects.get(pk=request.user.pk)
			# get the user's callGroup id?
			# need to check if user is office manager or physician in the callGroup
			if (user):
				eventList = EventEntry.objects.filter(
					Q(eventStatus='1'), Q(callGroup=callGroupId),
					startDate__lt=toDateTmp, endDate__gt=fromDateTmp
				)
			else:
				raise Exception('Only users can view scheduled events')	

			data = serializers.serialize("json", eventList, fields=('oncallPerson', 
				'oncallPerson__user', 'eventType', 'startDate', 'endDate', 'checkString'))

			addData = json.loads(data)
			members = CallGroupMember.objects.filter(
				call_group__id=callgroup_id).values_list('member__user__id')
			for d in addData:
				id = d['fields']['oncallPerson']
				user = MHLUser.objects.get(id=id)
				d['fields']['fullname'] = get_fullname(user)
				if (long(id),) in members:
					d['fields']['hasDeleted'] = 0
				else:
					d['fields']['hasDeleted'] = 1

			data = json.dumps(addData)
			logger.debug('user %s - got back %d events' % 
				(user, eventList.count()))
			SessionHelper.clearSessionStack(request, SessionHelper.SCHEDULE_UNDOSTACK_NAME)
			SessionHelper.clearSessionStack(request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
			return HttpResponse(content=json.dumps({'datas': data,
				'undoSize': 0,
				'redoSize': 0}),
				mimetype='application/json')
		else:
			r = HttpResponse()
			r.status_code = 403
			return r
	else: 
		form = DateEntryForm(initial={'fromDate': fromDateTmp, 'toDate': toDateTmp, })
		return render_to_response("DateEntry.html", {'form': form, })
Example #8
0
def undoOrRedo(request, practice_id, callgroup_id, srcStackName,
               targetStackName):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    user = request.user
    if request.method == 'POST':
        operateList = SessionHelper.popSessionStack(request, srcStackName)
        if (operateList is not None and len(operateList) > 0):
            operateList_n = []
            operateList_r = []
            for operateItem in operateList:
                type = operateItem["type"]
                data = operateItem["data"]
                view = operateItem["view"]
                pk = operateItem["pk"]
                eventObj = serializers.deserialize("json", data).next()
                if ("0" == type):
                    # set defaults
                    eventObj.object.callGroup_id = int(callgroup_id)
                    eventObj.object.notifyState = 2
                    eventObj.object.whoCanModify = 1
                    eventObj.object.eventStatus = 1
                    if validateNewEvent(eventObj):
                        # we are ok to save this new object
                        eventObj.object.creator = user
                        eventObj.object.creationdate = datetime.datetime.now()
                        eventObj.object.lastupdate = datetime.datetime.now()
                        eventObj.object.title = 'scheduled_event'
                        eventObj.save()
                        newOperate = {
                            'type':
                            "2",
                            'view':
                            view,
                            "pk":
                            eventObj.object.pk,
                            'data':
                            serializers.serialize(
                                "json", [eventObj.object],
                                fields=('oncallPerson', 'eventType',
                                        'startDate', 'endDate', 'checkString'))
                        }

                        SessionHelper.checkSessionStack(
                            request, SessionHelper.SCHEDULE_UNDOSTACK_NAME, pk,
                            eventObj.object.pk)
                        SessionHelper.checkSessionStack(
                            request, SessionHelper.SCHEDULE_REDOSTACK_NAME, pk,
                            eventObj.object.pk)

                        operateList_n.append(newOperate)
                        operateList_r.append(newOperate)
                elif ("1" == type or "2" == type):
                    # check checkString and fill in creationdate and lastupdate date
                    oldEvent = EventEntry.objects.get(id=eventObj.object.pk)
                    if (oldEvent.checkString == eventObj.object.checkString):
                        newType = ("1" == type and "1" or "0")

                        eventObj.object.callGroup_id = int(callgroup_id)
                        # necessary for easier access in the admin
                        eventObj.object.title = 'scheduled_event-%i' % (
                            eventObj.object.pk, )
                        eventObj.object.notifyState = 2
                        eventObj.object.whoCanModify = 1
                        eventObj.object.creator = user
                        eventObj.object.creationdate = oldEvent.creationdate
                        eventObj.object.lastupdate = datetime.datetime.now()
                        eventObj.object.eventStatus = newType

                        eventObj.save()

                        operateList_n.append({
                            'type':
                            newType,
                            'view':
                            view,
                            "pk":
                            eventObj.object.pk,
                            'data':
                            serializers.serialize(
                                "json", [oldEvent],
                                fields=('oncallPerson', 'eventType',
                                        'startDate', 'endDate', 'checkString'))
                        })
                        operateList_r.append({
                            'type':
                            newType,
                            'view':
                            view,
                            'pk':
                            pk,
                            'data':
                            serializers.serialize(
                                "json", [eventObj.object],
                                fields=('oncallPerson', 'eventType',
                                        'startDate', 'endDate', 'checkString'))
                        })
                request.session[SessionHelper.SCHEDULE_LASTVIEW] = view
            SessionHelper.pushSessionStack(request, targetStackName,
                                           operateList_n)
            response = {
                'operateList':
                operateList_r,
                'error':
                '',
                'undoSize':
                SessionHelper.getSessionStackSize(
                    request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
                'redoSize':
                SessionHelper.getSessionStackSize(
                    request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
            }
        else:
            response = {
                'operateList': [],
                'error':
                '',
                'count':
                0,
                'undoSize':
                SessionHelper.getSessionStackSize(
                    request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
                'redoSize':
                SessionHelper.getSessionStackSize(
                    request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
            }
        return HttpResponse(content=json.dumps(response),
                            mimetype='application/json')
Example #9
0
def bulkUpdateEvents(request, practice_id, callgroup_id=None):
    """
		bulk update eventEntry returns result of eventEntries updated and any 
		errors/warnings if there is a mismatch with checkString
	"""
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    user = request.user
    if request.method == 'POST':
        # form = BulkEventForm(request.POST) # never used.
        errorlist = []
        savelist = []
        operateList = []
        count = 0
        data = request.POST['data']
        view = request.POST['view']

        if checkSchedulerView(view):
            logger.debug('data from request is %s' % (data))
            for eventObj in serializers.deserialize("json", data):
                count = count + 1
                eventObj.object.callGroup_id = int(callgroup_id)
                # necessary for easier access in the admin
                eventObj.object.title = 'scheduled_event-%i' % (
                    eventObj.object.pk, )
                eventObj.object.notifyState = 2
                eventObj.object.whoCanModify = 1
                # we check for pk presence first
                if (eventObj.object.pk == None):
                    errorlist.append(
                        "0, error updating object - no key present %s %s" %
                        (eventObj.object.checkString, eventObj))
                elif checkDSEventConsistency(eventObj):
                    # check checkString and fill in creationdate and lastupdate date
                    oldEvent = EventEntry.objects.get(id=eventObj.object.pk)
                    if (oldEvent.checkString == eventObj.object.checkString):
                        # we are ok
                        eventObj.object.creator = user
                        eventObj.object.creationdate = oldEvent.creationdate
                        eventObj.object.lastupdate = datetime.datetime.now()

                        try:
                            # validate the updated EventEntry
                            eventObj.object.clean_fields()
                            eventObj.save()
                            operateList.append({
                                'type':
                                eventObj.object.eventStatus,
                                "view":
                                view,
                                "pk":
                                eventObj.object.pk,
                                'data':
                                serializers.serialize(
                                    "json", [oldEvent],
                                    fields=('oncallPerson', 'eventType',
                                            'startDate', 'endDate',
                                            'checkString'))
                            })
                            savelist.append('%s, %s' %
                                            (eventObj.object.id,
                                             eventObj.object.checkString))
                        except ValidationError:
                            errorlist.append(
                                "%d, update failed - validate error %s obj %s"
                                % (eventObj.object.pk,
                                   eventObj.object.checkString, eventObj))
                    else:
                        errorlist.append(
                            "%d, update failed - invalid checkString %s obj %s"
                            % (eventObj.object.pk, eventObj.object.checkString,
                               eventObj))
                else:
                    errorlist.append("%d, error updating object %s obj %s" %
                                     (eventObj.object.pk,
                                      eventObj.object.checkString, eventObj))
        else:
            errorlist.append("invalid view")

        SessionHelper.pushSessionStack(request,
                                       SessionHelper.SCHEDULE_UNDOSTACK_NAME,
                                       operateList)
        SessionHelper.clearSessionStack(request,
                                        SessionHelper.SCHEDULE_REDOSTACK_NAME)
        response = {
            'data':
            savelist,
            'error':
            errorlist,
            'count':
            count,
            'undoSize':
            SessionHelper.getSessionStackSize(
                request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
            'redoSize':
            SessionHelper.getSessionStackSize(
                request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
        }
        logger.debug('returned result %s' % (response))
        return HttpResponse(content=json.dumps(response),
                            mimetype='application/json')
    else:
        form = BulkEventForm()
        return render_to_response("bulkOperation.html", {
            'form': form,
        })
Example #10
0
def bulkNewEvents(request, practice_id, callgroup_id=None):
    """
		bulk add eventEntry
		returns result of eventEntries saved and any errors/warnings
	"""
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    user = request.user
    if request.method == 'POST':
        form = BulkEventForm(request.POST)
        data = request.POST['data']
        view = request.POST['view']
        errorlist = []  # this contains errors/warnings
        operateList = []
        count = 0  # count how many events we got
        newPks = dict()
        logger.debug('data from request is %s' % (data))

        if checkSchedulerView(view):
            for newdsEventObj in serializers.deserialize("json", data):
                count = count + 1
                # set defaults
                newdsEventObj.object.callGroup_id = int(callgroup_id)
                newdsEventObj.object.notifyState = 2
                newdsEventObj.object.whoCanModify = 1
                newdsEventObj.object.eventStatus = 1
                if validateNewEvent(newdsEventObj):
                    # we are ok to save this new object
                    newdsEventObj.object.creator = user
                    newdsEventObj.object.creationdate = datetime.datetime.now()
                    newdsEventObj.object.lastupdate = datetime.datetime.now()
                    newdsEventObj.object.title = 'scheduled_event'
                    try:
                        # validate the EventEntry
                        newdsEventObj.object.clean_fields()
                        newdsEventObj.save()
                        newPks[newdsEventObj.object.
                               checkString] = newdsEventObj.object.pk

                        operateList.append({
                            'type':
                            "2",
                            "view":
                            view,
                            "pk":
                            newdsEventObj.object.pk,
                            'data':
                            serializers.serialize(
                                "json", [newdsEventObj.object],
                                fields=('oncallPerson', 'eventType',
                                        'startDate', 'endDate', 'checkString'))
                        })
                    except ValidationError:
                        errorlist.append(
                            'Validate error saving new object: %s' %
                            (serializers.serialize(
                                "json", [newdsEventObj.object],
                                fields=('oncallPerson', 'eventType',
                                        'startDate', 'endDate',
                                        'checkString'))))
                else:
                    errorlist.append('%s, error saving new object' %
                                     (newdsEventObj.object.checkString))
        else:
            errorlist.append("invalid view")

        SessionHelper.pushSessionStack(request,
                                       SessionHelper.SCHEDULE_UNDOSTACK_NAME,
                                       operateList)
        SessionHelper.clearSessionStack(request,
                                        SessionHelper.SCHEDULE_REDOSTACK_NAME)
        response = {
            'data':
            newPks,
            'error':
            errorlist,
            'count':
            count,
            'undoSize':
            SessionHelper.getSessionStackSize(
                request, SessionHelper.SCHEDULE_UNDOSTACK_NAME),
            'redoSize':
            SessionHelper.getSessionStackSize(
                request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
        }
        logger.debug('returned result %s' % (response))
        return HttpResponse(content=json.dumps(response),
                            mimetype='application/json')
    else:
        form = BulkEventForm()
        return render_to_response("bulkOperation.html", {
            'form': form,
        })
Example #11
0
def getEvents(request, practice_id, callgroup_id=None):
    """
		gets events associated with a callgroup
		retuns eventList serialized in json format
	"""
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    fromDateTmp = datetime.date.today() - datetime.timedelta(
        days=15)  # defaults
    toDateTmp = datetime.date.today() + datetime.timedelta(days=30)
    eventList = []
    if request.method == 'POST':
        form = DateEntryForm(request.POST)
        # ok - checking for is_valid() on the form is buggy with DateTime - it seems?!
        if form.is_valid():
            # get fromDate and toDate and fetch the events
            fromDateTmp = form.cleaned_data['fromDate']
            logger.debug('fromDate from request is %s' % (fromDateTmp))
            toDateTmp = form.cleaned_data['toDate']
            logger.debug('toDate from request is %s' % (toDateTmp))

            callGroupId = callgroup_id

            logger.debug('callGroupId from request is %d' % int(callGroupId))

            user = MHLUser.objects.get(pk=request.user.pk)
            # get the user's callGroup id?
            # need to check if user is office manager or physician in the callGroup
            if (user):
                eventList = EventEntry.objects.filter(Q(eventStatus='1'),
                                                      Q(callGroup=callGroupId),
                                                      startDate__lt=toDateTmp,
                                                      endDate__gt=fromDateTmp)
            else:
                raise Exception('Only users can view scheduled events')

            data = serializers.serialize(
                "json",
                eventList,
                fields=('oncallPerson', 'oncallPerson__user', 'eventType',
                        'startDate', 'endDate', 'checkString'))

            addData = json.loads(data)
            members = CallGroupMember.objects.filter(
                call_group__id=callgroup_id).values_list('member__user__id')
            for d in addData:
                id = d['fields']['oncallPerson']
                user = MHLUser.objects.get(id=id)
                d['fields']['fullname'] = get_fullname(user)
                if (long(id), ) in members:
                    d['fields']['hasDeleted'] = 0
                else:
                    d['fields']['hasDeleted'] = 1

            data = json.dumps(addData)
            logger.debug('user %s - got back %d events' %
                         (user, eventList.count()))
            SessionHelper.clearSessionStack(
                request, SessionHelper.SCHEDULE_UNDOSTACK_NAME)
            SessionHelper.clearSessionStack(
                request, SessionHelper.SCHEDULE_REDOSTACK_NAME)
            return HttpResponse(content=json.dumps({
                'datas': data,
                'undoSize': 0,
                'redoSize': 0
            }),
                                mimetype='application/json')
        else:
            r = HttpResponse()
            r.status_code = 403
            return r
    else:
        form = DateEntryForm(initial={
            'fromDate': fromDateTmp,
            'toDate': toDateTmp,
        })
        return render_to_response("DateEntry.html", {
            'form': form,
        })