Esempio n. 1
0
    def handle(self, *args, **options):
            Event = collection.Node.find({"_type":"GSystemType","name":{'$in':["Classroom Session","Exam"]}})

            marks_enter = collection.Node.find({"member_of":{'$in':[ObjectId(Event[0]._id),ObjectId(Event[1]._id)]},"attribute_set.marks_entered":True})
            Mis_admin = collection.Node.one({"_type":"Group","name":"MIS_admin"})
            Mis_admin_name=""
            if  Mis_admin:
                Mis_admin_list = Mis_admin.group_admin
                Mis_admin_list.append(Mis_admin.created_by)
                user_obj = User.objects.get(id=Mis_admin.created_by)
                Mis_admin_name = user_obj.username

            for i in marks_enter:
              to_user_list = []
              event_status = collection.Node.one({"_type":"AttributeType","name":"event_status"})
              create_gattribute(ObjectId(i._id),event_status,unicode('Incomplete'))
              node = collection.Node.one({"_id":{'$in':i.group_set}})
              for j in node.group_admin:
                 user_obj = User.objects.get(id = j)
                 if user_obj not in to_user_list:
                   to_user_list.append(user_obj)
                   render_label = render_to_string(
                          "notification/label.html",
                          {
                              "sender": Mis_admin_name,
                              "activity": "Marks not entered",
                              "conjunction": "-"
                          })
                 notification.create_notice_type(render_label," Marks is not entered for Event" + i.name +"\n Please enter marks soon"   , "notification")
                 notification.send(to_user_list, render_label, {"from_user": Mis_admin_name})
Esempio n. 2
0
    def handle(self, *args, **options):
        Event = collection.Node.find({
            "_type": "GSystemType",
            "name": {
                '$in': ["Classroom Session", "Exam"]
            }
        })

        marks_enter = collection.Node.find({
            "member_of": {
                '$in': [ObjectId(Event[0]._id),
                        ObjectId(Event[1]._id)]
            },
            "attribute_set.marks_entered": True
        })
        Mis_admin = collection.Node.one({
            "_type": "Group",
            "name": "MIS_admin"
        })
        Mis_admin_name = ""
        if Mis_admin:
            Mis_admin_list = Mis_admin.group_admin
            Mis_admin_list.append(Mis_admin.created_by)
            user_obj = User.objects.get(id=Mis_admin.created_by)
            Mis_admin_name = user_obj.username

        for i in marks_enter:
            to_user_list = []
            event_status = collection.Node.one({
                "_type": "AttributeType",
                "name": "event_status"
            })
            create_gattribute(ObjectId(i._id), event_status,
                              unicode('Incomplete'))
            node = collection.Node.one({"_id": {'$in': i.group_set}})
            for j in node.group_admin:
                user_obj = User.objects.get(id=j)
                if user_obj not in to_user_list:
                    to_user_list.append(user_obj)
                    render_label = render_to_string(
                        "notification/label.html", {
                            "sender": Mis_admin_name,
                            "activity": "Marks not entered",
                            "conjunction": "-"
                        })
                notification.create_notice_type(
                    render_label, " Marks is not entered for Event" + i.name +
                    "\n Please enter marks soon", "notification")
                notification.send(to_user_list, render_label,
                                  {"from_user": Mis_admin_name})
Esempio n. 3
0
def unit_order_list(request, group_id, node_id):
    response_dict = {"success": False}
    unit_id_list = request.POST.get('unit_list', [])
    print "untlst:", unit_id_list
    try:
        items_sort_list_gattr_node = triple_collection.one({
            '_type':
            'GAttribute',
            'subject':
            ObjectId(node_id),
            'attribute_type':
            at_items_sort_list._id,
            'status':
            u'PUBLISHED'
        })
        if items_sort_list_gattr_node:
            ga_node = delete_gattribute(node_id=items_sort_list_gattr_node._id,
                                        deletion_type=0)

        if unit_id_list:
            unit_id_list = json.loads(unit_id_list)
            unit_obj_list = map(
                lambda each_id: Node.get_node_by_id(ObjectId(each_id)),
                unit_id_list)
            ga_node = create_gattribute(ObjectId(node_id), 'items_sort_list',
                                        unit_obj_list)
            response_dict["success"] = True

    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Esempio n. 4
0
def user_profile(request, group_id):
    from django.contrib.auth.models import User

    auth_node = get_group_name_id(group_id, get_obj=True)

    user_dict = {}
    user_details = User.objects.get(id=request.user.id)
    user_dict['fname'] = user_details.first_name
    user_dict['lname'] = user_details.last_name

    if request.method == "POST":
        user = User.objects.get(id=request.user.id)
        user_data = request.POST.getlist('forminputs[]', '')
        user_select_data = request.POST.getlist('formselects[]', '')
        apps_to_set = request.POST.getlist('selected_apps_list[]', [])
        apps_to_set = [ObjectId(app_id) for app_id in apps_to_set if app_id]

        apps_list = []
        apps_list_append = apps_list.append
        for each in apps_to_set:
            apps_list_append(node_collection.find_one({"_id": each}))

        at_apps_list = node_collection.one({
            '_type': 'AttributeType',
            'name': 'apps_list'
        })
        ga_node = create_gattribute(auth_node._id, at_apps_list, apps_list)

        for i in user_data:
            a = ast.literal_eval(i)
            if a.get('first_name', None) != None:
                user.first_name = a['first_name']
                user_dict['fname'] = user.first_name
            if a.get('last_name', None) != None:
                user.last_name = a['last_name']
                user_dict['lname'] = user.last_name
        user.save()
        for i in user_select_data:
            a = ast.literal_eval(i)
            if a.get('language_proficiency', None) != None:
                auth_node['language_proficiency'] = []
                for k in a.get('language_proficiency', ''):
                    language = get_language_tuple(k)
                    auth_node['language_proficiency'].append(language)
            if a.get('subject_proficiency', None) != None:
                auth_node['subject_proficiency'] = list(
                    a.get('subject_proficiency', ''))
        auth_node.save()
        user_dict['node'] = auth_node
        user_dict['success'] = True
        return HttpResponse(json.dumps(user_dict, cls=NodeJSONEncoder))
    else:
        user_dict['node'] = auth_node
        return render_to_response(
            "ndf/user_profile_form.html", {
                'group_id': group_id,
                'node': auth_node,
                'user': json.dumps(user_dict, cls=NodeJSONEncoder)
            },
            context_instance=RequestContext(request))
Esempio n. 5
0
    def handle(self, *args, **options):
        
        api = ox.api.API("http://wetube.gnowledge.org/api")

        countVideo = api.find({"query":{"operator":"&","conditions":[{"operator":"==","key":"project","value":"NROER"}]}})
        totalVideoNo = countVideo['data']['items']
        
        allVideo = api.find({"keys":["id","title","director","id","posterRatio","year","user"],"query":{"conditions":[{"oper\
    ator":"==","key":"project","value":"NROER"}],"operator":"&"},"range":[0,totalVideoNo],"sort":[{"operator":"+","key":"title"}]})

        allVideosData = allVideo['data']['items']
        
        pandora_video_st = collection.Node.one({'$and':[{'name':'Pandora_video'},{'_type':'GSystemType'}]})
        file_gst = collection.Node.one({'$and':[{'name':'File'},{'_type':'GSystemType'}]})
        source_id_AT = collection.Node.one({'$and':[{'name':'source_id'},{'_type':'AttributeType'}]})
        grp = collection.Node.one({'_type': 'Group', 'name':'home' })
        auth_id = User.objects.get(username='******').pk

        if auth_id:
            for each in allVideosData:
                
                pandora_video = collection.Node.one({'_type': 'File', 'member_of': {'$in': [pandora_video_st._id]}, 'name': unicode(each['title']).lower(), 'created_by': auth_id })
                
                if pandora_video is None:
                    
                    gs = collection.File()
                    gs.name = unicode(each['title']).lower()
                    gs.mime_type = "video"
                    gs.access_policy = u"PRIVATE"
                    gs.member_of = [file_gst._id, pandora_video_st._id]
                    gs.created_by = auth_id
                    gs.modified_by = auth_id
                    gs.group_set.append(grp._id)
                    gs.contributors.append(auth_id)
                    gs.save()

                    gs.reload()

                    create_gattribute(gs._id, source_id_AT, each['id'])
                    print "\n Document created for pandora video '",gs.name,"' sucessfully !! \n"

                else:
                    print "\n Document Pandora Video '",pandora_video.name,"' already created !! \n"

        else:
            print "\n Sorry .. Need to create user as 'nroer_team' for running this script \n"
Esempio n. 6
0
def user_profile(request, group_id):
    from django.contrib.auth.models import User

    auth_node = get_group_name_id(group_id, get_obj=True)

    user_dict={}
    user_details = User.objects.get(id=request.user.id)
    user_dict['fname'] = user_details.first_name
    user_dict['lname']  = user_details.last_name

    if request.method == "POST":
        user = User.objects.get(id=request.user.id)
        user_data = request.POST.getlist('forminputs[]','')
        user_select_data = request.POST.getlist('formselects[]','')
        apps_to_set = request.POST.getlist('selected_apps_list[]', [])
        apps_to_set = [ObjectId(app_id) for app_id in apps_to_set if app_id ]

        apps_list = []
        apps_list_append = apps_list.append
        for each in apps_to_set:
            apps_list_append(
                node_collection.find_one({
                    "_id": each
                })
            )

        at_apps_list = node_collection.one({'_type': 'AttributeType', 'name': 'apps_list'})
        ga_node = create_gattribute(auth_node._id, at_apps_list, apps_list)

        for i in user_data:
			a=ast.literal_eval(i)
			if  a.get('first_name',None) != None:
			  	user.first_name = a['first_name']
			  	user_dict['fname'] = user.first_name
			if a.get('last_name',None) != None:
				user.last_name = a['last_name']
			  	user_dict['lname'] = user.last_name
        user.save()
        for i in user_select_data:
			a=ast.literal_eval(i)
			if  a.get('language_proficiency',None) != None:
				auth_node['language_proficiency'] = []
				for k in a.get('language_proficiency',''):
					language = get_language_tuple(k)
					auth_node['language_proficiency'].append(language)
			if  a.get('subject_proficiency',None) != None:
				auth_node['subject_proficiency'] =  list(a.get('subject_proficiency',''))
        auth_node.save()
        user_dict['node'] = auth_node
        user_dict['success'] = True
        return HttpResponse(json.dumps(user_dict,cls=NodeJSONEncoder))
    else:
		user_dict['node'] = auth_node
		return render_to_response(  "ndf/user_profile_form.html",
				{'group_id':group_id,'node':auth_node,'user':json.dumps(user_dict,cls=NodeJSONEncoder)},
				context_instance=RequestContext(request)
		)
Esempio n. 7
0
def save_profile(request, user_id):
    from django.contrib.auth.models import User

    user_dict = {'success': True, 'message': 'Profile updated successfully.'}
    request_variables = {}
    auth_attr = None
    auth_obj = Author.get_author_by_userid(int(user_id))
    try:
        auth_id = auth_obj._id
        if request.method == "POST":

            first_name = request.POST.get('first_name', None)
            last_name = request.POST.get('last_name', None)
            educationallevel = request.POST.get('educationallevel', None)
            organization_name = request.POST.get('organization_name', None)
            enrollment_code = request.POST.get('enrollment_code', None)
            request_variables.update({
                'first_name': first_name,
                'last_name': last_name,
                'educationallevel': educationallevel,
                'organization_name': organization_name,
                'enrollment_code': enrollment_code
            })

            for at_name, ga_val in request_variables.items():
                if ga_val:
                    create_gattribute(auth_id, at_name, ga_val)

            auth_attr = request_variables

    except AttributeError as no_auth:
        # user_dict.update({'success': False, 'message': 'Something went wrong. Please try again later.'})
        pass
    except Exception as no_auth:
        # user_dict.update({'success': False, 'message': 'Something went wrong. Please try again later.'})
        pass
    # return HttpResponse(json.dumps(user_dict))

    return render_to_response(
        'ndf/widget_user_profile.html',
        {
            'auth_attr': auth_attr,  #'user_dict': json.dumps(user_dict)
        },
        context_instance=RequestContext(request))
Esempio n. 8
0
	def updater(self,all_events):
		'''
		This function will iterate over all events and will mark the "Scheduled" meets whose end_time is 
		over as "Completed" in event_status of event object's Attribute Set
		'''

		now = datetime.datetime.now()
		e_status = node_collection.one({'_type' : 'AttributeType' , 'name': 'event_status'})

		for event in all_events:
			for i in event.attribute_set:
				if unicode('end_time') in i.keys():
					end_time = i['end_time']
				elif unicode('event_status') in i.keys():
					status = i['event_status']	

			if status == unicode("Scheduled"):
				if now > end_time:
					create_gattribute(event._id , e_status , unicode("Completed"))
Esempio n. 9
0
def user_preferences(request, group_id, auth_id):
    try:
        grp = node_collection.one({'_id': ObjectId(auth_id)})
        if request.method == "POST":
            lst = []
            pref_to_set = request.POST['pref_to_set']
            pref_list = pref_to_set.split(",")
            if pref_list:
                for each in pref_list:
                    if each:
                        obj = node_collection.one({'_id': ObjectId(each)})
                        lst.append(obj)
                if lst:
                    ga_node = create_gattribute(grp._id, at_user_pref, lst)
                # gattribute = triple_collection.one({'$and':[{'_type':'GAttribute'},{'attribute_type':at_user_pref._id},{'subject':grp._id}]})
                # if gattribute:
                #     gattribute.delete()
                # if lst:
                #     create_attribute=collection.GAttribute()
                #     create_attribute.attribute_type=at_user_pref
                #     create_attribute.subject=grp._id
                #     create_attribute.object_value=lst
                #     create_attribute.save()
            return HttpResponse("Success")

        else:
            list_at_pref = []
            user_id = request.user.id
            if not at_user_pref:
                return HttpResponse("Failure")
            poss_attrs = grp.get_possible_attributes(at_user_pref._id)
            if poss_attrs:
                list_at_pref = poss_attrs['user_preference_off'][
                    'object_value']
            all_user_groups = []
            for each in get_all_user_groups():
                all_user_groups.append(each.name)
            st = node_collection.find({
                '$and': [{
                    '_type': 'Group'
                }, {
                    'author_set': {
                        '$in': [user_id]
                    }
                }, {
                    'name': {
                        '$nin': all_user_groups
                    }
                }]
            })
            data_list = set_drawer_widget(st, list_at_pref)
            return HttpResponse(json.dumps(data_list))
    except Exception as e:
        print "Exception in userpreference view " + str(e)
        return HttpResponse("Failure")
Esempio n. 10
0
def save_profile(request, user_id):
    from django.contrib.auth.models import User

    user_dict = {'success': True, 'message': 'Profile updated successfully.'}
    request_variables = {}
    auth_attr = None
    auth_obj = Author.get_author_by_userid(int(user_id))
    try:
        auth_id = auth_obj._id
        if request.method == "POST":

            first_name = request.POST.get('first_name', None)
            last_name = request.POST.get('last_name', None)
            educationallevel = request.POST.get('educationallevel', None)
            organization_name = request.POST.get('organization_name', None)
            enrollment_code = request.POST.get('enrollment_code', None)
            request_variables.update({'first_name': first_name, 'last_name': last_name,
                'educationallevel': educationallevel, 'organization_name': organization_name,
                'enrollment_code': enrollment_code})

            for at_name, ga_val in request_variables.items():
                if ga_val:
                    create_gattribute(auth_id, at_name, ga_val)

            auth_attr = request_variables

    except AttributeError as no_auth:
        # user_dict.update({'success': False, 'message': 'Something went wrong. Please try again later.'})
        pass
    except Exception as no_auth:
        # user_dict.update({'success': False, 'message': 'Something went wrong. Please try again later.'})
        pass
    # return HttpResponse(json.dumps(user_dict))


    return render_to_response('ndf/widget_user_profile.html',
                {
                    'auth_attr': auth_attr, #'user_dict': json.dumps(user_dict)
                },
                context_instance=RequestContext(request)
        )
Esempio n. 11
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True
    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Esempio n. 12
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True
    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Esempio n. 13
0
def user_preferences(request, group_id, auth_id):
    try:
        grp = node_collection.one({'_id': ObjectId(auth_id)})
        if request.method == "POST":
            lst = []
            pref_to_set = request.POST['pref_to_set']
            pref_list=pref_to_set.split(",")
            if pref_list:
                for each in pref_list:
                    if each:
                        obj = node_collection.one({'_id':ObjectId(each)})
                        lst.append(obj);
                if lst:
                    ga_node = create_gattribute(grp._id, at_user_pref, lst)
                # gattribute = triple_collection.one({'$and':[{'_type':'GAttribute'},{'attribute_type':at_user_pref._id},{'subject':grp._id}]})
                # if gattribute:
                #     gattribute.delete()
                # if lst:
                #     create_attribute=collection.GAttribute()
                #     create_attribute.attribute_type=at_user_pref
                #     create_attribute.subject=grp._id
                #     create_attribute.object_value=lst
                #     create_attribute.save()
            return HttpResponse("Success")


        else:
            list_at_pref=[]
            user_id=request.user.id
            if not at_user_pref:
                return HttpResponse("Failure")
            poss_attrs=grp.get_possible_attributes(at_user_pref._id)
            if poss_attrs:
                list_at_pref=poss_attrs['user_preference_off']['object_value']
            all_user_groups=[]
            for each in get_all_user_groups():
                all_user_groups.append(each.name)
            st = node_collection.find({'$and':[{'_type':'Group'},{'author_set':{'$in':[user_id]}},{'name':{'$nin':all_user_groups}}]})
            data_list=set_drawer_widget(st,list_at_pref)
            return HttpResponse(json.dumps(data_list))
    except Exception as e:
        print "Exception in userpreference view "+str(e)
        return HttpResponse("Failure")
Esempio n. 14
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        items_sort_list_gattr_node = triple_collection.one({'_type': 'GAttribute', 'subject': group_id, 
            'attribute_type': at_items_sort_list._id, 'status': u'PUBLISHED'})
        if items_sort_list_gattr_node:
            ga_node = delete_gattribute(node_id=items_sort_list_gattr_node._id, deletion_type=0)

        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True

    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
def create_thread_obj(node_id):
    '''
    Creates thread object.
        RT : has_thread
        AT : release_response, thread_interaction_type
    '''
    try:
        node_obj = node_collection.one({'_id': ObjectId(node_id)})
        release_response_val = True
        interaction_type_val = unicode('Comment')
        thread_obj = None
        thread_obj = node_collection.one({"_type": "GSystem", "member_of": ObjectId(twist_gst._id),"relation_set.thread_of": ObjectId(node_obj._id)})

        if thread_obj == None:
            # print "\n\n Creating new thread node"
            thread_obj = node_collection.collection.GSystem()
            thread_obj.name = u"Thread_of_" + unicode(node_obj.name)
            thread_obj.status = u"PUBLISHED"
            thread_obj.created_by = int(nroer_team_id)
            thread_obj.modified_by = int(nroer_team_id)
            thread_obj.contributors.append(int(nroer_team_id))
            thread_obj.member_of.append(ObjectId(twist_gst._id))
            thread_obj.group_set.append(home_group._id)
            thread_obj.save()
            # creating GRelation
            gr = create_grelation(node_obj._id, has_thread_rt, thread_obj._id)
            create_gattribute(thread_obj._id, rel_resp_at, release_response_val)
            create_gattribute(thread_obj._id, thr_inter_type_at, interaction_type_val)
            create_gattribute(node_obj._id, discussion_enable_at, True)
            thread_obj.reload()
            node_obj.reload()
            # print "\n\n thread_obj", thread_obj.attribute_set, "\n---\n"
            info_message = "\n- Successfully created thread obj - " + thread_obj._id.__str__() +" for - " + node_obj._id.__str__()
            log_print(info_message)

    except Exception as e:
        info_message = "\n- Error occurred while creating thread obj for - " + node_obj._id.__str__() +" - " + str(e)
        log_print(info_message)
Esempio n. 16
0
def create_thread_obj(node_id):
    '''
    Creates thread object.
        RT : has_thread
        AT : release_response, thread_interaction_type
    '''
    try:
        node_obj = node_collection.one({'_id': ObjectId(node_id)})
        release_response_val = True
        interaction_type_val = unicode('Comment')
        thread_obj = None
        thread_obj = node_collection.one({"_type": "GSystem", "member_of": ObjectId(twist_gst._id),"relation_set.thread_of": ObjectId(node_obj._id)})

        if thread_obj == None:
            # print "\n\n Creating new thread node"
            thread_obj = node_collection.collection.GSystem()
            thread_obj.name = u"Thread_of_" + unicode(node_obj.name)
            thread_obj.status = u"PUBLISHED"
            thread_obj.created_by = int(nroer_team_id)
            thread_obj.modified_by = int(nroer_team_id)
            thread_obj.contributors.append(int(nroer_team_id))
            thread_obj.member_of.append(ObjectId(twist_gst._id))
            thread_obj.group_set.append(home_group._id)
            thread_obj.save()
            # creating GRelation
            gr = create_grelation(node_obj._id, has_thread_rt, thread_obj._id)
            create_gattribute(thread_obj._id, rel_resp_at, release_response_val)
            create_gattribute(thread_obj._id, thr_inter_type_at, interaction_type_val)
            create_gattribute(node_obj._id, discussion_enable_at, True)
            thread_obj.reload()
            node_obj.reload()
            # print "\n\n thread_obj", thread_obj.attribute_set, "\n---\n"
            info_message = "\n- Successfully created thread obj - " + thread_obj._id.__str__() +" for - " + node_obj._id.__str__()
            log_print(info_message)

    except Exception as e:
        info_message = "\n- Error occurred while creating thread obj for - " + node_obj._id.__str__() +" - " + str(e)
        log_print(info_message)
def create_theme_topic_hierarchy(row):
    """

    Args:
        row (list): each row of CSV
        e.g: ["CR/XCR", "featured", "alignment", "content_org", "Theme name", "theme item name", .., .., .... , "topic"]

    Returns:
        TYPE: Description
    """

    # print row
    language = row[0]  # language field will get populated in this case.
    curricular = row[1]  # CR or XCR
    featured = int(row[2])  # 0 or 1
    alignment = row[3]  # like NCF
    content_org = row[4]
    theme_name = row[5]  # theme-name like National Curriculum
    # topic_name = row[-1:]

    # --- Theme processing ---

    # fetching a theme node
    theme_node = node_collection.one({
        'name': {
            '$regex': "^" + unicode(theme_name) + "$",
            '$options': 'i'
        },
        'group_set': {
            '$in': [home_group_id]
        },
        'member_of': theme_gst._id
    })

    # creating a new theme node:
    if not theme_node:
        theme_node = create_object(name=theme_name,
                                   member_of_id=theme_gst._id,
                                   featured=bool(featured),
                                   language=language)

        info_message = "- Created New Object : " + str(theme_node.name) + "\n"
        print info_message
        log_list.append(str(info_message))

    # casting curricular field to bool:
    if curricular == "CR":
        curricular = True
    elif curricular == "XCR":
        curricular = False
    else:  # needs to be confirm
        curricular = False

    # if theme_node already has curricular as attribute, it will update it's value
    # otherwise it will create a new attribute:
    ga_node = create_gattribute(theme_node._id, curricular_at, curricular)

    info_message = "- Created ga_node : " + str(ga_node.name) + "\n"
    print info_message
    log_list.append(str(info_message))

    ga_node = create_gattribute(theme_node._id, alignment_at,
                                unicode(alignment))

    info_message = "- Created ga_node : " + str(ga_node.name) + "\n"
    print info_message
    log_list.append(str(info_message))

    # --- END of Theme processing ---

    # --- theme-item and topic processing ---
    # from 5th item or 4rd index of row there will be start of theme-item and topic(at last)
    theme_item_topic_list = row[6:]

    # do not entertain any blank values here:
    theme_item_topic_list = [i for i in theme_item_topic_list if i]
    # print theme_item_topic_list

    topic_name = theme_item_topic_list.pop(
    )  # Only 1 topic name, last item of row/list
    theme_item_list = theme_item_topic_list  # list of only theme-item name's, after pop

    # to initiate with parent node:
    parent_node = theme_node

    # theme-item procesing ---
    for each_theme_item in theme_item_list:
        # print each_theme_item

        # fetching a theme-item node
        theme_item_node = node_collection.one({
            'name': {
                '$regex': "^" + unicode(each_theme_item) + "$",
                '$options': 'i'
            },
            'group_set': {
                '$in': [home_group_id]
            },
            'member_of': {
                '$in': [theme_item_gst._id]
            },
            'prior_node': {
                '$in': [parent_node._id]
            }
        })

        if not theme_item_node:

            theme_item_node = create_object(name=each_theme_item,
                                            member_of_id=theme_item_gst._id,
                                            prior_node_id=parent_node._id,
                                            language=language)

            info_message = "\n- Created theme-item : " + str(
                theme_item_node.name) + "\n"
            print info_message
            log_list.append(str(info_message))

        else:
            info_message = "\n!! Theme Item : " + str(
                theme_item_node.name) + " already exists!\n"
            print info_message
            log_list.append(str(info_message))

        # cheking for current theme-item's _id in collection_set of parent_node
        if not theme_item_node._id in parent_node.collection_set:
            add_to_collection_set(node_object=parent_node,
                                  id_to_be_added=theme_item_node._id)

        parent_node = theme_item_node

    # END of theme-item processing ---

    # topic processing ---

    # fetching a theme-item node
    topic_node = node_collection.one({
        'name': {
            '$regex': "^" + unicode(topic_name) + "$",
            '$options': 'i'
        },
        'group_set': {
            '$in': [home_group_id]
        },
        'member_of': {
            '$in': [topic_gst._id]
        },
        'prior_node': {
            '$in': [parent_node._id]
        }
    })

    if not topic_node:
        topic_node = create_object(name=topic_name, \
                                 member_of_id=topic_gst._id, \
                                 prior_node_id=parent_node._id, \
                                 content_org=content_org,\
                                 language=language)

        info_message = "\n--- Created topic : " + str(topic_node.name) + "\n"
        print info_message
        log_list.append(str(info_message))

    else:

        info_message = "\n!! Topic : " + str(
            topic_node.name) + " already exists!\n"
        print info_message
        log_list.append(str(info_message))

    # cheking for current theme-item's _id in collection_set of parent_node
    if not topic_node._id in parent_node.collection_set:
        add_to_collection_set(node_object=parent_node,
                              id_to_be_added=topic_node._id)
