Beispiel #1
0
class StartInviteTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username="******", email="*****@*****.**", password="******")
        self.org = Organization(name="Foo Org")
        self.org.save()
        assign_admin_perms(self.org, self.user)
        self.invite = OrganizationInvite(email="*****@*****.**", organization=self.org, user=self.user)
        self.invite.token = get_random_string(length=20, allowed_chars="ABCDEFGHJKMNPQRST23456789")
        self.invite.save()

    def test_receive_invite(self):
        url = reverse("start_invite", args=(self.invite.id, self.invite.token))
        resp = self.client.get(url)
        self.assertEquals(self.client.session["invite"], self.invite.id)
        self.assertEquals(resp.context["invite_user"], self.user)
        self.assertEquals(resp.context["organization"], self.org)
        self.assertEquals(resp.status_code, 200)

    def test_receive_invite_used(self):
        url = reverse("start_invite", args=(self.invite.id, self.invite.token))
        self.invite.is_used = True
        self.invite.save()
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 404)

    def test_receive_invite_does_not_exist(self):
        url = reverse("start_invite", args=(999, "fake"))
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 404)
Beispiel #2
0
class ConferenceResponseViewTestCase(TestCase):

    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization, twilio_sid='xxx', phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.conference = Conference(organization=self.organization, name='My Conf', phone_number=self.phone_number)
        self.conference.save()

    def test_incoming_call(self):
        self.conference.user_set.add(self.user)
        call = Call(conference=self.conference, user=self.user, twilio_sid='888')
        call.save()
        self.assertEquals(call.call_state, call.INCOMING)

        url = reverse('conference_response', args=(self.conference.id,))
        resp = self.client.post(url, {'CallSid':call.twilio_sid})
        #self.assertContains(resp.content, self.conference.name)
        call_result = Call.objects.get(id=call.id)
        self.assertEquals(call_result.call_state, Call.IN_CALL)
        self.assertTrue(CallEvent.objects.filter(call=call, event_type=CallEvent.JOIN).exists())
 def setUp(self):
     self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
     self.client.login(username='******', password='******')
     self.organization = Organization(name='Foo Org')
     self.organization.save()
     assign_admin_perms(self.organization, self.user)
     self.url = reverse('api_retrieve_organization', args=(self.organization.id,))
Beispiel #4
0
class UseInviteTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.org = Organization(name='Foo Org')
        self.org.save()
        assign_admin_perms(self.org, self.user)
        self.invite = OrganizationInvite(email='*****@*****.**',
                                         organization=self.org,
                                         user=self.user)
        self.invite.token = get_random_string(
            length=20, allowed_chars='ABCDEFGHJKMNPQRST23456789')
        self.invite.save()

    def test_use_invite(self):
        url = reverse('use_invite')
        self.client.login(username='******', password='******')
        session = self.client.session
        session['invite'] = self.invite.id
        session.save()
        resp = self.client.get(url)
        invite = OrganizationInvite.objects.get(id=self.invite.id)
        self.assertTrue(invite.is_used)
        self.assertEquals(resp.status_code, 302)

    def test_no_invite(self):
        url = reverse('use_invite')
        self.client.login(username='******', password='******')
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 302)
Beispiel #5
0
class UseInviteTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username="******", email="*****@*****.**", password="******")
        self.org = Organization(name="Foo Org")
        self.org.save()
        assign_admin_perms(self.org, self.user)
        self.invite = OrganizationInvite(email="*****@*****.**", organization=self.org, user=self.user)
        self.invite.token = get_random_string(length=20, allowed_chars="ABCDEFGHJKMNPQRST23456789")
        self.invite.save()

    def test_use_invite(self):
        url = reverse("use_invite")
        self.client.login(username="******", password="******")
        session = self.client.session
        session["invite"] = self.invite.id
        session.save()
        resp = self.client.get(url)
        invite = OrganizationInvite.objects.get(id=self.invite.id)
        self.assertTrue(invite.is_used)
        self.assertEquals(resp.status_code, 302)

    def test_no_invite(self):
        url = reverse("use_invite")
        self.client.login(username="******", password="******")
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 302)
Beispiel #6
0
def new_organization(request):
    """
    A view to create a new organization, which will then be verified by site
    staff
    """
    form = NewOrganizationForm(request.POST or None)
    captcha_form = CaptchaForm(request.POST or None)

    if form.is_valid() and captcha_form.is_valid():
        # Get authentication fields from the form
        authentication_field_ids = form.cleaned_data["authentication_fields"]
        authentication_fields = AuthenticationField.objects.filter(
            pk__in=authentication_field_ids)
        del form.cleaned_data["authentication_fields"]

        organization = Organization(**form.cleaned_data)
        organization.save()

        organization.authentication_fields.add(*authentication_fields)
        organization.save()

        messages.success(
            request,
            _("Organization profile created! Note that the organization "
              "profile won't be made visible until it has been verified "
              "by the site staff."))
        return redirect(
            reverse('organization:view_organization', args=(
                organization.id,)))
    else:
        return render(
            request, "organization/new_organization/new.html",
            {"form": form,
             "captcha_form": captcha_form})
Beispiel #7
0
    def setup_test_data(cls):
        cls.o1 = Organization(name="Google")
        cls.o2 = Organization(name="Yahoo")
        cls.o3 = Organization(name="Ubisoft")

        cls.o1.save()
        cls.o2.save()
        cls.o3.save()
Beispiel #8
0
    def form_valid(self, form):
        org = Organization(name=form.cleaned_data['name'])
        org.save()
        self.request.user.userprofile.phone_number = form.cleaned_data['phone_number']
        self.request.user.userprofile.save()

        assign_admin_perms(org, self.request.user)
        return super(OrganizationOnboardingView, self).form_valid(form)
Beispiel #9
0
 def test_create_invite(self):
     self.org = Organization(name='Foo Org')
     self.org.save()
     assign_admin_perms(self.org, self.user)
     url = reverse('api_invite_user', args=(self.org.id, ))
     data = {"email": "*****@*****.**"}
     resp = self.client.post(url, data, format='json')
     self.assertEquals(20, len(resp.data['token']))
     self.assertEquals(resp.data['user']['id'], self.user.id)
Beispiel #10
0
 def post(self):
     form = AddOrganizationForm()
     if not form.validate_on_submit():
         return self.get()
     org = Organization(date=datetime.datetime.now().date(),
                        owner_id=current_user.id)
     form.populate_obj(org)
     org.save(add=True)
     return redirect(url_for('organization.organizations'))
