Example #1
0
 def get(self, request, contact_id=None, *args, **kwargs):
     if contact_id:
         try:
             contact = Contact.objects.select_related("userprofile", "organisation").get(
                 id=contact_id
             )
             return ResponseSuccess({"result": contact.to_dict()})
         except Contact.DoesNotExist:
             raise NotFoundApiExceptions("Contact does not exist or access is denied")
     else:
         filter_kwargs = pluck(request.query_params, ["name", "country", "organisation"])
         contacts = Contact.objects.filter(**filter_kwargs)
     return ResponseSuccess({"results": [_contact.to_dict() for _contact in contacts]})
    def post(self, request, task_id=None):
        task_id = task_id or request.POST.get("task_id")
        data = pluck(
            request.POST,
            [
                "id",
                "name",
                "description",
                "due_date",
                "content_type",
                "model_id",
                "model_key",
                "assignee",
                "assignee_id",
                "case_id",
                "priority",
                "status",
                "data",
                "btn_value",
                "data_estimate",
                "data_remaining",
            ],
        )

        json_data = data.get("data") or {}
        regex = r"^data_"
        for param_key in request.POST:
            matches = re.split(regex, param_key)
            if len(matches) > 1:
                sub_key = matches[1]
                value = request.POST[param_key]
                if value == "__remove":
                    if get(json_data, sub_key):
                        json_data.pop(sub_key)
                else:
                    json_data[sub_key] = value
        data["data"] = json.dumps(json_data)
        if data.get("btn_value") == "save":
            cache.set("lasttaskupdate", timezone.now().strftime("%Y-%m-%dT%H:%M:%S"), 60 * 60)
            if not task_id:
                # we need the object attachments to create task
                result = self.client(request.user).create_update_task(
                    content_type=request.POST.get("content_type"),
                    model_id=request.POST.get("model_id"),
                    data=data,
                )
            else:
                result = self.client(request.user).create_update_task(task_id=task_id, data=data)
        elif get(data, "btn_value") == "delete":
            result = self.client(request.user).delete_task(task_id=get(data, "id"))
        return HttpResponse(json.dumps({"result": result}), content_type="application/json")
Example #3
0
    def post(self, request, user_id=None, user_group=None, *args, **kwargs):
        client = self.client(request.user)

        if self.delete_user:
            result = client.delete_user(user_id=user_id)
            return HttpResponse(
                json.dumps({
                    "alert": "User deleted.",
                    "redirect_url": "reload"
                }))

        required_fields = ["name", "email", "phone"]
        if SECURITY_GROUP_TRA_ADMINISTRATOR in request.user.groups:
            required_fields.append("roles")
        user = {}
        if user_id:
            user = client.get_user(user_id)
            if user["tra"]:
                required_fields.append("job_title_id")
            else:
                required_fields.append("country")
        else:
            required_fields += ["password", "password_confirm"]
            user["email"] = request.POST.get("email")  # Can't update email
        user.update(
            pluck(
                request.POST,
                [
                    "name",
                    "phone",
                    "timezone",
                    "roles",
                    "job_title_id",
                    "active",
                    "set_verified",
                ],
            ))
        user["country_code"] = request.POST.get("country",
                                                user.get("country_code"))
        user["groups"] = request.POST.getlist(
            "roles"
        )  # translation needed as the create write key doesn't match the update
        action = request.resolver_match.url_name
        user["tra"] = True if action.endswith("investigator") else False
        errors = validate_required_fields(request, required_fields) or {}
        if password_errors := self.validate_password(request, user):
            errors.update(password_errors)