Esempio n. 18
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    print "inside unit_create_edit", parent_group_name, parent_group_id
    print "request path", request.method
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        print "group names :", all_groups_names
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }

        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,
                                    tags=tags,
                                    author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if resource_name:
            unit_node['project_config'].update(
                {"resource_name": resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"resource_name": "Resources"})
        else:
            unit_node['project_config'].update(
                {"resource_name": "Resource Name"})

        if blog_name:
            unit_node['project_config'].update({"blog_name": blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"blog_name": "e-Notes"})
        else:
            unit_node['project_config'].update({"blog_name": "blog Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_content', kwargs={'group_id': unit_node._id}))
Esempio n. 19
0
def create_task_at_rt(request, rt_list, at_list, task_node, assign, group_name,
                      group_id):
    file_id = (request.POST.get("files"))
    file_name = (request.POST.get("files_name"))

    for each in rt_list:
        rel_type_node = node_collection.one({
            '_type': "RelationType",
            'name': each
        })
        field_value_list = None

        if rel_type_node["object_cardinality"] > 1:
            field_value_list = request.POST.get(rel_type_node["name"], "")
            if "[" in field_value_list and "]" in field_value_list:
                field_value_list = json.loads(field_value_list)
            else:
                field_value_list = request.POST.getlist(rel_type_node["name"])

        else:
            field_value_list = request.POST.getlist(rel_type_node["name"])

        # rel_type_node_type = "GRelation"
        for i, field_value in enumerate(field_value_list):
            field_value = parse_template_data(rel_type_node.object_type,
                                              field_value,
                                              field_instance=rel_type_node)
            field_value_list[i] = field_value

        task_gs_triple_instance = create_grelation(
            task_node._id,
            node_collection.collection.RelationType(rel_type_node),
            field_value_list)

    for each in at_list:
        field_value = []
        if request.POST.get(each, ""):
            attributetype_key = node_collection.find_one({
                "_type": 'AttributeType',
                'name': each
            })
            subject = task_node._id
            object_value = ""
            if each == 'Assignee':
                if type(assign) == list:
                    object_value = assign
                else:
                    field_value.append(assign)
                    object_value = field_value

            else:
                field_value = request.POST.get(each, "")

                date_format_string = ""
                if each in ["start_time", "end_time"]:
                    date_format_string = "%d/%m/%Y"

                field_value = parse_template_data(
                    eval(attributetype_key["data_type"]),
                    field_value,
                    date_format_string=date_format_string)
                # newattribute.object_value = field_value
                object_value = field_value

            # newattribute.save()
            ga_node = create_gattribute(subject, attributetype_key,
                                        object_value)

    if request.FILES.getlist('UploadTask'):
        attributetype_key = node_collection.find_one({
            "_type": 'AttributeType',
            'name': 'Upload_Task'
        })
        ga_node = create_gattribute(task_node._id, attributetype_key, file_id)

    assignee_list = []
    assignee_list_id = []
    if type(assign) == list:
        assignee_list_id = assign
    else:
        assignee_list_id.append(assign)
    user_to_be_notified = []
    if assignee_list_id:
        for eachuser in assignee_list_id:
            if eachuser:
                bx = User.objects.get(id=int(eachuser))
                assignee_list.append(bx.username)
                user_to_be_notified.append(bx)
        for eachuser in user_to_be_notified:
            activ = "Task reported"
            msg = "Task '" + task_node.name + \
              "' has been reported by " + request.user.username + \
              "\n     - Status: " + request.POST.get('Status', '') + \
              "\n     - Assignee: " + ", ".join(assignee_list) + \
              "\n     - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id)

            set_notif_val(request, group_id, msg, activ, eachuser)
Esempio n. 20
0
def node_create_edit(request,
                    group_id=None,
                    member_of=None,
                    detail_url_name=None,
                    node_type='GSystem',
                    node_id=None):
    '''
    creation as well as edit of node
    '''
    # check for POST method to node update operation
    if request.method == "POST":

        # put validations
        if node_type not in node_collection.db.connection._registered_documents.keys():
            raise ValueError('Improper node_type passed')

        kwargs={}
        group_name, group_id = Group.get_group_name_id(group_id)
        member_of_name, member_of_id = GSystemType.get_gst_name_id(member_of)

        if node_id: # existing node object
            node_obj = Node.get_node_by_id(node_id)

        else: # create new
            kwargs={
                    'group_set': group_id,
                    'member_of': member_of_id
                    }
            node_obj = node_collection.collection[node_type]()

        language = get_language_tuple(request.POST.get('language', None))
        node_obj.fill_gstystem_values(request=request,
                                    language=language,
                                            **kwargs)
        node_obj.save(group_id=group_id)
        node_id = node_obj['_id']

        # Consider for Blog page creation
        if member_of_name == "Page":
            blog_page_gst_name, blog_page_gst_id = GSystemType.get_gst_name_id("Blog page")
            if blog_page_gst_id in node_obj.type_of:
                discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"})
                create_gattribute(node_obj._id, discussion_enable_at, True)
                return_status = create_thread_for_node(request,group_id, node_obj)

                active_user_ids_list = [request.user.id]
                if GSTUDIO_BUDDY_LOGIN:
                    active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.datetime.now())
                # removing redundancy of user ids:
                active_user_ids_list = dict.fromkeys(active_user_ids_list).keys()
                counter_objs_cur = Counter.get_counter_objs_cur(active_user_ids_list, group_id)
                for each_counter_obj in counter_objs_cur:
                    each_counter_obj['page']['blog']['created'] += 1
                    each_counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS
                    each_counter_obj.last_update = datetime.datetime.now()
                    each_counter_obj.save()

        post_req = request.POST
        attrs_to_create_update = [f for f in post_req.keys() if ('attribute' in f)]
        attrs_to_create_update = [a.split('_')[1] for a in attrs_to_create_update]

        for each_attr_name in attrs_to_create_update:
            each_attr_name_obj = Node.get_name_id_from_type(each_attr_name, 'AttributeType', get_obj=True)
            post_req_attr_key = 'attribute_'+each_attr_name
            post_method = 'getlist' if (each_attr_name_obj.data_type in [list, 'list']) else 'get'
            create_gattribute(node_id,
                            each_attr_name_obj,
                            object_value=getattr(post_req, post_method)(post_req_attr_key))


        return HttpResponseRedirect(reverse(detail_url_name, kwargs={'group_id': group_id, 'node_id': node_id}))
Esempio n. 21
0
def parse_data_create_gsystem(json_file_path, file_name):
    json_file_content = ""

    try:
        print "\n file_name == ",file_name

        with open(json_file_path) as json_file:
            json_file_content = json_file.read()

        json_documents_list = json.loads(json_file_content)

        # Process data in proper format
        node = node_collection.collection.GSystem()
        node_keys = node.keys()
        node_structure = node.structure

        json_documents_list_spaces = json_documents_list
        json_documents_list = []

        # Removes leading and trailing spaces from keys as well as values
        for json_document_spaces in json_documents_list_spaces:
            json_document = {}

            for key_spaces, value_spaces in json_document_spaces.iteritems():
                json_document[key_spaces.strip().lower()] = value_spaces.strip()

            json_documents_list.append(json_document)

    except Exception as e:
        error_message = "\n While parsing the file ("+json_file_path+") got following error...\n " + str(e)
        log_list.append(error_message)
        print error_message
        raise error_message


    for i, json_document in enumerate(json_documents_list):
        try:
    
            global node_repeated
            node_repeated = False
    
            info_message = "\n ============ #"+ str(i+1) +" : Start of "+gsystem_type_name+"'s GSystem ("+json_document['name']+") creation/updation ============\n"
            log_list.append(info_message)

            parsed_json_document = {}
            attribute_relation_list = []
            for key in json_document.iterkeys():
                # print "\n key ",key
                parsed_key = key.lower()
                parsed_key = parsed_key.replace(" ", "_")
                if parsed_key in node_keys:
                    if node_structure[parsed_key] == unicode:
                        parsed_json_document[parsed_key] = unicode(json_document[key])
                    elif node_structure[parsed_key] == datetime.datetime:
                        parsed_json_document[parsed_key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y")
                    else:
                        parsed_json_document[parsed_key] = json_document[key]
                else:
                    parsed_json_document[key] = json_document[key]
                    attribute_relation_list.append(key)
            print "\nparsed_json_document: ", parsed_json_document
            info_message = "\n Creating "+gsystem_type_name+" ("+parsed_json_document["name"]+")..."
            log_list.append(info_message)
            print "\n HERE == "
            node = create_edit_gsystem(gsystem_type_id, gsystem_type_name, parsed_json_document, user_id)
            #print "\n node created === ", node._id, " === ", node.name, node.altnames
            # print "attribute_relation_list == ",attribute_relation_list
            #print node
            if node:
                if not attribute_relation_list:
                    # Neither possible attribute fields, nor possible relations defined for this node
                    info_message = "\n "+gsystem_type_name+" ("+node.name+"): Neither possible attribute fields, nor possible relations defined for this node !\n"
                    log_list.append(info_message)
                    continue
                #print "bfr possible attrbs"
                gst_possible_attributes_dict = node.get_possible_attributes(gsystem_type_id)
                print "\n gsystem_type_id ===",gst_possible_attributes_dict
                relation_list = []
                json_document['name'] = node.name

                # Write code for setting atrributes
                for key in attribute_relation_list:
                    is_relation = True

                    for attr_key, attr_value in gst_possible_attributes_dict.iteritems():
                        #print "\n\n attr_key === ", attr_key
                        #print "\n\n altnames --  === ", attr_value['altnames']
                        if attr_value['altnames'] and key == attr_value['altnames'].lower() or key == attr_key.lower():
                            is_relation = False

                            if json_document[key]:
                                try:
                                    if attr_value['data_type'] == basestring:
                                        if u"\u2013" in json_document[key]:
                                            json_document[key] = json_document[key].replace(u"\u2013", "-")

                                    info_message = "\n For GAttribute parsing content | key: " + attr_key + " -- " + json_document[key]
                                    log_list.append(info_message)

                                    if attr_value['data_type'] == unicode:
                                        print unicode(json_document[key])
                                        json_document[key] = unicode(json_document[key])

                                    elif attr_value['data_type'] == bool: 
                                        if json_document[key].lower() == "yes":
                                            json_document[key] = True
                                        elif json_document[key].lower() == "no":
                                            json_document[key] = False
                                        else:
                                            json_document[key] = None

                                    elif attr_value['data_type'] == datetime.datetime:

                                        # Use small-case altnames
                                        if key in ["dob", "date of birth", "date of registration"]:
                                            if json_document[key]:
                                                json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y")
                                        else:
                                            if json_document[key]:
                                                json_document[key] = datetime.datetime.strptime(json_document[key], "%Y")

                                    elif attr_value['data_type'] in [int, float, long]:
                                        if not json_document[key]:
                                            json_document[key] = 0
                                        else:
                                            if attr_value['data_type'] == int:
                                                json_document[key] = int(json_document[key])
                                            elif attr_value['data_type'] == float:
                                                json_document[key] = float(json_document[key])
                                            else:
                                                json_document[key] = long(json_document[key])

                                    elif type(attr_value['data_type']) == IS:
                                        for op in attr_value['data_type']._operands:
                                            if op.lower() == json_document[key].lower():
                                                json_document[key] = op

                                    elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]):
                                        if "," not in json_document[key]:
                                            # Necessary to inform perform_eval_type() that handle this value as list
                                            json_document[key] = "\"" + json_document[key] + "\", "

                                        else:
                                            formatted_value = ""
                                            for v in json_document[key].split(","):
                                                formatted_value += "\""+v.strip(" ")+"\", "
                                            json_document[key] = formatted_value

                                        perform_eval_type(key, json_document, "GSystem")

                                    subject_id = node._id

                                    attribute_type_node = None
                                    if attr_key in attr_type_dict:
                                        attribute_type_node = attr_type_dict[attr_key]
                                    else:
                                        attribute_type_node = node_collection.one({
                                            '_type': "AttributeType",
                                            '$or': [{
                                                'name': {'$regex': "^" + attr_key + "$", '$options': 'i'}
                                            }, {
                                                'altnames': {'$regex': "^" + attr_key + "$", '$options': 'i'}
                                            }]
                                        })
                                        attr_type_dict[attr_key] = attribute_type_node

                                    object_value = json_document[key]

                                    ga_node = None

                                    info_message = "\n Creating GAttribute (" + node.name + " -- " + attribute_type_node.name + " -- " + str(json_document[key]) + ") ...\n"
                                    log_list.append(info_message)
                                    ga_node = create_gattribute(subject_id, attribute_type_node, object_value)
                                except Exception as e:
                                    error_message = "\n While creating GAttribute (" + attr_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) + "\n"
                                    log_list.append(error_message)
                                    print error_message # Keep it!

                                # To break outer for loop as key found
                                break

                            else:
                                error_message = "\n DataNotFound: No data found for field ("+attr_key+") while creating GSystem (" + gsystem_type_name + " -- " + node.name + ") !!!\n"
                                log_list.append(error_message)

                    if is_relation:
                        relation_list.append(key)

                if not relation_list:
                    # No possible relations defined for this node
                    info_message = "\n "+gsystem_type_name+" ("+node.name+"): No possible relations defined for this node !!!\n"
                    log_list.append(info_message)

                else:
                    gst_possible_relations_dict = node.get_possible_relations(gsystem_type_id)

                    # Write code for setting relations
                    for key in relation_list:
                        is_relation = True

                        for rel_key, rel_value in gst_possible_relations_dict.iteritems():
                            if key == rel_value['altnames'].lower() or key == rel_key.lower():
                                is_relation = False

                                if json_document[key]:
                                    # Here semi-colon(';') is used instead of comma(',')
                                    # Beacuse one of the value may contain comma(',') which causes problem in finding required value in database
                                    try:
                                        if ";" not in json_document[key]:
                                            # Necessary to inform perform_eval_type() that handle this value as list
                                            json_document[key] = "\""+json_document[key]+"\", "

                                        else:
                                            formatted_value = ""
                                            for v in json_document[key].split(";"):
                                                formatted_value += "\""+v.strip(" ")+"\", "
                                            json_document[key] = formatted_value

                                        info_message = "\n For GRelation parsing content | key: " + rel_key + " -- " + json_document[key]
                                        log_list.append(info_message)

                                        perform_eval_type(key, json_document, "GSystem", "GSystem")

                                        # for right_subject_id in json_document[key]:
                                        subject_id = node._id

                                        # Here we are appending list of ObjectIds of GSystemType's type_of field 
                                        # along with the ObjectId of GSystemType's itself (whose GSystem is getting created)
                                        # This is because some of the RelationType's are holding Base class's ObjectId
                                        # and not that of the Derived one's
                                        # Delibrately keeping GSystemType's ObjectId first in the list
                                        # And hence, used $in operator in the query!
                                        rel_subject_type = []
                                        rel_subject_type.append(gsystem_type_id)
                                        if gsystem_type_node.type_of:
                                            rel_subject_type.extend(gsystem_type_node.type_of)

                                        relation_type_node = None
                                        if rel_key in rel_type_dict:
                                            relation_type_node = rel_type_dict[rel_key]
                                        else:
                                            relation_type_node = node_collection.one({
                                                '_type': "RelationType",
                                                '$or': [{
                                                    'name': {'$regex': "^" + rel_key + "$", '$options': 'i'}
                                                }, {
                                                    'altnames': {'$regex': "^" + rel_key + "$", '$options': 'i'}
                                                }],
                                                'subject_type': {'$in': rel_subject_type}
                                            })
                                            rel_type_dict[rel_key] = relation_type_node

                                        info_message = "\n Creating GRelation ("+node.name+" -- "+rel_key+" -- "+str(json_document[key])+") ...\n"
                                        log_list.append(info_message)
                                        gr_node = create_grelation(subject_id, relation_type_node, json_document_spaces[key])
                                    except Exception as e:
                                        error_message = "\n While creating GRelation (" + rel_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n" + str(e) + "\n"
                                        log_list.append(error_message)
                                        pass

                                    if college_gst._id in relation_type_node.object_type:
                                        # Fetch college node's group id
                                        # Append it to node's group_set
                                        node_group_set = node.group_set
                                        is_group_set_changed = False

                                        # Iterate through each college
                                        # Find it's corresponding group's ObjectId
                                        # Append it to node's group_set
                                        for each in json_document[key]:
                                            each = ObjectId(each)
                                            each_str = str(each)
                                            
                                        # Update node's group_set with updated list
                                        # if changed
                                        if is_group_set_changed:
                                            node_collection.collection.update({
                                                "_id": subject_id
                                            }, {
                                                "$set": {"group_set": node_group_set}
                                            },
                                                upsert=False, multi=False
                                            )

                                    # To break outer for loop if key found
                                    break

                                else:
                                    error_message = "\n DataNotFound: No data found for relation ("+rel_key+") while creating GSystem ("+gsystem_type_name+" -- "+node.name+") !!!\n"
                                    log_list.append(error_message)
                                    # print error_message

                                    break
                    

        except Exception as e:
            error_message = "\n While creating "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e)
            log_list.append(error_message)
            print error_message # Keep it!
            import sys
            print "\n ****\n"
            print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
Esempio n. 22
0
 u'59816df569602a015784baea', u'594b833869602a013f0cb6ce', u'594cfbea69602a014089845b', \
 u'597ebd7b69602a0154bb417e', u'5945daf42c4796014ce12d2d', u'59aff39869602a0155bfac16']

try:
    module_obj_list = []
    for each_id in module_sort_order_ids:
        try:
            each_node = Node.get_node_by_id(ObjectId(each_id))
            if each_node:
                module_obj_list.append(each_node)
        except Exception as modulde_not_found_err:
            print "\nError in module_not_found for each_id: ", each_id, "\nError: ", modulde_not_found_err
            pass
    print "\nTotal modules: ", len(module_obj_list)
    home_grp_id = node_collection.one({'_type': 'Group', 'name': 'home'})._id
    create_gattribute(home_grp_id, 'items_sort_list', module_obj_list)
except Exception as module_sort_order_ids_err:
    pass
    print "\nError in module_sort_order_ids. ", module_sort_order_ids_err
units_cur = node_collection.find({
    '_type': 'Group',
    '_id': {
        '$in': units_for_renaming_leaf_nodes
    }
})
for each_unit in units_cur:
    try:
        if each_unit:
            print "\nUnit: ", each_unit.name
            all_leaf_node_ids = dig_nodes_field(parent_node=each_unit,
                                                only_leaf_nodes=True)
Esempio n. 23
0
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None):
  """
  View for handling Event and it's sub-types create-edit-view
  """
  auth = None

  try:
        group_id = ObjectId(group_id) #group_id is a valid ObjectId
  except:
        group_name, group_id = get_group_name_id(group_id) #instead of group_id the name of the object is passed via URL to the function
  group_obj = node_collection.one({'_id': group_id})
  app_set = ""
  title = ""    #Stores the name of the type of event such as Meeting, Inauguration, etc.
  session_of=""
  module=""
  Add=""
  announced_course =""
  batch =""
  event_gst = None
  event_gs = None

  property_order_list = []

  template_prefix = "mis"

  group_inverse_rel_id = [] 
  Group_type=node_collection.one({'_id':ObjectId(group_id)}) #instance of the group object in which the event is created e.g. "home" is a group
  for i in Group_type.relation_set:
       if unicode("group_of") in i.keys():
          group_inverse_rel_id = i['group_of']
  Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}})
  Eventtype='Eventtype'

  if Group_name:

      if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True:
           Eventtype='CollegeEvents'     
      else:
           Eventtype='Eventtype'

  Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"})
  Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1}) #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ...
  app_collection_set=[] #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list
  if Event_Types:
    for eachset in Event_Types.collection_set:
          app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      

  iteration=request.POST.get("iteration","")
  if iteration == "":
        iteration=1
        
  for i in range(int(iteration)):
   if app_set_id:
     event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) #GSystemType Object for the event corresponding to app_set_id e.g. Meeting
     title = event_gst.name
     event_gs = node_collection.collection.GSystem() #create a new GSystem Object for the Event
     event_gs.member_of.append(event_gst._id) #event_gs is a member_of event_gst

   if app_set_instance_id: #app_set_instance_id is the objectid of the event object which is already created
     event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
   property_order_list = get_property_order_with_value(event_gs) #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc..
   
   if request.method == "POST":
    # [A] Save event-node's base-field(s)
    # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
    # get_node_common_fields(request, event_gs, group_id, event_gst)
    # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
    # print "\n event_gs: \n", event_gs.keys()
    # for k, v in event_gs.items():
    #   print "\n ", k, " -- ", v
    is_changed = get_node_common_fields(request, event_gs, group_id, event_gst)
    if is_changed:
      # Remove this when publish button is setup on interface
      event_gs.status = u"PUBLISHED"
    if (request.POST.get("name","")) == "":
        if i>0:
            field_value=request.POST.get('start_time'+"_"+str(i),'')  
        else:
            field_value = request.POST.get('start_time','')
        # print "----------------Field Value-----------"
        # print field_value
        if event_gst.name == "Exam":
           name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value 
        else:
           name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value
        # print "-----------------Name------------------"
        # print name
        event_gs.name=name 

    # if request.POST.get("is_bigbluebutton") == unicode("Yes"):
    #   event_gs.is_bigbluebutton = True
    # else:
    #   event_gs.is_bigbluebutton = False  

    event_gs.save(is_changed=is_changed,groupid=group_id)
    # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n"
    check_attendee = True
    # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]}
        # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'}
        # print " ", field_set["name"]

        # * Fetch only Attribute field(s) / Relation field(s)
        
        if field_set.has_key('_id'): #Implies field_set is not a basefield but is an AT/RT
          field_instance = node_collection.one({'_id': field_set['_id']})#field_instance is an instance for AT or RT e.g. start_time
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            
            if field_instance["name"] == "attendees":
              continue

            field_data_type = field_set['data_type'] #data type of AT/RT e.g. datetime.datetime for start_time

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            open_event = False
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                
                if field_instance["name"] in request.FILES:
                  field_value = request.FILES[field_instance["name"]]
                  
                else:
                  field_value = ""
                
                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = event_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              if "date_month_day_year" in field_instance["validators"]:
                     if i>0:
                       field_value=request.POST.get(field_instance["name"]+"_"+str(i))  
                     else:
                        field_value = request.POST[field_instance["name"]]
                        
              else:
                # Other AttributeTypes 
                field_value = request.POST[field_instance["name"]]
              # field_instance_type = "GAttribute"
              # print "\n Parsing data for: ", field_instance["name"]
              if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif field_instance["name"] in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")
              
              if field_value:
                event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value)
                # print "--------------------------------------------------------------------------------------------------"
                # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name

              if field_instance["name"] == 'open_event':
                open_event = field_value

            else: #field_instance_type == RelationType
              field_value_list = request.POST.getlist(field_instance["name"])
              # field_instance_type = "GRelation"
              #code for creation of relation Session of 
              for i, field_value in enumerate(field_value_list):
                try:
                  field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M")
                except:
                   field_value = parse_template_data(ObjectId, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M")
                field_value_list[i] = field_value
              if field_value_list:
                if field_instance["name"] == "has_attendees" and open_event == "False":
                    send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs)
                else:
                  event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)

    # End of for loop on property_order_list
    # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id }))
    '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))'''
    if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
       if i==( (int(iteration))-1):
          #code to send mail to every one
          return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id}))
  
    else:
          event_attendees = []
          event_node = node_collection.one({'_id':ObjectId(event_gs._id)})
          for i in event_node.relation_set:
             if unicode('has_attendees') in i.keys():
                event_attendees = i['has_attendees']
          send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs, event_attendees)
          return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id}))

  event_attendees = request.POST.getlist('has_attendees','')
  
  event_gs.get_neighbourhood(event_gs.member_of)
  course=[]
  val=False
  for i in event_gs.relation_set:
       if unicode('event_has_batch') in i.keys():
            batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])})
            batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1})
            for i in batch_relation['relation_set']:
               if  unicode('has_course') in i.keys(): 
                   announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])})
                   for i in  announced_course.relation_set:
                      if unicode('announced_for') in i.keys():
                            course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])})
       if unicode('session_of') in i.keys(): 
                session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])})                     
                module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}})
  event_gs.event_coordinator
  Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"})
  if  Mis_admin:
    Mis_admin_list=Mis_admin.group_admin
    Mis_admin_list.append(Mis_admin.created_by)
    if request.user.id in Mis_admin_list:
        Add="Allow"  
    else: 
        Add= "Stop"
  else:
    Add="Stop"       

    
  if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
     template="ndf/Nussd_event_Schedule.html"
  else:
      template = "ndf/event_create_edit.html"
  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'group_id': group_id, 'groupid': group_id, 
                        'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title':title,
                        'property_order_list': property_order_list,
                        'Add':Add
                      }

  if app_set_instance_id:
    event_detail={}
    events={}
    if event_gs.event_coordinator:
      event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) 
      event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id)
      events["cordinator"]=event_detail
    if announced_course:
      event_detail["course"]=str(announced_course.name) 
      event_detail["course_id"]=str(announced_course._id)
      events["course"]=event_detail
    event_detail={}
    if batch:  
      event_detail["batchname"]=str(batch.name)
      event_detail["batchid"]=str(batch._id)
      events["batch"]=event_detail
    event_detail={}
    if session_of:
       event_detail["sessionname"]=str(session_of.name)
       event_detail["sessionid"]=str(session_of._id)
       for i in session_of.attribute_set:
         if unicode('course_structure_minutes') in i.keys():
          event_detail["sessionminutes"] = str(i['course_structure_minutes'])
       
       events["session"]=event_detail
    event_detail={}
    if module:
       event_detail["Modulename"]=str(module.name)
       event_detail["Moduleid"]=str(module._id)
       events["Module"]=event_detail
    context_variables['node'] = event_gs
    context_variables['edit_details']=events
    
    # print "\n template-list: ", [template, default_template]
    # template = "ndf/fgh.html"
    # default_template = "ndf/dsfjhk.html"
    # return render_to_response([template, default_template], 

  return render_to_response(template, 
                              context_variables,
                              context_instance = RequestContext(request)
                            )
