Exemple #1
0
def profile(request):
    context = {}
    mapper = ProjectAllocationMapper(request)
    context["profile"] = mapper.get_user(request.user)
    context["piEligibility"] = context["profile"]["piEligibility"]

    return render(request, "tas/profile.html", context)
Exemple #2
0
def user_projects(request):
    context = {}

    username = request.user.username
    mapper = ProjectAllocationMapper(request)
    user = mapper.get_user(username)

    context["is_pi_eligible"] = user["piEligibility"].lower() == "eligible"
    context["username"] = username
    context["projects"] = mapper.get_user_projects(username,
                                                   to_pytas_model=True)

    return render(request, "projects/user_projects.html", context)
Exemple #3
0
def profile_edit(request):
    mapper = ProjectAllocationMapper(request)
    user_info = mapper.get_user(request.user)

    if request.method == "POST":
        request_pi_eligibility = request.POST.get("request_pi_eligibility")
        department_directory_link = request.POST.get("directorylink")
        kwargs = {"is_pi_eligible": request_pi_eligibility}
        form = UserProfileForm(request.POST, initial=user_info, **kwargs)

        if form.is_valid():
            data = form.cleaned_data
            try:
                mapper.update_user_profile(
                    request.user,
                    data,
                    request_pi_eligibility,
                    department_directory_link,
                )
                messages.success(request, "Your profile has been updated!")
                return HttpResponseRedirect(reverse("tas:profile"))
            except DuplicateUserError:
                messages.error(request, "A user with this email already exists")
            except Exception:
                messages.error(request, "An error occurred updating your profile")
                LOG.exception(
                    (
                        "An unknown error occurred updating user profile for "
                        f"{request.user.username}"
                    )
                )
        else:
            user_info["title"] = form.data.get("title")
    else:
        kwargs = {"is_pi_eligible": False}
        if user_info["piEligibility"].upper() == "ELIGIBLE":
            kwargs = {"is_pi_eligible": True}
        form = UserProfileForm(initial=user_info, **kwargs)

    context = {
        "form": form,
        "user": user_info,
        "piEligibility": user_info["piEligibility"],
        "canRequestPI": can_request_pi(user_info.get("title", "")),
    }
    return render(request, "tas/profile_edit.html", context)
Exemple #4
0
def create_project(request):
    mapper = ProjectAllocationMapper(request)
    form_args = {"request": request}

    user = mapper.get_user(request.user.username)
    if user["piEligibility"].lower() != "eligible":
        messages.error(
            request,
            "Only PI Eligible users can create new projects. "
            "If you would like to request PI Eligibility, please "
            '<a href="/user/profile/edit/">submit a PI Eligibility '
            "request</a>.",
        )
        return HttpResponseRedirect(reverse("projects:user_projects"))
    if request.POST:
        form = ProjectCreateForm(request.POST, **form_args)
        if form.is_valid():
            # title, description, typeId, fieldId
            project = form.cleaned_data.copy()
            # let's check that any provided nickname is unique
            project["nickname"] = project["nickname"].strip()
            nickname_valid = (project["nickname"]
                              and ProjectExtras.objects.filter(
                                  nickname=project["nickname"]).count() < 1
                              and Project.objects.filter(
                                  nickname=project["nickname"]).count() < 1)

            if not nickname_valid:
                form.add_error("__all__", "Project nickname unavailable")
                return render(request, "projects/create_project.html",
                              {"form": form})

            project.pop("accept_project_terms", None)

            # pi
            pi_user_id = mapper.get_portal_user_id(request.user.username)
            project["piId"] = pi_user_id

            # allocations
            allocation = {
                "resourceId": 39,
                "requestorId": pi_user_id,
                "computeRequested": 20000,
            }

            supplemental_details = project.pop("supplemental_details", None)
            funding_source = project.pop("funding_source", None)

            # if supplemental_details == None:
            #    raise forms.ValidationError("Justifcation is required")
            if not supplemental_details:
                supplemental_details = "(none)"

            if funding_source:
                allocation[
                    "justification"] = "%s\n\n--- Funding source(s) ---\n\n%s" % (
                        supplemental_details,
                        funding_source,
                    )
            else:
                allocation["justification"] = supplemental_details

            project["allocations"] = [allocation]

            # startup
            project["typeId"] = 2

            # source
            project["source"] = "Chameleon"
            try:
                created_project = mapper.save_project(project,
                                                      request.get_host())
                logger.info("newly created project: " +
                            json.dumps(created_project))
                messages.success(request, "Your project has been created!")
                return HttpResponseRedirect(
                    reverse("projects:view_project",
                            args=[created_project["id"]]))
            except:
                logger.exception("Error creating project")
                form.add_error(
                    "__all__",
                    "An unexpected error occurred. Please try again")
        else:
            form.add_error(
                "__all__",
                "There were errors processing your request. "
                "Please see below for details.",
            )
    else:
        form = ProjectCreateForm(**form_args)

    return render(request, "projects/create_project.html", {"form": form})