def save_obj(vals):
    # prepare data
    nome = ' '.join([
        get_field(vals, 'S'),
        get_field(vals, 'T').title(),
        get_field(vals, 'U').title()
    ])

    desc = desc_localization(vals)
    desc += desc_atendimento(vals)

    tags = [
        'Escola',
        get_field(vals, 'S'),
        get_field(vals, 'H').title(),
        get_field(vals, 'J').title()
    ]

    contato = desc_contato(vals)
    user = User.objects.get(username='******')
    now = datetime.now()

    # save data
    o = Organization()
    o.name = nome
    o.description = desc
    o.contact = contato
    o.creator = user
    o.creation_date = now
    o.save()

    # save m2m relations
    o.categories.add(category_id)
    for tag in tags:
        o.tags.add(tag)
Beispiel #12
0
    def test_get_organization_by_name(self):

        o1 = Organization(name = "Google")
        o2 = Organization(name = "Yahoo")
        o3 = Organization(name = "Ubisoft")

        o1.save()
        o2.save()
        o3.save()

        #test typical cases
        self.assertIsNotNone(get_organization_by_name(o1.name))
        self.assertIsNotNone(get_organization_by_name(o2.name))
        self.assertIsNotNone(get_organization_by_name(o3.name))

        self.assertEqual(get_organization_by_name(o1.name), o1)
        self.assertEqual(get_organization_by_name(o2.name), o2)
        self.assertEqual(get_organization_by_name(o3.name), o3)

        self.assertIsNone(get_organization_by_name("Apple"))
        self.assertIsNone(get_organization_by_name("IBM"))
        self.assertIsNone(get_organization_by_name("Cisco"))

        self.assertNotEqual(get_organization_by_name("Apple"), o1)
        self.assertNotEqual(get_organization_by_name("IBM"), o1)
        self.assertNotEqual(get_organization_by_name("Cisco"), o1)

        self.assertNotEqual(get_organization_by_name("Apple"), o2)
        self.assertNotEqual(get_organization_by_name("IBM"), o2)
        self.assertNotEqual(get_organization_by_name("Cisco"), o2)

        self.assertNotEqual(get_organization_by_name("Apple"), o3)
        self.assertNotEqual(get_organization_by_name("IBM"), o3)
        self.assertNotEqual(get_organization_by_name("Cisco"), o3)
Beispiel #13
0
    def test_get_organization_by_id(self):

        o1 = Organization(name = "Google")
        o2 = Organization(name = "Yahoo")
        o3 = Organization(name = "Ubisoft")

        o1.save()
        o2.save()
        o3.save()

        #test typical cases
        self.assertIsNotNone(get_organization_by_id(o1.id))
        self.assertIsNotNone(get_organization_by_id(o2.id))
        self.assertIsNotNone(get_organization_by_id(o3.id))

        self.assertEqual(get_organization_by_id(o1.id), o1)
        self.assertEqual(get_organization_by_id(o2.id), o2)
        self.assertEqual(get_organization_by_id(o3.id), o3)

        self.assertIsNone(get_organization_by_id(100))
        self.assertIsNone(get_organization_by_id(200))
        self.assertIsNone(get_organization_by_id(300))

        self.assertNotEqual(get_organization_by_id(100), o1)
        self.assertNotEqual(get_organization_by_id(200), o1)
        self.assertNotEqual(get_organization_by_id(300), o1)

        self.assertNotEqual(get_organization_by_id(100), o2)
        self.assertNotEqual(get_organization_by_id(200), o2)
        self.assertNotEqual(get_organization_by_id(300), o2)

        self.assertNotEqual(get_organization_by_id(100), o3)
        self.assertNotEqual(get_organization_by_id(200), o3)
        self.assertNotEqual(get_organization_by_id(300), o3)
Beispiel #14
0
 def setUp(self):
     self.user = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
     self.org = Organization(name='Foo Org')
     self.org.save()
     assign_admin_perms(self.org, self.user)
     self.invite = OrganizationInvite(email='*****@*****.**',
                                      organization=self.org,
                                      user=self.user)
     self.invite.token = get_random_string(
         length=20, allowed_chars='ABCDEFGHJKMNPQRST23456789')
     self.invite.save()
Beispiel #15
0
    def setup_test_data(cls):
        cls.o1 = Organization(name="Google")
        cls.o2 = Organization(name="Yahoo")

        cls.o1.save()
        cls.o2.save()

        volunteer_1 = [
            'Yoshi', "Yoshi", "Turtle", "Mario Land", "Nintendo Land",
            "Nintendo State", "Nintendo Nation", "2374983247",
            "*****@*****.**"
        ]
        cls.v1 = create_volunteer_with_details(volunteer_1, cls.o2)
Beispiel #16
0
class CreateInviteTestCase(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username="******", email="*****@*****.**", password="******")
        self.client.login(username="******", password="******")

    def test_create_invite(self):
        self.org = Organization(name="Foo Org")
        self.org.save()
        assign_admin_perms(self.org, self.user)
        url = reverse("api_invite_user", args=(self.org.id,))
        data = {"email": "*****@*****.**"}
        resp = self.client.post(url, data, format="json")
        self.assertEquals(20, len(resp.data["token"]))
        self.assertEquals(resp.data["user"]["id"], self.user.id)
Beispiel #17
0
 def post(self):
     args = self.parser.parse_args()
     org = Organization(name=args['name'],
                        owner_id=self.authorized_user.id,
                        org_type=args['org_type'],
                        org_desc=args['org_desc'])
     org.save(add=True)
     return jsonify({
         'adding':
         'OK',
         'organization':
         org.to_dict(only=('id', 'name', 'creation_date', 'owner_id',
                           'org_type', 'org_desc', 'api_token'))
     })
def save_obj(vals):
    # prepare data
    nome = ' '.join([
        get_field(vals, 'S'),
        get_field(vals, 'T').title(),
        get_field(vals, 'U').title()
    ])

    desc = desc_localization(vals)
    desc += desc_atendimento(vals)

    tags = ['Escola', get_field(vals, 'S'), get_field(vals, 'H').title(),
             get_field(vals, 'J').title()]

    contato = desc_contato(vals)
    user = User.objects.get(username='******')
    now = datetime.now()

    # save data
    o = Organization()
    o.name = nome
    o.description = desc
    o.contact = contato
    o.creator = user
    o.creation_date = now
    o.save()

    # save m2m relations
    o.categories.add(category_id)
    for tag in tags:
        o.tags.add(tag)
class ViewOrganizationTestCase(APITestCase):

    def setUp(self):
        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.client.login(username='******', password='******')
        self.organization = Organization(name='Foo Org')
        self.organization.save()
        assign_admin_perms(self.organization, self.user)
        self.url = reverse('api_retrieve_organization', args=(self.organization.id,))

    def test_view_organization(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['id'], self.organization.id)
        self.assertEqual(response.data['name'], self.organization.name)
        self.assertEqual(len(response.data['user_set']), len(self.organization.user_set.all()))
Beispiel #20
0
 def get_authorized_org():
     try:
         return Organization.get_by(
             id=jwt.decode(session['current_org_jwt'],
                           Config.JWT_SECRET_KEY)['payload']['id'])
     except (TypeError, KeyError):
         return None
