Beispiel #1
0
 def test_edit_projec_view_with_changing_roles(self):
   """
   Project edit with deleting and adding new roles.
   """
   project = {
     'name': "Name",
     'details': 'This needs to be big',
     'description': 'This needs to be big',
     'responsible': 'Marjori',
     'phone': '123123',
     'email': '*****@*****.**',
     'skills': [1],
     'causes': [2],
     'job': {
       'start_date': 20140416,
       'end_date': 20140417
     },
     'nonprofit': 1
   }
   factory = APIRequestFactory()
   n = self.create_nonprofit()
   r = Role(name="role name")
   r.save()
   p = Project(nonprofit=n, name='name', slug="name")
   p.save()
   p.roles.add(r)
   project['id'] = p.id
   request = factory.put("/save/project/", {'project': project})
   force_authenticate(request, user=n.user)
   response = views.save_project(request)
   newP = Project.objects.get(id=p.id)
   self.assertEqual(newP.roles.count(), 0)
   self.assertEquals(response.status_code, status.HTTP_201_CREATED)
Beispiel #2
0
 def test_edit_projec_view_with_changing_roles(self):
     """
 Project edit with deleting and adding new roles.
 """
     project = {
         'name': "Name",
         'details': 'This needs to be big',
         'description': 'This needs to be big',
         'responsible': 'Marjori',
         'phone': '123123',
         'email': '*****@*****.**',
         'skills': [1],
         'causes': [2],
         'job': {
             'start_date': 20140416,
             'end_date': 20140417
         },
         'nonprofit': 1
     }
     factory = APIRequestFactory()
     n = self.create_nonprofit()
     r = Role(name="role name")
     r.save()
     p = Project(nonprofit=n, name='name', slug="name")
     p.save()
     p.roles.add(r)
     project['id'] = p.id
     request = factory.put("/save/project/", {'project': project})
     force_authenticate(request, user=n.user)
     response = views.save_project(request)
     newP = Project.objects.get(id=p.id)
     self.assertEqual(newP.roles.count(), 0)
     self.assertEquals(response.status_code, status.HTTP_201_CREATED)
Beispiel #3
0
 def test_edit_project_view_with_changing_roles_one_stays(self):
   """
   Project edit with deleting 1 role but keeping another.
   """
   project = {
     'name': "Name",
     'details': 'This needs to be big',
     'description': 'This needs to be big',
     'responsible': 'Marjori',
     'phone': '123123',
     'email': '*****@*****.**',
     'skills': [{'id': 1}],
     'causes': [{'id': 1}],
     'job': {
       'start_date': 20140416,
       'end_date': 20140417,
       'can_be_done_remotely': True,
     },
     'nonprofit': 1
   }
   factory = APIRequestFactory()
   n = self.create_nonprofit()
   r = Role(name="role name")
   r.save()
   r1 = Role(name="role name 1")
   r1.save()
   p = Project(nonprofit=n, name='name', slug="name")
   p.save()
   p.roles.add(r)
   p.roles.add(r1)
   project['id'] = p.id
   project['roles'] = [{'id': r.id}]
   request = factory.put("/save/project/", {'project': json.dumps(project)})
   force_authenticate(request, user=n.user)
   with transaction.atomic():
     response = views.save_project(request)
   newP = Project.objects.get(id=p.id)
   #self.assertEqual(newP.roles.count(), 1)
   self.assertEquals(response.status_code, status.HTTP_201_CREATED)