Esempio n. 24
0
def setup_default_gapps():
  '''
  This sets up default GAPPS for group(s).
  '''

  default_gapps_names_list = ["Page", "File", "Forum", "MIS", "Task", "Batch", "Event"]# "Meeting"]
  info_message = "\n Default GAPPS names: " + str(default_gapps_names_list)

  # Fetch GAPPS and populate their document-node in a different list
  default_gapps_list = [] # Will hold document of each corresponding GAPP name from above given list
  meta_type_gapp = node_collection.one({'_type': "MetaType", 'name': META_TYPE[0]})
  info_message += "\n Default GAPPS list: \n"
  for each in default_gapps_names_list:
    gapp_node = node_collection.one({'_type': "GSystemType", 'member_of': meta_type_gapp._id, 'name': each})

    if gapp_node:
      default_gapps_list.append(gapp_node)
      info_message += " " + gapp_node.name + "("+str(gapp_node._id)+")\n"

  log_list.append(info_message)

  # If length of list-of-names & list-of-documents doesn't match throw Exception
  if len(default_gapps_names_list) != len(default_gapps_list):
    error_message = "\n GAPPSSetupError: Few GAPPS not found!!!\n"
    log_list.append(error_message)
    raise Exception(error_message)

  # Fetch AttributeType node - apps_list
  at_apps_list = node_collection.one({'_type': "AttributeType", 'name': "apps_list"})
  if not at_apps_list:
    error_message = "\n GAPPSSetupError: AttributeType (apps_list) doesn't exists.. please create explicitly!!!\n"
    log_list.append(error_message)
    raise Exception(error_message)
  info_message = "\n AttributeType: " + at_apps_list.name + "("+str(at_apps_list._id)+")\n"
  log_list.append(info_message)

  # Fetch MIS_admin group - required for fetching GSystems of College GSystemType
  mis_admin = node_collection.one({'_type': "Group",
                                   '$or': [{'name': {'$regex': u"MIS_admin", '$options': 'i'}},
                                           {'altnames': {'$regex': u"MIS_admin", '$options': 'i'}}],
                                   'group_type': "PRIVATE"
                                  },
                                  {'name': 1}
                                  )
  if not mis_admin:
    error_message = "\n GAPPSSetupError: Group (MIS_admin) doesn't exists.. please check!!!\n"
    log_list.append(error_message)
    raise Exception(error_message)
  info_message = "\n Group: " + mis_admin.name + "("+str(mis_admin._id)+")\n"
  log_list.append(info_message)

  # Fetch GSystems of College GSystemType belonging to MIS_admin group
  college = node_collection.one({'_type': "GSystemType", 'name': u"College"}, {'name': 1})
  if not college:
    error_message = "\n GAPPSSetupError: GSystemType (College) doesn't exists.. please check!!!\n"
    log_list.append(error_message)
    raise Exception(error_message)
  info_message = "\n GSystemType: " + college.name + "("+str(college._id)+")\n"
  log_list.append(info_message)

  college_cur = list(node_collection.find({'_type': "GSystem", 'member_of': college._id, 'group_set': mis_admin._id}))

  for i, each in enumerate(college_cur):
    g = node_collection.one({'_type': "Group", 'name': each.name, 'group_type': "PRIVATE"}, {'name': 1})
    if g:
      info_message = "\n "+str(i+1)+") Setting GAPPS for this college group ("+g.name+" -- "+str(g._id)+")\n"
      log_list.append(info_message)

      is_apps_list = triple_collection.one({'_type': "GAttribute", 'subject': g._id, 'attribute_type': at_apps_list._id})
      if is_apps_list:
        info_message = " Default GAPPs list already exists for Group ("+g.name+" -- "+str(g._id)+"), so overriding it..."
        log_list.append(info_message)
        res = triple_collection.collection.update({'_id': is_apps_list._id}, {'$set': {'object_value': default_gapps_list}}, upsert=False, multi=False)
        if res["n"]:
          is_apps_list.reload()
          info_message = "\n Successfully overridden: " + str(is_apps_list._id) + "\n"
          log_list.append(info_message)
        else:
          info_message = "\n Not overridden: " + str(is_apps_list._id) + "\n"
          log_list.append(info_message)

      else:
        info_message = " Default GAPPs list doesn't exists for Group ("+g.name+" -- "+str(g._id)+"), so creating..."
        log_list.append(info_message)
        ga = create_gattribute(g._id, at_apps_list, default_gapps_list)
        info_message = "\n Successfully created: " + str(ga._id) + "\n"
        log_list.append(info_message)

    else:
      error_message = "\n GAPPSSetupError: This college group ("+each.name+") doesn't exists.. please create explicitly!!!\n"
      log_list.append(error_message)
Esempio n. 25
0
def parse_data_create_gsystem(json_file_path):
    json_file_content = ""

    try:
        with open(json_file_path) as json_file:
            json_file_content = json_file.read()

        json_documents_list = json.loads(json_file_content)

        # Process data in proper format
        node = node_collection.collection.File()
        node_keys = node.keys()
        node_structure = node.structure

        json_documents_list_spaces = json_documents_list
        json_documents_list = []

        # Removes leading and trailing spaces from keys as well as values
        for json_document_spaces in json_documents_list_spaces:
            json_document = {}

            for key_spaces, value_spaces in json_document_spaces.iteritems():
                json_document[key_spaces.strip().lower()] = value_spaces.strip()

            json_documents_list.append(json_document)

    except Exception as e:
        error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e)
        log_list.append(str(error_message))
        raise error_message

    for i, json_document in enumerate(json_documents_list):
      
        info_message = "\n\n\n******************** Processing row number : ["+ str(i)+ "] ********************"
        print info_message
        log_list.append(str(info_message))
        
        try:

            # print "base_folder : ", json_document["base_folder"]
            # print "file_name : ", json_document["file_name"]
            is_base_folder = check_folder_exists(json_document["file_name"], json_document["base_folder"])
            # print "is_base_folder : ", is_base_folder

            if is_base_folder:
                info_message = "- File gsystem holding collection is created. Having name : '" + str(json_document["base_folder"]) + "' and ObjectId : '" + str(is_base_folder) + "'"
                print info_message
                log_list.append(info_message)

            parsed_json_document = {}
            attribute_relation_list = []
            
            for key in json_document.iterkeys():
                parsed_key = key.lower()
                
                if parsed_key in node_keys:
                    # print parsed_key
                    # adding the default field values like: created_by, member_of, ...

                    # created_by:
                    if parsed_key == "created_by":
                        if json_document[key]:
                            temp_user_id = get_user_id(json_document[key].strip())
                            if temp_user_id:
                                parsed_json_document[parsed_key] = temp_user_id
                            else:
                                parsed_json_document[parsed_key] = nroer_team_id                            
                        else:
                            # parsed_json_document[parsed_key] = get_user_id("nroer_team")
                            parsed_json_document[parsed_key] = nroer_team_id
                       # print "---", parsed_json_document[parsed_key]
                      
                    # contributors:
                    elif parsed_key == "contributors":
                        if json_document[key]:
                            contrib_list = json_document[key].split(",")

                            temp_contributors = []
                            for each_user in contrib_list:
                                user_id = get_user_id(each_user.strip())
                                if user_id:
                                    temp_contributors.append(user_id)

                            parsed_json_document[parsed_key] = temp_contributors
                        else:
                            parsed_json_document[parsed_key] = [nroer_team_id]
                            # print "===", parsed_json_document[parsed_key]
                      
                    # tags:
                    elif (parsed_key == "tags") and json_document[key]:
                        
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))

                        # tag_list = json_document[key].replace("\n", "").split(",")
                        # temp_tag_list = []
                        # for each_tag in tag_list:
                        #   if each_tag:
                        #     temp_tag_list.append(each_tag.strip())
                        # parsed_json_document[parsed_key] = temp_tag_list
                        # print parsed_json_document[parsed_key]
                      
                    # member_of:
                    elif parsed_key == "member_of":
                        parsed_json_document[parsed_key] = [file_gst._id]
                        # print parsed_json_document[parsed_key]
                      
                    else:
                        # parsed_json_document[parsed_key] = json_document[key]
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))

                    # --- END of processing for remaining fields

                else:
                    parsed_json_document[key] = json_document[key]
                    attribute_relation_list.append(key)
              
            # calling method to create File GSystems
            nodeid = create_resource_gsystem(parsed_json_document)
            # print type(nodeid), "nodeid ------- : ", nodeid, "\n"

            # starting processing for the attributes and relations saving
            if isinstance(nodeid, ObjectId) and attribute_relation_list:

                node = node_collection.one({ "_id": ObjectId(nodeid) })

                gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id)
                # print gst_possible_attributes_dict

                relation_list = []
                json_document['name'] = node.name

                # Write code for setting atrributes
                for key in attribute_relation_list:
                  
                    is_relation = True
                    # print "\n", key, "----------\n"
                    
                    for attr_key, attr_value in gst_possible_attributes_dict.iteritems():
                        # print "\n", attr_key,"======", attr_value
                        
                        if key == attr_key:
                            # print key
                            is_relation = False

                            # setting value to "0" for int, float, long (to avoid casting error)
                            # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]):
                            #     json_document[key] = 0

                            if json_document[key]:

                                info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key]  + "'"
                                print info_message
                                log_list.append(str(info_message))

                                cast_to_data_type(json_document[key], attr_value['data_type'])

                                if attr_value['data_type'] == "curricular":
                                    # setting int values for CR/XCR
                                    if json_document[key] == "CR":
                                        json_document[key] = 1
                                    elif json_document[key] == "XCR":
                                        json_document[key] = 0
                                    else:  # needs to be confirm
                                        json_document[key] = 0

                                json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type'])

                                # if attr_value['data_type'] == basestring:

                                #     info_message = "\n- For GAttribute parsing content | key: " + attr_key + " -- value: " + json_document[key]
                                #     print info_message
                                #     log_list.append(str(info_message))

                                # elif attr_value['data_type'] == unicode:
                                #     json_document[key] = unicode(json_document[key])

                                # elif attr_value['data_type'] == bool: 
                                #     # setting int values for CR/XCR
                                #     if json_document[key] == "CR":
                                #       json_document[key] = 1
                                #     elif json_document[key] == "XCR":
                                #       json_document[key] = 0
                                    
                                #     json_document[key] = bool(int(json_document[key]))
                                    
                                # elif attr_value['data_type'] == datetime.datetime:
                                #     json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y")

                                # elif attr_value['data_type'] == int:
                                #     json_document[key] = int(json_document[key])
                                # elif attr_value['data_type'] == float:
                                #     json_document[key] = float(json_document[key])
                                # elif attr_value['data_type'] == long:
                                #     json_document[key] = long(json_document[key])

                                # elif type(attr_value['data_type']) == IS:
                                #     for op in attr_value['data_type']._operands:
                                #         if op.lower() == json_document[key].lower():
                                #             json_document[key] = op

                                # elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]):
                                #     if "," not in json_document[key]:
                                #         # Necessary to inform perform_eval_type() that handle this value as list
                                #         json_document[key] = "\"" + json_document[key] + "\", "

                                #     else:
                                #         formatted_value = ""
                                #         for v in json_document[key].split(","):
                                #             formatted_value += "\""+v.strip(" ")+"\", "
                                #             json_document[key] = formatted_value

                                #     perform_eval_type(key, json_document, "GSystem")

                                subject_id = node._id
                                # print "\n-----\nsubject_id: ", subject_id
                                attribute_type_node = node_collection.one({'_type': "AttributeType", 
                                                   '$or': [{'name': {'$regex': "^"+attr_key+"$", '$options': 'i'}}, 
                                                   {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'}}]
                                                   })
                                # print "\nattribute_type_node: ", attribute_type_node.name
                                object_value = json_document[key]
                                # print "\nobject_value: ", object_value
                                ga_node = None

                                info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n"
                                print info_message
                                log_list.append(str(info_message))

                                ga_node = create_gattribute(subject_id, attribute_type_node, object_value)
                                
                                info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
                                print info_message
                                log_list.append(str(info_message))
                                
                                # To break outer for loop as key found
                                break

                            else:
                                error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n"
                                print error_message
                                log_list.append(str(error_message))

                        # ---END of if (key == attr_key)

                    if is_relation:
                        relation_list.append(key)

                # print "relation_list : ", relation_list
                if not relation_list:
                    # No possible relations defined for this node
                    info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n"
                    print info_message
                    log_list.append(str(info_message))
                    return

                gst_possible_relations_dict = node.get_possible_relations(file_gst._id)

                # processing each entry in relation_list
                for key in relation_list:
                  is_relation = True

                  for rel_key, rel_value in gst_possible_relations_dict.iteritems():
                    if key == rel_key: # commented because teaches is only relation being used for time being
                    # if key == "teaches":
                      is_relation = False

                      if json_document[key]:

                        # -----------------------------
                        hierarchy_output = None
                        def _get_id_from_hierarchy(hier_list, oid=None):
                          '''
                          Returns the last hierarchical element's ObjectId.
                          Arguments to be passes is list of unicode names.
                          e.g.
                          hier_list = [u'NCF', u'Science', u'Physical world', u'Materials', u'States of matter', u'Liquids']
                          '''
                          
                          if len(hier_list) >= 2:
                            # print hier_list, "len(hier_list) : ", len(hier_list)
                            try:

                              if oid:
                                curr_oid = node_collection.one({ "_id": oid })
                                # print "curr_oid._id", curr_oid._id

                              else:
                                curr_oid = node_collection.one({ "name": hier_list[0], 'group_set': {'$all': [ObjectId(home_group._id)]}, 'member_of': {'$in': [ObjectId(theme_gst._id), ObjectId(theme_item_gst._id), ObjectId(topic_gst._id)]} })

                              if curr_oid:
                                next_oid = node_collection.one({ 
                                                          "name": hier_list[1],
                                                          'group_set': {'$all': [ObjectId(home_group._id)]},
                                                          'member_of': {'$in': [ObjectId(theme_item_gst._id), ObjectId(topic_gst._id)]},
                                                          '_id': {'$in': curr_oid.collection_set }
                                                          })

                                # print "||||||", next_oid.name
                                hier_list.remove(hier_list[0])
                                # print "calling _get_id_from_hierarchy(", hier_list,", ", next_oid._id,")" 

                                _get_id_from_hierarchy(hier_list, next_oid._id)
                              else:
                                error_message = "!! ObjectId of curr_oid does not found."
                                print error_message
                                log_list.append(error_message)

                            except Exception as e:
                              error_message = "\n!! Error in getting _id from teaches hierarchy. " + str(e)
                              print error_message
                              log_list.append(error_message)

                          else:
                            global hierarchy_output
                            hierarchy_output = oid if oid else None

                          return hierarchy_output
                          # -----------------------------                  

                        # most often the data is hierarchy sep by ":"
                        if ":" in json_document[key]:
                          formatted_list = []
                          temp_teaches_list = json_document[key].replace("\n", "").split(":")
                          # print "\n temp_teaches", temp_teaches
                          for v in temp_teaches_list:
                            formatted_list.append(v.strip())

                          right_subject_id = []
                          rsub_id = _get_id_from_hierarchy(formatted_list) if formatted_list else None
                          # print hierarchy_output," |||||||||||||||||||", rsub_id

                          # checking every item in hierarchy exist and leaf node's _id found
                          if rsub_id:
                            right_subject_id.append(rsub_id)
                            json_document[key] = right_subject_id
                            # print json_document[key]
                          else:
                            error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + "cannot be created.\n"
                            log_list.append(error_message)
                            break
                        
                        # sometimes direct leaf-node may be present without hierarchy and ":"
                        else:
                          formatted_list = list(json_document[key].strip())
                          right_subject_id = []
                          right_subject_id.append(_get_id_from_hierarchy(formatted_list))
                          json_document[key] = right_subject_id

                        # print "\n----------", json_document[key]
                        info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key])
                        print info_message
                        log_list.append(str(info_message))
                        # print list(json_document[key])

                        # perform_eval_type(key, json_document, "GSystem", "GSystem")

                        for right_subject_id in json_document[key]:
                          # print "\njson_document[key]: ", json_document[key]

                          subject_id = node._id

                          rel_subject_type = []
                          rel_subject_type.append(file_gst._id)
                          
                          if file_gst.type_of:
                              rel_subject_type.extend(file_gst.type_of)

                          relation_type_node = node_collection.one({'_type': "RelationType", 
                                                                    '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}}, 
                                                                            {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}],
                                                                    'subject_type': {'$in': rel_subject_type}
                                                            })

                          right_subject_id_or_list = []
                          right_subject_id_or_list.append(ObjectId(right_subject_id))
                          
                          nodes = triple_collection.find({'_type': "GRelation", 
                                      'subject': subject_id, 
                                      'relation_type.$id': relation_type_node._id
                                    })

                          # sending list of all the possible right subject to relation
                          for n in nodes:
                            if not n.right_subject in right_subject_id_or_list:
                              right_subject_id_or_list.append(n.right_subject)

                          info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..."
                          print info_message
                          log_list.append(str(info_message))
                          gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list)
                                                    
                          info_message = "\n- Grelation processing done.\n"
                          print info_message
                          log_list.append(str(info_message))

                        # To break outer for loop if key found
                        break

                      else:
                        error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n"
                        print error_message
                        log_list.append(str(error_message))

                        break

              # print relation_list

            else:  # node object or attribute_relation_list does not exist.
                info_message = "\n!! Either resource is already created -- OR -- file is already saved into gridfs/DB -- OR -- file does not exists."
                print info_message
                log_list.append(str(info_message))

                continue

        except Exception as e:
            error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e)
            print error_message # Keep it!
            log_list.append(str(error_message))
Esempio n. 26
0
    def handle(self, *args, **options):

          collection = get_database()[Node.collection_name]

          Event = collection.Node.find({"_type":"GSystemType","name":{'$in':["Classroom Session","Exam"]}})

          yesterday = date.today() - timedelta(1)
          day_before_yesterday=date.today() - timedelta(2)
          date1=datetime.date.today()
          ti=time(0,0)
          Today=datetime.datetime.combine(date1,ti)
          yesterday=datetime.datetime.combine(yesterday,ti)
          day_before_yesterday=datetime.datetime.combine(day_before_yesterday,ti)
          no_of_days=0

          #get the Mis Admin
          Mis_admin=collection.Node.one({"_type":"Group","name":"MIS_admin"})
          Mis_admin_name=""
          if  Mis_admin:
              Mis_admin_list=Mis_admin.group_admin
              Mis_admin_list.append(Mis_admin.created_by)
              user_obj = User.objects.get(id=Mis_admin.created_by)
              Mis_admin_name=user_obj.username
          
          
              
           
          Attendance_Event = collection.Node.find({"member_of":{'$in':[ObjectId(Event[0]._id),ObjectId(Event[1]._id)]},"attribute_set.start_time":{'$gte':day_before_yesterday,'$lt':Today}})

          rescheduled_Attendance_events=collection.Node.find({"member_of":{'$in':[ObjectId(Event[0]._id),ObjectId(Event[1]._id)]},"attribute_set.reschedule_attendance.reschedule_till":{'$gt':yesterday}})
          
          rescheduled_events = collection.Node.find({"member_of":{'$in':[ObjectId(Event[0]._id),ObjectId(Event[1]._id)]},"attribute_set.event_edit_reschedule.reschedule_till":{'$gt':yesterday}}) 
          
          Attendance_marked_event = collection.Node.find({"member_of":{'$in':[ObjectId(Event[0]._id),ObjectId(Event[1]._id)]},"relation_set.has_attended":{"$exists":False},"attribute_set.start_time":{'$gte':yesterday,'lt':Today}})

          reschedule_attendance = collection.Node.one({"_type":"AttributeType","name":"reschedule_attendance"})
          
          reschedule_event=collection.Node.one({"_type":"AttributeType","name":"event_edit_reschedule"})
          
          reschedule_dates = {}
          for i in Attendance_Event:
             for j in i.attribute_set:
               if unicode('reschedule_attendance') in j.keys():
                  reschedule_dates = j['reschedule_attendance']
             reschedule_dates["reschedule_allow"] = False
             create_gattribute(ObjectId(i._id),reschedule_attendance,reschedule_dates)
              
          reschedule_dates={}
          for i in rescheduled_events:
              for j in i.attribute_set:
                       if unicode('event_edit_reschedule') in j.keys():
                         reschedule_dates = j['event_edit_reschedule']
              reschedule_dates['reschedule_allow'] = False
              create_gattribute(ObjectId(i._id),reschedule_event,reschedule_dates)
              
          reschedule_dates={}
          for i in rescheduled_Attendance_events:
             for j in i.attribute_set:
               if unicode('reschedule_attendance') in j .keys():
                  reschedule_dates = j['reschedule_attendance']
               reschedule_dates["reschedule_allow"] = False
             create_gattribute(ObjectId(i._id),reschedule_attendance,reschedule_dates)

          
          for i in Attendance_marked_event:
            event_status = collection.Node.one({"_type":"AttributeType","name":"event_status"})
            create_gattribute(ObjectId(i._id),event_status,unicode('Incomplete'))
            
            for j in i.attribute_set:
              if unicode("start_time") in j.keys():
                   if (j["start_time"] >= day_before_yesterday and j["start_time"] <  yesterday):
                      no_of_days = 2
                   if (j["start_time"] >=  yesterday and j["start_time"] < Today):
                      no_of_days = 1
                    
            to_user_list=[]
            #node is the node of the college Group
            node = collection.Node.one({"_type":"Group","_id":{'$in':i.group_set}})
            for j in node.group_admin:
              user_obj = User.objects.get(id=j)
              if user_obj not in to_user_list:
                      to_user_list.append(user_obj)
              render_label = render_to_string(
                    "notification/label.html",
                    {
                        "sender": Mis_admin_name,
                        "activity": "Attendance not marked",
                        "conjunction": "-"
                    })
              notification.create_notice_type(render_label,"Attendance is not marked for "+ i.name +" Event \n Attendance would be blocked after" + str(no_of_days) + "days" , "notification")
              notification.send(to_user_list, render_label, {"from_user": Mis_admin_name})