Exemple #5
0
def create_allocation(request, project_id, allocation_id=-1):
    mapper = ProjectAllocationMapper(request)

    user = mapper.get_user(request.user.username)
    if user["piEligibility"].lower() != "eligible":
        messages.error(
            request,
            "Only PI Eligible users can request allocations. If you would "
            "like to request PI Eligibility, please "
            '<a href="/user/profile/edit/">submit a PI Eligibility '
            "request</a>.",
        )
        return HttpResponseRedirect(reverse("projects:user_projects"))

    project = mapper.get_project(project_id)

    allocation = None
    allocation_id = int(allocation_id)
    if allocation_id > 0:
        for a in project.allocations:
            if a.id == allocation_id:
                allocation = a

    # goofiness that we should clean up later; requires data cleansing
    abstract = project.description
    if "--- Supplemental details ---" in abstract:
        additional = abstract.split("\n\n--- Supplemental details ---\n\n")
        abstract = additional[0]
        additional = additional[1].split("\n\n--- Funding source(s) ---\n\n")
        justification = additional[0]
        if len(additional) > 1:
            funding_source = additional[1]
        else:
            funding_source = ""
    elif allocation:
        justification = allocation.justification
        if "--- Funding source(s) ---" in justification:
            parts = justification.split("\n\n--- Funding source(s) ---\n\n")
            justification = parts[0]
            funding_source = parts[1]
        else:
            funding_source = ""
    else:
        justification = ""
        funding_source = ""

    if request.POST:
        form = AllocationCreateForm(
            request.POST,
            initial={
                "description": abstract,
                "supplemental_details": justification,
                "funding_source": funding_source,
            },
        )
        if form.is_valid():
            allocation = form.cleaned_data.copy()
            allocation["computeRequested"] = 20000

            # Also update the project
            project.description = allocation.pop("description", None)

            supplemental_details = allocation.pop("supplemental_details", None)

            logger.error(supplemental_details)
            funding_source = allocation.pop("funding_source", None)

            # if supplemental_details == None:
            #    raise forms.ValidationError("Justifcation is required")
            # This is required
            if not supplemental_details:
                supplemental_details = "(none)"

            logger.error(supplemental_details)

            if funding_source:
                allocation[
                    "justification"] = "%s\n\n--- Funding source(s) ---\n\n%s" % (
                        supplemental_details,
                        funding_source,
                    )
            else:
                allocation["justification"] = supplemental_details

            allocation["projectId"] = project_id
            allocation["requestorId"] = mapper.get_portal_user_id(
                request.user.username)
            allocation["resourceId"] = "39"

            if allocation_id > 0:
                allocation["id"] = allocation_id

            try:
                logger.info(
                    "Submitting allocation request for project %s: %s" %
                    (project.id, allocation))
                updated_project = mapper.save_project(project.as_dict())
                mapper.save_allocation(allocation, project.chargeCode,
                                       request.get_host())
                messages.success(
                    request, "Your allocation request has been submitted!")
                return HttpResponseRedirect(
                    reverse("projects:view_project",
                            args=[updated_project["id"]]))
            except:
                logger.exception("Error creating allocation")
                form.add_error(
                    "__all__",
                    "An unexpected error occurred. Please try again")
        else:
            form.add_error(
                "__all__",
                "There were errors processing your request. "
                "Please see below for details.",
            )
    else:
        form = AllocationCreateForm(
            initial={
                "description": abstract,
                "supplemental_details": justification,
                "funding_source": funding_source,
            })
    context = {
        "form": form,
        "project": project,
        "alloc_id": allocation_id,
        "alloc": allocation,
    }
    return render(request, "projects/create_allocation.html", context)