Beispiel #4
0
def save_project(request, format=None):
    # Need a nonprofit user
    try:
        request.user.nonprofit
    except Exception as e:
        if not request.user.is_staff:
            error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
            return Response({"User not authenticated. " + error}, status.HTTP_403_FORBIDDEN)

    try:
        obj = json.loads(request.DATA["project"])
    except:
        obj = request.DATA["project"]

    project = Project.objects.get(id=obj["id"])

    try:
        if obj["name"] != project.name:
            slug = create_project_slug(obj["name"])
        else:
            slug = project.slug
        project.name = obj["name"]
        # Renaming the image file if the slug has changed
        if slug != project.slug and project.image.name:
            try:
                c = boto.connect_s3()
                bucket = c.get_bucket("atadosapp")
                k = bucket.get_key(project.image.name)
                if k:
                    name = "project/%s/%s.jpg" % (project.nonprofit.user.slug, obj["slug"])
                    if name != project.image.name:
                        k.copy("atadosapp", name)
                        k.delete()
                        project.image.name = name
                else:
                    return Response(
                        {"detail": "Could not get boto key to change project image name on S3."},
                        status.HTTP_400_BAD_REQUEST,
                    )
            except Exception as e:
                print e
                pass

        project.slug = slug
        project.details = obj["details"]
        project.description = obj["description"]
        project.facebook_event = obj.get("facebook_event", None)
        project.responsible = obj["responsible"]
        project.phone = obj["phone"]
        project.email = obj["email"]

        obja = obj.get("address", None)
        if obja:
            if project.address:
                address = project.address
            else:
                address = Address()
            address.addressline = obja.get("addressline", "")
            address.addressline2 = obja.get("addressline2", "")
            address.addressnumber = obja.get("addressnumber", "")
            address.neighborhood = obja.get("neighborhood", "")
            address.zipcode = obja.get("zipcode", "")
            address.city = City.objects.get(id=obja.get("city", None))
            address.save()
            project.address = address

        roles = obj.get("roles", [])

        # Remove the roles that were deleted
        for pr in project.roles.all():
            found = False

            for r in roles:
                if r.get("id", None) == pr.id:
                    found = True

            if not found:
                project.roles.remove(pr)

        for r in roles:
            found = False
            for pr in project.roles.all():
                if r.get("id", None) == pr.id:
                    found = True
            if found:
                role = Role.objects.get(id=r["id"])
            else:
                role = Role()
            role.name = r.get("name", "")
            role.prerequisites = r.get("prerequisites", "")
            role.details = r.get("details", "")
            role.vacancies = r.get("vacancies", 1)
            role.save()
            project.roles.add(role)

        # Removing all skills then adding new ones
        skills = obj.get("skills", [])
        for s in project.skills.all():
            project.skills.remove(s)

        for s in skills:
            project.skills.add(Skill.objects.get(id=s))

        # Removing all causes then adding new ones
        causes = obj.get("causes", None)
        for c in project.causes.all():
            project.causes.remove(c)

        for c in causes:
            project.causes.add(Cause.objects.get(id=c))

        if obj.get("work", None):
            try:
                work = project.work
            except:
                work = Work()
                work.project = project
            work.weekly_hours = obj["work"].get("weekly_hours", 0)
            work.can_be_done_remotely = obj["work"].get("can_be_done_remotely", None)
            work.save()

            if obj["work"].get("availabilities", None):
                for a in project.work.availabilities.all():
                    project.work.availabilities.remove(a)

                availabilities = obj["work"]["availabilities"]

                for a in availabilities:
                    availability = Availability()
                    availability.weekday = a["weekday"]
                    availability.period = a["period"]
                    availability.save()
                    work.availabilities.add(availability)
            else:
                project.work.availabilities = []

            work.save()
            try:
                project.job.delete()
                project.job = None
            except:
                pass

        elif obj.get("job", None):
            try:
                job = project.job
            except:
                job = Job()
                job.project = project
            job.start_date = datetime.utcfromtimestamp(obj["job"]["start_date"] / 1000).replace(
                tzinfo=pytz.timezone("Etc/GMT")
            )
            job.end_date = datetime.utcfromtimestamp(obj["job"]["end_date"] / 1000).replace(
                tzinfo=pytz.timezone("Etc/GMT")
            )
            job.save()
            try:
                project.work.delete()
                project.work = None
            except:
                pass

    except Exception as e:
        error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
        return Response({"detail": error}, status.HTTP_400_BAD_REQUEST)

    project.save()
    return Response(ProjectSerializer(project).data, status.HTTP_201_CREATED)