Esempio n. 27
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
            '_type': 'GSystem',
            'member_of': gst_module_id,
            'collection_set': {
                '$in': [unit_id]
            }
        })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_gstystem_values(tags=tags,
                                       author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_about', kwargs={'group_id': unit_node._id}))
Esempio n. 28
0
def main():
  grp_dict={}
  columns = defaultdict(list)

  with open(schema_file_csv, 'rb') as f:
    reader = csv.DictReader(f, delimiter=",")
    file_content=[]
    for row in reader:
      file_content.append(row)
    for each in file_content:
      check_group = node_collection.one({'name': str(each['category']), '_type' : 'Group'})
      check_sub_group = node_collection.one({'name': str(each['name']), '_type' : 'Group'})

      if not check_group:
          group_create(each['category'])
      if not check_sub_group:
          group_create(each['name'])
              
      get_parent_group = node_collection.one({'name': str(each['category']), '_type' : 'Group'})
      get_child_group = node_collection.one({'name': str(each['name']), '_type' : 'Group'})
      if get_child_group._id not in get_parent_group.collection_set:
        get_parent_group.collection_set.append(get_child_group._id)
        get_parent_group.save()
      if get_child_group._id not in get_parent_group.post_node:
        get_parent_group.post_node.append(get_child_group._id)
        get_parent_group.save()
      get_group = node_collection.one({'name': str(each['name']), '_type' : 'Group'})
      get_group.content = unicode(each['description'])
      get_group.content = unicode(each['description'])
      get_group.save()
      create_gattribute(get_group._id, email_id_AT, unicode(each['email']))  
      create_gattribute(get_group._id, house_street_AT, unicode(each['address: Street']))  
      create_gattribute(get_group._id, town_city_AT, unicode(each['address: Place']))  
      create_gattribute(get_group._id, state_AT, unicode(each['address: State']))
      if each['address: PIN']:
        create_gattribute(get_group._id, pin_code_AT, long(each['address: PIN']))
      create_gattribute(get_group._id, contact_point_AT, unicode(each['contactPoint']))  
      create_gattribute(get_group._id, telephone_AT, unicode(each['telephone']))  
      create_gattribute(get_group._id, website_AT, unicode(each['website']))
      
    
      print ("\n Partners details added!\n\n")
Esempio n. 29
0
del_thread_node_ids = [each_thr.right_subject for each_thr in del_has_thread_grel]
# fetch thread only if it has any comments attached to it
del_thread_cur = node_collection.find({'_id': {'$in': del_thread_node_ids}, 'author_set': {'$ne': []}})
print "\nTotal Old Threads holding comments references: ", del_thread_cur.count()

# if yes find related/newly created thread obj ('PUBLISHED')
# attach the comments to the newly created thread obj
for each_th_obj in del_thread_cur:
	# print "\neach_th_obj.author_set: ", each_th_obj.author_set, " -- ", each_th_obj._id
	subj_id = node_and_del_thread[each_th_obj._id]
	pub_has_thread_grel = triple_collection.find_one({'relation_type': has_thread_rt._id, 
		'subject': subj_id, 'status': 'PUBLISHED'})
	# print "\n ObjectId(pub_has_thread_grel.right_subject): ", ObjectId(pub_has_thread_grel.right_subject)

	triples_of_del_th = triple_collection.find({'subject': each_th_obj._id, '_type': 'GAttribute'})
	print create_gattribute(ObjectId(pub_has_thread_grel.right_subject), 'release_response', True)
	# triple_collection.collection.update({'subject': each_th_obj._id, '_type': 'GAttribute'},
	# {'$set': {'subject': ObjectId(pub_has_thread_grel.right_subject)}},upsert=False, multi=True)
	pub_thread_res = node_collection.collection.update({
		'_id': ObjectId(pub_has_thread_grel.right_subject)},
		{'$addToSet': {'author_set': {'$each': each_th_obj.author_set}}},
		upsert=False, multi=False)
	print "\nPublished Thread updates result: ", pub_thread_res
	del_thread_replies = node_collection.collection.update({
		'prior_node': each_th_obj._id, 'member_of': reply_gst._id},
		{'$set': {'prior_node': [ObjectId(pub_has_thread_grel.right_subject)],
		'origin': [{u'thread_id': ObjectId(pub_has_thread_grel.right_subject)}]}},
		upsert=False, multi=True)
	print "\nDeleted Thread updates result: ", del_thread_replies

th = node_collection.find({'member_of': twist_gst._id})
Esempio n. 30
0
def parse_data_create_gsystem(json_file_path, file_name):
    json_file_content = ""

    try:
        print "\n file_name == ",file_name

        with open(json_file_path) as json_file:
            json_file_content = json_file.read()

        json_documents_list = json.loads(json_file_content)

        # Process data in proper format
        node = node_collection.collection.GSystem()
        node_keys = node.keys()
        node_structure = node.structure

        json_documents_list_spaces = json_documents_list
        json_documents_list = []

        # Removes leading and trailing spaces from keys as well as values
        for json_document_spaces in json_documents_list_spaces:
            json_document = {}

            for key_spaces, value_spaces in json_document_spaces.iteritems():
                json_document[key_spaces.strip().lower()] = value_spaces.strip()

            json_documents_list.append(json_document)

    except Exception as e:
        error_message = "\n While parsing the file ("+json_file_path+") got following error...\n " + str(e)
        log_list.append(error_message)
        print error_message
        raise error_message


    for i, json_document in enumerate(json_documents_list):
        try:
            if file_name == "QuizItem.csv":
                print "\n\n *******************"
                question_content = json_document['content']
                question_content = question_content.split(' ')
                question_content = question_content[:4]
                question_content = ' '.join(question_content)
                json_document['name'] = question_content
                json_document['altnames'] = json_document['content']
                group_id = ObjectId(json_document['group_id'])
                group_obj = node_collection.one({'_id': group_id})
                if group_obj:
                    group_id = group_obj._id
                else:
                    group_id = home_grp._id
                user_id = int(json_document['user_id'])
                print "\n\n NAME ======= ", json_document['name'], group_id, user_id
            global node_repeated
            node_repeated = False
            n_name = ""
            if "first name" in json_document:
                n_name = json_document["first name"] + " "
                if json_document["middle name"]:
                    n_name += json_document["middle name"]
                    if json_document["last name"]:
                        n_name += " "
                n_name += json_document["last name"]
                json_document["name"] = n_name.title()

            info_message = "\n ============ #"+ str(i+1) +" : Start of "+gsystem_type_name+"'s GSystem ("+json_document['name']+") creation/updation ============\n"
            log_list.append(info_message)

            parsed_json_document = {}
            attribute_relation_list = []
            for key in json_document.iterkeys():
                # print "\n key ",key
                parsed_key = key.lower()
                parsed_key = parsed_key.replace(" ", "_")
                if parsed_key in node_keys:
                    if node_structure[parsed_key] == unicode:
                        parsed_json_document[parsed_key] = unicode(json_document[key])
                    elif node_structure[parsed_key] == datetime.datetime:
                        parsed_json_document[parsed_key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y")
                    else:
                        parsed_json_document[parsed_key] = json_document[key]
                else:
                    parsed_json_document[key] = json_document[key]
                    attribute_relation_list.append(key)

            info_message = "\n Creating "+gsystem_type_name+" ("+parsed_json_document["name"]+")..."
            log_list.append(info_message)
            print "\n HERE == "
            node = create_edit_gsystem(gsystem_type_id, gsystem_type_name, parsed_json_document, user_id)
            print "\n node created === ", node._id, " === ", node.name, node.altnames
            # print "attribute_relation_list == ",attribute_relation_list
            if node:
                if not attribute_relation_list:
                    # Neither possible attribute fields, nor possible relations defined for this node
                    info_message = "\n "+gsystem_type_name+" ("+node.name+"): Neither possible attribute fields, nor possible relations defined for this node !\n"
                    log_list.append(info_message)
                    continue

                gst_possible_attributes_dict = node.get_possible_attributes(gsystem_type_id)
                print "\n gsystem_type_id ===",gst_possible_attributes_dict
                relation_list = []
                json_document['name'] = node.name

                # Write code for setting atrributes
                for key in attribute_relation_list:
                    is_relation = True

                    for attr_key, attr_value in gst_possible_attributes_dict.iteritems():
                        # print "\n\n attr_key === ", attr_key
                        # print "\n\n altnames --  === ", attr_value['altnames']
                        if attr_value['altnames'] and key == attr_value['altnames'].lower() or key == attr_key.lower():
                            is_relation = False

                            if json_document[key]:
                                try:
                                    if attr_value['data_type'] == basestring:
                                        if u"\u2013" in json_document[key]:
                                            json_document[key] = json_document[key].replace(u"\u2013", "-")

                                    info_message = "\n For GAttribute parsing content | key: " + attr_key + " -- " + json_document[key]
                                    log_list.append(info_message)

                                    if attr_value['data_type'] == unicode:
                                        json_document[key] = unicode(json_document[key])

                                    elif attr_value['data_type'] == bool: 
                                        if json_document[key].lower() == "yes":
                                            json_document[key] = True
                                        elif json_document[key].lower() == "no":
                                            json_document[key] = False
                                        else:
                                            json_document[key] = None

                                    elif attr_value['data_type'] == datetime.datetime:

                                        # Use small-case altnames
                                        if key in ["dob", "date of birth", "date of registration"]:
                                            if json_document[key]:
                                                json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y")
                                        else:
                                            if json_document[key]:
                                                json_document[key] = datetime.datetime.strptime(json_document[key], "%Y")

                                    elif attr_value['data_type'] in [int, float, long]:
                                        if not json_document[key]:
                                            json_document[key] = 0
                                        else:
                                            if attr_value['data_type'] == int:
                                                json_document[key] = int(json_document[key])
                                            elif attr_value['data_type'] == float:
                                                json_document[key] = float(json_document[key])
                                            else:
                                                json_document[key] = long(json_document[key])

                                    elif type(attr_value['data_type']) == IS:
                                        for op in attr_value['data_type']._operands:
                                            if op.lower() == json_document[key].lower():
                                                json_document[key] = op

                                    elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]):
                                        if "," not in json_document[key]:
                                            # Necessary to inform perform_eval_type() that handle this value as list
                                            json_document[key] = "\"" + json_document[key] + "\", "

                                        else:
                                            formatted_value = ""
                                            for v in json_document[key].split(","):
                                                formatted_value += "\""+v.strip(" ")+"\", "
                                            json_document[key] = formatted_value

                                        perform_eval_type(key, json_document, "GSystem")

                                    subject_id = node._id

                                    attribute_type_node = None
                                    if attr_key in attr_type_dict:
                                        attribute_type_node = attr_type_dict[attr_key]
                                    else:
                                        attribute_type_node = node_collection.one({
                                            '_type': "AttributeType",
                                            '$or': [{
                                                'name': {'$regex': "^" + attr_key + "$", '$options': 'i'}
                                            }, {
                                                'altnames': {'$regex': "^" + attr_key + "$", '$options': 'i'}
                                            }]
                                        })
                                        attr_type_dict[attr_key] = attribute_type_node

                                    object_value = json_document[key]

                                    ga_node = None

                                    info_message = "\n Creating GAttribute (" + node.name + " -- " + attribute_type_node.name + " -- " + str(json_document[key]) + ") ...\n"
                                    log_list.append(info_message)
                                    ga_node = create_gattribute(subject_id, attribute_type_node, object_value)
                                except Exception as e:
                                    error_message = "\n While creating GAttribute (" + attr_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) + "\n"
                                    log_list.append(error_message)
                                    print error_message # Keep it!

                                # To break outer for loop as key found
                                break

                            else:
                                error_message = "\n DataNotFound: No data found for field ("+attr_key+") while creating GSystem (" + gsystem_type_name + " -- " + node.name + ") !!!\n"
                                log_list.append(error_message)

                    if is_relation:
                        relation_list.append(key)

                if not relation_list:
                    # No possible relations defined for this node
                    info_message = "\n "+gsystem_type_name+" ("+node.name+"): No possible relations defined for this node !!!\n"
                    log_list.append(info_message)

                else:
                    gst_possible_relations_dict = node.get_possible_relations(gsystem_type_id)

                    # Write code for setting relations
                    for key in relation_list:
                        is_relation = True

                        for rel_key, rel_value in gst_possible_relations_dict.iteritems():
                            if key == rel_value['altnames'].lower() or key == rel_key.lower():
                                is_relation = False

                                if json_document[key]:
                                    # Here semi-colon(';') is used instead of comma(',')
                                    # Beacuse one of the value may contain comma(',') which causes problem in finding required value in database
                                    try:
                                        if ";" not in json_document[key]:
                                            # Necessary to inform perform_eval_type() that handle this value as list
                                            json_document[key] = "\""+json_document[key]+"\", "

                                        else:
                                            formatted_value = ""
                                            for v in json_document[key].split(";"):
                                                formatted_value += "\""+v.strip(" ")+"\", "
                                            json_document[key] = formatted_value

                                        info_message = "\n For GRelation parsing content | key: " + rel_key + " -- " + json_document[key]
                                        log_list.append(info_message)

                                        perform_eval_type(key, json_document, "GSystem", "GSystem")

                                        # for right_subject_id in json_document[key]:
                                        subject_id = node._id

                                        # Here we are appending list of ObjectIds of GSystemType's type_of field 
                                        # along with the ObjectId of GSystemType's itself (whose GSystem is getting created)
                                        # This is because some of the RelationType's are holding Base class's ObjectId
                                        # and not that of the Derived one's
                                        # Delibrately keeping GSystemType's ObjectId first in the list
                                        # And hence, used $in operator in the query!
                                        rel_subject_type = []
                                        rel_subject_type.append(gsystem_type_id)
                                        if gsystem_type_node.type_of:
                                            rel_subject_type.extend(gsystem_type_node.type_of)

                                        relation_type_node = None
                                        if rel_key in rel_type_dict:
                                            relation_type_node = rel_type_dict[rel_key]
                                        else:
                                            relation_type_node = node_collection.one({
                                                '_type': "RelationType",
                                                '$or': [{
                                                    'name': {'$regex': "^" + rel_key + "$", '$options': 'i'}
                                                }, {
                                                    'altnames': {'$regex': "^" + rel_key + "$", '$options': 'i'}
                                                }],
                                                'subject_type': {'$in': rel_subject_type}
                                            })
                                            rel_type_dict[rel_key] = relation_type_node

                                        info_message = "\n Creating GRelation ("+node.name+" -- "+rel_key+" -- "+str(json_document[key])+") ...\n"
                                        log_list.append(info_message)
                                        gr_node = create_grelation(subject_id, relation_type_node, json_document[key])
                                    except Exception as e:
                                        error_message = "\n While creating GRelation (" + rel_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n" + str(e) + "\n"
                                        log_list.append(error_message)
                                        pass

                                    if college_gst._id in relation_type_node.object_type:
                                        # Fetch college node's group id
                                        # Append it to node's group_set
                                        node_group_set = node.group_set
                                        is_group_set_changed = False

                                        # Iterate through each college
                                        # Find it's corresponding group's ObjectId
                                        # Append it to node's group_set
                                        for each in json_document[key]:
                                            each = ObjectId(each)
                                            each_str = str(each)
                                            if each_str in college_dict:
                                                college_group_id = college_dict[each_str]
                                                if college_group_id not in node_group_set:
                                                    node_group_set.append(college_group_id)
                                                    is_group_set_changed = True
                                            else:
                                                # If not found in college_dict
                                                # Then find and update college_dict
                                                college_node = node_collection.collection.aggregate([{
                                                    "$match": {"_id": each}
                                                }, {
                                                    "$project": {"group_id": "$relation_set.has_group"}
                                                }])

                                                college_node = college_node["result"]
                                                if college_node:
                                                    college_node = college_node[0]
                                                    college_group_id = college_node["group_id"]
                                                    if college_group_id:
                                                        college_group_id = college_group_id[0][0]
                                                        college_dict[each_str] = college_group_id
                                                        node_group_set.append(college_group_id)
                                                        is_group_set_changed = True

                                        # Update node's group_set with updated list
                                        # if changed
                                        if is_group_set_changed:
                                            node_collection.collection.update({
                                                "_id": subject_id
                                            }, {
                                                "$set": {"group_set": node_group_set}
                                            },
                                                upsert=False, multi=False
                                            )

                                    # To break outer for loop if key found
                                    break

                                else:
                                    error_message = "\n DataNotFound: No data found for relation ("+rel_key+") while creating GSystem ("+gsystem_type_name+" -- "+node.name+") !!!\n"
                                    log_list.append(error_message)
                                    # print error_message

                                    break

                # Create enrollment code (Only for Student)
                if create_student_enrollment_code and not node_repeated:
                    enrollment_code_at = node_collection.one({
                        "_type": "AttributeType", "name": "enrollment_code"
                    })

                    node_exist = node_collection.one({"_id": node._id, "attribute_set.enrollment_code": {"$exists": True}})
                    if not node_exist:
                        # It means enrollment_code is not set for given student node
                        # Then set it
                        try:
                            college_id = None
                            group_id = None
                            for k, v in college_dict.items():
                                college_id = ObjectId(k)
                                group_id = ObjectId(v)

                            student_enrollment_code = get_student_enrollment_code(college_id, node._id, json_document["date of registration"], group_id)

                            info_message = "\n Creating GAttribute (" + node.name + " -- " + enrollment_code_at.name + " -- " + str(student_enrollment_code) + ") ...\n"
                            log_list.append(info_message)
                            ga_node = create_gattribute(node._id, enrollment_code_at, student_enrollment_code)
                        except Exception as e:
                            error_message = "\n StudentEnrollmentCreateError: " + str(e) + "!!!"
                            log_list.append(error_message)

                elif create_private_college_group:
                    # Create a private group for respective college node
                    node_exist = node_collection.one({"_id": node._id, "relation_set.has_group": {"$exists": True}})
                    if not node_exist:
                        try:
                            info_message = "\n Creating private group for given college (" + node.name + ") via RelationType (has_group)...\n"
                            log_list.append(info_message)
                            college_group, college_group_gr = create_college_group_and_setup_data(node)
                        except Exception as e:
                            error_message = "\n CollegeGroupCreateError: " + str(e) + "!!!"
                            log_list.append(error_message)

        except Exception as e:
            error_message = "\n While creating "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e)
            log_list.append(error_message)
            print error_message # Keep it!
            import sys
            print "\n ****\n"
            print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
Esempio n. 31
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})

        if resource_name:
            unit_node['project_config'].update( {"resource_name":resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"resource_name":"Resources"})
        else:
            unit_node['project_config'].update( {"resource_name":"Resource Name"})

        if blog_name:
            unit_node['project_config'].update( {"blog_name":blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"blog_name":"e-Notes"})
        else:
            unit_node['project_config'].update( {"blog_name":"blog Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_content',
            kwargs={'group_id': unit_node._id}))
Esempio n. 32
0
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None):
  """
  Creates/Modifies document of given person-type.
  """
  auth = None
  if ObjectId.is_valid(group_id) is False :
    group_ins = node_collection.one({'_type': "Group", "name": group_id})
    auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    if group_ins:
      group_id = str(group_ins._id)
    else :
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
      if auth :
        group_id = str(auth._id)
  else :
    pass

  app = None
  if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:
    app = node_collection.one({'_id': ObjectId(app_id)})

  app_name = app.name 

  # app_name = "mis"
  app_set = ""
  app_collection_set = []
  title = ""

  person_gst = None
  person_gs = None
  college_node = None
  college_id = None
  student_enrollment_code = u""
  create_student_enrollment_code = False
  existing_colg = []
  registration_date = None

  property_order_list = []

  template = ""
  template_prefix = "mis"

  if request.user:
    if auth is None:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
    agency_type = auth.agency_type
    agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if agency_type_node:
      for eachset in agency_type_node.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))

  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  college_node = node_collection.one({
      "_id": ObjectId(group_id),
      "relation_set.group_of": {"$exists": True}
  }, {
      "relation_set.group_of": 1
  })

  if app_set_id:
    person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
    template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_create_edit.html"
    title = person_gst.name
    person_gs = node_collection.collection.GSystem()
    person_gs.member_of.append(person_gst._id)

  if app_set_instance_id:
    person_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})

  property_order_list = get_property_order_with_value(person_gs)#.property_order

  if request.method == "POST":
    if person_gst.name == "Student" and "_id" not in person_gs:
      create_student_enrollment_code = True

    # [A] Save person-node's base-field(s)
    is_changed = get_node_common_fields(request, person_gs, group_id, person_gst)

    if is_changed:
      # Remove this when publish button is setup on interface
      person_gs.status = u"PUBLISHED"

    person_gs.save(is_changed=is_changed,groupid=group_id)
    for each_rel in person_gs.relation_set:
      if each_rel and "officer_incharge_of" in each_rel:
        existing_colg = each_rel["officer_incharge_of"]
    if college_node:
        mis_admin = node_collection.one({
            "_type": "Group",
            "name": "MIS_admin"
        }, {
            "_id": 1
        }
        )

        node_collection.collection.update({
            "_id": person_gs._id
        }, {
            "$addToSet": {"group_set": mis_admin._id}
        },
        upsert=False, multi=False
        )

    # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # Fetch only Attribute field(s) / Relation field(s)
        if '_id' in field_set:
          field_instance = node_collection.one({'_id': field_set['_id']})
          fi_name = field_instance["name"]
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            field_data_type = field_set['data_type']

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                user_id = request.user.id
                if fi_name in request.FILES:
                  field_value = request.FILES[fi_name]

                else:
                  field_value = ""

                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = person_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              else:
                # Other AttributeTypes
                if fi_name in request.POST:
                    field_value = request.POST[fi_name]

              # field_instance_type = "GAttribute"
              if fi_name in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif fi_name in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
                registration_date = field_value
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")

              if field_value:
                person_gs_triple_instance = create_gattribute(person_gs._id, node_collection.collection.AttributeType(field_instance), field_value)

            else:
              if field_instance["object_cardinality"] > 1:
                field_value_list = request.POST.get(fi_name, "")
                if "[" in field_value_list and "]" in field_value_list:
                  field_value_list = json.loads(field_value_list)
                else:
                  field_value_list = request.POST.getlist(fi_name)

              else:
                field_value_list = request.POST.getlist(fi_name)

              if META_TYPE[3] in field_instance.member_of_names_list:
                # If Binary relationship found
                # [id, id, ...]
                # field_instance_type = "GRelation"
                for i, field_value in enumerate(field_value_list):
                  field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                  field_value_list[i] = field_value
              else:
                # Relationship Other than Binary one found; e.g, Triadic
                # [[id, id, ...], [id, id, ...], ...]
                # field_instance_type = "GRelation"
                for i, field_value_inner_list in enumerate(field_value_list):
                  for j, field_value in enumerate(field_value_inner_list):
                    field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                    field_value_list[i][j] = field_value

              person_gs_triple_instance = create_grelation(person_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)

    # Setting enrollment code for student node only while creating it
    if create_student_enrollment_code:
        # Create enrollment code for student node only while registering a new node
        for rel in college_node.relation_set:
          if rel and "group_of" in rel:
            college_id = rel["group_of"][0]

        student_enrollment_code = get_student_enrollment_code(college_id, person_gs._id, registration_date, ObjectId(group_id))

        enrollment_code_at = node_collection.one({
            "_type": "AttributeType", "name": "enrollment_code"
        })

        try:
            ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code)
        except Exception as e:
            print "\n StudentEnrollmentCreateError: " + str(e) + "!!!"

    # [C] Code to link GSystem Node and Author node via "has_login" relationship;
    #     and Subscribe the Author node to College group if user "Program Officer"
    person_gs.reload()
    auth_node = None
    for attr in person_gs.attribute_set:
      if "email_id" in attr:
        if attr["email_id"]:
          auth_node = node_collection.one({'_type': "Author", 'email': attr["email_id"].lower()})
          break

    if auth_node:
      has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"})
      if has_login_rt:
        # Linking GSystem Node and Author node via "has_login" relationship;
        gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id)

        # Set author_agency field's value of author node as "Program Officer"
        # Required to identify at time of log-in in order to display
        # required modules defined for Program Officers under MIS GApp
        if auth_node.agency_type != u"Program Officer":
          auth_node.agency_type = u"Program Officer"
          auth_node.save(groupid=group_id)

      if "Program Officer" in person_gs.member_of_names_list:
        # If Person node (GSystem) is of Program Officer type
        # then only go for subscription
        college_id_list = []
        # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of")
        for rel in person_gs.relation_set:
          if "officer_incharge_of" in rel:
            if rel["officer_incharge_of"]:
              for college_id in rel["officer_incharge_of"]:
                if college_id not in college_id_list:
                  college_id_list.append(college_id)
              break  # break outer-loop (of relation_set)

        if college_id_list:
          # If College's ObjectId exists (list as PO might be assigned to more than one college)
          # Then prepare a list of their corresponding private group(s) (via "has_group")
          college_cur = node_collection.find(
            {'_id': {'$in': college_id_list}},
            {'relation_set.has_group': 1}
          )

          college_group_id_list = []
          for college in college_cur:
            for rel in college.relation_set:
              if rel and "has_group" in rel:
                if rel["has_group"]:
                  if rel["has_group"][0] not in college_group_id_list:
                    college_group_id_list.append(rel["has_group"][0])

                  break  # break inner-loop (college.relation_set)

          if college_group_id_list:
            # If college-group list exists
            # Then update their group_admin field (append PO's created_by)
            res = node_collection.collection.update(
              {'_id': {'$in': college_group_id_list}},
              {'$addToSet': {'group_admin': auth_node.created_by}},
              upsert=False, multi=True
            )
        old_college_id_list = []
        if existing_colg:
          if len(existing_colg) > len(college_id_list):
            for each_colg_id in existing_colg:
              if each_colg_id not in college_id_list:
                old_college_id_list.append(each_colg_id)

            old_college_cur = node_collection.find(
              {'_id': {'$in': old_college_id_list}},
              {'relation_set.has_group': 1}
            )

            old_college_group_id_list = []
            for college in old_college_cur:
              for rel in college.relation_set:
                if rel and "has_group" in rel:
                  if rel["has_group"]:
                    if rel["has_group"][0] not in old_college_group_id_list:
                      old_college_group_id_list.append(rel["has_group"][0])

                    break  # break inner-loop (college.relation_set)

            if old_college_group_id_list:
              # If college-group list exists
              # Then update their group_admin field (remove PO's created_by)
              res = node_collection.collection.update(
                {'_id': {'$in': old_college_group_id_list}, '$or': [{'group_admin': auth_node.created_by},
                {'author_set': auth_node.created_by}]},
                {'$pull': {'group_admin': auth_node.created_by, 'author_set': auth_node.created_by}},
                upsert=False, multi=True
              )
              # The code below is commented as the college groups are PRIVATE.
              # for rel in person_gs.relation_set:
              #   if rel and "officer_incharge_of" in rel:
              #       pass
              #   else:
              #       node_collection.collection.update({'_id': auth_node._id},
              #       {'$set': {'agency_type': u"Other"}},
              #       upsert=False, multi=False
              #       )
              # Its purpose is to change the agency type back to Other

              auth_node.reload()
    # if person_gst.name != "Student":
    #     return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
    # else:
    return HttpResponseRedirect(reverse('mis:mis_app_instance_detail',kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id, "app_set_instance_id":unicode(person_gs._id)}))

    # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
  
  default_template = "ndf/person_create_edit.html"

  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'groupid': group_id, 'group_id': group_id,
                        'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title':title,
                        'property_order_list': property_order_list
                      }

  if person_gst and person_gst.name in ["Voluntary Teacher", "Master Trainer"]:
    nussd_course_type = node_collection.one({'_type': "AttributeType", 'name': "nussd_course_type"}, {'_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1})

    if nussd_course_type["data_type"] == "IS()":
      # Below code does little formatting, for example:
      # data_type: "IS()" complex_value: [u"ab", u"cd"] dt:
      # "IS(u'ab', u'cd')"
      dt = "IS("
      for v in nussd_course_type.complex_data_type:
          dt = dt + "u'" + v + "'" + ", " 
      dt = dt[:(dt.rfind(", "))] + ")"
      nussd_course_type["data_type"] = dt

    nussd_course_type["data_type"] = eval(nussd_course_type["data_type"])
    nussd_course_type["value"] = None
    context_variables['nussd_course_type'] = nussd_course_type

  if app_set_instance_id:
    person_gs.get_neighbourhood(person_gs.member_of)

    if "trainer_teaches_course_in_college" in person_gs:
      l = []
      for each_course_college in person_gs.trainer_teaches_course_in_college:
        # Fetch Course Type (i.e. nussd_course_type)
        ct = ""
        for each_attr in each_course_college[0].attribute_set:
          if "nussd_course_type" in each_attr and each_attr:
            ct = each_attr["nussd_course_type"]
            break

        univ_name = ""
        for each_rel in each_course_college[1].relation_set:
          if "college_affiliated_to" in each_rel and each_rel:
              univ = node_collection.find_one({"_id": {"$in": each_rel["college_affiliated_to"]}})
              univ_name = univ.name if univ else ""

        l.append((
            ct, each_course_college[0].name, each_course_college[1].name,
            each_course_college[0]._id.__str__(),
            each_course_college[1]._id.__str__(),
            univ_name
        ))
      if l:
        person_gs.trainer_teaches_course_in_college = l

    context_variables['node'] = person_gs

  try:
    return render_to_response([template, default_template], 
                              context_variables,
                              context_instance = RequestContext(request)
                            )

  except TemplateDoesNotExist as tde:
    error_message = "\n PersonCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n"
    raise Http404(error_message)

  except Exception as e:
    error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n"
    raise Exception(error_message)
Esempio n. 33
0
def node_create_edit(request,
                    group_id=None,
                    member_of=None,
                    detail_url_name=None,
                    node_type='GSystem',
                    node_id=None):
    '''
    creation as well as edit of node
    '''
    # check for POST method to node update operation
    if request.method == "POST":

        # put validations
        if node_type not in node_collection.db.connection._registered_documents.keys():
            raise ValueError('Improper node_type passed')

        kwargs={}
        group_name, group_id = Group.get_group_name_id(group_id)
        member_of_name, member_of_id = GSystemType.get_gst_name_id(member_of)

        if node_id: # existing node object
            node_obj = Node.get_node_by_id(node_id)

        else: # create new
            kwargs={
                    'group_set': group_id,
                    'member_of': member_of_id
                    }
            node_obj = node_collection.collection[node_type]()

        language = get_language_tuple(request.POST.get('language', None))
        node_obj.fill_gstystem_values(request=request,
                                    language=language,
                                            **kwargs)
        node_obj.save(group_id=group_id)
        node_id = node_obj['_id']

        # Consider for Blog page creation
        if member_of_name == "Page":
            blog_page_gst_name, blog_page_gst_id = GSystemType.get_gst_name_id("Blog page")
            if blog_page_gst_id in node_obj.type_of:
                discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"})
                create_gattribute(node_obj._id, discussion_enable_at, True)
                return_status = create_thread_for_node(request,group_id, node_obj)

                active_user_ids_list = [request.user.id]
                if GSTUDIO_BUDDY_LOGIN:
                    active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.datetime.now())
                # removing redundancy of user ids:
                active_user_ids_list = dict.fromkeys(active_user_ids_list).keys()
                counter_objs_cur = Counter.get_counter_objs_cur(active_user_ids_list, group_id)
                for each_counter_obj in counter_objs_cur:
                    each_counter_obj['page']['blog']['created'] += 1
                    each_counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS
                    each_counter_obj.last_update = datetime.datetime.now()
                    each_counter_obj.save()

        post_req = request.POST
        attrs_to_create_update = [f for f in post_req.keys() if ('attribute' in f)]
        attrs_to_create_update = [a.split('_')[1] for a in attrs_to_create_update]

        for each_attr_name in attrs_to_create_update:
            each_attr_name_obj = Node.get_name_id_from_type(each_attr_name, 'AttributeType', get_obj=True)
            post_req_attr_key = 'attribute_'+each_attr_name
            post_method = 'getlist' if (each_attr_name_obj.data_type in [list, 'list']) else 'get'
            create_gattribute(node_id,
                            each_attr_name_obj,
                            object_value=getattr(post_req, post_method)(post_req_attr_key))


        return HttpResponseRedirect(reverse(detail_url_name, kwargs={'group_id': group_id, 'node_id': node_id}))
Esempio n. 34
0
def update(request,rt_list,at_list,task_node,group_id,group_name):
      file_id=(request.POST.get("files"))
      file_name=(request.POST.get("files_name"))
      user_to_be_notified = []
      assignee_list = []
      change_list = []
      for each in rt_list:
        rel_type_node = node_collection.one({'_type': "RelationType", 'name': each})
        field_value_list = None

        if rel_type_node["object_cardinality"] > 1:
          field_value_list = request.POST.get(rel_type_node["name"], "")
          if "[" in field_value_list and "]" in field_value_list:
            field_value_list = json.loads(field_value_list)
          else:
            field_value_list = request.POST.getlist(rel_type_node["name"])

        else:
          field_value_list = request.POST.getlist(rel_type_node["name"])

        for i, field_value in enumerate(field_value_list):
          field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node)
          field_value_list[i] = field_value

        old_value = []
        for rel in task_node.relation_set:
          for k in rel:
            if rel_type_node.name == k:
              vals_cur = node_collection.find({'_id': {'$in': rel[k]}}, {'name': 1})
              for v_node in vals_cur:
                old_value.append(v_node.name)
                break

        new_value = []
        vals_cur = node_collection.find({'_id': {'$in': field_value_list}}, {'name': 1})
        for v_node in vals_cur:
          new_value.append(v_node.name)
          break

        if old_value != new_value:
          change_list.append(each.encode('utf8') + ' changed from ' + ", ".join(old_value) + ' to ' + ", ".join(new_value))  # updated  details

        task_gs_triple_instance = create_grelation(task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list)
        task_node.reload()

      for each in at_list:
        if request.POST.get(each, ""):
          attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': each})
          attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id})
          if each == "Assignee":
            field_value = request.POST.getlist(each, "")

            for i, val in enumerate(field_value):
              field_value[i] = int(val)

            assignee_list_id = field_value

            for eachuser in assignee_list_id:
              bx = User.objects.get(id=int(eachuser))

              if bx:
                if bx.username not in assignee_list:
                  assignee_list.append(bx.username)

                # Adding to list which holds user's to be notified about the task
                if bx not in user_to_be_notified:
                  user_to_be_notified.append(bx)

          else:
            field_value = request.POST.get(each, "")

            date_format_string = ""
            if each in ["start_time", "end_time"]:
              date_format_string = "%d/%m/%Y"

            field_value = parse_template_data(eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string)

          if attr: # already attribute exist
            if not attr.object_value == field_value:
              # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details
              if attributetype_key["data_type"] == "datetime.datetime":
                change_list.append(each.encode('utf8')+' changed from ' + attr.object_value.strftime("%d/%m/%Y") + ' to ' + field_value.strftime("%d/%m/%Y"))  # updated details

              else:
                change_list.append(each.encode('utf8')+' changed from ' + str(attr.object_value) + ' to ' + str(field_value))  # updated    details

              attr.object_value = field_value
              attr.save(groupid=group_id)

          else:
            # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each})
            # newattribute = triple_collection.collection.GAttribute()
            # newattribute.subject = task_node._id
            # newattribute.attribute_type = attributetype_key
            # newattribute.object_value = request.POST.get(each,"")
            # newattribute.object_value = field_value
            # newattribute.save()
            ga_node = create_gattribute(task_node._id, attributetype_key, field_value)
            # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details
            change_list.append(each.encode('utf8')+' set to '+str(field_value)) # updated details

        elif each == 'Upload_Task':
          attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': 'Upload_Task'})
          attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id})
          if attr:
            value=get_file_node(attr.object_value)
            change_list.append(each.encode('utf8')+' changed from '+str(value).strip('[]')+' to '+str(file_name))
            # attr.object_value=file_id
            # attr.save()
            ga_node = create_gattribute(attr.subject, attributetype_key, file_id)

          else:
            # newattribute = node_collection.collection.GAttribute()
            # newattribute.subject = task_node._id
            # newattribute.attribute_type = attributetype_key
            # newattribute.object_value = file_id
            # newattribute.save()
            ga_node = create_gattribute(task_node._id, attributetype_key, file_id)
            change_list.append(each.encode('utf8')+' set to '+file_name.encode('utf8')) # updated details

      # userobj = User.objects.get(id=task_node.created_by)
      # if userobj and userobj not in user_to_be_notified:
      #   user_to_be_notified.append(userobj)

      for each_author in task_node.author_set:
        each_author = User.objects.get(id=each_author)
        if each_author and each_author not in user_to_be_notified:
          user_to_be_notified.append(each_author)

      # Sending notification to all watchers about the updates of the task
      for eachuser in user_to_be_notified:
        activ="task updated"
        msg = "Task '" + task_node.name + \
          "' has been updated by " + request.user.username + \
          "\n     - Changes: " + str(change_list).strip('[]') + \
          "\n     - Status: " + request.POST.get('Status','') + \
          "\n     - Assignee: " + ", ".join(assignee_list) + \
          "\n     - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id)
        bx=User.objects.get(username=eachuser)
        set_notif_val(request,group_id,msg,activ,bx)

      if change_list or content_org:
        GST_task_update_history = node_collection.one({'_type': "GSystemType", 'name': 'task_update_history'})
        update_node = node_collection.collection.GSystem()
        get_node_common_fields(request, update_node, group_id, GST_task_update_history)
        if change_list:
          update_node.altnames = unicode(str(change_list))

        else:
          update_node.altnames = unicode('[]')

        update_node.prior_node = [task_node._id]
        update_node.name = unicode(task_node.name+"-update_history")
        update_node.save(groupid=group_id)
        update_node.name = unicode(task_node.name+"-update_history-"+str(update_node._id))
        update_node.save(groupid=group_id)
        task_node.post_node.append(update_node._id)
        task_node.save(groupid=group_id)

        # patch
        GST_TASK = node_collection.one({'_type': "GSystemType", 'name': 'Task'})
        get_node_common_fields(request, task_node, group_id, GST_TASK)
        task_node.save(groupid=group_id)