Exemple #6
0
def create_project(request):
    mapper = ProjectAllocationMapper(request)
    form_args = {"request": request}

    user = mapper.get_user(request.user.username)
    if user["piEligibility"].lower() != "eligible":
        messages.error(
            request,
            "Only PI Eligible users can create new projects. "
            "If you would like to request PI Eligibility, please "
            '<a href="/user/profile/edit/">submit a PI Eligibility '
            "request</a>.",
        )
        return HttpResponseRedirect(reverse("projects:user_projects"))
    if request.POST:
        form = ProjectCreateForm(request.POST, **form_args)
        allocation_form = AllocationCreateForm(
            request.POST, initial={"publication_up_to_date": True})
        allocation_form.fields[
            "publication_up_to_date"].widget = forms.HiddenInput()
        funding_formset = FundingFormset(request.POST, initial=[{}])
        consent_form = ConsentForm(request.POST)
        if (form.is_valid() and allocation_form.is_valid()
                and funding_formset.is_valid() and consent_form.is_valid()):
            # title, description, typeId, fieldId
            project = form.cleaned_data.copy()
            allocation_data = allocation_form.cleaned_data.copy()
            # let's check that any provided nickname is unique
            project["nickname"] = project["nickname"].strip()
            nickname_valid = (project["nickname"]
                              and ProjectExtras.objects.filter(
                                  nickname=project["nickname"]).count() < 1
                              and Project.objects.filter(
                                  nickname=project["nickname"]).count() < 1)

            if not nickname_valid:
                form.add_error("__all__", "Project nickname unavailable")
                return render(request, "projects/create_project.html",
                              {"form": form})

            # pi
            pi_user_id = mapper.get_portal_user_id(request.user.username)
            project["piId"] = pi_user_id

            # allocations
            allocation = {
                "resourceId": 39,
                "requestorId": pi_user_id,
                "computeRequested": 20000,
                "justification": allocation_data.pop("justification", None),
            }

            project["allocations"] = [allocation]
            project["description"] = allocation_data.pop("description", None)

            # source
            project["source"] = "Chameleon"
            created_project = None
            try:
                with transaction.atomic():
                    created_project = mapper.save_project(
                        project, request.get_host())
                    _save_fundings(funding_formset, created_project["id"])
                logger.info("newly created project: " +
                            json.dumps(created_project))
                messages.success(request, "Your project has been created!")
                return HttpResponseRedirect(
                    reverse("projects:view_project",
                            args=[created_project["id"]]))
            except:
                # delete project from keycloak
                if created_project:
                    keycloak_client = KeycloakClient()
                    keycloak_client.delete_project(
                        created_project["chargeCode"])
                logger.exception("Error creating project")
                form.add_error(
                    "__all__",
                    "An unexpected error occurred. Please try again")
        else:
            form.add_error(
                "__all__",
                "There were errors processing your request. "
                "Please see below for details.",
            )
    else:
        form = ProjectCreateForm(**form_args)
        allocation_form = AllocationCreateForm(
            initial={"publication_up_to_date": True})
        allocation_form.fields[
            "publication_up_to_date"].widget = forms.HiddenInput()
        funding_formset = FundingFormset(initial=[{}])
        consent_form = ConsentForm()

    return render(
        request,
        "projects/create_project.html",
        {
            "form": form,
            "allocation_form": allocation_form,
            "funding_formset": funding_formset,
            "consent_form": consent_form,
        },
    )
Exemple #7
0
def create_allocation(request, project_id, allocation_id=-1):
    mapper = ProjectAllocationMapper(request)

    user = mapper.get_user(request.user.username)
    if user["piEligibility"].lower() != "eligible":
        messages.error(
            request,
            "Only PI Eligible users can request allocations. If you would "
            "like to request PI Eligibility, please "
            '<a href="/user/profile/edit/">submit a PI Eligibility '
            "request</a>.",
        )
        return HttpResponseRedirect(reverse("projects:user_projects"))

    project = mapper.get_project(project_id)

    allocation = None
    allocation_id = int(allocation_id)
    if allocation_id > 0:
        for a in project.allocations:
            if a.id == allocation_id:
                allocation = a

    abstract = project.description
    if allocation:
        justification = allocation.justification
    else:
        justification = ""

    funding_source = [
        model_to_dict(f)
        for f in Funding.objects.filter(project__id=project_id, is_active=True)
    ]
    # add extra form
    funding_source.append({})

    if request.POST:
        form = AllocationCreateForm(
            request.POST,
            initial={
                "description": abstract,
                "justification": justification,
            },
        )
        formset = FundingFormset(
            request.POST,
            initial=funding_source,
        )
        consent_form = ConsentForm(request.POST)
        if form.is_valid() and formset.is_valid() and consent_form.is_valid():
            allocation = form.cleaned_data.copy()
            allocation["computeRequested"] = 20000

            # Also update the project and fundings
            project.description = allocation.pop("description", None)
            justification = allocation.pop("justification", None)

            allocation["projectId"] = project_id
            allocation["requestorId"] = mapper.get_portal_user_id(
                request.user.username)
            allocation["resourceId"] = "39"
            allocation["justification"] = justification

            if allocation_id > 0:
                allocation["id"] = allocation_id

            try:
                logger.info(
                    "Submitting allocation request for project %s: %s" %
                    (project.id, allocation))
                with transaction.atomic():
                    updated_project = mapper.save_project(project.as_dict())
                    mapper.save_allocation(allocation, project.chargeCode,
                                           request.get_host())
                    new_funding_source = _save_fundings(formset, project_id)
                    _remove_fundings(funding_source, new_funding_source)
                messages.success(
                    request, "Your allocation request has been submitted!")
                return HttpResponseRedirect(
                    reverse("projects:view_project",
                            args=[updated_project["id"]]))
            except:
                logger.exception("Error creating allocation")
                form.add_error(
                    "__all__",
                    "An unexpected error occurred. Please try again")
        else:
            form.add_error(
                "__all__",
                "There were errors processing your request. "
                "Please see below for details.",
            )
    else:
        form = AllocationCreateForm(initial={
            "description": abstract,
            "justification": justification,
        })
        formset = FundingFormset(initial=funding_source)
        consent_form = ConsentForm()
    context = {
        "form": form,
        "funding_formset": formset,
        "consent_form": consent_form,
        "project": project,
        "alloc_id": allocation_id,
        "alloc": allocation,
    }
    return render(request, "projects/create_allocation.html", context)