Beispiel #5
0
def create_project(request, format=None):

    nonprofit = None
    # Need a nonprofit user
    try:
        nonprofit = request.user.nonprofit
    except Exception as e:
        if not request.user.is_staff:
            error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
            return Response({"User not authenticated. " + error}, status.HTTP_403_FORBIDDEN)

    try:
        obj = json.loads(request.DATA["project"])
    except:
        obj = request.DATA["project"]

    project = Project()
    try:
        # Getting required field
        if nonprofit:
            project.nonprofit = nonprofit
        else:
            project.nonprofit = Nonprofit.objects.get(id=obj["nonprofit"])

        project.name = obj["name"]
        project.slug = create_project_slug(project.name)
        project.details = obj["details"]
        project.description = obj["description"]
        project.responsible = obj["responsible"]
        project.phone = obj["phone"]
        project.email = obj["email"]
        project.save()

        skills = obj["skills"]
        for s in skills:
            project.skills.add(Skill.objects.get(id=s))

        causes = obj["causes"]
        for c in causes:
            project.causes.add(Cause.objects.get(id=c))

        if obj.get("work", None):
            work = Work()
            work.project = project
            work.weekly_hours = obj["work"].get("weekly_hours", 0)
            work.can_be_done_remotely = obj["work"].get("can_be_done_remotely", False)
            work.save()

            availabilities = obj["work"].get("availabilities", None)
            if availabilities:
                for a in availabilities:
                    availability = Availability()
                    availability.weekday = a["weekday"]
                    availability.period = a["period"]
                    availability.save()
                    work.availabilities.add(availability)
            work.save()
        elif obj.get("job", None):
            job = Job()
            job.project = project
            job.start_date = datetime.utcfromtimestamp(obj["job"]["start_date"] / 1000).replace(
                tzinfo=pytz.timezone("America/Sao_Paulo")
            )
            job.end_date = datetime.utcfromtimestamp(obj["job"]["end_date"] / 1000).replace(
                tzinfo=pytz.timezone("America/Sao_Paulo")
            )
            job.save()

        has_work = False
        has_job = False
        try:
            project.work
            has_work = True
        except:
            pass
        try:
            project.job
            has_job = True
        except:
            pass

        if not has_job and not has_work:
            return Response({"detail": "Needs to have project or work."}, status.HTTP_400_BAD_REQUEST)

        # Doing not required fields
        try:
            obja = obj.get("address", None)
            if obja:
                address = Address()
                address.addressline = obja.get("addressline", None)
                address.addressline2 = obja.get("addressline2", None)
                address.addressnumber = obja.get("addressnumber", None)
                address.neighborhood = obja.get("neighborhood", None)
                address.zipcode = obja.get("zipcode", None)
                if obja.get("city", None) and obja["city"].get("id", None):
                    address.city = City.objects.get(id=obja["city"]["id"])
                address.save()
                project.address = address
                project.save()

            project.facebook_event = obj.get("facebook_event", None)

            project.image = request.FILES.get("image")
            project.image_small = request.FILES.get("image")
            project.image_medium = request.FILES.get("image")
            project.image_large = request.FILES.get("image")

            roles = obj.get("roles", None)
            if roles:
                for r in roles:
                    role = Role()
                    role.name = r["name"]
                    role.prerequisites = r["prerequisites"]
                    role.details = r["details"]
                    role.vacancies = r["vacancies"]
                    role.save()
                    project.roles.add(role)
        except Exception as e:
            error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
            print error

    except Exception as e:
        error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
        return Response({"detail": error}, status.HTTP_400_BAD_REQUEST)

    project.save()
    return Response({"detail": "Project succesfully created.", "slug": project.slug}, status.HTTP_201_CREATED)