Esempio n. 35
0
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None):
  """
  View for handling Event and it's sub-types create-edit-view
  """
  auth = None
  # if ObjectId.is_valid(group_id) is False :
  #   group_ins = node_collection.one({'_type': "Group","name": group_id})
  #   auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #   if group_ins:
  #     group_id = str(group_ins._id)
  #   else :
  #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #     if auth :
  #       group_id = str(auth._id)
  # else :
  #   pass
  try:
        group_id = ObjectId(group_id)
  except:
        group_name, group_id = get_group_name_id(group_id)
  ''' 
  app = None
  if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:
    app = node_collection.one({'_id': ObjectId(app_id)})

  app_name = app.name 
  '''
  app_set = ""
  app_collection_set = []
  title = ""
  session_of=""
  module=""
  Add=""
  announced_course =""
  batch =""
  event_gst = None
  event_gs = None

  property_order_list = []

  template_prefix = "mis"

  '''if request.user:
    if auth is None:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
    agency_type = auth.agency_type
    Event_Types = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if Event_Types:
      for eachset in Event_Types.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      
  '''

  group_inverse_rel_id = [] 
  Group_type=node_collection.one({'_id':ObjectId(group_id)})
  for i in Group_type.relation_set:
       if unicode("group_of") in i.keys():
          group_inverse_rel_id = i['group_of']
  Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}})
  Eventtype='Eventtype'
  if Group_name:

      if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True:
           Eventtype='CollegeEvents'     
      else:
           Eventtype='Eventtype'
  Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"})
  Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1})
  app_collection_set=[]
  if Event_Types:
    for eachset in Event_Types.collection_set:
          app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      

  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  iteration=request.POST.get("iteration","")
  if iteration == "":
        iteration=1
  
        
  for i in range(int(iteration)):
   if app_set_id:
     event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
     title = event_gst.name
     event_gs = node_collection.collection.GSystem()
     event_gs.member_of.append(event_gst._id)

   if app_set_instance_id:
     event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
   property_order_list = get_property_order_with_value(event_gs)#.property_order
   
   if request.method == "POST":
    # [A] Save event-node's base-field(s)
    # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
    # get_node_common_fields(request, event_gs, group_id, event_gst)
    # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
    # print "\n event_gs: \n", event_gs.keys()
    # for k, v in event_gs.items():
    #   print "\n ", k, " -- ", v
    is_changed = get_node_common_fields(request, event_gs, group_id, event_gst)
    if is_changed:
      # Remove this when publish button is setup on interface
      event_gs.status = u"PUBLISHED"
    if (request.POST.get("name","")) == "":
        if i>0:
            field_value=request.POST.get('start_time'+"_"+str(i),'')  
        else:
            field_value = request.POST.get('start_time','')
        if event_gst.name == "Exam":
           name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value 
        else:
           name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value
        event_gs.name=name 
    
    event_gs.save(is_changed=is_changed,groupid=group_id)
    # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n"
  
    # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]}
        # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'}
        # print " ", field_set["name"]

        # * Fetch only Attribute field(s) / Relation field(s)
        
        if field_set.has_key('_id'):
          field_instance = node_collection.one({'_id': field_set['_id']})
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            
            if field_instance["name"] == "attendees":
              continue

            field_data_type = field_set['data_type']

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                
                if field_instance["name"] in request.FILES:
                  field_value = request.FILES[field_instance["name"]]
                  
                else:
                  field_value = ""
                
                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = event_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              if "date_month_day_year" in field_instance["validators"]:
                     if i>0:
                       field_value=request.POST.get(field_instance["name"]+"_"+str(i))  
                     else:
                        field_value = request.POST[field_instance["name"]]
                        
              else:
                # Other AttributeTypes 
                field_value = request.POST[field_instance["name"]]
              # field_instance_type = "GAttribute"
              # print "\n Parsing data for: ", field_instance["name"]
              if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif field_instance["name"] in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")
              
              if field_value:
                event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value)
                # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name

            else:
              field_value_list = request.POST.getlist(field_instance["name"])
              # field_instance_type = "GRelation"
              #code for creation of relation Session of 
              for i, field_value in enumerate(field_value_list):
                field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M")
                field_value_list[i] = field_value
              if field_value_list:
                event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)
              # if isinstance(event_gs_triple_instance, list):
              #   print "\n"
              #   for each in event_gs_triple_instance:
              #     print " event_gs_triple_instance: ", each._id, " -- ", each.name
              #   print "\n"

              # else:
              #   print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name
    # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id }))
    '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))'''
    if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
       if i==( (int(iteration))-1):
          #code to send mail to every one
          return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id}))
  
    else:
          to_user_list = []
          event_organizer_str = ""
          event_coordinator_str = ""
          event_organized_by = []
          event_coordinator = []
          event_node = node_collection.one({'_id':ObjectId(event_gs._id)})
          for i in event_node.relation_set:
             if unicode('event_organised_by') in i.keys():
                event_organized_by = i['event_organised_by']
             if unicode('has_attendees') in i.keys():
                event_attendees = i['has_attendees']
             if unicode('event_coordinator') in i.keys():
                event_coordinator = i['event_coordinator'] 
          event_url = "/"+str(group_id)+"/event/"+str(app_set_id) +"/"+str(event_node._id)
          site = Site.objects.get(pk=1)
          site = site.name.__str__()
          event_link = "http://" + site + event_url
          event_organized_by_cur = node_collection.find({"_id":{'$in':event_organized_by}})
          event_coordinator_cur = node_collection.find({"_id":{'$in':event_coordinator}})
          for i in event_coordinator_cur:
              event_coordinator_str = event_coordinator_str + i.name + "  "
          for i in event_organized_by_cur:
              event_organizer_str = event_coordinator_str + i.name + "  "     
          for j in event_attendees:
                      auth = node_collection.one({"_id":ObjectId(j)})
                      user_obj = User.objects.get(id=auth.created_by)
                      if user_obj not in to_user_list:
                              to_user_list.append(user_obj)
                      render_label = render_to_string(
                            "notification/label.html",
                            {
                                "sender": "metaStudio",
                                "activity": "Event Created",
                                "conjunction": "-"
                            })
          if event_organized_by:
             msg_string = "\n Event is organized by " + str ( event_organizer_str ) 
          else:
             msg_string = "" 
          notification.create_notice_type(render_label,"Invitation for Event"+ " " + str(event_node.name) + msg_string   + "\n Event will be co-ordinated by " +str (event_coordinator_str) 
                        + "\n- Please click [[" + event_link + "][here]] to view the details of the event" , "notification")
          notification.send(to_user_list, render_label, {"from_user":"******"})

          return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id}))
  event_attendees = request.POST.getlist('has_attendees','')

  
  event_gs.get_neighbourhood(event_gs.member_of)
  course=[]
  val=False
  for i in event_gs.relation_set:
       if unicode('event_has_batch') in i.keys():
            batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])})
            batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1})
            for i in batch_relation['relation_set']:
               if  unicode('has_course') in i.keys(): 
                   announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])})
                   for i in  announced_course.relation_set:
                      if unicode('announced_for') in i.keys():
                            course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])})
       if unicode('session_of') in i.keys(): 
                session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])})                     
                module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}})
  event_gs.event_coordinator
  Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"})
  if  Mis_admin:
    Mis_admin_list=Mis_admin.group_admin
    Mis_admin_list.append(Mis_admin.created_by)
    if request.user.id in Mis_admin_list:
        Add="Allow"  
    else: 
        Add= "Stop"
  else:
    Add="Stop"       

    
  if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
     template="ndf/Nussd_event_Schedule.html"
  else:
      template = "ndf/event_create_edit.html"
  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'group_id': group_id, 'groupid': group_id, 
                        'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title':title,
                        'property_order_list': property_order_list,
                        'Add':Add
                      }

  if app_set_instance_id:
    event_detail={}
    events={}
    if event_gs.event_coordinator:
      event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) 
      event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id)
      events["cordinator"]=event_detail
    if announced_course:
      event_detail["course"]=str(announced_course.name) 
      event_detail["course_id"]=str(announced_course._id)
      events["course"]=event_detail
    event_detail={}
    if batch:  
      event_detail["batchname"]=str(batch.name)
      event_detail["batchid"]=str(batch._id)
      events["batch"]=event_detail
    event_detail={}
    if session_of:
       event_detail["sessionname"]=str(session_of.name)
       event_detail["sessionid"]=str(session_of._id)
       for i in session_of.attribute_set:
         if unicode('course_structure_minutes') in i.keys():
          event_detail["sessionminutes"] = str(i['course_structure_minutes'])
       
       events["session"]=event_detail
    event_detail={}
    if module:
       event_detail["Modulename"]=str(module.name)
       event_detail["Moduleid"]=str(module._id)
       events["Module"]=event_detail
    context_variables['node'] = event_gs
    context_variables['edit_details']=events
    
    # print "\n template-list: ", [template, default_template]
    # template = "ndf/fgh.html"
    # default_template = "ndf/dsfjhk.html"
    # return render_to_response([template, default_template], 

  return render_to_response(template, 
                              context_variables,
                              context_instance = RequestContext(request)
                            )
    def handle(self, *args, **options):

        collection = get_database()[Node.collection_name]

        Event = collection.Node.find({
            "_type": "GSystemType",
            "name": {
                '$in': ["Classroom Session", "Exam"]
            }
        })

        yesterday = date.today() - timedelta(1)
        day_before_yesterday = date.today() - timedelta(2)
        date1 = datetime.date.today()
        ti = time(0, 0)
        Today = datetime.datetime.combine(date1, ti)
        yesterday = datetime.datetime.combine(yesterday, ti)
        day_before_yesterday = datetime.datetime.combine(
            day_before_yesterday, ti)
        no_of_days = 0

        #get the Mis Admin
        Mis_admin = collection.Node.one({
            "_type": "Group",
            "name": "MIS_admin"
        })
        Mis_admin_name = ""
        if Mis_admin:
            Mis_admin_list = Mis_admin.group_admin
            Mis_admin_list.append(Mis_admin.created_by)
            user_obj = User.objects.get(id=Mis_admin.created_by)
            Mis_admin_name = user_obj.username

        Attendance_Event = collection.Node.find({
            "member_of": {
                '$in': [ObjectId(Event[0]._id),
                        ObjectId(Event[1]._id)]
            },
            "attribute_set.start_time": {
                '$gte': day_before_yesterday,
                '$lt': Today
            }
        })

        rescheduled_Attendance_events = collection.Node.find({
            "member_of": {
                '$in': [ObjectId(Event[0]._id),
                        ObjectId(Event[1]._id)]
            },
            "attribute_set.reschedule_attendance.reschedule_till": {
                '$gt': yesterday
            }
        })

        rescheduled_events = collection.Node.find({
            "member_of": {
                '$in': [ObjectId(Event[0]._id),
                        ObjectId(Event[1]._id)]
            },
            "attribute_set.event_edit_reschedule.reschedule_till": {
                '$gt': yesterday
            }
        })

        Attendance_marked_event = collection.Node.find({
            "member_of": {
                '$in': [ObjectId(Event[0]._id),
                        ObjectId(Event[1]._id)]
            },
            "relation_set.has_attended": {
                "$exists": False
            },
            "attribute_set.start_time": {
                '$gte': yesterday,
                'lt': Today
            }
        })

        reschedule_attendance = collection.Node.one({
            "_type":
            "AttributeType",
            "name":
            "reschedule_attendance"
        })

        reschedule_event = collection.Node.one({
            "_type": "AttributeType",
            "name": "event_edit_reschedule"
        })

        reschedule_dates = {}
        for i in Attendance_Event:
            for j in i.attribute_set:
                if unicode('reschedule_attendance') in j.keys():
                    reschedule_dates = j['reschedule_attendance']
            reschedule_dates["reschedule_allow"] = False
            create_gattribute(ObjectId(i._id), reschedule_attendance,
                              reschedule_dates)

        reschedule_dates = {}
        for i in rescheduled_events:
            for j in i.attribute_set:
                if unicode('event_edit_reschedule') in j.keys():
                    reschedule_dates = j['event_edit_reschedule']
            reschedule_dates['reschedule_allow'] = False
            create_gattribute(ObjectId(i._id), reschedule_event,
                              reschedule_dates)

        reschedule_dates = {}
        for i in rescheduled_Attendance_events:
            for j in i.attribute_set:
                if unicode('reschedule_attendance') in j.keys():
                    reschedule_dates = j['reschedule_attendance']
                reschedule_dates["reschedule_allow"] = False
            create_gattribute(ObjectId(i._id), reschedule_attendance,
                              reschedule_dates)

        for i in Attendance_marked_event:
            event_status = collection.Node.one({
                "_type": "AttributeType",
                "name": "event_status"
            })
            create_gattribute(ObjectId(i._id), event_status,
                              unicode('Incomplete'))

            for j in i.attribute_set:
                if unicode("start_time") in j.keys():
                    if (j["start_time"] >= day_before_yesterday
                            and j["start_time"] < yesterday):
                        no_of_days = 2
                    if (j["start_time"] >= yesterday
                            and j["start_time"] < Today):
                        no_of_days = 1

            to_user_list = []
            #node is the node of the college Group
            node = collection.Node.one({
                "_type": "Group",
                "_id": {
                    '$in': i.group_set
                }
            })
            for j in node.group_admin:
                user_obj = User.objects.get(id=j)
                if user_obj not in to_user_list:
                    to_user_list.append(user_obj)
                render_label = render_to_string(
                    "notification/label.html", {
                        "sender": Mis_admin_name,
                        "activity": "Attendance not marked",
                        "conjunction": "-"
                    })
                notification.create_notice_type(
                    render_label, "Attendance is not marked for " + i.name +
                    " Event \n Attendance would be blocked after" +
                    str(no_of_days) + "days", "notification")
                notification.send(to_user_list, render_label,
                                  {"from_user": Mis_admin_name})
Esempio n. 37
0
 u'597ebd7b69602a0154bb417e', u'5945daf42c4796014ce12d2d', u'59aff39869602a0155bfac16']


try:
    module_obj_list = []
    for each_id in module_sort_order_ids:
        try:
            each_node = Node.get_node_by_id(ObjectId(each_id))
            if each_node:
                module_obj_list.append(each_node)
        except Exception as modulde_not_found_err:
            print "\nError in module_not_found for each_id: ", each_id, "\nError: ", modulde_not_found_err
            pass
    print "\nTotal modules: ", len(module_obj_list)
    home_grp_id = node_collection.one({'_type': 'Group', 'name': 'home'})._id
    create_gattribute(home_grp_id, 'items_sort_list', module_obj_list)
except Exception as module_sort_order_ids_err:
    pass
    print "\nError in module_sort_order_ids. ", module_sort_order_ids_err
units_cur = node_collection.find({'_type': 'Group', '_id': {'$in': units_for_renaming_leaf_nodes}})
for each_unit in units_cur:
    try:
        if each_unit:
            print "\nUnit: ", each_unit.name
            all_leaf_node_ids = dig_nodes_field(parent_node=each_unit, only_leaf_nodes=True)
            all_leaf_node_cur = node_collection.find({'_id': {'$in': all_leaf_node_ids}})
            print "\nLeaf nodes found: ", all_leaf_node_cur.count()
            for each_node in all_leaf_node_cur:
                name_val = each_node.name
                if name_val != each_node.altnames:
                    each_node.altnames = name_val # Unique name --> Display name