Beispiel #21
0
 def get(self, org_id, jwt_):
     org = Organization.get_by(id=org_id)
     if org and check_tokens(jwt_, org.api_token):
         session['current_org_jwt'] = create_jwt(
             org.to_dict(only=('id', 'name')))
         return jsonify({'authorization': 'OK'})
     return jsonify({'error': 'incorrect Organization ID or JWT'})
Beispiel #22
0
def edit_organization(request, id='', *arg, **kwargs):
    organization = get_object_or_None(Organization, pk=id) or Organization()

    geojson = create_geojson([organization], convert=False)
    if geojson and geojson.get('features'):
        geojson['features'][0]['properties']['userCanEdit'] = True
    geojson = json.dumps(geojson)

    def on_get(request, form):
        form = FormOrganizationGeoRef(instance=organization)
        form.helper.form_action = reverse('edit_organization',
                                          kwargs={'id': organization.id})
        return form

    def on_after_save(request, obj):
        return {
            'redirect': reverse('view_organization', kwargs={'id': obj.id})
        }

    return {
        'on_get': on_get,
        'on_after_save': on_after_save,
        'geojson': geojson,
        'organization': organization
    }
Beispiel #23
0
class CreateInviteTestCase(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.client.login(username='******', password='******')

    def test_create_invite(self):
        self.org = Organization(name='Foo Org')
        self.org.save()
        assign_admin_perms(self.org, self.user)
        url = reverse('api_invite_user', args=(self.org.id, ))
        data = {"email": "*****@*****.**"}
        resp = self.client.post(url, data, format='json')
        self.assertEquals(20, len(resp.data['token']))
        self.assertEquals(resp.data['user']['id'], self.user.id)
Beispiel #24
0
def registration_view(request):
    if request.method == 'POST':
        if request.data.get('name', "") == "":
            return Response({"name": "Can't be empty"},
                            status=status.HTTP_400_BAD_REQUEST)

        num_count = Organization.objects.filter(
            name=request.data.get('name', "")).count()

        if num_count != 0:
            return Response({"name": "Already Exists"},
                            status=status.HTTP_400_BAD_REQUEST)

        new_org = Organization(name=request.data.get('name', ""))
        serializer = OrganizationSerializer(new_org, data=request.data)
        data = {}
        if serializer.is_valid():
            temp_org = serializer.save()

            profile = get_object_or_404(Profile, user=request.user)
            profile.organizations.add(temp_org)

            data['response'] = "Successfully Signed Up"
            data['id'] = temp_org.id
            data['name'] = temp_org.name
            data['title'] = temp_org.title
            data['date_created'] = temp_org.date_created.astimezone(
                timezone('Asia/Kolkata')).strftime("%Y-%m-%d %H:%M:%S")
            data['unique_code'] = temp_org.unique_code
            return Response(data)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Beispiel #25
0
 def setUp(self):
     self.user = User.objects.create_user(username="******", email="*****@*****.**", password="******")
     self.org = Organization(name="Foo Org")
     self.org.save()
     assign_admin_perms(self.org, self.user)
     self.invite = OrganizationInvite(email="*****@*****.**", organization=self.org, user=self.user)
     self.invite.token = get_random_string(length=20, allowed_chars="ABCDEFGHJKMNPQRST23456789")
     self.invite.save()
Beispiel #26
0
class StartInviteTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.org = Organization(name='Foo Org')
        self.org.save()
        assign_admin_perms(self.org, self.user)
        self.invite = OrganizationInvite(email='*****@*****.**',
                                         organization=self.org,
                                         user=self.user)
        self.invite.token = get_random_string(
            length=20, allowed_chars='ABCDEFGHJKMNPQRST23456789')
        self.invite.save()

    def test_receive_invite(self):
        url = reverse('start_invite',
                      args=(
                          self.invite.id,
                          self.invite.token,
                      ))
        resp = self.client.get(url)
        self.assertEquals(self.client.session['invite'], self.invite.id)
        self.assertEquals(resp.context['invite_user'], self.user)
        self.assertEquals(resp.context['organization'], self.org)
        self.assertEquals(resp.status_code, 200)

    def test_receive_invite_used(self):
        url = reverse('start_invite',
                      args=(
                          self.invite.id,
                          self.invite.token,
                      ))
        self.invite.is_used = True
        self.invite.save()
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 404)

    def test_receive_invite_does_not_exist(self):
        url = reverse('start_invite', args=(
            999,
            'fake',
        ))
        resp = self.client.get(url)
        self.assertEquals(resp.status_code, 404)
Beispiel #27
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    # If person isn't signed in, we don't want to let them visit this page yet
    if not request.user.is_authenticated():
        return redirect('/admin')

    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']

    # Check to see if this organization is already being used anywhere
    organization_on_stage_found = False
    try:
        # organization_query = Organization.objects.all()
        # organization_query = organization_query.filter(id=organization_id)
        organization_query = Organization.objects.filter(id=organization_id)
        if len(organization_query):
            organization_on_stage = organization_query[0]
            organization_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e)

    try:
        if organization_on_stage_found:
            # Update
            organization_on_stage.name = organization_name
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'Organization updated.')
        else:
            # Create new
            organization_on_stage = Organization(name=organization_name, )
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'New organization saved.')
    except Exception as e:
        handle_record_not_saved_exception(e)
        messages.add_message(request, messages.ERROR,
                             'Could not save organization.')

    return HttpResponseRedirect(
        reverse('organization:organization_list', args=()))
Beispiel #28
0
def add(request):
    
    if request.POST:

        organization_name = request.POST.get('organization_name', None)
        organization_desc = request.POST.get('organization_desc', None)
        level = request.POST.get('level', None)
        parent_organization_name = request.POST.get('org.parent_organization_name', None)
        
        
        #验证重复组织机构名称
        organization_names = Organization.objects.filter(organization_name__iexact=organization_name)
        if organization_names:
            return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId', 'organizationindex'), "callbackType":request.POST.get('callbackType',None), "message":u'组织机构名称已经存在不能添加'}), mimetype='application/json')
        else:
            organization = Organization(organization_name=organization_name, organization_desc=organization_desc, level=level)
            organization.save()
            
            if parent_organization_name != None and parent_organization_name != '':
                try:
                    parent_organization = Organization.objects.get(organization_name__iexact=parent_organization_name)
                except:
                    return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId', 'organizationindex'), "callbackType":request.POST.get('callbackType',None), "message":u'父级组织机构无效请重新选择或置空'}), mimetype='application/json')
                organization.parent_organization = parent_organization
            else:
                organization.parent_organization = organization
                
            organization.save()
            Log(username=request.user.username, content=u"成功添加组织机构信息: " + organization.organization_name, level=1).save()
            return HttpResponse(simplejson.dumps({"statusCode":200, "navTabId":request.POST.get('navTabId', 'organizationindex'), "callbackType":request.POST.get('callbackType','closeCurrent'), "message":u'添加成功'}), mimetype='application/json')
        
    return render_to_response('organization/add.html')
