示例#1
0
def addProviderInGroup(request, practice_id, callgroup_id):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    from_user = request.session['MHL_Users']['MHLUser']
    to_user = request.POST['to_user']
    to_user = Provider.objects.get(id=to_user)
    call_group = CallGroup.objects.get(id=callgroup_id)
    practice = PracticeLocation.objects.get(id=practice_id)
    current_practice = request.session['MHL_Users'][
        'OfficeStaff'].current_practice

    if to_user.current_practice and to_user.current_practice.id == current_practice.id:
        msg = 'Congratulations! We have added this member to call group. You can:'
    else:
        msg = '''This user is not in your practice now. We have sent an invitation to 
		him/her for confirm to join this call group.
		(He/She will not join your practice by accept this invitation.)'''

    try:
        members = CallGroupMemberPending(from_user=from_user,
                                         to_user=to_user,
                                         call_group=call_group,
                                         practice=practice,
                                         created_time=datetime.datetime.now())
        members.save()
        return HttpResponse(json.dumps({'err': msg}))
    except Exception:
        return HttpResponse(
            json.dumps({'ok': 'There is an error, please refresh page.'}))
示例#2
0
def rulesCheck(request, practice_id, callgroup_id=None):
	"""
		checks for holes in oncall coverage in eventEntry records for the next 14 days
		calls utils rulesCheckInternal(callGroupId, fromDateTmp, toDateTmp)
		returns eventEntry list and list of holes in coverage
	"""
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	# get all the events for next 2 weeks
	fromDateTmp = datetime.datetime.now()
	toDateTmp = fromDateTmp + datetime.timedelta(days=14)
	if request.method == 'POST':
		form = DateEntryForm(request.POST)
		# datestring is needed for the rulesCheckInternal
		fromDateStr = fromDateTmp.strftime("%Y-%m-%d %H:%M:%S")
		toDateStr = toDateTmp.strftime("%Y-%m-%d %H:%M:%S")
		eventList, errorList = rulesCheckInternal(callgroup_id, fromDateStr, toDateStr)
		logger.debug('returned result %d error %d' % (len(eventList), len(errorList)))
		data = serializers.serialize("json", eventList)
		response = {'data': data, 'error': errorList}
		logger.debug('rulescheck result %s' % (response))
		# TODO: need to dump out response
		return HttpResponse(content=json.dumps(errorList), mimetype='application/json')
	else: 
		form = DateEntryForm(initial={'fromDate': fromDateTmp, 'toDate': toDateTmp, })
		return render_to_response("DateEntry.html", {'form': form, })
示例#3
0
def getPrintableSchedule(request, practice_id, callgroup_id=None):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	callgroup = CallGroup.objects.get(pk=callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)

	return export_schedule_to_pdf(request, callgroup)
示例#4
0
def rulesCheck(request, practice_id, callgroup_id=None):
    """
		checks for holes in oncall coverage in eventEntry records for the next 14 days
		calls utils rulesCheckInternal(callGroupId, fromDateTmp, toDateTmp)
		returns eventEntry list and list of holes in coverage
	"""
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    # get all the events for next 2 weeks
    fromDateTmp = datetime.datetime.now()
    toDateTmp = fromDateTmp + datetime.timedelta(days=14)
    if request.method == 'POST':
        form = DateEntryForm(request.POST)
        # datestring is needed for the rulesCheckInternal
        fromDateStr = fromDateTmp.strftime("%Y-%m-%d %H:%M:%S")
        toDateStr = toDateTmp.strftime("%Y-%m-%d %H:%M:%S")
        eventList, errorList = rulesCheckInternal(callgroup_id, fromDateStr,
                                                  toDateStr)
        logger.debug('returned result %d error %d' %
                     (len(eventList), len(errorList)))
        data = serializers.serialize("json", eventList)
        response = {'data': data, 'error': errorList}
        logger.debug('rulescheck result %s' % (response))
        # TODO: need to dump out response
        return HttpResponse(content=json.dumps(errorList),
                            mimetype='application/json')
    else:
        form = DateEntryForm(initial={
            'fromDate': fromDateTmp,
            'toDate': toDateTmp,
        })
        return render_to_response("DateEntry.html", {
            'form': form,
        })
示例#5
0
def checkProviderInCallGroup(request, practice_id, callgroup_id):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    user = request.POST['id']
    members = CallGroupMember.objects.filter(call_group__id=callgroup_id,
                                             member=user)
    pendings = CallGroupMemberPending.objects.filter(
        call_group__id=callgroup_id,
        practice__id=practice_id,
        to_user=user,
        accept_status=0)
    current_practice = request.session['MHL_Users'][
        'OfficeStaff'].current_practice

    to_user = Provider.objects.get(id=user)
    providers = Provider.objects.filter(practices=current_practice)

    if members:
        return HttpResponse(json.dumps('member'))
    elif pendings:
        return HttpResponse(json.dumps('pending'))
    else:
        if to_user in providers:
            return HttpResponse(json.dumps('inpracitce'))
        else:
            return HttpResponse(json.dumps('ok'))