Esempio n. 38
0
def event_create_edit(request,
                      group_id,
                      app_set_id=None,
                      app_set_instance_id=None):
    """
  View for handling Event and it's sub-types create-edit-view
  """
    auth = None

    try:
        group_id = ObjectId(group_id)  #group_id is a valid ObjectId
    except:
        group_name, group_id = get_group_name_id(
            group_id
        )  #instead of group_id the name of the object is passed via URL to the function

    app_set = ""
    title = ""  #Stores the name of the type of event such as Meeting, Inauguration, etc.
    session_of = ""
    module = ""
    Add = ""
    announced_course = ""
    batch = ""
    event_gst = None
    event_gs = None

    property_order_list = []

    template_prefix = "mis"

    group_inverse_rel_id = []
    Group_type = node_collection.one(
        {'_id': ObjectId(group_id)}
    )  #instance of the group object in which the event is created e.g. "home" is a group
    for i in Group_type.relation_set:
        if unicode("group_of") in i.keys():
            group_inverse_rel_id = i['group_of']
    Group_name = node_collection.one({
        '_type': 'GSystem',
        '_id': {
            '$in': group_inverse_rel_id
        }
    })
    Eventtype = 'Eventtype'

    if Group_name:

        if (any(unicode('has_group') in d
                for d in Group_name.relation_set)) == True:
            Eventtype = 'CollegeEvents'
        else:
            Eventtype = 'Eventtype'

    Glisttype = node_collection.find({"_type": "GSystemType", "name": "GList"})
    Event_Types = node_collection.one(
        {
            "member_of": ObjectId(Glisttype[0]["_id"]),
            "name": Eventtype
        }, {'collection_set': 1}
    )  #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ...
    app_collection_set = [
    ]  #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list
    if Event_Types:
        for eachset in Event_Types.collection_set:
            app_collection_set.append(
                node_collection.one({"_id": eachset}, {
                    '_id': 1,
                    'name': 1,
                    'type_of': 1
                }))

    iteration = request.POST.get("iteration", "")
    if iteration == "":
        iteration = 1

    for i in range(int(iteration)):
        if app_set_id:
            event_gst = node_collection.one(
                {
                    '_type': "GSystemType",
                    '_id': ObjectId(app_set_id)
                }, {
                    'name': 1,
                    'type_of': 1
                }
            )  #GSystemType Object for the event corresponding to app_set_id e.g. Meeting
            title = event_gst.name
            event_gs = node_collection.collection.GSystem(
            )  #create a new GSystem Object for the Event
            event_gs.member_of.append(
                event_gst._id)  #event_gs is a member_of event_gst

        if app_set_instance_id:  #app_set_instance_id is the objectid of the event object which is already created
            event_gs = node_collection.one({
                '_type': "GSystem",
                '_id': ObjectId(app_set_instance_id)
            })
        property_order_list = get_property_order_with_value(
            event_gs
        )  #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc..

        if request.method == "POST":
            print "#####################"
            print request.POST.getlist(u'event_coordinator')
            print "#####################"
            # [A] Save event-node's base-field(s)
            # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
            # get_node_common_fields(request, event_gs, group_id, event_gst)
            # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys()
            # print "\n event_gs: \n", event_gs.keys()
            # for k, v in event_gs.items():
            #   print "\n ", k, " -- ", v
            is_changed = get_node_common_fields(request, event_gs, group_id,
                                                event_gst)
            if is_changed:
                # Remove this when publish button is setup on interface
                event_gs.status = u"PUBLISHED"
            if (request.POST.get("name", "")) == "":
                if i > 0:
                    field_value = request.POST.get('start_time' + "_" + str(i),
                                                   '')
                else:
                    field_value = request.POST.get('start_time', '')
                # print "----------------Field Value-----------"
                # print field_value
                if event_gst.name == "Exam":
                    name = "Exam" + "--" + slugify(
                        request.POST.get("batch_name",
                                         "")) + "--" + field_value
                else:
                    name = "Class" + "--" + slugify(
                        request.POST.get("course_name",
                                         "")) + "--" + field_value
                # print "-----------------Name------------------"
                # print name
                event_gs.name = name

            event_gs.save(is_changed=is_changed, groupid=group_id)
            # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n"

            # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs)
            for tab_details in property_order_list:
                for field_set in tab_details[1]:
                    print "##########################"
                    print "field_set:"
                    print field_set
                    print "##########################s"
                    # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]}
                    # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'}
                    # print " ", field_set["name"]

                    # * Fetch only Attribute field(s) / Relation field(s)

                    if field_set.has_key(
                            '_id'
                    ):  #Implies field_set is not a basefield but is an AT/RT
                        field_instance = node_collection.one(
                            {'_id': field_set['_id']}
                        )  #field_instance is an instance for AT or RT e.g. start_time
                        field_instance_type = type(field_instance)

                        if field_instance_type in [
                                AttributeType, RelationType
                        ]:

                            if field_instance["name"] == "attendees":
                                continue

                            field_data_type = field_set[
                                'data_type']  #data type of AT/RT e.g. datetime.datetime for start_time

                            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
                            if field_instance_type == AttributeType:
                                if "File" in field_instance["validators"]:
                                    # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used

                                    if field_instance["name"] in request.FILES:
                                        field_value = request.FILES[
                                            field_instance["name"]]

                                    else:
                                        field_value = ""

                                    # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                                    if field_value != '' and field_value != u'':
                                        file_name = event_gs.name + " -- " + field_instance[
                                            "altnames"]
                                        content_org = ""
                                        tags = ""
                                        field_value = save_file(
                                            field_value,
                                            file_name,
                                            request.user.id,
                                            group_id,
                                            content_org,
                                            tags,
                                            access_policy="PRIVATE",
                                            count=0,
                                            first_object="",
                                            oid=True)[0]

                                if "date_month_day_year" in field_instance[
                                        "validators"]:
                                    if i > 0:
                                        field_value = request.POST.get(
                                            field_instance["name"] + "_" +
                                            str(i))
                                    else:
                                        field_value = request.POST[
                                            field_instance["name"]]

                                else:
                                    # Other AttributeTypes
                                    field_value = request.POST[
                                        field_instance["name"]]
                                # field_instance_type = "GAttribute"
                                # print "\n Parsing data for: ", field_instance["name"]
                                if field_instance["name"] in [
                                        "12_passing_year",
                                        "degree_passing_year"
                                ]:  #, "registration_year"]:
                                    field_value = parse_template_data(
                                        field_data_type,
                                        field_value,
                                        date_format_string="%Y")
                                elif field_instance["name"] in [
                                        "dob", "registration_date"
                                ]:
                                    field_value = parse_template_data(
                                        field_data_type,
                                        field_value,
                                        date_format_string="%d/%m/%Y")
                                else:
                                    field_value = parse_template_data(
                                        field_data_type,
                                        field_value,
                                        date_format_string="%d/%m/%Y %H:%M")

                                if field_value:
                                    event_gs_triple_instance = create_gattribute(
                                        event_gs._id,
                                        node_collection.collection.
                                        AttributeType(field_instance),
                                        field_value)
                                    # print "--------------------------------------------------------------------------------------------------"
                                    # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name

                            else:  #field_instance_type == RelationType
                                field_value_list = request.POST.getlist(
                                    field_instance["name"])
                                # print "#######################"
                                # print field_value_list
                                # print "#######################"
                                # field_instance_type = "GRelation"
                                #code for creation of relation Session of
                                for i, field_value in enumerate(
                                        field_value_list):
                                    print "#######"
                                    print field_value
                                    print "#######"
                                    field_value = parse_template_data(
                                        ObjectId,
                                        field_value,
                                        field_instance=field_instance,
                                        date_format_string="%d/%m/%Y %H:%M")
                                    field_value_list[i] = field_value
                                if field_value_list:
                                    event_gs_triple_instance = create_grelation(
                                        event_gs._id,
                                        node_collection.collection.
                                        RelationType(field_instance),
                                        field_value_list)
                                # if isinstance(event_gs_triple_instance, list):
                                #   print "\n"
                                #   for each in event_gs_triple_instance:
                                #     print " event_gs_triple_instance: ", each._id, " -- ", each.name
                                #   print "\n"

                                # else:
                                #   print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name
            #End of for loop on property_order_list
            # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id }))
            '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))'''
            if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
                if i == ((int(iteration)) - 1):
                    #code to send mail to every one
                    return HttpResponseRedirect(
                        reverse('event_app_instance_detail',
                                kwargs={
                                    'group_id': group_id,
                                    "app_set_id": app_set_id,
                                    "app_set_instance_id": event_gs._id
                                }))

            else:
                to_user_list = []
                event_organizer_str = ""
                event_coordinator_str = ""
                event_organized_by = []
                event_attendees = []
                event_coordinator = []
                event_node = node_collection.one(
                    {'_id': ObjectId(event_gs._id)})
                for i in event_node.relation_set:
                    if unicode('event_organised_by') in i.keys():
                        event_organized_by = i['event_organised_by']
                    if unicode('has_attendees') in i.keys():
                        event_attendees = i['has_attendees']
                    if unicode('event_coordinator') in i.keys():
                        event_coordinator = i['event_coordinator']
                event_url = "/" + str(group_id) + "/event/" + str(
                    app_set_id) + "/" + str(event_node._id)
                site = Site.objects.get(pk=1)
                site = site.name.__str__()
                event_link = "http://" + site + event_url
                event_organized_by_cur = node_collection.find(
                    {"_id": {
                        '$in': event_organized_by
                    }})
                event_coordinator_cur = node_collection.find(
                    {"_id": {
                        '$in': event_coordinator
                    }})
                for i in event_coordinator_cur:
                    event_coordinator_str = event_coordinator_str + i.name + "  "
                for i in event_organized_by_cur:
                    event_organizer_str = event_coordinator_str + i.name + "  "
                for j in event_attendees:
                    auth = node_collection.one({"_id": ObjectId(j)})
                    user_obj = User.objects.get(id=auth.created_by)
                    if user_obj not in to_user_list:
                        to_user_list.append(user_obj)
                    render_label = render_to_string(
                        "notification/label.html", {
                            "sender": "metaStudio",
                            "activity": "Event Created",
                            "conjunction": "-"
                        })
                if event_organized_by:
                    msg_string = "\n Event is organized by " + str(
                        event_organizer_str)
                else:
                    msg_string = ""
                print "--------------------------"
                print event_node.name
                print event_node._id
                print "--------------------------"
                SALT = '8cd8ef52e8e101574e400365b55e11a6'
                URL = 'http://test-install.blindsidenetworks.com/bigbluebutton/'
                createMeeting(event_node.name, event_node._id, 'welcome',
                              'mPW', 'aPW', SALT, URL, 'www.google.com')
                url = joinURL(event_node._id, 'user', 'mPW', SALT, URL)
                event_node.url = unicode(url)
                event_node.save()
                # url_create = createMeetingURL(event_node.name, event_node._id, 'aPW', 'mPW', 'welcome', 'www.google.com', SALT , URL);
                print "##########"
                print event_node.url
                print "##########"
                # bbb_start(event_node.name, event_node._id)
                message_string = "Invitation for Event" + " " + str(
                    event_node.name
                ) + msg_string + "\n Event will be co-ordinated by " + str(
                    event_coordinator_str
                ) + "\n- Please click [[" + event_link + "][here]] to view the details of the event"
                message_string = "Hello World"
                notification.create_notice_type(
                    render_label, message_string, "notification"
                )  ##This is sent via email to all attendees in the group
                notification.send(to_user_list, render_label,
                                  {"from_user": "******"})

                return HttpResponseRedirect(
                    reverse('event_app_instance_detail',
                            kwargs={
                                'group_id': group_id,
                                "app_set_id": app_set_id,
                                "app_set_instance_id": event_node._id
                            }))
    event_attendees = request.POST.getlist('has_attendees', '')

    event_gs.get_neighbourhood(event_gs.member_of)
    course = []
    val = False
    for i in event_gs.relation_set:
        if unicode('event_has_batch') in i.keys():
            batch = node_collection.one({
                '_type':
                "GSystem",
                '_id':
                ObjectId(i['event_has_batch'][0])
            })
            batch_relation = node_collection.one(
                {
                    '_type': "GSystem",
                    '_id': ObjectId(batch._id)
                }, {'relation_set': 1})
            for i in batch_relation['relation_set']:
                if unicode('has_course') in i.keys():
                    announced_course = node_collection.one({
                        "_type":
                        "GSystem",
                        '_id':
                        ObjectId(i['has_course'][0])
                    })
                    for i in announced_course.relation_set:
                        if unicode('announced_for') in i.keys():
                            course = node_collection.one({
                                "_type":
                                "GSystem",
                                '_id':
                                ObjectId(i['announced_for'][0])
                            })
        if unicode('session_of') in i.keys():
            session_of = node_collection.one({
                '_type':
                "GSystem",
                '_id':
                ObjectId(i['session_of'][0])
            })
            module = node_collection.one({
                '_type': "GSystem",
                '_id': {
                    '$in': session_of.prior_node
                }
            })
    event_gs.event_coordinator
    Mis_admin = node_collection.one({"_type": "Group", "name": "MIS_admin"})
    if Mis_admin:
        Mis_admin_list = Mis_admin.group_admin
        Mis_admin_list.append(Mis_admin.created_by)
        if request.user.id in Mis_admin_list:
            Add = "Allow"
        else:
            Add = "Stop"
    else:
        Add = "Stop"

    if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam':
        template = "ndf/Nussd_event_Schedule.html"
    else:
        template = "ndf/event_create_edit.html"
    # default_template = "ndf/"+template_prefix+"_create_edit.html"
    context_variables = {
        'group_id': group_id,
        'groupid': group_id,
        'app_collection_set': app_collection_set,
        'app_set_id': app_set_id,
        'title': title,
        'property_order_list': property_order_list,
        'Add': Add
    }

    if app_set_instance_id:
        event_detail = {}
        events = {}
        if event_gs.event_coordinator:
            event_detail["cordinatorname"] = str(
                event_gs.event_coordinator[0].name)
            event_detail["cordinatorid"] = str(
                event_gs.event_coordinator[0]._id)
            events["cordinator"] = event_detail
        if announced_course:
            event_detail["course"] = str(announced_course.name)
            event_detail["course_id"] = str(announced_course._id)
            events["course"] = event_detail
        event_detail = {}
        if batch:
            event_detail["batchname"] = str(batch.name)
            event_detail["batchid"] = str(batch._id)
            events["batch"] = event_detail
        event_detail = {}
        if session_of:
            event_detail["sessionname"] = str(session_of.name)
            event_detail["sessionid"] = str(session_of._id)
            for i in session_of.attribute_set:
                if unicode('course_structure_minutes') in i.keys():
                    event_detail["sessionminutes"] = str(
                        i['course_structure_minutes'])

            events["session"] = event_detail
        event_detail = {}
        if module:
            event_detail["Modulename"] = str(module.name)
            event_detail["Moduleid"] = str(module._id)
            events["Module"] = event_detail
        context_variables['node'] = event_gs
        context_variables['edit_details'] = events

        # print "\n template-list: ", [template, default_template]
        # template = "ndf/fgh.html"
        # default_template = "ndf/dsfjhk.html"
        # return render_to_response([template, default_template],

    return render_to_response(template,
                              context_variables,
                              context_instance=RequestContext(request))
Esempio n. 39
0
def update(request, rt_list, at_list, task_node, group_id, group_name):
    file_id = (request.POST.get("files"))
    file_name = (request.POST.get("files_name"))
    user_to_be_notified = []
    assignee_list = []
    change_list = []
    for each in rt_list:
        rel_type_node = node_collection.one({
            '_type': "RelationType",
            'name': each
        })
        field_value_list = None

        if rel_type_node["object_cardinality"] > 1:
            field_value_list = request.POST.get(rel_type_node["name"], "")
            if "[" in field_value_list and "]" in field_value_list:
                field_value_list = json.loads(field_value_list)
            else:
                field_value_list = request.POST.getlist(rel_type_node["name"])

        else:
            field_value_list = request.POST.getlist(rel_type_node["name"])

        for i, field_value in enumerate(field_value_list):
            field_value = parse_template_data(rel_type_node.object_type,
                                              field_value,
                                              field_instance=rel_type_node)
            field_value_list[i] = field_value

        old_value = []
        for rel in task_node.relation_set:
            for k in rel:
                if rel_type_node.name == k:
                    vals_cur = node_collection.find({'_id': {
                        '$in': rel[k]
                    }}, {'name': 1})
                    for v_node in vals_cur:
                        old_value.append(v_node.name)
                        break

        new_value = []
        vals_cur = node_collection.find({'_id': {
            '$in': field_value_list
        }}, {'name': 1})
        for v_node in vals_cur:
            new_value.append(v_node.name)
            break

        if old_value != new_value:
            change_list.append(
                each.encode('utf8') + ' changed from ' + ", ".join(old_value) +
                ' to ' + ", ".join(new_value))  # updated  details

        task_gs_triple_instance = create_grelation(
            task_node._id,
            node_collection.collection.RelationType(rel_type_node),
            field_value_list)
        task_node.reload()

    for each in at_list:
        if request.POST.get(each, ""):
            attributetype_key = node_collection.find_one({
                "_type": 'AttributeType',
                'name': each
            })
            attr = triple_collection.find_one({
                "_type":
                "GAttribute",
                "subject":
                task_node._id,
                "attribute_type":
                attributetype_key._id
            })
            if each == "Assignee":
                field_value = request.POST.getlist(each, "")

                for i, val in enumerate(field_value):
                    field_value[i] = int(val)

                assignee_list_id = field_value

                for eachuser in assignee_list_id:
                    bx = User.objects.get(id=int(eachuser))

                    if bx:
                        if bx.username not in assignee_list:
                            assignee_list.append(bx.username)

                        # Adding to list which holds user's to be notified about the task
                        if bx not in user_to_be_notified:
                            user_to_be_notified.append(bx)

            else:
                field_value = request.POST.get(each, "")

                date_format_string = ""
                if each in ["start_time", "end_time"]:
                    date_format_string = "%d/%m/%Y"

                field_value = parse_template_data(
                    eval(attributetype_key["data_type"]),
                    field_value,
                    date_format_string=date_format_string)

            if attr:  # already attribute exist
                if not attr.object_value == field_value:
                    # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details
                    if attributetype_key["data_type"] == "datetime.datetime":
                        change_list.append(
                            each.encode('utf8') + ' changed from ' +
                            attr.object_value.strftime("%d/%m/%Y") + ' to ' +
                            field_value.strftime("%d/%m/%Y")
                        )  # updated details

                    else:
                        change_list.append(
                            each.encode('utf8') + ' changed from ' +
                            str(attr.object_value) + ' to ' +
                            str(field_value))  # updated    details

                    attr.object_value = field_value
                    attr.save(groupid=group_id)

            else:
                # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each})
                # newattribute = triple_collection.collection.GAttribute()
                # newattribute.subject = task_node._id
                # newattribute.attribute_type = attributetype_key
                # newattribute.object_value = request.POST.get(each,"")
                # newattribute.object_value = field_value
                # newattribute.save()
                ga_node = create_gattribute(task_node._id, attributetype_key,
                                            field_value)
                # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details
                change_list.append(
                    each.encode('utf8') + ' set to ' +
                    str(field_value))  # updated details

        elif each == 'Upload_Task':
            attributetype_key = node_collection.find_one({
                "_type": 'AttributeType',
                'name': 'Upload_Task'
            })
            attr = triple_collection.find_one({
                "_type":
                "GAttribute",
                "subject":
                task_node._id,
                "attribute_type":
                attributetype_key._id
            })
            if attr:
                value = get_file_node(attr.object_value)
                change_list.append(
                    each.encode('utf8') + ' changed from ' +
                    str(value).strip('[]') + ' to ' + str(file_name))
                # attr.object_value=file_id
                # attr.save()
                ga_node = create_gattribute(attr.subject, attributetype_key,
                                            file_id)

            else:
                # newattribute = node_collection.collection.GAttribute()
                # newattribute.subject = task_node._id
                # newattribute.attribute_type = attributetype_key
                # newattribute.object_value = file_id
                # newattribute.save()
                ga_node = create_gattribute(task_node._id, attributetype_key,
                                            file_id)
                change_list.append(
                    each.encode('utf8') + ' set to ' +
                    file_name.encode('utf8'))  # updated details

    # userobj = User.objects.get(id=task_node.created_by)
    # if userobj and userobj not in user_to_be_notified:
    #   user_to_be_notified.append(userobj)

    for each_author in task_node.author_set:
        each_author = User.objects.get(id=each_author)
        if each_author and each_author not in user_to_be_notified:
            user_to_be_notified.append(each_author)

    # Sending notification to all watchers about the updates of the task
    for eachuser in user_to_be_notified:
        activ = "task updated"
        msg = "Task '" + task_node.name + \
          "' has been updated by " + request.user.username + \
          "\n     - Changes: " + str(change_list).strip('[]') + \
          "\n     - Status: " + request.POST.get('Status','') + \
          "\n     - Assignee: " + ", ".join(assignee_list) + \
          "\n     - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id)
        bx = User.objects.get(username=eachuser)
        set_notif_val(request, group_id, msg, activ, bx)

    if change_list or content_org:
        GST_task_update_history = node_collection.one({
            '_type':
            "GSystemType",
            'name':
            'task_update_history'
        })
        update_node = node_collection.collection.GSystem()
        get_node_common_fields(request, update_node, group_id,
                               GST_task_update_history)
        if change_list:
            update_node.altnames = unicode(str(change_list))

        else:
            update_node.altnames = unicode('[]')

        update_node.prior_node = [task_node._id]
        update_node.name = unicode(task_node.name + "-update_history")
        update_node.save(groupid=group_id)
        update_node.name = unicode(task_node.name + "-update_history-" +
                                   str(update_node._id))
        update_node.save(groupid=group_id)
        task_node.post_node.append(update_node._id)
        task_node.save(groupid=group_id)

        # patch
        GST_TASK = node_collection.one({
            '_type': "GSystemType",
            'name': 'Task'
        })
        get_node_common_fields(request, task_node, group_id, GST_TASK)
        task_node.save(groupid=group_id)
def create_theme_topic_hierarchy(row):
    """
    
    Args:
        row (list): each row of CSV
        e.g: ["CR/XCR", "featured", "alignment", "content_org", "Theme name", "theme item name", .., .., .... , "topic"]
    
    Returns:
        TYPE: Description
    """

    # print row
    language = row[0]   # language field will get populated in this case.
    curricular = row[1] # CR or XCR
    featured = int(row[2])   # 0 or 1
    alignment = row[3]  # like NCF
    content_org = row[4]
    theme_name = row[5] # theme-name like National Curriculum
    # topic_name = row[-1:]

    # --- Theme processing ---

    # fetching a theme node
    theme_node = node_collection.one({
                                    'name': {'$regex': "^" + unicode(theme_name) + "$", '$options': 'i'},
                                    'group_set': {'$in': [home_group_id]},
                                    'member_of': theme_gst._id
                                })

    # creating a new theme node:
    if not theme_node:
        theme_node = create_object(name=theme_name, member_of_id=theme_gst._id, featured=bool(featured), language=language)

        info_message = "- Created New Object : "+ str(theme_node.name) + "\n"
        print info_message 
        log_list.append(str(info_message))


    # casting curricular field to bool:
    if curricular == "CR":
        curricular = True
    elif curricular == "XCR":
        curricular = False
    else:  # needs to be confirm
        curricular = False

    # if theme_node already has curricular as attribute, it will update it's value
    # otherwise it will create a new attribute:
    ga_node = create_gattribute(theme_node._id, curricular_at, curricular)

    info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
    print info_message 
    log_list.append(str(info_message))

    ga_node = create_gattribute(theme_node._id, alignment_at, unicode(alignment))

    info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
    print info_message 
    log_list.append(str(info_message))

    # --- END of Theme processing ---
    
    # --- theme-item and topic processing ---
    # from 5th item or 4rd index of row there will be start of theme-item and topic(at last)
    theme_item_topic_list = row[6:]
    
    # do not entertain any blank values here:
    theme_item_topic_list = [i for i in theme_item_topic_list if i]
    # print theme_item_topic_list

    topic_name = theme_item_topic_list.pop()  # Only 1 topic name, last item of row/list
    theme_item_list = theme_item_topic_list  # list of only theme-item name's, after pop

    # to initiate with parent node:
    parent_node = theme_node

    # theme-item procesing ---
    for each_theme_item in theme_item_list:
        # print each_theme_item

        # fetching a theme-item node
        theme_item_node = node_collection.one({
                                'name': {'$regex': "^" + unicode(each_theme_item) + "$", '$options': 'i'},
                                'group_set': {'$in': [home_group_id]},
                                'member_of': {'$in': [theme_item_gst._id]},
                                'prior_node': {'$in': [parent_node._id]}
                            })

        if not theme_item_node:
            
            theme_item_node = create_object(name=each_theme_item, member_of_id=theme_item_gst._id, prior_node_id=parent_node._id, language=language)
            
            info_message = "\n- Created theme-item : "+ str(theme_item_node.name) + "\n"
            print info_message 
            log_list.append(str(info_message))

        else: 
            info_message = "\n!! Theme Item : "+ str(theme_item_node.name) + " already exists!\n"
            print info_message 
            log_list.append(str(info_message))
        
        # cheking for current theme-item's _id in collection_set of parent_node
        if not theme_item_node._id in parent_node.collection_set: 
            add_to_collection_set(node_object=parent_node, id_to_be_added=theme_item_node._id)

        parent_node = theme_item_node

    # END of theme-item processing ---

    # topic processing ---

    # fetching a theme-item node
    topic_node = node_collection.one({
                        'name': {'$regex': "^" + unicode(topic_name) + "$", '$options': 'i'},
                        'group_set': {'$in': [home_group_id]},
                        'member_of': {'$in': [topic_gst._id]},
                        'prior_node': {'$in': [parent_node._id]}
                    })

    if not topic_node:
        topic_node = create_object(name=topic_name, \
                                 member_of_id=topic_gst._id, \
                                 prior_node_id=parent_node._id, \
                                 content_org=content_org,\
                                 language=language)

        info_message = "\n--- Created topic : "+ str(topic_node.name) + "\n"
        print info_message
        log_list.append(str(info_message))

    else:

        info_message = "\n!! Topic : "+ str(topic_node.name) + " already exists!\n"
        print info_message
        log_list.append(str(info_message))
        
    # cheking for current theme-item's _id in collection_set of parent_node
    if not topic_node._id in parent_node.collection_set:
        add_to_collection_set(node_object=parent_node, id_to_be_added=topic_node._id)
Esempio n. 41
0
def parse_data_create_gsystem(json_file_path):
    json_file_content = ""

    try:
        with open(json_file_path) as json_file:
            json_file_content = json_file.read()

        json_documents_list = json.loads(json_file_content)

        # Initiating empty node obj and other related data variables
        node = node_collection.collection.File()
        node_keys = node.keys()
        node_structure = node.structure
        # print "\n\n---------------", node_keys

        json_documents_list_spaces = json_documents_list
        json_documents_list = []

        # Removes leading and trailing spaces from keys as well as values
        for json_document_spaces in json_documents_list_spaces:
            json_document = {}

            for key_spaces, value_spaces in json_document_spaces.iteritems():
                json_document[key_spaces.strip().lower()] = value_spaces.strip()

            json_documents_list.append(json_document)

    except Exception as e:
        error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e)
        log_print(error_message)
        raise error_message

    for i, json_document in enumerate(json_documents_list):

        info_message = "\n\n\n********** Processing row number : ["+ str(i + 2) + "] **********"
        log_print(info_message)

        try:

            parsed_json_document = {}
            attribute_relation_list = []

            for key in json_document.iterkeys():
                parsed_key = key.lower()

                if parsed_key in node_keys:
                    # print parsed_key

                    # adding the default field values e.g: created_by, member_of
                    # created_by:
                    if parsed_key == "created_by":
                        if json_document[key]:
                            temp_user_id = get_user_id(json_document[key].strip())
                            if temp_user_id:
                                parsed_json_document[parsed_key] = temp_user_id
                            else:
                                parsed_json_document[parsed_key] = nroer_team_id
                        else:
                            parsed_json_document[parsed_key] = nroer_team_id
                        # print "---", parsed_json_document[parsed_key]

                    # contributors:
                    elif parsed_key == "contributors":
                        if json_document[key]:
                            contrib_list = json_document[key].split(",")

                            temp_contributors = []
                            for each_user in contrib_list:
                                user_id = get_user_id(each_user.strip())
                                if user_id:
                                    temp_contributors.append(user_id)

                            parsed_json_document[parsed_key] = temp_contributors
                        else:
                            parsed_json_document[parsed_key] = [nroer_team_id]
                            # print "===", parsed_json_document[parsed_key]

                    # tags:
                    elif (parsed_key == "tags") and json_document[key]:
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))
                        # print parsed_json_document[parsed_key]

                    # member_of:
                    elif parsed_key == "member_of":
                        parsed_json_document[parsed_key] = [file_gst._id]
                        # print parsed_json_document[parsed_key]

                      # --- END of adding the default field values

                    else:
                        # parsed_json_document[parsed_key] = json_document[key]
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))
                        # print parsed_json_document[parsed_key]

                    # --- END of processing for remaining fields

                else:  # key is not in the node_keys
                    parsed_json_document[key] = json_document[key]
                    attribute_relation_list.append(key)
                    # print "key : ", key

            # --END of for loop ---

            # calling method to create File GSystems
            node_obj = create_resource_gsystem(parsed_json_document, i)
            nodeid = node_obj._id if node_obj else None
            # print "nodeid : ", nodeid

            # ----- for updating language -----
            node_lang = get_language_tuple(eval(parsed_json_document['language']))
            # print "============= :", node_lang
            # print "============= lang :", node_obj.language

            if node_obj and node_obj.language != node_lang:

                update_res = node_collection.collection.update(
                                    {'_id': ObjectId(nodeid), 'language': {'$ne': node_lang}},
                                    {'$set': {'language': node_lang}},
                                    upsert=False,
                                    multi=False
                                )

                if update_res['updatedExisting']:
                    node_obj.reload()

                    info_message = "\n\n- Update to language of resource: " + str(update_res)
                    log_print(info_message)

                    info_message = "\n\n- Now language of resource updates to: " + str(node_obj.language)
                    log_print(info_message)
                # print "============= lang :", node_obj.language

            # ----- END of updating language -----


            collection_name = parsed_json_document.get('collection', '')

            if collection_name and nodeid:

                collection_node = node_collection.find_one({
                        # '_type': 'File',
                        'member_of': {'$in': [file_gst._id]},
                        'group_set': {'$in': [home_group._id]},
                        'name': unicode(collection_name)
                    })

                if collection_node:
                    add_to_collection_set(collection_node, nodeid)

            thumbnail_url = parsed_json_document.get('thumbnail')
            # print "thumbnail_url : ", thumbnail_url

            if thumbnail_url and nodeid:
                try:
                    info_message = "\n\n- Attaching thumbnail to resource\n"
                    log_print(info_message)
                    attach_resource_thumbnail(thumbnail_url, nodeid, parsed_json_document, i)

                except Exception, e:
                    print e

            # print type(nodeid), "-------", nodeid, "\n"

            # create thread node
            if isinstance(nodeid, ObjectId):
                thread_result = create_thread_obj(nodeid)

            # starting processing for the attributes and relations saving
            if isinstance(nodeid, ObjectId) and attribute_relation_list:

                node = node_collection.one({ "_id": ObjectId(nodeid) })

                gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id)
                # print gst_possible_attributes_dict

                relation_list = []
                json_document['name'] = node.name

                # Write code for setting atrributes
                for key in attribute_relation_list:

                    is_relation = True
                    # print "\n", key, "----------\n"

                    for attr_key, attr_value in gst_possible_attributes_dict.iteritems():
                        # print "\n", attr_key,"======", attr_value

                        if key == attr_key:
                            # print key
                            is_relation = False

                            # setting value to "0" for int, float, long (to avoid casting error)
                            # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]):
                            #     json_document[key] = 0

                            if json_document[key]:
                                # print "key : ", key, "\nvalue : ",json_document[key]

                                info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key]  + "'"
                                log_print(info_message)

                                cast_to_data_type(json_document[key], attr_value['data_type'])

                                if attr_value['data_type'] == "curricular":
                                    # setting int values for CR/XCR
                                    if json_document[key] == "CR":
                                        json_document[key] = 1
                                    elif json_document[key] == "XCR":
                                        json_document[key] = 0
                                    else:  # needs to be confirm
                                        json_document[key] = 0

                                    # json_document[key] = bool(int(json_document[key]))

                                # print attr_value['data_type'], "@@@@@@@@@  : ", json_document[key]
                                json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type'])
                                # print key, " !!!!!!!!!  : ", json_document[key]

                                subject_id = node._id
                                # print "\n-----\nsubject_id: ", subject_id
                                attribute_type_node = node_collection.one({
                                                                '_type': "AttributeType",
                                                                '$or': [
                                                                        {'name':
                                                                            {'$regex': "^"+attr_key+"$",
                                                                            '$options': 'i'}
                                                                        },
                                                                        {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'}
                                                                        }
                                                                    ]
                                                               })

                                # print "\nattribute_type_node: ", attribute_type_node.name
                                object_value = json_document[key]
                                # print "\nobject_value: ", object_value
                                ga_node = None

                                info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n"
                                log_print(info_message)

                                ga_node = create_gattribute(subject_id, attribute_type_node, object_value)

                                info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
                                log_print(info_message)

                                # To break outer for loop as key found
                                break

                            else:
                                error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n"
                                log_print(error_message)

                        # ---END of if (key == attr_key)

                    if is_relation:
                        relation_list.append(key)

                if not relation_list:
                    # No possible relations defined for this node
                    info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n"
                    log_print(info_message)
                    return

                gst_possible_relations_dict = node.get_possible_relations(file_gst._id)


                # processing each entry in relation_list
                # print "=== relation_list : ", relation_list

                for key in relation_list:
                  is_relation = True

                  for rel_key, rel_value in gst_possible_relations_dict.iteritems():
                    if key == rel_key:
                    # if key == "teaches":
                        is_relation = False

                        if json_document[key]:

                            # most often the data is hierarchy sep by ":"
                            if ":" in json_document[key]:
                                formatted_list = []
                                temp_teaches_list = json_document[key].replace("\n", "").split(":")
                                # print "\n temp_teaches", temp_teaches

                                for v in temp_teaches_list:
                                    formatted_list.append(v.strip())

                                right_subject_id = []
                                # print "~~~~~~~~~~~", formatted_list
                                # rsub_id = _get_id_from_hierarchy(formatted_list)
                                rsub_id = get_id_from_hierarchy(formatted_list)
                                # print "=== rsub_id : ", rsub_id
                                hierarchy_output = None

                                # checking every item in hierarchy exist and leaf node's _id found
                                if rsub_id:
                                    right_subject_id.append(rsub_id)
                                    json_document[key] = right_subject_id
                                    # print json_document[key]

                                else:
                                    error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + " cannot be created.\n"
                                    log_print(error_message)
                                    break

                            # sometimes direct leaf-node may be present without hierarchy and ":"
                            else:
                                formatted_list = list(json_document[key].strip())
                                right_subject_id = []
                                right_subject_id.append(_get_id_from_hierarchy(formatted_list))
                                json_document[key] = right_subject_id

                            # print "\n----------", json_document[key]
                            info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key])
                            log_print(info_message)
                            # print list(json_document[key])

                            # perform_eval_type(key, json_document, "GSystem", "GSystem")

                            for right_subject_id in json_document[key]:
                                # print "\njson_document[key]: ", json_document[key]

                                subject_id = node._id
                                # print "subject_id : ", subject_id
                                # print "node.name: ", node.name
                                # Here we are appending list of ObjectIds of GSystemType's type_of field
                                # along with the ObjectId of GSystemType's itself (whose GSystem is getting created)
                                # This is because some of the RelationType's are holding Base class's ObjectId
                                # and not that of the Derived one's
                                # Delibrately keeping GSystemType's ObjectId first in the list
                                # And hence, used $in operator in the query!
                                rel_subject_type = []
                                rel_subject_type.append(file_gst._id)

                                if file_gst.type_of:
                                    rel_subject_type.extend(file_gst.type_of)

                                relation_type_node = node_collection.one({'_type': "RelationType",
                                                                          '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}},
                                                                                  {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}],
                                                                          'subject_type': {'$in': rel_subject_type}
                                                                  })

                                right_subject_id_or_list = []
                                right_subject_id_or_list.append(ObjectId(right_subject_id))

                                nodes = triple_collection.find({'_type': "GRelation",
                                            'subject': subject_id,
                                            'relation_type.$id': relation_type_node._id
                                          })

                                # sending list of all the possible right subject to relation
                                for n in nodes:
                                    if not n.right_subject in right_subject_id_or_list:
                                        right_subject_id_or_list.append(n.right_subject)

                                info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..."
                                log_print(info_message)

                                gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list)

                                info_message = "\n- Grelation processing done.\n"
                                log_print(info_message)

                            # To break outer for loop if key found
                            break

                        else:
                            error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n"
                            log_print(error_message)

                            break

              # print relation_list
            else:
                info_message = "\n!! Either resource is already created or file is already saved into filehive/DB or file not found"
                log_print(info_message)

                continue

        except Exception as e:
            error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e)
            print "!!!!!!!!!!!!EEEEEEEERRRRRRRRRRRRRROOOOOOORRRRRRRRRRRRR......................"

            # file_error_msg = "\nFile with following details got an error: \n"
            file_error_msg = "\n========================" + " Row No : " + str(i + 2) + " ========================\n"
            # file_error_msg += "- Row No   : " + str(i + 2) + "\n"
            file_error_msg += "- Name     : " + json_document["name"] + "\n"
            file_error_msg += "- File Name: " + json_document["file_name"] + "\n"
            file_error_msg += "- ERROR    : " + str(e) + "\n\n"
            file_error_msg += "- Following are the row details : \n\n" + unicode(json.dumps(json_document, sort_keys=True, indent=4, ensure_ascii=False)) + "\n"
            file_error_msg += "============================================================\n\n\n"
            log_error_rows.append(file_error_msg)

            log_print(error_message)