Beispiel #29
0
 def test_create_invite(self):
     self.org = Organization(name="Foo Org")
     self.org.save()
     assign_admin_perms(self.org, self.user)
     url = reverse("api_invite_user", args=(self.org.id,))
     data = {"email": "*****@*****.**"}
     resp = self.client.post(url, data, format="json")
     self.assertEquals(20, len(resp.data["token"]))
     self.assertEquals(resp.data["user"]["id"], self.user.id)
Beispiel #30
0
    def test_create_multiple_organization_method(self):
        org_list = Organization.create_multiple_organizations(3)

        # Check number of orgs created
        self.assertEqual(len(Organization.objects.all()), 3)

        # Check their names
        self.assertEqual(org_list[0].name, 'org-1')
        self.assertEqual(org_list[1].name, 'org-2')
        self.assertEqual(org_list[2].name, 'org-3')
Beispiel #31
0
 def get_active_order(user):
     timezone = Organization.objects.all()[0].timezone  # only one can exist
     timezone = pytz.timezone(str(timezone))
     # get active order for today
     cutoff = Organization.get_today_start_utc()
     active_order = Order.objects.filter(customer__user=user,
                                         timestamp__gte=cutoff,
                                         ordered=False)
     order_list = [order.json_format(timezone) for order in active_order]
     return order_list
Beispiel #32
0
    def test_create_multiple_organization_method(self):
        org_list = Organization.create_multiple_organizations(3)

        # Check number of orgs created
        self.assertEqual(len(Organization.objects.all()), 3)

        # Check their names
        self.assertEqual(org_list[0].name, 'org-1')
        self.assertEqual(org_list[1].name, 'org-2')
        self.assertEqual(org_list[2].name, 'org-3')
Beispiel #33
0
    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization,
                                        twilio_sid='xxx',
                                        phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.client.login(usernam='foo', password='******')

        self.url = reverse('api_create_conference',
                           args=(self.organization.id, ))
Beispiel #34
0
    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization,
                                        twilio_sid='xxx',
                                        phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.conference = Conference(organization=self.organization,
                                     name='My Conf',
                                     phone_number=self.phone_number)
        self.conference.save()
Beispiel #35
0
    def get_team_history(team, start_date, end_date):
        """only executor of the team will call this function to get the team's history"""
        timezone = Organization.objects.all()[0].timezone  # only one can exist
        timezone = pytz.timezone(str(timezone))

        start_date = parse(start_date)
        if end_date == "":
            end_date = datetime.datetime.now() + datetime.timedelta(days=1)
            end_date = end_date.date()
        else:
            end_date = parse(end_date)

        start_utc = Organization.convert_to_utc(start_date)
        end_utc = Organization.convert_to_utc(end_date)

        order_history = Order.objects.filter(
            team=team, timestamp__gte=start_utc).filter(timestamp__lte=end_utc)
        order_list = [o.json_format(timezone) for o in order_history]
        return order_list
Beispiel #36
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    # If person isn't signed in, we don't want to let them visit this page yet
    if not request.user.is_authenticated():
        return redirect('/admin')

    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']

    # Check to see if this organization is already being used anywhere
    organization_on_stage_found = False
    try:
        # organization_query = Organization.objects.all()
        # organization_query = organization_query.filter(id=organization_id)
        organization_query = Organization.objects.filter(id=organization_id)
        if len(organization_query):
            organization_on_stage = organization_query[0]
            organization_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e)

    try:
        if organization_on_stage_found:
            # Update
            organization_on_stage.name = organization_name
            organization_on_stage.save()
            messages.add_message(request, messages.INFO, 'Organization updated.')
        else:
            # Create new
            organization_on_stage = Organization(
                name=organization_name,
            )
            organization_on_stage.save()
            messages.add_message(request, messages.INFO, 'New organization saved.')
    except Exception as e:
        handle_record_not_saved_exception(e)
        messages.add_message(request, messages.ERROR, 'Could not save organization.')

    return HttpResponseRedirect(reverse('organization:organization_list', args=()))
Beispiel #37
0
    def test_delete_organization(self):
	
        o1 = Organization(name = "Google")
        o2 = Organization(name = "Yahoo")
        o3 = Organization(name = "Ubisoft")

        o1.save()
        o2.save()
        o3.save()
		
        self.assertTrue(delete_organization(o1.id))
        self.assertTrue(delete_organization(o2.id))
        self.assertTrue(delete_organization(o3.id))
        self.assertFalse(delete_organization(100))
        self.assertFalse(delete_organization(200))
        self.assertFalse(delete_organization(300))
Beispiel #38
0
    def get_order_history(user, days=30):
        # gets past ordered history
        timezone = Organization.objects.all()[0].timezone  # only one can exist
        timezone = pytz.timezone(str(timezone))

        today = Organization.get_today_start_utc()
        cutoff = today - datetime.timedelta(days=days)
        order_history = Order.objects.filter(customer__user=user,
                                             timestamp__gte=cutoff,
                                             ordered=True)
        order_list = [order.json_format(timezone) for order in order_history]
        return order_list
Beispiel #39
0
    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization, twilio_sid='xxx', phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.conference = Conference(organization=self.organization, name='My Conf', phone_number=self.phone_number)
        self.conference.save()
Beispiel #40
0
    def test_create_multiple_organization_method(self):
        """
        Test creation of multiple organization using fake factory function.
        """
        org_list = Organization.create_multiple_organizations(3)

        # Check number of orgs created
        self.assertEqual(len(Organization.objects.all()), 3)

        # Check their names
        self.assertEqual(org_list[0].name, 'org-1')
        self.assertEqual(org_list[1].name, 'org-2')
        self.assertEqual(org_list[2].name, 'org-3')