示例#6
0
def getPrintableSchedule(request, practice_id, callgroup_id=None):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    callgroup = CallGroup.objects.get(pk=callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)

    return export_schedule_to_pdf(request, callgroup)
示例#7
0
    def test_checkMultiCallGroupId(self):
        #init practice and call group
        call_group = CallGroup(description='test', team='team')
        call_group.save()

        practice = PracticeLocation(
            practice_name='test',
            practice_longit='0.1',
            practice_lat='0.0',
        )
        practice.save()
        practice.call_groups.add(call_group)

        #pass a valid parameter
        result = checkMultiCallGroupId(practice.id, call_group.id)
        self.assertEqual(call_group.id, result)

        #practice not exist
        #		result = checkMultiCallGroupId(117, 0)
        #		self.assertRaises(PracticeLocation.DoesNotExist, result)

        #pass a invalid call group parameter
        result = checkMultiCallGroupId(practice.id, 0)
        self.assertEqual(call_group.id, result)

        #ther is a specialty
        practice2 = PracticeLocation(
            practice_name='test2',
            practice_longit='0.1',
            practice_lat='0.0',
        )
        practice2.save()

        specialty_name = 'Specialty A'
        specialty1 = Specialty()
        specialty1.name = specialty_name
        specialty1.practice_location = practice2
        specialty1.number_selection = 3
        specialty1.save()
        specialty1.call_groups.add(call_group)

        result = checkMultiCallGroupId(practice2.id, 0)
        self.assertEqual(call_group.id, result)
示例#8
0
def checkUserInCallGroup(request, practice_id, callgroup_id=None):
    userId = request.POST['userId']
    user = User.objects.get(pk=userId)
    member = Provider.objects.filter(user=user)
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    group = CallGroup.objects.get(pk=callgroup_id)
    if userId and callgroup_id:
        m = CallGroupMember.objects.filter(call_group=group, member=member)
        if len(m) > 0:
            return HttpResponse(json.dumps('ok'))
        else:
            return HttpResponse(json.dumps('err'))
示例#9
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)
示例#10
0
def saveViewInfo(request, practice_id, callgroup_id=None):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)
	if request.method == 'POST':
		view = request.POST['view']
		if checkSchedulerView(view):
			request.session[SessionHelper.SCHEDULE_LASTVIEW] = view
			response = {'view': view}
	else:
		response = {'view': ''}
	return HttpResponse(content=json.dumps(response), mimetype='application/json')
示例#11
0
def checkUserInCallGroup(request, practice_id, callgroup_id=None):
	userId = request.POST['userId']
	user = User.objects.get(pk=userId)
	member = Provider.objects.filter(user=user)
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	group = CallGroup.objects.get(pk=callgroup_id)
	if userId and callgroup_id:
		m = CallGroupMember.objects.filter(call_group=group, member=member)
		if len(m) > 0:
			return HttpResponse(json.dumps('ok'))
		else:
			return HttpResponse(json.dumps('err'))
示例#12
0
def addPrvoderIn(request, practice_id, callgroup_id):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	to_user = request.POST['to_user']
	to_user = Provider.objects.get(id=to_user)
	call_group = CallGroup.objects.get(id=callgroup_id)
	try:
		CallGroupMember(call_group=call_group,
			member=to_user, alt_provider=1).save()
		msg = 'Congratulations! We have added this member to call group. You can:'
		return HttpResponse(json.dumps({'err': msg}))
	except Exception:
		return HttpResponse(json.dumps({'ok': 'There is an error, please refresh page.'}))
示例#13
0
def addPrvoderIn(request, practice_id, callgroup_id):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    to_user = request.POST['to_user']
    to_user = Provider.objects.get(id=to_user)
    call_group = CallGroup.objects.get(id=callgroup_id)
    try:
        CallGroupMember(call_group=call_group, member=to_user,
                        alt_provider=1).save()
        msg = 'Congratulations! We have added this member to call group. You can:'
        return HttpResponse(json.dumps({'err': msg}))
    except Exception:
        return HttpResponse(
            json.dumps({'ok': 'There is an error, please refresh page.'}))
示例#14
0
def getViewInfo(request, practice_id, callgroup_id=None):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	if (not canAccessMultiCallGroup(request.user, long(callgroup_id), practice_id)):
		return err403(request)
	if request.method == 'GET':
		try:
			view = request.session[SessionHelper.SCHEDULE_LASTVIEW]
			response = {'view': view}
		except KeyError: 
			response = {'view': ''}	
	else:
		response = {'view': ''}
	return HttpResponse(content=json.dumps(response), mimetype='application/json')