Esempio n. 42
0
def setup_default_gapps():
    '''
  This sets up default GAPPS for group(s).
  '''

    default_gapps_names_list = [
        "Page", "File", "Forum", "MIS", "Task", "Batch", "Event"
    ]  # "Meeting"]
    info_message = "\n Default GAPPS names: " + str(default_gapps_names_list)

    # Fetch GAPPS and populate their document-node in a different list
    default_gapps_list = [
    ]  # Will hold document of each corresponding GAPP name from above given list
    meta_type_gapp = node_collection.one({
        '_type': "MetaType",
        'name': META_TYPE[0]
    })
    info_message += "\n Default GAPPS list: \n"
    for each in default_gapps_names_list:
        gapp_node = node_collection.one({
            '_type': "GSystemType",
            'member_of': meta_type_gapp._id,
            'name': each
        })

        if gapp_node:
            default_gapps_list.append(gapp_node)
            info_message += " " + gapp_node.name + "(" + str(
                gapp_node._id) + ")\n"

    log_list.append(info_message)

    # If length of list-of-names & list-of-documents doesn't match throw Exception
    if len(default_gapps_names_list) != len(default_gapps_list):
        error_message = "\n GAPPSSetupError: Few GAPPS not found!!!\n"
        log_list.append(error_message)
        raise Exception(error_message)

    # Fetch AttributeType node - apps_list
    at_apps_list = node_collection.one({
        '_type': "AttributeType",
        'name': "apps_list"
    })
    if not at_apps_list:
        error_message = "\n GAPPSSetupError: AttributeType (apps_list) doesn't exists.. please create explicitly!!!\n"
        log_list.append(error_message)
        raise Exception(error_message)
    info_message = "\n AttributeType: " + at_apps_list.name + "(" + str(
        at_apps_list._id) + ")\n"
    log_list.append(info_message)

    # Fetch MIS_admin group - required for fetching GSystems of College GSystemType
    mis_admin = node_collection.one(
        {
            '_type':
            "Group",
            '$or': [{
                'name': {
                    '$regex': u"MIS_admin",
                    '$options': 'i'
                }
            }, {
                'altnames': {
                    '$regex': u"MIS_admin",
                    '$options': 'i'
                }
            }],
            'group_type':
            "PRIVATE"
        }, {'name': 1})
    if not mis_admin:
        error_message = "\n GAPPSSetupError: Group (MIS_admin) doesn't exists.. please check!!!\n"
        log_list.append(error_message)
        raise Exception(error_message)
    info_message = "\n Group: " + mis_admin.name + "(" + str(
        mis_admin._id) + ")\n"
    log_list.append(info_message)

    # Fetch GSystems of College GSystemType belonging to MIS_admin group
    college = node_collection.one({
        '_type': "GSystemType",
        'name': u"College"
    }, {'name': 1})
    if not college:
        error_message = "\n GAPPSSetupError: GSystemType (College) doesn't exists.. please check!!!\n"
        log_list.append(error_message)
        raise Exception(error_message)
    info_message = "\n GSystemType: " + college.name + "(" + str(
        college._id) + ")\n"
    log_list.append(info_message)

    college_cur = list(
        node_collection.find({
            '_type': "GSystem",
            'member_of': college._id,
            'group_set': mis_admin._id
        }))

    for i, each in enumerate(college_cur):
        g = node_collection.one(
            {
                '_type': "Group",
                'name': each.name,
                'group_type': "PRIVATE"
            }, {'name': 1})
        if g:
            info_message = "\n " + str(
                i + 1
            ) + ") Setting GAPPS for this college group (" + g.name + " -- " + str(
                g._id) + ")\n"
            log_list.append(info_message)

            is_apps_list = triple_collection.one({
                '_type':
                "GAttribute",
                'subject':
                g._id,
                'attribute_type':
                at_apps_list._id
            })
            if is_apps_list:
                info_message = " Default GAPPs list already exists for Group (" + g.name + " -- " + str(
                    g._id) + "), so overriding it..."
                log_list.append(info_message)
                res = triple_collection.collection.update(
                    {'_id': is_apps_list._id},
                    {'$set': {
                        'object_value': default_gapps_list
                    }},
                    upsert=False,
                    multi=False)
                if res["n"]:
                    is_apps_list.reload()
                    info_message = "\n Successfully overridden: " + str(
                        is_apps_list._id) + "\n"
                    log_list.append(info_message)
                else:
                    info_message = "\n Not overridden: " + str(
                        is_apps_list._id) + "\n"
                    log_list.append(info_message)

            else:
                info_message = " Default GAPPs list doesn't exists for Group (" + g.name + " -- " + str(
                    g._id) + "), so creating..."
                log_list.append(info_message)
                ga = create_gattribute(g._id, at_apps_list, default_gapps_list)
                info_message = "\n Successfully created: " + str(ga._id) + "\n"
                log_list.append(info_message)

        else:
            error_message = "\n GAPPSSetupError: This college group (" + each.name + ") doesn't exists.. please create explicitly!!!\n"
            log_list.append(error_message)
from gnowsys_ndf.ndf.models import *
from gnowsys_ndf.ndf.views.methods import create_gattribute
try:
	page_gst = node_collection.one({'_type': "GSystemType", 'name': "Page"})
	blogpage_gst = node_collection.one({'_type': "GSystemType", 'name': "Blog page"})
	blog_pages = node_collection.find({'member_of':page_gst._id, 'type_of': blogpage_gst._id}).sort('created_at', -1)
	twist_gst = node_collection.one({'_type': 'GSystemType', 'name': 'Twist'})
	rel_resp_at = node_collection.one({'_type': 'AttributeType', 'name': 'release_response'})
	print "\n Total blog pages found: ",blog_pages.count()

	for each_blog_page in blog_pages:
		if each_blog_page.relation_set:
			for each_rel in each_blog_page.relation_set:
				if each_rel and "has_thread" in each_rel:
					thread_node_obj = node_collection.one({'_id': ObjectId(each_rel['has_thread'][0])})
					if thread_node_obj:
						if thread_node_obj.attribute_set:
							create_gattribute(thread_node_obj._id, rel_resp_at, True)
except Exception as e:
	print "\n Exception occurred : ", str(e), " !!!"
	pass

Esempio n. 44
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {'$in': [unit_id]}
            })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_about',
            kwargs={'group_id': unit_node._id}))
def parse_data_create_gsystem(json_file_path):
    json_file_content = ""

    try:
        with open(json_file_path) as json_file:
            json_file_content = json_file.read()

        json_documents_list = json.loads(json_file_content)

        # Initiating empty node obj and other related data variables
        node = node_collection.collection.GSystem()
        node_keys = node.keys()
        node_structure = node.structure
        # print "\n\n---------------", node_keys

        json_documents_list_spaces = json_documents_list
        json_documents_list = []

        # Removes leading and trailing spaces from keys as well as values
        for json_document_spaces in json_documents_list_spaces:
            json_document = {}

            for key_spaces, value_spaces in json_document_spaces.iteritems():
                json_document[key_spaces.strip().lower()] = value_spaces.strip()

            json_documents_list.append(json_document)

    except Exception as e:
        error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e)
        log_print(error_message)
        raise error_message

    for i, json_document in enumerate(json_documents_list):

        info_message = "\n\n\n********** Processing row number : ["+ str(i + 2) + "] **********"
        log_print(info_message)

        try:

            parsed_json_document = {}
            attribute_relation_list = []

            for key in json_document.iterkeys():
                parsed_key = key.lower()

                if parsed_key in node_keys:
                    # print parsed_key

                    # adding the default field values e.g: created_by, member_of
                    # created_by:
                    if parsed_key == "created_by":
                        if json_document[key]:
                            temp_user_id = get_user_id(json_document[key].strip())
                            if temp_user_id:
                                parsed_json_document[parsed_key] = temp_user_id
                            else:
                                parsed_json_document[parsed_key] = nroer_team_id
                        else:
                            parsed_json_document[parsed_key] = nroer_team_id
                        # print "---", parsed_json_document[parsed_key]

                    # contributors:
                    elif parsed_key == "contributors":
                        if json_document[key]:
                            contrib_list = json_document[key].split(",")

                            temp_contributors = []
                            for each_user in contrib_list:
                                user_id = get_user_id(each_user.strip())
                                if user_id:
                                    temp_contributors.append(user_id)

                            parsed_json_document[parsed_key] = temp_contributors
                        else:
                            parsed_json_document[parsed_key] = [nroer_team_id]
                            # print "===", parsed_json_document[parsed_key]

                    # tags:
                    elif (parsed_key == "tags") and json_document[key]:
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))
                        # print parsed_json_document[parsed_key]

                    # member_of:
                    elif parsed_key == "member_of":
                        parsed_json_document[parsed_key] = [file_gst._id]
                        # print parsed_json_document[parsed_key]

                      # --- END of adding the default field values

                    else:
                        # parsed_json_document[parsed_key] = json_document[key]
                        parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key))
                        # print parsed_json_document[parsed_key]

                    # --- END of processing for remaining fields

                else:  # key is not in the node_keys
                    parsed_json_document[key] = json_document[key]
                    attribute_relation_list.append(key)
                    # print "key : ", key

            # --END of for loop ---

            # calling method to create File GSystems
            node_obj = create_resource_gsystem(parsed_json_document, i)
            nodeid = node_obj._id if node_obj else None
            # print "nodeid : ", nodeid

            # ----- for updating language -----
            # node_lang = get_language_tuple(eval(parsed_json_document['language']))
            # print "============= :", node_lang
            # print "============= lang :", node_obj.language

            # if node_obj and node_obj.language != node_lang:

            #     update_res = node_collection.collection.update(
            #                         {'_id': ObjectId(nodeid), 'language': {'$ne': node_lang}},
            #                         {'$set': {'language': node_lang}},
            #                         upsert=False,
            #                         multi=False
            #                     )

            #     if update_res['updatedExisting']:
            #         node_obj.reload()

            #         info_message = "\n\n- Update to language of resource: " + str(update_res)
            #         log_print(info_message)

            #         info_message = "\n\n- Now language of resource updates to: " + str(node_obj.language)
            #         log_print(info_message)
                # print "============= lang :", node_obj.language

            # ----- END of updating language -----

            collection_name = parsed_json_document.get('collection', '')

            if collection_name and nodeid:

                collection_node = node_collection.find_one({
                        # '_type': 'File',
                        'member_of': {'$in': [file_gst._id]},
                        'group_set': {'$in': [home_group._id]},
                        'name': unicode(collection_name)
                    })

                if collection_node:
                    add_to_collection_set(collection_node, nodeid)

            thumbnail_url = parsed_json_document.get('thumbnail')
            # print "thumbnail_url : ", thumbnail_url

            if (thumbnail_url and nodeid) and (thumbnail_url != parsed_json_document.get('thumbnail') ):
                try:
                    info_message = "\n\n- Attaching thumbnail to resource\n"
                    log_print(info_message)
                    attach_resource_thumbnail(thumbnail_url, nodeid, parsed_json_document, i)

                except Exception, e:
                    print e

            # print type(nodeid), "-------", nodeid, "\n"
            if (thumbnail_url == parsed_json_document.get('resource_link')) and (warehouse_group._id in node_obj.group_set) :
                for i,each_groupid in enumerate(node_obj.group_set):
                    if each_groupid == warehouse_group._id:
                        node_obj.group_set.pop(i)
                if home_group._id not in node_obj.group_set:
                    node_obj.group_set.append(home_group._id)
                node_obj.save()

        # create thread node
            if isinstance(nodeid, ObjectId):
                thread_result = create_thread_obj(nodeid)

            # starting processing for the attributes and relations saving
            if isinstance(nodeid, ObjectId) and attribute_relation_list:

                node = node_collection.one({ "_id": ObjectId(nodeid) })

                gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id)
                # print gst_possible_attributes_dict

                relation_list = []
                json_document['name'] = node.name

                # Write code for setting atrributes
                for key in attribute_relation_list:

                    is_relation = True
                    # print "\n", key, "----------\n"

                    for attr_key, attr_value in gst_possible_attributes_dict.iteritems():
                        # print "\n", attr_key,"======", attr_value

                        if key == attr_key:
                            # print key
                            is_relation = False

                            # setting value to "0" for int, float, long (to avoid casting error)
                            # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]):
                            #     json_document[key] = 0

                            if json_document[key]:
                                # print "key : ", key, "\nvalue : ",json_document[key]

                                info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key]  + "'"
                                log_print(info_message)

                                cast_to_data_type(json_document[key], attr_value['data_type'])

                                if attr_value['data_type'] == "curricular":
                                    # setting int values for CR/XCR
                                    if json_document[key] == "CR":
                                        json_document[key] = 1
                                    elif json_document[key] == "XCR":
                                        json_document[key] = 0
                                    else:  # needs to be confirm
                                        json_document[key] = 0

                                    # json_document[key] = bool(int(json_document[key]))

                                # print attr_value['data_type'], "@@@@@@@@@  : ", json_document[key]
                                json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type'])
                                # print key, " !!!!!!!!!  : ", json_document[key]

                                subject_id = node._id
                                # print "\n-----\nsubject_id: ", subject_id
                                attribute_type_node = node_collection.one({
                                                                '_type': "AttributeType",
                                                                '$or': [
                                                                        {'name':
                                                                            {'$regex': "^"+attr_key+"$",
                                                                            '$options': 'i'}
                                                                        },
                                                                        {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'}
                                                                        }
                                                                    ]
                                                               })

                                # print "\nattribute_type_node: ", attribute_type_node.name
                                object_value = json_document[key]
                                # print "\nobject_value: ", object_value
                                ga_node = None

                                info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n"
                                log_print(info_message)

                                ga_node = create_gattribute(subject_id, attribute_type_node, object_value)

                                info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
                                log_print(info_message)

                                # To break outer for loop as key found
                                break

                            else:
                                error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n"
                                log_print(error_message)

                        # ---END of if (key == attr_key)

                    if is_relation:
                        relation_list.append(key)

                if not relation_list:
                    # No possible relations defined for this node
                    info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n"
                    log_print(info_message)
                    return

                gst_possible_relations_dict = node.get_possible_relations(file_gst._id)

                # processing each entry in relation_list
                # print "=== relation_list : ", relation_list

                for key in relation_list:
                  is_relation = True

                  for rel_key, rel_value in gst_possible_relations_dict.iteritems():
                    if key == rel_key:
                    # if key == "teaches":
                        is_relation = False

                        if json_document[key]:

                            # most often the data is hierarchy sep by ":"
                            if ":" in json_document[key]:
                                formatted_list = []
                                temp_teaches_list = json_document[key].replace("\n", "").split(":")
                                # print "\n temp_teaches", temp_teaches

                                for v in temp_teaches_list:
                                    formatted_list.append(v.strip())

                                right_subject_id = []
                                # print "~~~~~~~~~~~", formatted_list
                                # rsub_id = _get_id_from_hierarchy(formatted_list)
                                rsub_id = get_id_from_hierarchy(formatted_list)
                                # print "=== rsub_id : ", rsub_id
                                hierarchy_output = None

                                # checking every item in hierarchy exist and leaf node's _id found
                                if rsub_id:
                                    right_subject_id.append(rsub_id)
                                    json_document[key] = right_subject_id
                                    # print json_document[key]

                                else:
                                    error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + " cannot be created.\n"
                                    log_print(error_message)
                                    break

                            # sometimes direct leaf-node may be present without hierarchy and ":"
                            else:
                                formatted_list = list(json_document[key].strip())
                                right_subject_id = []
                                right_subject_id.append(_get_id_from_hierarchy(formatted_list))
                                json_document[key] = right_subject_id

                            # print "\n----------", json_document[key]
                            info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key])
                            log_print(info_message)
                            # print list(json_document[key])

                            # perform_eval_type(key, json_document, "GSystem", "GSystem")

                            for right_subject_id in json_document[key]:
                                # print "\njson_document[key]: ", json_document[key]

                                subject_id = node._id
                                # print "subject_id : ", subject_id
                                # print "node.name: ", node.name
                                # Here we are appending list of ObjectIds of GSystemType's type_of field
                                # along with the ObjectId of GSystemType's itself (whose GSystem is getting created)
                                # This is because some of the RelationType's are holding Base class's ObjectId
                                # and not that of the Derived one's
                                # Delibrately keeping GSystemType's ObjectId first in the list
                                # And hence, used $in operator in the query!
                                rel_subject_type = []
                                rel_subject_type.append(file_gst._id)

                                if file_gst.type_of:
                                    rel_subject_type.extend(file_gst.type_of)

                                relation_type_node = node_collection.one({'_type': "RelationType",
                                                                          '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}},
                                                                                  {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}],
                                                                          'subject_type': {'$in': rel_subject_type}
                                                                  })

                                right_subject_id_or_list = []
                                right_subject_id_or_list.append(ObjectId(right_subject_id))

                                nodes = triple_collection.find({'_type': "GRelation",
                                            'subject': subject_id,
                                            'relation_type': relation_type_node._id
                                          })

                                # sending list of all the possible right subject to relation
                                for n in nodes:
                                    if not n.right_subject in right_subject_id_or_list:
                                        right_subject_id_or_list.append(n.right_subject)

                                info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..."
                                log_print(info_message)

                                gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list)

                                info_message = "\n- Grelation processing done.\n"
                                log_print(info_message)

                            # To break outer for loop if key found
                            break

                        else:
                            error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n"
                            log_print(error_message)

                            break

              # print relation_list
            else:
                info_message = "\n!! Either resource is already created or file is already saved into filehive/DB or file not found"
                log_print(info_message)

                continue

        except Exception as e:
            error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e)
            print "!!!!!!!!!!!!EEEEEEEERRRRRRRRRRRRRROOOOOOORRRRRRRRRRRRR......................"

            # file_error_msg = "\nFile with following details got an error: \n"
            file_error_msg = "\n========================" + " Row No : " + str(i + 2) + " ========================\n"
            # file_error_msg += "- Row No   : " + str(i + 2) + "\n"
            file_error_msg += "- Name     : " + json_document["name"] + "\n"
            file_error_msg += "- File Name: " + json_document["file_name"] + "\n"
            file_error_msg += "- ERROR    : " + str(e) + "\n\n"
            file_error_msg += "- Following are the row details : \n\n" + unicode(json.dumps(json_document, sort_keys=True, indent=4, ensure_ascii=False)) + "\n"
            file_error_msg += "============================================================\n\n\n"
            log_error_rows.append(file_error_msg)

            log_print(error_message)
