Ejemplo n.º 1
0
def create_supplemental_project(request, artifact):
    mapper = ProjectAllocationMapper(request)

    pi = artifact.project.pi
    artifact_url = request.build_absolute_uri(
        reverse("sharing_portal:detail", kwargs={"pk": artifact.pk}))
    supplemental_project = {
        "nickname": f"reproducing_{artifact.id}",
        "title": f"Reproducing '{artifact.title}'",
        "description":
        f"This project is for reproducing the artifact '{artifact.title}' {artifact_url}",
        "typeId": artifact.project.type.id,
        "fieldId": artifact.project.field.id,
        "piId": artifact.project.pi.id,
    }
    # Approval code is commented out during initial preview release.
    allocation_data = {
        "resourceId": 39,
        "requestorId": pi.id,
        "computeRequested": 1000,
        "status": "approved",
        #"dateReviewed": timezone.now(),
        #"start": timezone.now(),
        #"end": timezone.now() + timedelta(days=6*30),
        #"decisionSummary": "automatically approved for reproducibility",
        #"computeAllocated": 1000,
        #"justification": "Automatic decision",
    }
    supplemental_project["allocations"] = [allocation_data]
    supplemental_project["source"] = "Daypass"
    created_tas_project = mapper.save_project(supplemental_project,
                                              request.get_host())
    # We can assume only 1 here since this project is new
    #allocation = Allocation.objects.get(project_id=created_tas_project["id"])
    #allocation.status = "approved"
    #allocation.save()
    return Project.objects.get(id=created_tas_project["id"])
Ejemplo n.º 2
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})
Ejemplo n.º 3
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,
        },
    )
Ejemplo n.º 4
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)
Ejemplo n.º 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

    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)