Пример #1
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))
Пример #2
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)
Пример #3
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)
Пример #4
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)
                            )
Пример #5
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)
Пример #6
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)
                            )
Пример #7
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)
Пример #8
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)
Пример #9
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)
Пример #10
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)