Beispiel #6
0
def save_project(request, format=None):
  # Need a nonprofit user
  try:
    request.user.nonprofit
  except Exception as e:
    error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
    return Response({"User not authenticated. " + error}, status.HTTP_403_FORBIDDEN)

  try:
    obj = json.loads(request.DATA['project'])
  except:
    obj = request.DATA['project']

  project = Project.objects.get(id=obj['id'])

  try:
    if obj['name'] != project.name:
      slug = create_project_slug(obj['name'])
    else:
      slug = project.slug
    project.name = obj['name']
    # Renaming the image file if the slug has changed
    if slug != project.slug and project.image.name:
      try:
        c = boto.connect_s3()
        bucket = c.get_bucket('atadosapp')
        k = bucket.get_key(project.image.name)
        if k:
          name = "project/%s/%s.jpg" % (project.nonprofit.user.slug, obj['slug'])
          if name != project.image.name:
            k.copy('atadosapp', name)
            k.delete()
            project.image.name = name;
        else:
          return Response({'detail': 'Could not get boto key to change project image name on S3.'}, status.HTTP_400_BAD_REQUEST)
      except Exception as e:
        print e
        pass

    project.slug = slug
    project.details = obj['details']
    project.description = obj['description']
    project.facebook_event = obj.get('facebook_event', None)
    project.responsible = obj['responsible']
    project.phone = obj['phone']
    project.email = obj['email']

    obja = obj.get('address', None)
    if obja:
      if project.address:
        address = project.address
      else:
        address = Address()
      address.addressline = obja.get('addressline', '')
      address.addressline2 = obja.get('addressline2', '')
      address.addressnumber = obja.get('addressnumber', '')
      address.neighborhood = obja.get('neighborhood', '')
      address.zipcode = obja.get('zipcode', '')
      address.city = City.objects.get(id=obja.get('city', None))
      address.save()

    roles = obj.get('roles', [])

    # Remove the roles that were deleted
    for pr in project.roles.all():
      found = False

      for r in roles:
        if r.get('id', None) == pr.id:
          found = True

      if not found:
        project.roles.remove(pr)

    for r in roles:
      found = False
      for pr in project.roles.all():
        if r.get('id', None) == pr.id:
          found = True
      if found:
        role = Role.objects.get(id=r['id'])
      else:
        role = Role()
      role.name = r.get('name', '')
      role.prerequisites = r.get('prerequisites', '')
      role.details = r.get('details', '')
      role.vacancies = r.get('vacancies', 1)
      role.save()
      project.roles.add(role)

    # Removing all skills then adding new ones
    skills = obj.get('skills', [])
    for s in project.skills.all():
      project.skills.remove(s)

    for s in skills:
      project.skills.add(Skill.objects.get(id=s))

    # Removing all causes then adding new ones
    causes = obj.get('causes', None)
    for c in project.causes.all():
      project.causes.remove(c)

    for c in causes:
      project.causes.add(Cause.objects.get(id=c))

    if obj.get('work', None):
      try:
        work = project.work
      except:
        work = Work()
        work.project = project
      work.weekly_hours = obj['work'].get('weekly_hours', 0)
      work.can_be_done_remotely = obj['work'].get('can_be_done_remotely', None)
      work.save()

      if obj['work'].get('availabilities', None):
        for a in project.work.availabilities.all():
          project.work.availabilities.remove(a)

        availabilities = obj['work']['availabilities']

        for a in availabilities:
          availability = Availability()
          availability.weekday = a['weekday']
          availability.period = a['period']
          availability.save()
          work.availabilities.add(availability)
      else:
        project.work.availabilities = []

      work.save()
      try:
        project.job.delete()
        project.job = None
      except:
        pass

    elif obj.get('job', None):
      try:
        job = project.job
      except:
        job = Job()
        job.project = project
      job.start_date = datetime.utcfromtimestamp(obj['job']['start_date']/1000).replace(tzinfo=pytz.timezone("America/Sao_Paulo"))
      job.end_date = datetime.utcfromtimestamp(obj['job']['end_date']/1000).replace(tzinfo=pytz.timezone("America/Sao_Paulo"))
      job.save()
      try:
        project.work.delete()
        project.work = None
      except:
        pass

    project.save()

  except Exception as e:
    error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
    return Response({'detail': error}, status.HTTP_400_BAD_REQUEST)

  return Response(ProjectSerializer(project).data, status.HTTP_201_CREATED)