Example #4
0
    def post(self,
             request,
             case_id,
             organisation_id,
             role_key=None,
             *args,
             **kwargs):
        sampled = request.data.get("sampled", "true") == "true"
        organisation = Organisation.objects.get(id=organisation_id)
        case = Case.objects.get(id=case_id)
        case_role, _ = OrganisationCaseRole.objects.get_or_create(
            case=case, organisation=organisation)

        # Add/update LOA contact
        if self.post_type == "loa":
            # Create a contact to store LOA details if present
            loa_updated = False
            loa_contact = case_role.auth_contact
            auth_contact_details = (pluck(
                request.data,
                [
                    "LOA_contact_id", "name", "org_name", "email", "phone",
                    "address"
                ],
            ) or {})
            contact_id = auth_contact_details.get("LOA_contact_id")
            email = auth_contact_details.get("email")
            if not loa_contact or loa_contact.id != contact_id:
                # If we get an id, stick with that
                if contact_id:
                    try:
                        loa_contact = Contact.objects.get(id=contact_id)
                    except Exception:
                        pass
                if email:
                    # No contact so try to find one based on email
                    try:
                        loa_contact = Contact.objects.get(email__iexact=email)
                    except Exception:
                        loa_contact = Contact.objects.create(
                            created_by=request.user)
                    # Create a new org if there isn't one, or it doesn't match supplied name
                    loa_org_name = auth_contact_details.get("org_name")
                    loa_contact.organisation = organisation

                    for field, value in auth_contact_details.items():
                        if (value and hasattr(loa_contact, field)
                                and getattr(loa_contact, field) != value):
                            setattr(loa_contact, field, value)
                            loa_updated = True
                    if loa_updated:
                        loa_contact.save()
                    # write back
                case_role.auth_contact = loa_contact
                case_role.save()

            return ResponseSuccess(
                {"result": {
                    "success": case_role.to_dict()
                }})
        # Approve into case and set case role
        approve = request.data.get("approve")
        if approve:
            if approve == "accept":
                if not case_role.approved_at:
                    case_role.approved_at = timezone.now()
                    case_role.approved_by = request.user
                    case_role.save()
            elif approve == "reject":
                role_key = "rejected"
                if case_role.approved_at:
                    case_role.approved_at = None
                    case_role.approved_by = None
                    case_role.save()

        if self.verify:
            case_role.validated_by = request.user
            case_role.validated_at = timezone.now()
            case_role.save()
            return ResponseSuccess(
                {"result": {
                    "validated_at": case_role.to_dict()
                }})
        role = CaseRole.objects.get(key=role_key)
        case_role.role = role
        case_role.sampled = sampled
        case_role.save()
        audit_log(
            audit_type=AUDIT_TYPE_EVENT,
            user=request.user,
            model=case,
            case=case,
            milestone=True,
            data={
                "message":
                f"The role of {organisation} was set to {role} in case {case.name}"
            },
        )
        return ResponseSuccess({"result": {"new_role": role.to_dict()}})
Example #5
0
    def post(self,
             request,
             organisation_id,
             invitation_id=None,
             *args,
             **kwargs):  # noqa: C901
        from invitations.models import Invitation

        case_spec = request.data.get("case_spec") or []
        data = pluck(request.data, ["email", "name", "group", "phone"])
        data["is_active"] = request.data.get("active",
                                             "False").upper() == "TRUE"
        organisation = Organisation.objects.get(id=organisation_id)
        user = None
        contact = None
        data["case_spec"] = json.loads(case_spec) if isinstance(
            case_spec, str) else case_spec
        if invitation_id:
            try:
                invite = Invitation.objects.get(
                    id=invitation_id,
                    organisation=organisation,
                    deleted_at__isnull=True,
                )
                if invite.accepted_at or data["email"] != invite.email:
                    invitation_id = None
                else:
                    if data and data.get("email"):
                        data["email"] = data["email"].lower()
                    invite.meta = data
                    invite.save()
                    contact = invite.contact
                    _save_contact = False
                    if contact.phone != data.get("phone"):
                        contact.phone = convert_to_e164(
                            data["phone"],
                            data.get("country",
                                     request.user.userprofile.country.code),
                        )
                        _save_contact = True
                    if contact.name != data.get("name"):
                        contact.name = data["name"]
                        _save_contact = True
                    if _save_contact:
                        contact.save()
            except Invitation.DoesNotExist:
                raise NotFoundApiExceptions("Invalid invitation")
        if not invitation_id:
            try:
                user = User.objects.get(
                    email=data.get("email").strip().lower())
                # if the user already exists, send an email to the user and leave it at that.
                invite = Invitation.objects.invite_existing_user(
                    user=user,
                    organisation=organisation,
                    invited_by=request.user,
                    name=data.get("name"),
                )
            except User.DoesNotExist:
                invite = Invitation.objects.create_user_invite(
                    user_email=data["email"].lower(),
                    organisation=organisation,
                    invited_by=request.user,
                    meta=data,
                )
        return ResponseSuccess({
            "result": {
                "user": user.to_dict() if user else None,
                "contact": contact.to_dict() if contact else None,
                "invite": invite.to_dict(),
            }
        })