Beispiel #41
0
def registration_view(request):  # For signup
    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            user = serializer.save()
            refresh = RefreshToken.for_user(user)

            profile = get_object_or_404(Profile, user=user)
            org = Organization(name=user.username)
            org.save()

            profile.organizations.add(org)

            data['response'] = "Successfully Signed Up"
            data['username'] = user.username
            data['userid'] = user.id
            data['refresh'] = str(refresh)
            data['access'] = str(refresh.access_token)
            return Response(data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #42
0
    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization, twilio_sid='xxx', phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.client.login(usernam='foo', password='******')

        self.url = reverse('api_create_conference', args=(self.organization.id,))
Beispiel #43
0
class ConferenceResponseViewTestCase(TestCase):
    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization,
                                        twilio_sid='xxx',
                                        phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.conference = Conference(organization=self.organization,
                                     name='My Conf',
                                     phone_number=self.phone_number)
        self.conference.save()

    def test_incoming_call(self):
        self.conference.user_set.add(self.user)
        call = Call(conference=self.conference,
                    user=self.user,
                    twilio_sid='888')
        call.save()
        self.assertEquals(call.call_state, call.INCOMING)

        url = reverse('conference_response', args=(self.conference.id, ))
        resp = self.client.post(url, {'CallSid': call.twilio_sid})
        #self.assertContains(resp.content, self.conference.name)
        call_result = Call.objects.get(id=call.id)
        self.assertEquals(call_result.call_state, Call.IN_CALL)
        self.assertTrue(
            CallEvent.objects.filter(call=call,
                                     event_type=CallEvent.JOIN).exists())
def save_obj(vals):
    tipo, name, endereco, contato = vals
    contact = "{}\n{}".format(endereco, contato)

    o = Organization()

    o.name = name.title().replace('Emei',
                                  'EMEI').replace('Emef',
                                                  'EMEF').replace('Ee', 'EE')
    o.contact = contact
    o.description = ''

    o.creator = elaste
    o.creation_date = datetime.now()

    o.save()
    for t in [tipo, 'Jacareí']:
        o.tags.add(t)

    o.community.add(jacarei)
Beispiel #45
0
    def setup_test_data(cls):
        cls.o1 = Organization(name="Google")
        cls.o2 = Organization(name="Yahoo")

        cls.o1.save()
        cls.o2.save()
        city_name = 'Bothell'
        state_name = 'Washington'
        country_name = 'United States'
        country = get_country_by_name(country_name)
        state = get_state_by_name(state_name)
        city = get_city_by_name(city_name)
        volunteer_1 = {
            'username': '******',
            'first_name': "Yoshi",
            'last_name': "Turtle",
            'address': "Mario Land",
            'city': city,
            'state': state,
            'country': country,
            'phone_number': "2374983247",
            'email': "*****@*****.**"
        }
        cls.v1 = create_volunteer_with_details(volunteer_1, cls.o2)
def save_obj(vals):
    tipo, name, endereco, contato = vals
    contact = "{}\n{}".format(endereco, contato)

    o = Organization()

    o.name = name.title().replace('Emei', 'EMEI').replace('Emef', 'EMEF'
        ).replace('Ee', 'EE')
    o.contact = contact
    o.description = ''

    o.creator = elaste
    o.creation_date = datetime.now()

    o.save()
    for t in [tipo, 'Jacareí']:
        o.tags.add(t)

    o.community.add(jacarei)
Beispiel #47
0
    def order_summary(team):
        timezone = Organization.objects.all()[0].timezone  # only one can exist
        timezone = pytz.timezone(str(timezone))

        today = Organization.get_today_start_utc()
        unordered = Order.objects.filter(team=team,
                                         timestamp__gte=today,
                                         ordered=False)
        unordered_json = [u.json_format(timezone) for u in unordered]

        all_orders = Order.objects.filter(team=team, timestamp__gte=today)
        all_orders_json = [o.json_format(timezone) for o in all_orders]

        if len(unordered_json):
            unordered_df = pd.DataFrame(unordered_json)

            unordered_df['price'] = unordered_df['price'].astype('float32')
            meals_by_vendors = unordered_df.groupby(["vendor",
                                                     "meal"]).size().to_dict()
            meals_by_vendors_json = {}
            for (vendor, meal), v in meals_by_vendors.items():
                try:
                    meals_by_vendors_json[vendor][meal] = v
                except KeyError:
                    meals_by_vendors_json[vendor] = {meal: v}

            total_owning_by_vendors_json = unordered_df.groupby(
                "vendor").sum().to_dict()
        else:
            meals_by_vendors_json = {'': {'': ''}}
            total_owning_by_vendors_json = {'': ''}

        vendor_info = [v.json_format() for v in team.vendors.all()]

        return {
            'meals_by_vendors':
            meals_by_vendors_json,
            'total_owning_by_vendors':
            total_owning_by_vendors_json,
            'vendor_info':
            vendor_info,
            'detail_order_info':
            sorted(all_orders_json, key=lambda x: (x['vendor'], x['meal']))
        }
Beispiel #48
0
def personnel_department(org_id):
    org = Organization.get_by_id(current_user, org_id)
    if org is None:
        return abort(403)
    if request.method == 'POST':
        Vacancy(org_id=org_id,
                salary=request.form['salary'],
                title=request.form['title']).save(add=True)

    organization_info = {
        'org': org,
        'personnel': org.personnels,
        'workers': org.get_workers(),
        'required_workers': org.get_required_workers(),
    }

    return render_template("personnel_department.html",
                           **organization_info,
                           len=len)
def new_organizations(access_points):

    organizations = []

    for index in range(3):

        org = {
            'Organization_OrganizationName': {
                'sources': access_points,
                'value': 'New Test organization {}'.format(index),
                'confidence': '1',
            },
            'Organization_OrganizationDivisionId': {
                'sources': access_points,
                'value': 'ocd-division/country:us',
                'confidence': '1',
            }
        }

        organization = Organization.create(org)

        organizations.append(organization)

    return organizations
Beispiel #50
0
	def get(self):
		self.response.headers['Content-Type'] = 'application/json'
		target = self.request.get('target')

		url = '%s%s/api/organization/tree?entity=%s' % (config.PROTOCOL, config.APP_HOSTNAME, target)
		result = urlfetch.fetch(url)
		if result.status_code == 200:
			orgtree = json.loads(result.content)
		else:
			orgtree = None

		logging.warning('DEBUG OperationList - orgtree: %s' % str(orgtree))

		key = ndb.Key(urlsafe = target)
		operationlist = []
		replaced = []
		has_parent = True
		if orgtree is not None:
			while has_parent:
				if key.kind() == 'CN':
					entity = CN.get_by_key(key.urlsafe())
					operations = CustomOperation.fetch_by_target(entity.key.urlsafe())
				if key.kind() == 'OU':
					entity = OU.get_by_key(key.urlsafe())
					operations = Operation.fetch_by_target(entity.key.urlsafe())
				if key.kind() == 'Organization':
					entity = Organization.get_by_key(key.urlsafe())
					operations = Operation.fetch_by_target(entity.key.urlsafe())
					has_parent = False
				
				for operation in operations:
					operationdict = {'key': operation.key.urlsafe(), 'name': operation.name, 'target': operation.target.urlsafe(), 'target_kind': key.kind(), 'direction': operation.direction, 'amount': operation.amount, 'frequency': operation.frequency, 'cutoff_date': json.loads(operation.cutoff_date), 'delay_raise': operation.delay_raise, 'created': tools.datetime_to_str(operation.created), 'updated': tools.datetime_to_str(operation.updated)}

					if key.kind() == 'CN':
						operationdict['parent'] = operation.parent.urlsafe()
						replaced.append(operation.parent.urlsafe())

					operationlist.append(operationdict)

				if has_parent:
					key = entity.parent

		index = 0
		operationlist_clone = operationlist[:]
		for operation in operationlist_clone:
			logging.warning('DEBUG OperationList multidirectional - replaced: %s - operation[key]: %s- in: %s' % (str(replaced), operation['key'], str(operation['key'] in replaced)))
			if operation['key'] in replaced:
				operationlist.pop(index)
			else:
				index += 1
			logging.warning('operationlist(%i) - operationlist_clone(%i)' % (len(operationlist), len(operationlist_clone)))

		if self.request.get('direction') in ['in', 'out']:
			index = 0
			oplist_clone = operationlist[:]
			logging.warning('DEBUG OperationList unidirectional - operationlist(%i): %s' % (len(oplist_clone), str(operationlist)))
			for op in oplist_clone:
				if op['direction'] != self.request.get('direction'):
					operationlist.pop(index)
				else:
					index += 1
				logging.warning('operationlist(%i) - operationlist_clone(%i)' % (len(operationlist), len(oplist_clone)))

		self.response.write(json.dumps(operationlist))
    def test_search_volunteers(self):

        o1 = Organization(name="Apple")
        o2 = Organization(name="Google")

        o1.save()
        o2.save()

        self.v1.organization=o1
        self.v2.organization=o2
        self.v3.unlisted_organization="Government of Canada"

        self.v1.save()
        self.v2.save()
        self.v3.save()

        # if no search parameters are given,
        # it returns all volunteers
        search_list = search_volunteers("", "", "", "", "", "")
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 3)
        self.assertIn(self.v1, search_list)
        self.assertIn(self.v2, search_list)
        self.assertIn(self.v3, search_list)

        search_list = search_volunteers(None, None, None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 3)
        self.assertIn(self.v1, search_list)
        self.assertIn(self.v2, search_list)
        self.assertIn(self.v3, search_list)

        # test exact search
        search_list = search_volunteers(
                                        "Yoshi",
                                        "Turtle",
                                        "Nintendo Land",
                                        "Nintendo State",
                                        "Nintendo Nation",
                                        "Apple"
                                        )
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 1)
        self.assertIn(self.v1, search_list)
        self.assertNotIn(self.v2, search_list)
        self.assertNotIn(self.v3, search_list)

        # test partial search
        search_list = search_volunteers("Yoshi", None, None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 1)
        self.assertIn(self.v1, search_list)
        self.assertNotIn(self.v2, search_list)
        self.assertNotIn(self.v3, search_list)

        search_list = search_volunteers(None, "Doe", None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 2)
        self.assertIn(self.v3, search_list)
        self.assertIn(self.v2, search_list)

        # test no search matches
        search_list = search_volunteers(
                                        "Billy",
                                        "Doe",
                                        "Montreal",
                                        "Quebec",
                                        "Canada",
                                        "Ubisoft"
                                        )
        self.assertEqual(len(search_list), 0)
        self.assertNotIn(self.v1, search_list)
        self.assertNotIn(self.v2, search_list)
        self.assertNotIn(self.v3, search_list)
    def test_search_volunteers(self):
 
        u1 = User.objects.create_user('Yoshi')
        u2 = User.objects.create_user('Ashley')
        u3 = User.objects.create_user('Zelda')

        o1 = Organization(organization_name = "Apple")
        o2 = Organization(organization_name = "Google")

        o1.save()
        o2.save()

        v1 = Volunteer(first_name = "Yoshi",
                        last_name = "Doe",
                        address = "7 Oak Street",
                        city = "Elmgrove",
                        state = "California",
                        country = "USA",
                        phone_number = "23454545",
                        organization = o1,
                        email = "*****@*****.**",
                        user = u1)

        v2 = Volunteer(first_name = "Ashley",
                        last_name = "Doe",
                        address = "7 Alpine Street",
                        city = "Maplegrove",
                        state = "Wyoming",
                        country = "USA",
                        phone_number = "23454545",
                        organization = o2,
                        email = "*****@*****.**",
                        user = u2)

        v3 = Volunteer(id = 999,
                        first_name = "Zelda",
                        last_name = "Doe",
                        address = "7 Elm Street",
                        city = "Oakgrove",
                        state = "California",
                        country = "USA",
                        phone_number = "23454545",
                        unlisted_organization = "Government of Canada",
                        email = "*****@*****.**",
                        user = u3)               

        v1.save()
        v2.save()
        v3.save()

        #if no search parameters are given, it returns all volunteers 
        search_list = search_volunteers("", "", "", "", "", "")
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 3)
        self.assertIn(v1, search_list)
        self.assertIn(v2, search_list)
        self.assertIn(v3, search_list)

        search_list = search_volunteers(None, None, None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 3)
        self.assertIn(v1, search_list)
        self.assertIn(v2, search_list)
        self.assertIn(v3, search_list)

        #test exact search
        search_list = search_volunteers("Yoshi", "Doe", "Elmgrove", "California", "USA", "Apple")
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 1)
        self.assertIn(v1, search_list)
        self.assertNotIn(v2, search_list)
        self.assertNotIn(v3, search_list)

        #test partial search
        search_list = search_volunteers("Yoshi", None, None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 1)
        self.assertIn(v1, search_list)
        self.assertNotIn(v2, search_list)
        self.assertNotIn(v3, search_list)

        search_list = search_volunteers(None, "Doe", None, None, None, None)
        self.assertNotEqual(search_list, False)
        self.assertEqual(len(search_list), 3)
        self.assertIn(v1, search_list)
        self.assertIn(v2, search_list)
        self.assertIn(v3, search_list)

        #test no search matches
        search_list = search_volunteers("Billy", "Doe", "Montreal", "Quebec", "Canada", "Ubisoft")
        self.assertEqual(len(search_list), 0)
        self.assertNotIn(v1, search_list)
        self.assertNotIn(v2, search_list)
        self.assertNotIn(v3, search_list)