示例#15
0
	def test_checkMultiCallGroupId(self):
		#init practice and call group
		call_group = CallGroup(description='test', team='team')
		call_group.save()
		
		practice = PracticeLocation(practice_name='test',
								practice_longit='0.1',
								practice_lat='0.0',)
		practice.save()
		practice.call_groups.add(call_group)
		
		#pass a valid parameter
		result = checkMultiCallGroupId(practice.id, call_group.id)
		self.assertEqual(call_group.id, result)
		
		#practice not exist
#		result = checkMultiCallGroupId(117, 0)
#		self.assertRaises(PracticeLocation.DoesNotExist, result)
		
		#pass a invalid call group parameter
		result = checkMultiCallGroupId(practice.id, 0)
		self.assertEqual(call_group.id, result)
		
		#ther is a specialty
		practice2 = PracticeLocation(practice_name='test2',
								practice_longit='0.1',
								practice_lat='0.0',)
		practice2.save()
		
		specialty_name = 'Specialty A'
		specialty1 = Specialty()
		specialty1.name = specialty_name
		specialty1.practice_location = practice2
		specialty1.number_selection = 3
		specialty1.save()
		specialty1.call_groups.add(call_group)
		
		result = checkMultiCallGroupId(practice2.id, 0)
		self.assertEqual(call_group.id, result)
示例#16
0
def saveViewInfo(request, practice_id, callgroup_id=None):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)
    if request.method == 'POST':
        view = request.POST['view']
        if checkSchedulerView(view):
            request.session[SessionHelper.SCHEDULE_LASTVIEW] = view
            response = {'view': view}
    else:
        response = {'view': ''}
    return HttpResponse(content=json.dumps(response),
                        mimetype='application/json')
示例#17
0
def getViewInfo(request, practice_id, callgroup_id=None):
    callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
    if (not canAccessMultiCallGroup(request.user, long(callgroup_id),
                                    practice_id)):
        return err403(request)
    if request.method == 'GET':
        try:
            view = request.session[SessionHelper.SCHEDULE_LASTVIEW]
            response = {'view': view}
        except KeyError:
            response = {'view': ''}
    else:
        response = {'view': ''}
    return HttpResponse(content=json.dumps(response),
                        mimetype='application/json')
示例#18
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)
示例#19
0
def checkProviderInCallGroup(request, practice_id, callgroup_id):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	user = request.POST['id']
	members = CallGroupMember.objects.filter(call_group__id=callgroup_id, member=user)
	pendings = CallGroupMemberPending.objects.filter(call_group__id=callgroup_id, 
						practice__id=practice_id, to_user=user, accept_status=0)
	current_practice = request.session['MHL_Users']['OfficeStaff'].current_practice

	to_user = Provider.objects.get(id=user)
	providers = Provider.objects.filter(practices=current_practice)

	if members:
		return HttpResponse(json.dumps('member'))
	elif pendings:
		return HttpResponse(json.dumps('pending'))
	else:
		if to_user in providers:
			return HttpResponse(json.dumps('inpracitce'))
		else:
			return HttpResponse(json.dumps('ok'))
示例#20
0
def addProviderInGroup(request, practice_id, callgroup_id):
	callgroup_id = checkMultiCallGroupId(practice_id, callgroup_id)
	from_user = request.session['MHL_Users']['MHLUser']
	to_user = request.POST['to_user']
	to_user = Provider.objects.get(id=to_user)
	call_group = CallGroup.objects.get(id=callgroup_id)
	practice = PracticeLocation.objects.get(id=practice_id)
	current_practice = request.session['MHL_Users']['OfficeStaff'].current_practice

	if to_user.current_practice and to_user.current_practice.id == current_practice.id:
		msg = 'Congratulations! We have added this member to call group. You can:'
	else:
		msg = '''This user is not in your practice now. We have sent an invitation to 
		him/her for confirm to join this call group.
		(He/She will not join your practice by accept this invitation.)'''

	try:
		members = CallGroupMemberPending(from_user=from_user, 
				to_user=to_user, call_group=call_group, practice=practice, 
					created_time=datetime.datetime.now())
		members.save()
		return HttpResponse(json.dumps({'err': msg}))
	except Exception:
		return HttpResponse(json.dumps({'ok': 'There is an error, please refresh page.'}))
示例#21
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,
        })
示例#22
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,
        })
示例#23
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,
        })
示例#24
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')
示例#25
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, })
示例#26
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, })
示例#27
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')
示例#28
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, })