Esempio n. 46
0
    subj_id = node_and_del_thread[each_th_obj._id]
    pub_has_thread_grel = triple_collection.find_one({
        'relation_type':
        has_thread_rt._id,
        'subject':
        subj_id,
        'status':
        'PUBLISHED'
    })
    # print "\n ObjectId(pub_has_thread_grel.right_subject): ", ObjectId(pub_has_thread_grel.right_subject)

    triples_of_del_th = triple_collection.find({
        'subject': each_th_obj._id,
        '_type': 'GAttribute'
    })
    print create_gattribute(ObjectId(pub_has_thread_grel.right_subject),
                            'release_response', True)
    # triple_collection.collection.update({'subject': each_th_obj._id, '_type': 'GAttribute'},
    # {'$set': {'subject': ObjectId(pub_has_thread_grel.right_subject)}},upsert=False, multi=True)
    pub_thread_res = node_collection.collection.update(
        {'_id': ObjectId(pub_has_thread_grel.right_subject)},
        {'$addToSet': {
            'author_set': {
                '$each': each_th_obj.author_set
            }
        }},
        upsert=False,
        multi=False)
    print "\nPublished Thread updates result: ", pub_thread_res
    del_thread_replies = node_collection.collection.update(
        {
            'prior_node': each_th_obj._id,
Esempio n. 47
0
def person_create_edit(request,
                       group_id,
                       app_id,
                       app_set_id=None,
                       app_set_instance_id=None,
                       app_name=None):
    """
  Creates/Modifies document of given person-type.
  """
    auth = None
    if ObjectId.is_valid(group_id) is False:
        group_ins = node_collection.one({'_type': "Group", "name": group_id})
        auth = node_collection.one({
            '_type': 'Author',
            'name': unicode(request.user.username)
        })
        if group_ins:
            group_id = str(group_ins._id)
        else:
            auth = node_collection.one({
                '_type': 'Author',
                'name': unicode(request.user.username)
            })
            if auth:
                group_id = str(auth._id)
    else:
        pass

    app = None
    if app_id is None:
        app = node_collection.one({'_type': "GSystemType", 'name': app_name})
        if app:
            app_id = str(app._id)
    else:
        app = node_collection.one({'_id': ObjectId(app_id)})

    app_name = app.name

    # app_name = "mis"
    app_set = ""
    app_collection_set = []
    title = ""

    person_gst = None
    person_gs = None
    college_node = None
    college_id = None
    student_enrollment_code = u""
    create_student_enrollment_code = False
    existing_colg = []
    registration_date = None

    property_order_list = []

    template = ""
    template_prefix = "mis"

    if request.user:
        if auth is None:
            auth = node_collection.one({
                '_type': 'Author',
                'name': unicode(request.user.username)
            })
        agency_type = auth.agency_type
        agency_type_node = node_collection.one(
            {
                '_type': "GSystemType",
                'name': agency_type
            }, {'collection_set': 1})
        if agency_type_node:
            for eachset in agency_type_node.collection_set:
                app_collection_set.append(
                    node_collection.one({"_id": eachset}, {
                        '_id': 1,
                        'name': 1,
                        'type_of': 1
                    }))

    # for eachset in app.collection_set:
    #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
    college_node = node_collection.one(
        {
            "_id": ObjectId(group_id),
            "relation_set.group_of": {
                "$exists": True
            }
        }, {"relation_set.group_of": 1})

    if app_set_id:
        person_gst = node_collection.one(
            {
                '_type': "GSystemType",
                '_id': ObjectId(app_set_id)
            }, {
                'name': 1,
                'type_of': 1
            })
        template = "ndf/" + person_gst.name.strip().lower().replace(
            ' ', '_') + "_create_edit.html"
        title = person_gst.name
        person_gs = node_collection.collection.GSystem()
        person_gs.member_of.append(person_gst._id)

    if app_set_instance_id:
        person_gs = node_collection.one({
            '_type': "GSystem",
            '_id': ObjectId(app_set_instance_id)
        })

    property_order_list = get_property_order_with_value(
        person_gs)  #.property_order

    if request.method == "POST":
        if person_gst.name == "Student" and "_id" not in person_gs:
            create_student_enrollment_code = True

        # [A] Save person-node's base-field(s)
        is_changed = get_node_common_fields(request, person_gs, group_id,
                                            person_gst)

        if is_changed:
            # Remove this when publish button is setup on interface
            person_gs.status = u"PUBLISHED"

        person_gs.save(is_changed=is_changed, groupid=group_id)
        for each_rel in person_gs.relation_set:
            if each_rel and "officer_incharge_of" in each_rel:
                existing_colg = each_rel["officer_incharge_of"]
        if college_node:
            mis_admin = node_collection.one(
                {
                    "_type": "Group",
                    "name": "MIS_admin"
                }, {"_id": 1})

            node_collection.collection.update(
                {"_id": person_gs._id},
                {"$addToSet": {
                    "group_set": mis_admin._id
                }},
                upsert=False,
                multi=False)

        # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs)
        for tab_details in property_order_list:
            for field_set in tab_details[1]:
                # Fetch only Attribute field(s) / Relation field(s)
                if '_id' in field_set:
                    field_instance = node_collection.one(
                        {'_id': field_set['_id']})
                    fi_name = field_instance["name"]
                    field_instance_type = type(field_instance)

                    if field_instance_type in [AttributeType, RelationType]:
                        field_data_type = field_set['data_type']

                        # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
                        if field_instance_type == AttributeType:
                            if "File" in field_instance["validators"]:
                                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                                user_id = request.user.id
                                if fi_name in request.FILES:
                                    field_value = request.FILES[fi_name]

                                else:
                                    field_value = ""

                                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                                if field_value != '' and field_value != u'':
                                    file_name = person_gs.name + " -- " + field_instance[
                                        "altnames"]
                                    content_org = ""
                                    tags = ""
                                    field_value = save_file(
                                        field_value,
                                        file_name,
                                        user_id,
                                        group_id,
                                        content_org,
                                        tags,
                                        access_policy="PRIVATE",
                                        count=0,
                                        first_object="",
                                        oid=True)[0]

                            else:
                                # Other AttributeTypes
                                if fi_name in request.POST:
                                    field_value = request.POST[fi_name]

                            # field_instance_type = "GAttribute"
                            if fi_name in [
                                    "12_passing_year", "degree_passing_year"
                            ]:  #, "registration_year"]:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%Y")
                            elif fi_name in ["dob", "registration_date"]:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%d/%m/%Y")
                                registration_date = field_value
                            else:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%d/%m/%Y %H:%M")

                            if field_value:
                                person_gs_triple_instance = create_gattribute(
                                    person_gs._id,
                                    node_collection.collection.AttributeType(
                                        field_instance), field_value)

                        else:
                            if field_instance["object_cardinality"] > 1:
                                field_value_list = request.POST.get(
                                    fi_name, "")
                                if "[" in field_value_list and "]" in field_value_list:
                                    field_value_list = json.loads(
                                        field_value_list)
                                else:
                                    field_value_list = request.POST.getlist(
                                        fi_name)

                            else:
                                field_value_list = request.POST.getlist(
                                    fi_name)

                            if META_TYPE[
                                    3] in field_instance.member_of_names_list:
                                # If Binary relationship found
                                # [id, id, ...]
                                # field_instance_type = "GRelation"
                                for i, field_value in enumerate(
                                        field_value_list):
                                    field_value = parse_template_data(
                                        field_data_type,
                                        field_value,
                                        field_instance=field_instance,
                                        date_format_string="%m/%d/%Y %H:%M")
                                    field_value_list[i] = field_value
                            else:
                                # Relationship Other than Binary one found; e.g, Triadic
                                # [[id, id, ...], [id, id, ...], ...]
                                # field_instance_type = "GRelation"
                                for i, field_value_inner_list in enumerate(
                                        field_value_list):
                                    for j, field_value in enumerate(
                                            field_value_inner_list):
                                        field_value = parse_template_data(
                                            field_data_type,
                                            field_value,
                                            field_instance=field_instance,
                                            date_format_string="%m/%d/%Y %H:%M"
                                        )
                                        field_value_list[i][j] = field_value

                            person_gs_triple_instance = create_grelation(
                                person_gs._id,
                                node_collection.collection.RelationType(
                                    field_instance), field_value_list)

        # Setting enrollment code for student node only while creating it
        if create_student_enrollment_code:
            # Create enrollment code for student node only while registering a new node
            for rel in college_node.relation_set:
                if rel and "group_of" in rel:
                    college_id = rel["group_of"][0]

            student_enrollment_code = get_student_enrollment_code(
                college_id, person_gs._id, registration_date,
                ObjectId(group_id))

            enrollment_code_at = node_collection.one({
                "_type": "AttributeType",
                "name": "enrollment_code"
            })

            try:
                ga_node = create_gattribute(person_gs._id, enrollment_code_at,
                                            student_enrollment_code)
            except Exception as e:
                print "\n StudentEnrollmentCreateError: " + str(e) + "!!!"

        # [C] Code to link GSystem Node and Author node via "has_login" relationship;
        #     and Subscribe the Author node to College group if user "Program Officer"
        person_gs.reload()
        auth_node = None
        for attr in person_gs.attribute_set:
            if "email_id" in attr:
                if attr["email_id"]:
                    auth_node = node_collection.one({
                        '_type':
                        "Author",
                        'email':
                        attr["email_id"].lower()
                    })
                    break

        if auth_node:
            has_login_rt = node_collection.one({
                '_type': "RelationType",
                'name': "has_login"
            })
            if has_login_rt:
                # Linking GSystem Node and Author node via "has_login" relationship;
                gr_node = create_grelation(person_gs._id, has_login_rt,
                                           auth_node._id)

                # Set author_agency field's value of author node as "Program Officer"
                # Required to identify at time of log-in in order to display
                # required modules defined for Program Officers under MIS GApp
                if auth_node.agency_type != u"Program Officer":
                    auth_node.agency_type = u"Program Officer"
                    auth_node.save(groupid=group_id)

            if "Program Officer" in person_gs.member_of_names_list:
                # If Person node (GSystem) is of Program Officer type
                # then only go for subscription
                college_id_list = []
                # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of")
                for rel in person_gs.relation_set:
                    if "officer_incharge_of" in rel:
                        if rel["officer_incharge_of"]:
                            for college_id in rel["officer_incharge_of"]:
                                if college_id not in college_id_list:
                                    college_id_list.append(college_id)
                            break  # break outer-loop (of relation_set)

                if college_id_list:
                    # If College's ObjectId exists (list as PO might be assigned to more than one college)
                    # Then prepare a list of their corresponding private group(s) (via "has_group")
                    college_cur = node_collection.find(
                        {'_id': {
                            '$in': college_id_list
                        }}, {'relation_set.has_group': 1})

                    college_group_id_list = []
                    for college in college_cur:
                        for rel in college.relation_set:
                            if rel and "has_group" in rel:
                                if rel["has_group"]:
                                    if rel["has_group"][
                                            0] not in college_group_id_list:
                                        college_group_id_list.append(
                                            rel["has_group"][0])

                                    break  # break inner-loop (college.relation_set)

                    if college_group_id_list:
                        # If college-group list exists
                        # Then update their group_admin field (append PO's created_by)
                        res = node_collection.collection.update(
                            {'_id': {
                                '$in': college_group_id_list
                            }}, {
                                '$addToSet': {
                                    'group_admin': auth_node.created_by
                                }
                            },
                            upsert=False,
                            multi=True)
                old_college_id_list = []
                if existing_colg:
                    if len(existing_colg) > len(college_id_list):
                        for each_colg_id in existing_colg:
                            if each_colg_id not in college_id_list:
                                old_college_id_list.append(each_colg_id)

                        old_college_cur = node_collection.find(
                            {'_id': {
                                '$in': old_college_id_list
                            }}, {'relation_set.has_group': 1})

                        old_college_group_id_list = []
                        for college in old_college_cur:
                            for rel in college.relation_set:
                                if rel and "has_group" in rel:
                                    if rel["has_group"]:
                                        if rel["has_group"][
                                                0] not in old_college_group_id_list:
                                            old_college_group_id_list.append(
                                                rel["has_group"][0])

                                        break  # break inner-loop (college.relation_set)

                        if old_college_group_id_list:
                            # If college-group list exists
                            # Then update their group_admin field (remove PO's created_by)
                            res = node_collection.collection.update(
                                {
                                    '_id': {
                                        '$in': old_college_group_id_list
                                    },
                                    '$or': [{
                                        'group_admin': auth_node.created_by
                                    }, {
                                        'author_set': auth_node.created_by
                                    }]
                                }, {
                                    '$pull': {
                                        'group_admin': auth_node.created_by,
                                        'author_set': auth_node.created_by
                                    }
                                },
                                upsert=False,
                                multi=True)
                            # The code below is commented as the college groups are PRIVATE.
                            # for rel in person_gs.relation_set:
                            #   if rel and "officer_incharge_of" in rel:
                            #       pass
                            #   else:
                            #       node_collection.collection.update({'_id': auth_node._id},
                            #       {'$set': {'agency_type': u"Other"}},
                            #       upsert=False, multi=False
                            #       )
                            # Its purpose is to change the agency type back to Other

                            auth_node.reload()
        # if person_gst.name != "Student":
        #     return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
        # else:
        return HttpResponseRedirect(
            reverse('mis:mis_app_instance_detail',
                    kwargs={
                        'group_id': group_id,
                        "app_id": app_id,
                        "app_set_id": app_set_id,
                        "app_set_instance_id": unicode(person_gs._id)
                    }))

        # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))

    default_template = "ndf/person_create_edit.html"

    # default_template = "ndf/"+template_prefix+"_create_edit.html"
    context_variables = {
        'groupid': group_id,
        'group_id': group_id,
        'app_id': app_id,
        'app_name': app_name,
        'app_collection_set': app_collection_set,
        'app_set_id': app_set_id,
        'title': title,
        'property_order_list': property_order_list
    }

    if person_gst and person_gst.name in [
            "Voluntary Teacher", "Master Trainer"
    ]:
        nussd_course_type = node_collection.one(
            {
                '_type': "AttributeType",
                'name': "nussd_course_type"
            }, {
                '_type': 1,
                '_id': 1,
                'data_type': 1,
                'complex_data_type': 1,
                'name': 1,
                'altnames': 1
            })

        if nussd_course_type["data_type"] == "IS()":
            # Below code does little formatting, for example:
            # data_type: "IS()" complex_value: [u"ab", u"cd"] dt:
            # "IS(u'ab', u'cd')"
            dt = "IS("
            for v in nussd_course_type.complex_data_type:
                dt = dt + "u'" + v + "'" + ", "
            dt = dt[:(dt.rfind(", "))] + ")"
            nussd_course_type["data_type"] = dt

        nussd_course_type["data_type"] = eval(nussd_course_type["data_type"])
        nussd_course_type["value"] = None
        context_variables['nussd_course_type'] = nussd_course_type

    if app_set_instance_id:
        person_gs.get_neighbourhood(person_gs.member_of)

        if "trainer_teaches_course_in_college" in person_gs:
            l = []
            for each_course_college in person_gs.trainer_teaches_course_in_college:
                # Fetch Course Type (i.e. nussd_course_type)
                ct = ""
                for each_attr in each_course_college[0].attribute_set:
                    if "nussd_course_type" in each_attr and each_attr:
                        ct = each_attr["nussd_course_type"]
                        break

                univ_name = ""
                for each_rel in each_course_college[1].relation_set:
                    if "college_affiliated_to" in each_rel and each_rel:
                        univ = node_collection.find_one({
                            "_id": {
                                "$in": each_rel["college_affiliated_to"]
                            }
                        })
                        univ_name = univ.name if univ else ""

                l.append((ct, each_course_college[0].name,
                          each_course_college[1].name,
                          each_course_college[0]._id.__str__(),
                          each_course_college[1]._id.__str__(), univ_name))
            if l:
                person_gs.trainer_teaches_course_in_college = l

        context_variables['node'] = person_gs

    try:
        return render_to_response([template, default_template],
                                  context_variables,
                                  context_instance=RequestContext(request))

    except TemplateDoesNotExist as tde:
        error_message = "\n PersonCreateEditViewError: This html template (" + str(
            tde) + ") does not exists !!!\n"
        raise Http404(error_message)

    except Exception as e:
        error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n"
        raise Exception(error_message)
Esempio n. 48
0
    def handle(self, *args, **options):

        api = ox.api.API("http://wetube.gnowledge.org/api")

        countVideo = api.find({
            "query": {
                "operator":
                "&",
                "conditions": [{
                    "operator": "==",
                    "key": "project",
                    "value": "NROER"
                }]
            }
        })
        totalVideoNo = countVideo['data']['items']

        allVideo = api.find({
            "keys":
            ["id", "title", "director", "id", "posterRatio", "year", "user"],
            "query": {
                "conditions": [{
                    "oper\
    ator": "==",
                    "key": "project",
                    "value": "NROER"
                }],
                "operator":
                "&"
            },
            "range": [0, totalVideoNo],
            "sort": [{
                "operator": "+",
                "key": "title"
            }]
        })

        allVideosData = allVideo['data']['items']

        pandora_video_st = collection.Node.one(
            {'$and': [{
                'name': 'Pandora_video'
            }, {
                '_type': 'GSystemType'
            }]})
        file_gst = collection.Node.one(
            {'$and': [{
                'name': 'File'
            }, {
                '_type': 'GSystemType'
            }]})
        source_id_AT = collection.Node.one(
            {'$and': [{
                'name': 'source_id'
            }, {
                '_type': 'AttributeType'
            }]})
        grp = collection.Node.one({'_type': 'Group', 'name': 'home'})
        auth_id = User.objects.get(username='******').pk

        if auth_id:
            for each in allVideosData:

                pandora_video = collection.Node.one({
                    '_type':
                    'File',
                    'member_of': {
                        '$in': [pandora_video_st._id]
                    },
                    'name':
                    unicode(each['title']).lower(),
                    'created_by':
                    auth_id
                })

                if pandora_video is None:

                    gs = collection.File()
                    gs.name = unicode(each['title']).lower()
                    gs.mime_type = "video"
                    gs.access_policy = u"PRIVATE"
                    gs.member_of = [file_gst._id, pandora_video_st._id]
                    gs.created_by = auth_id
                    gs.modified_by = auth_id
                    gs.group_set.append(grp._id)
                    gs.contributors.append(auth_id)
                    gs.save()

                    gs.reload()

                    create_gattribute(gs._id, source_id_AT, each['id'])
                    print "\n Document created for pandora video '", gs.name, "' sucessfully !! \n"

                else:
                    print "\n Document Pandora Video '", pandora_video.name, "' already created !! \n"

        else:
            print "\n Sorry .. Need to create user as 'nroer_team' for running this script \n"
Esempio n. 49
0
def video_edit(request,group_id,_id):
    # ins_objectid  = ObjectId()
    # if ins_objectid.is_valid(group_id) is False :
    #     group_ins = node_collection.find_one({'_type': "Group","name": group_id})
    #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #     if group_ins:
    #         group_id = str(group_ins._id)
    #     else :
    #         auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #         if auth :
    #             group_id = str(auth._id)
    # else :
    #     pass
    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)
        
    vid_node = node_collection.one({"_id": ObjectId(_id)})
    title = GST_VIDEO.name
    video_obj=request.GET.get("vid_id","")
    group_obj = node_collection.one({'_id': ObjectId(group_id)})
    ce_id = request.GET.get('course_event_id')
    course_tab_title = request.POST.get("course_tab_title",'')
    res = request.GET.get('res')

    if request.method == "POST":

        # get_node_common_fields(request, vid_node, group_id, GST_VIDEO)
        vid_node.save(is_changed=get_node_common_fields(request, vid_node, group_id, GST_VIDEO),groupid=group_id)
        thread_create_val = request.POST.get("thread_create",'')
        course_tab_title = request.POST.get("course_tab_title",'')
        # help_info_page = request.POST.getlist('help_info_page','')
        help_info_page = request.POST['help_info_page']
        if help_info_page:
            help_info_page = json.loads(help_info_page)
        
        discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"})
        if thread_create_val == "Yes":
            create_gattribute(vid_node._id, discussion_enable_at, True)
            return_status = create_thread_for_node(request,group_id, vid_node)
        else:
            create_gattribute(vid_node._id, discussion_enable_at, False)

        # print "\n\n help_info_page ================ ",help_info_page
        if help_info_page and u"None" not in help_info_page:
            has_help_rt = node_collection.one({'_type': "RelationType", 'name': "has_help"})
            try:
                help_info_page = map(ObjectId, help_info_page)
                create_grelation(vid_node._id, has_help_rt,help_info_page)
            except Exception as invalidobjectid:
                # print "\n\n ERROR -------- ",invalidobjectid
                pass
        else:

            # Check if node had has_help RT
            grel_dict = get_relation_value(vid_node._id,"has_help")
            # print "\n\n grel_dict ==== ", grel_dict
            if grel_dict:
                grel_id = grel_dict.get("grel_id","")
                if grel_id:
                    for each_grel_id in grel_id:
                        del_status, del_status_msg = delete_grelation(
                            subject_id=vid_node._id,
                            node_id=each_grel_id,
                            deletion_type=0
                        )
                        # print "\n\n del_status == ",del_status
                        # print "\n\n del_status_msg == ",del_status_msg
        if "CourseEventGroup" not in group_obj.member_of_names_list:
            get_node_metadata(request,vid_node)
            teaches_list = request.POST.get('teaches_list', '')  # get the teaches list
            assesses_list = request.POST.get('assesses_list', '')  # get the teaches list
            if teaches_list !='':
                teaches_list=teaches_list.split(",")
            create_grelation_list(vid_node._id,"teaches",teaches_list)
            if assesses_list !='':
                assesses_list=assesses_list.split(",")
            create_grelation_list(vid_node._id,"assesses",assesses_list)
            return HttpResponseRedirect(reverse('video_detail', kwargs={'group_id': group_id, '_id': vid_node._id}))
        else:
            vid_node.status = u"PUBLISHED"
            vid_node.save()
            if course_tab_title:
                if course_tab_title == "raw material":
                    course_tab_title = "raw_material"
                return HttpResponseRedirect(reverse('course_'+course_tab_title + '_detail', kwargs={'group_id': group_id, 'node_id': str(vid_node._id)}))
            return HttpResponseRedirect(reverse('course_about', kwargs={'group_id': group_id}))
            # url = "/"+ str(group_id) +"/?selected="+str(vid_node._id)+"#view_page"
            # return HttpResponseRedirect(url)

    else:
        vid_col = node_collection.find({'member_of': GST_VIDEO._id,'group_set': ObjectId(group_id)})
        nodes_list = []
        for each in vid_col:
          nodes_list.append(str((each.name).strip().lower()))

        return render_to_response("ndf/video_edit.html",
                                  { 'node': vid_node, 'title': title,
                                    'group_id': group_id,
                                    'groupid':group_id,
                                    'video_obj':video_obj,
                                    'nodes_list':nodes_list,
                                    'ce_id': ce_id,
                                    'res': res, 'course_tab_title':course_tab_title
                                },
                                  context_instance=RequestContext(request)
                              )
Esempio n. 50
0
def organization_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None):
  """
  Creates/Modifies document of given organization-type.
  """
  auth = None
  # if ObjectId.is_valid(group_id) is False :
  #   group_ins = node_collection.one({'_type': "Group","name": group_id})
  #   auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #   if group_ins:
  #     group_id = str(group_ins._id)
  #   else :
  #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #     if auth :
  #       group_id = str(auth._id)
  # else :
  #   pass
  group_name, group_id = get_group_name_id(group_id)
  app = None
  if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:
    app = node_collection.one({'_id': ObjectId(app_id)},{'_id':1, 'name':1})
  app_name = app.name

  # app_name = "mis"
  app_set = ""
  app_collection_set = []
  title = ""

  organization_gst = None
  organization_gs = None

  property_order_list = []

  template = ""
  template_prefix = "mis"

  if request.user:
    if auth is None:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
    agency_type = auth.agency_type
    agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if agency_type_node:
      for eachset in agency_type_node.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      
  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))

  if app_set_id:
    organization_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
    template = "ndf/organization_create_edit.html"
    title = organization_gst.name
    organization_gs = node_collection.collection.GSystem()
    organization_gs.member_of.append(organization_gst._id)

  if app_set_instance_id:
    organization_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
  property_order_list = get_property_order_with_value(organization_gs)#.property_order
  if request.method == "POST":
    # [A] Save organization-node's base-field(s)
    is_changed = get_node_common_fields(request, organization_gs, group_id, organization_gst)

    if is_changed:
      # Remove this when publish button is setup on interface
      organization_gs.status = u"PUBLISHED"

    organization_gs.save(is_changed=is_changed,groupid=group_id)

    # [B] Store AT and/or RT field(s) of given organization-node (i.e., organization_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # Fetch only Attribute field(s) / Relation field(s)
        if '_id' in field_set:
          field_instance = node_collection.one({'_id': field_set['_id']})
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            if field_instance["name"] == "attendees":
              continue

            field_data_type = field_set['data_type']

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                
                if field_instance["name"] in request.FILES:
                  field_value = request.FILES[field_instance["name"]]

                else:
                  field_value = ""
                
                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = organization_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              else:
                # Other AttributeTypes 
                field_value = request.POST[field_instance["name"]]

              # field_instance_type = "GAttribute"
              if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif field_instance["name"] in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")

              if field_value:
                organization_gs_triple_instance = create_gattribute(organization_gs._id, node_collection.collection.AttributeType(field_instance), field_value)

            else:
              if field_instance["object_cardinality"] > 1:
                field_value_list = request.POST.get(field_instance["name"], "")
                if "[" in field_value_list and "]" in field_value_list:
                  field_value_list = json.loads(field_value_list)
                else:
                  field_value_list = request.POST.getlist(field_instance["name"])

              else:
                field_value_list = request.POST.getlist(field_instance["name"])

              # field_instance_type = "GRelation"
              for i, field_value in enumerate(field_value_list):
                field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                field_value_list[i] = field_value

              organization_gs_triple_instance = create_grelation(organization_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)

    # [C] Create private group only for College GSystems
    if "College" in organization_gs.member_of_names_list:
      # Create a group for respective college node
      college_group, college_group_gr = create_college_group_and_setup_data(organization_gs)

    return HttpResponseRedirect(
      reverse(
        app_name.lower()+":"+template_prefix+'_app_detail',
        kwargs={'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id}
      )
    )

  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'groupid': group_id, 'group_id': group_id,
                        'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title': title,
                        'property_order_list': property_order_list
                      }
  if app_set_instance_id:
    #   organization_gs.get_neighbourhood(organization_gs.member_of)
    #   context_variables['node'] = organization_gs
    context_variables['node_id'] = organization_gs._id
    context_variables['node_name'] = organization_gs.name

  try:
    return render_to_response(template,
                              context_variables,
                              context_instance = RequestContext(request)
                            )

  except TemplateDoesNotExist as tde:
    error_message = "\n OrganizationCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n"
    raise Http404(error_message)

  except Exception as e:
    error_message = "\n OrganizationCreateEditViewError: " + str(e) + " !!!\n"
    raise Exception(error_message)
Esempio n. 51
0
def create_task_at_rt(request,rt_list,at_list,task_node,assign,group_name,group_id):
  file_id=(request.POST.get("files"))
  file_name=(request.POST.get("files_name"))

  for each in rt_list:
        rel_type_node = node_collection.one({'_type': "RelationType", 'name': each})
        field_value_list = None

        if rel_type_node["object_cardinality"] > 1:
          field_value_list = request.POST.get(rel_type_node["name"], "")
          if "[" in field_value_list and "]" in field_value_list:
            field_value_list = json.loads(field_value_list)
          else:
            field_value_list = request.POST.getlist(rel_type_node["name"])

        else:
          field_value_list = request.POST.getlist(rel_type_node["name"])

        # rel_type_node_type = "GRelation"
        for i, field_value in enumerate(field_value_list):
          field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node)
          field_value_list[i] = field_value

        task_gs_triple_instance = create_grelation(task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list)

  for each in at_list:
        field_value = []
        if request.POST.get(each,""):
          attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': each})
          subject = task_node._id
          object_value = ""
          if each == 'Assignee':
              if type(assign) == list:
                object_value = assign
              else:
                field_value.append(assign)
                object_value = field_value


          else:
            field_value = request.POST.get(each, "")

            date_format_string = ""
            if each in ["start_time", "end_time"]:
              date_format_string = "%d/%m/%Y"

            field_value = parse_template_data(eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string)
            # newattribute.object_value = field_value
            object_value = field_value


          # newattribute.save()
          ga_node = create_gattribute(subject, attributetype_key, object_value)

  if request.FILES.getlist('UploadTask'):
        attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':'Upload_Task'})
        ga_node = create_gattribute(task_node._id, attributetype_key, file_id)


  assignee_list = []
  assignee_list_id = []
  if type(assign) == list:
    assignee_list_id = assign
  else:
    assignee_list_id.append(assign)
  user_to_be_notified = []
  if assignee_list_id:
      for eachuser in assignee_list_id:
        if eachuser:
              bx = User.objects.get(id=int(eachuser))
              assignee_list.append(bx.username)
              user_to_be_notified.append(bx)
      for eachuser in user_to_be_notified:
          activ = "Task reported"
          msg = "Task '" + task_node.name + \
            "' has been reported by " + request.user.username + \
            "\n     - Status: " + request.POST.get('Status', '') + \
            "\n     - Assignee: " + ", ".join(assignee_list) + \
            "\n     - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id)

          set_notif_val(request, group_id, msg, activ, eachuser)
Esempio n. 52
0
def main():
    grp_dict = {}
    columns = defaultdict(list)

    with open(schema_file_csv, 'rb') as f:
        reader = csv.DictReader(f, delimiter=",")
        file_content = []
        for row in reader:
            file_content.append(row)
        for each in file_content:
            check_group = node_collection.one({
                'name': str(each['category']),
                '_type': 'Group'
            })
            check_sub_group = node_collection.one({
                'name': str(each['name']),
                '_type': 'Group'
            })

            if not check_group:
                group_create(each['category'])
            if not check_sub_group:
                group_create(each['name'])

            get_parent_group = node_collection.one({
                'name':
                str(each['category']),
                '_type':
                'Group'
            })
            get_child_group = node_collection.one({
                'name': str(each['name']),
                '_type': 'Group'
            })
            if get_child_group._id not in get_parent_group.collection_set:
                get_parent_group.collection_set.append(get_child_group._id)
                get_parent_group.save()
            if get_child_group._id not in get_parent_group.post_node:
                get_parent_group.post_node.append(get_child_group._id)
                get_parent_group.save()
            get_group = node_collection.one({
                'name': str(each['name']),
                '_type': 'Group'
            })
            get_group.content = unicode(each['description'])
            get_group.content = unicode(each['description'])
            get_group.save()
            create_gattribute(get_group._id, email_id_AT,
                              unicode(each['email']))
            create_gattribute(get_group._id, house_street_AT,
                              unicode(each['address: Street']))
            create_gattribute(get_group._id, town_city_AT,
                              unicode(each['address: Place']))
            create_gattribute(get_group._id, state_AT,
                              unicode(each['address: State']))
            if each['address: PIN']:
                create_gattribute(get_group._id, pin_code_AT,
                                  long(each['address: PIN']))
            create_gattribute(get_group._id, contact_point_AT,
                              unicode(each['contactPoint']))
            create_gattribute(get_group._id, telephone_AT,
                              unicode(each['telephone']))
            create_gattribute(get_group._id, website_AT,
                              unicode(each['website']))

            print("\n Partners details added!\n\n")