Beispiel #7
0
def create_project(request, format=None):
  # Need a nonprofit user
  try:
    request.user.nonprofit
  except Exception as e:
    error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
    return Response({"User not authenticated. " + error}, status.HTTP_403_FORBIDDEN)

  try:
    obj = json.loads(request.DATA['project'])
  except:
    obj = request.DATA['project']

  project = Project()
  try:
    # Getting required field
    project.nonprofit = request.user.nonprofit
    project.name = obj['name']
    project.slug = create_project_slug(project.name)
    project.details = obj['details']
    project.description = obj['description']
    project.responsible = obj['responsible']
    project.phone = obj['phone']
    project.email = obj['email']
    project.save()

    skills = obj['skills']
    for s in skills:
      project.skills.add(Skill.objects.get(id=s))

    causes = obj['causes']
    for c in causes:
      project.causes.add(Cause.objects.get(id=c))

    if obj.get('work', None):
      work =  Work()
      work.project = project
      work.weekly_hours = obj['work'].get('weekly_hours', 0)
      work.can_be_done_remotely = obj['work'].get('can_be_done_remotely', False)
      work.save()

      availabilities = obj['work'].get('availabilities', None)
      if availabilities:
        for a in availabilities:
          availability = Availability()
          availability.weekday = a['weekday']
          availability.period = a['period']
          availability.save()
          work.availabilities.add(availability)
      work.save()
    elif obj.get('job', None):
      job = Job()
      job.project = project
      job.start_date = datetime.utcfromtimestamp(obj['job']['start_date']/1000).replace(tzinfo=pytz.timezone("America/Sao_Paulo"))
      job.end_date = datetime.utcfromtimestamp(obj['job']['end_date']/1000).replace(tzinfo=pytz.timezone("America/Sao_Paulo"))
      job.save()

    has_work = False
    has_job = False
    try:
      project.work
      has_work = True
    except:
      pass
    try:
      project.job
      has_job = True
    except:
      pass

    if not has_job and not has_work:
      return Response({'detail': 'Needs to have project or work.'}, status.HTTP_400_BAD_REQUEST)

    # Doing not required fields
    try:
      project.facebook_event = obj.get('facebook_event', None)
      obja = obj['address']
      project.address = Address()
      project.address.addressline = obja['addressline']
      project.address.addressline2 = obja['addressline2']
      project.address.addressnumber = obja['addressnumber']
      project.address.neighborhood = obja['neighborhood']
      project.address.zipcode = obja['zipcode']
      project.address.city = City.objects.get(id=obja['city']['id'])
      project.address.save()
      project.image = request.FILES.get('image')
      roles = obj['roles']
      for r in roles:
        role = Role()
        role.name = r['name']
        role.prerequisites = r['prerequisites']
        role.details = r['details']
        role.vacancies = r['vacancies']
        role.save()
        project.roles.add(role)
    except:
      pass

    project.save()

  except Exception as e:
    error = "ERROR - %d - %s" % (sys.exc_traceback.tb_lineno, e)
    return Response({'detail': error}, status.HTTP_400_BAD_REQUEST)

  return Response({'detail': 'Project succesfully created.'}, status.HTTP_201_CREATED)