Beispiel #53
0
    def test_get_organizations_ordered_by_name(self):

        o1 = Organization(name = "Google")
        o2 = Organization(name = "Yahoo")
        o3 = Organization(name = "Ubisoft")
        o4 = Organization(name = "IBM")
        o5 = Organization(name = "Cisco")

        o1.save()
        o2.save()
        o3.save()
        o4.save()
        o5.save()

        #test typical cases
        organization_list = get_organizations_ordered_by_name()
        self.assertIsNotNone(organization_list)
        self.assertIn(o1, organization_list)
        self.assertIn(o2, organization_list)
        self.assertIn(o3, organization_list)
        self.assertIn(o4, organization_list)
        self.assertIn(o5, organization_list)
        self.assertEqual(len(organization_list), 5)

        #test order
        self.assertEqual(organization_list[0], o5)
        self.assertEqual(organization_list[1], o1)
        self.assertEqual(organization_list[2], o4)
        self.assertEqual(organization_list[3], o3)
        self.assertEqual(organization_list[4], o2)
Beispiel #54
0
class CreateConferenceTestCase(APITestCase):

    def setUp(self):
        self.organization = Organization(name='Foo Org')
        self.organization.save()

        self.phone_number = PhoneNumber(organization=self.organization, twilio_sid='xxx', phone_number='+15550009999')
        self.phone_number.save()

        self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        self.user.userprofile.phone_number = "5556667777"
        self.user.userprofile.save()

        self.client.login(usernam='foo', password='******')

        self.url = reverse('api_create_conference', args=(self.organization.id,))

    @patch.object(ConferenceCallService, '_make_call')
    def test_create_conference_with_no_participants(self, mock_method):
        mock_method.return_value = '123'
        data = {
            "name": "Lonely Conference",
            "phone_number": self.phone_number.id,
            "users": []
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(Conference.objects.filter(name=data["name"]).exists())
        self.assertFalse(mock_method.called)

    @patch.object(ConferenceCallService, '_make_call')
    def test_create_conference_with_self_participants(self, mock_method):
        mock_method.return_value = '123'
        data = {
            "name": "Lonely Conference",
            "user_set": [
                self.user.id
            ]
        }

        response = self.client.post(self.url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertTrue(Conference.objects.filter(name=data["name"]).exists())
        conf = Conference.objects.get(id=response.data['id'])
        self.assertEquals(conf.organization, self.organization)
        self.assertEquals(len(conf.user_set.all()), 1)
        self.assertEquals(conf.user_set.all()[0], self.user)
        self.assertTrue(mock_method.called)

    @patch.object(ConferenceCallService, '_make_call')
    def test_create_conference_with_multiple_participants(self, mock_method):
        mock_method.return_value = '123'
        new_user = User.objects.create_user(username='******', email='*****@*****.**', password='******')
        new_user.userprofile.phone_number = "5556667777"
        new_user.userprofile.save()


        data = {
            "name": "Party Conference",
            "phone_number": self.phone_number.id,
            "user_set": [
                self.user.id,
                new_user.id
            ]
        }

        response = self.client.post(self.url, data, format='json')
        conf = Conference.objects.get(id=response.data['id'])
        self.assertEquals(len(conf.user_set.all()), 2)
Beispiel #55
0
def import_we_vote_organizations_from_json(request, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    if load_from_uri:
        # Request json file from We Vote servers
        print "Loading Organizations from We Vote Master servers"
        request = requests.get(ORGANIZATIONS_URL, params={
            "key": WE_VOTE_API_KEY,  # This comes from an environment variable
        })
        structured_json = json.loads(request.text)
    else:
        # Load saved json from local file
        print "Loading organizations from local file"

        with open(ORGANIZATIONS_JSON_FILE) as json_data:
            structured_json = json.load(json_data)

    for one_organization in structured_json:
        print "id_we_vote: {id_we_vote}, name: {name}, url: {url}".format(id_we_vote=one_organization["id_we_vote"],
                                                                          name=one_organization["name"],
                                                                          url=one_organization["url"],)
        # Make sure we have the minimum required variables
        if len(one_organization["id_we_vote"]) == 0 or len(one_organization["name"]) == 0:
            continue

        # Check to see if this organization is already being used anywhere
        organization_on_stage_found = False
        try:
            if len(one_organization["id_we_vote"]) > 0:
                organization_query = Organization.objects.filter(id_we_vote=one_organization["id_we_vote"])
                if len(organization_query):
                    organization_on_stage = organization_query[0]
                    organization_on_stage_found = True
            elif len(one_organization["name"]) > 0:
                organization_query = Organization.objects.filter(name=one_organization["name"])
                if len(organization_query):
                    organization_on_stage = organization_query[0]
                    organization_on_stage_found = True
        except Exception as e:
            handle_record_not_found_exception(e)

        try:
            if organization_on_stage_found:
                # Update
                organization_on_stage.id_we_vote = one_organization["id_we_vote"]
                organization_on_stage.name = one_organization["name"]
                organization_on_stage.url = one_organization["url"]
                organization_on_stage.save()
                messages.add_message(request, messages.INFO, "Organization updated: {name}".format(
                    name=one_organization["name"]))
            else:
                # Create new
                organization_on_stage = Organization(
                    id_we_vote=one_organization["id_we_vote"],
                    name=one_organization["name"],
                    url=one_organization["url"],
                )
                organization_on_stage.save()
                messages.add_message(request, messages.INFO, "New organization imported: {name}".format(
                    name=one_organization["name"]))
        except Exception as e:
            handle_record_not_saved_exception(e)
            messages.add_message(
                request, messages.ERROR,
                "Could not save Organization, id_we_vote: {id_we_vote}, name: {name}, url: {url}".format(
                    id_we_vote=one_organization["id_we_vote"],
                    name=one_organization["name"],
                    url=one_organization["url"],))
Beispiel #56
0
def organizations_import_from_sample_file(request=None, load_from_uri=False):  # TODO FINISH BUILDING/TESTING THIS
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     logger.info("Loading Organizations from We Vote Master servers")
    #     request = requests.get(ORGANIZATIONS_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file
    logger.info("Loading organizations from local file")

    with open('organization/import_data/organizations_sample.json') as json_data:
        structured_json = json.load(json_data)

    organizations_saved = 0
    organizations_updated = 0
    organizations_not_processed = 0
    for one_organization in structured_json:
        logger.debug(
            u"we_vote_id: {we_vote_id}, organization_name: {organization_name}, "
            u"organization_website: {organization_website}".format(**one_organization)
        )
        # Make sure we have the minimum required variables
        if not positive_value_exists(one_organization["we_vote_id"]) or \
                not positive_value_exists(one_organization["organization_name"]):
            organizations_not_processed += 1
            continue

        # Check to see if this organization is already being used anywhere
        organization_on_stage_found = False
        try:
            if positive_value_exists(one_organization["we_vote_id"]):
                organization_query = Organization.objects.filter(we_vote_id=one_organization["we_vote_id"])
                if len(organization_query):
                    organization_on_stage = organization_query[0]
                    organization_on_stage_found = True
            elif positive_value_exists(one_organization["organization_name"]):
                organization_query = Organization.objects.filter(
                    organization_name=one_organization["organization_name"])
                if len(organization_query):
                    organization_on_stage = organization_query[0]
                    organization_on_stage_found = True
        except Organization.DoesNotExist:
            # No problem that we aren't finding existing organization
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        try:
            if organization_on_stage_found:
                # Update
                organization_on_stage.we_vote_id = one_organization["we_vote_id"]
                organization_on_stage.organization_name = one_organization["organization_name"]
                organization_on_stage.organization_website = one_organization["organization_website"]
                organization_on_stage.organization_twitter_handle = one_organization["organization_twitter_handle"]
                organization_on_stage.save()
                # messages.add_message(request, messages.INFO, u"Organization updated: {organization_name}".format(
                #     organization_name=one_organization["organization_name"]))
                organizations_updated += 1
            else:
                # Create new
                organization_on_stage = Organization(
                    we_vote_id=one_organization["we_vote_id"],
                    organization_name=one_organization["organization_name"],
                    organization_twitter_handle=one_organization["organization_twitter_handle"],
                    organization_website=one_organization["organization_website"],
                    organization_email=one_organization["organization_email"] if 'organization_email' in
                                                                                 one_organization else '',
                    organization_facebook=one_organization["organization_facebook"] if 'organization_facebook' in
                                                                                       one_organization else '',
                    organization_image=one_organization["organization_image"] if 'organization_image' in
                                                                                 one_organization else '',
                )
                organization_on_stage.save()
                organizations_saved += 1
                # messages.add_message(request, messages.INFO, u"New organization imported: {organization_name}".format(
                #     organization_name=one_organization["organization_name"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            if request is not None:
                messages.add_message(request, messages.ERROR,
                                     "Could not save Organization, we_vote_id: {we_vote_id}, "
                                     "organization_name: {organization_name}, "
                                     "organization_website: {organization_website}".format(
                                         we_vote_id=one_organization["we_vote_id"],
                                         organization_name=one_organization["organization_name"],
                                         organization_website=one_organization["organization_website"],
                                     ))
            organizations_not_processed += 1

    organizations_results = {
        'saved': organizations_saved,
        'updated': organizations_updated,
        'not_processed': organizations_not_processed,
    }
    return organizations_results
Beispiel #57
0
def save_org(vals):
    name = "{} {}".format(
            get_field(vals, 'D'), get_field(vals, 'E'))

    desc = """
####Localização

{C} fica no distrito {K} da Subprefeitura {L} da capital paulista.

####Horário de Atendimento

{Y}

""".format(
        C=get_field(vals, 'C'),
        K=get_field(vals, 'K'),
        L=get_field(vals, 'L'),
        Y=get_field(vals, 'Y'),
    )

    if get_field(vals, 'G') or get_field(vals, 'S'):
        desc += """
####Registros e Certificações

"""
        if get_field(vals, 'G'):
            desc += """
- Código INEP da Instituição de Ensino: {G}""".format(G=get_field(vals, 'G'))
        if get_field(vals, 'S'):
            desc += """
- Cadastro Nacional de Pessoa Jurídica (CNPJ): {S}""".format(S=get_field(
                                                                vals, 'S'))

    desc += """

####Referência

- [{U}]({V} "{W}"), {X}
    """.format(
        U=get_field(vals, 'U'),
        V=get_field(vals, 'V'),
        W=get_field(vals, 'W'),
        X=get_field(vals, 'X'),
    )

    contact = """
{H}, {I} | {J}
CEP: {M}, São Paulo-SP

Fone: {O} {P}

Email: {Q}
    """.format(
        H=get_field(vals, 'H'),
        I=get_field(vals, 'I'),
        J=get_field(vals, 'J'),
        M=get_field(vals, 'M'),
        O=get_field(vals, 'O'),
        P=get_field(vals, 'P'),
        Q=get_field(vals, 'Q'),
    )

    link = get_field(vals, 'R')

    cat = get_field(vals, 'T')
    if cat == 'Cultura': cat = 'Cultura e Arte'
    categoria = ''
    if cat:
        cat = OrganizationCategoryTranslation.objects.filter(name__icontains=cat)
        if cat.count():
            categoria =cat[0].category


    # Palavras-Chave
    tags = [get_field(vals, f) for f in [ 'Z', 'AA', 'AB', 'AC', 'AD', 'AE'] ]

    # Público-Alvo
    public = [get_field(vals, f) for f in [
        'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP']]

    now = datetime.now()

    o = Organization()
    o.name = name
    o.description = desc
    o.contact = contact
    o.link = link
    o.category = categoria
    o.creation_date = now
    o.creator = mariarita
    o.save()
    for t in tags:
        o.tags.add(t)
    for p in public:
        p, c = TargetAudience.objects.get_or_create(name=p)
        o.target_audiences.add(p)
    print 'OK'
def save_obj(vals):
    imp, transf, comunidade, name, desc, folder, tipo, geom = vals
    geom = eval(geom)
    print type(geom)
    print 'saving: ', vals
    if ',' in comunidade:
        comunidade = comunidade.split(',')[0]
    if comunidade == 'morro-do-INPS':
        comunidade = 'morro-do-inps'
    elif comunidade == 'mineiros':
        comunidade = 'morro-dos-mineiros'
    elif comunidade == 'conjunto-habitacional-BNH':
        comunidade = 'conjunto-habitacional-bnh'


    if transf == 'sim':
        tipo = 'polys'
        x,y, z = map(float, geom[0].split(','))
        geom = []
        geom.append('%s,%s,%s' % (x + 0.0005, y + 0.0005, z))
        geom.append('%s,%s,%s' % (x + 0.0005, y - 0.0005, z))
        geom.append('%s,%s,%s' % (x - 0.0005, y - 0.0005, z))
        geom.append('%s,%s,%s' % (x - 0.0005, y + 0.0005, z))
        geom.append('%s,%s,%s' % (x + 0.0005, y + 0.0005, z))

    if tipo == 'polys':
        coords = ''
        for i, coord in enumerate(geom):
            x,y, z = coord.split(',')
            coords += '%s %s' % (y, x)
            if not i == len(geom) - 1:
                coords += ', '
        geo_ref = 'GEOMETRYCOLLECTION ( POLYGON (( %s )))' % coords
    elif tipo == 'point':
        x,y, z = geom[0].split(',')
        geo_ref = 'GEOMETRYCOLLECTION ( POINT ( %s %s))' % (y, x)


    if imp == 'R':
        r = Resource()
        r.name = name
        r.description = desc
        if comunidade:
            c = Community.objects.get(slug=comunidade)
            r.community = c
        r.geometry = geo_ref
        r.save()

    elif imp == 'N':
        n = Need()
        n.title = name
        n.description = desc
        if comunidade:
            c = Community.objects.get(slug=comunidade)
            n.community = c
        n.geometry = geo_ref
        # n.target_audiences.add(1)
        n.save()

    elif imp == 'O':
        if name:
            o = Organization()
            o.name = name
            o.description = desc
            o.save()
            if comunidade:
                c = Community.objects.get(slug=comunidade)
                o.community.add(c)

            b = OrganizationBranch()
            b.name = name + ' - sede'
            b.geometry = geo_ref
            b.organization = o
            b.save()