예제 #1
0
    def save(self, event = None):
        assert event
        contact = Contact(first_name = self.cleaned_data['first_name'],
                          middle_initial = self.cleaned_data['middle_initial'],
                          last_name = self.cleaned_data['last_name'],
                          title = self.cleaned_data['title'],
                          email = self.cleaned_data['email'],
                          phone1 = self.cleaned_data['phone1'],
                          addr1_row1 = self.cleaned_data['addr1_row1'],
                          addr1_row2 = self.cleaned_data['addr1_row2'],
                          addr1_city = self.cleaned_data['addr1_city'],
                          addr1_state = self.cleaned_data['addr1_state'],
                          addr1_zip = self.cleaned_data['addr1_zip'],
                          addr1_country = self.cleaned_data['addr1_country'])

        contact.save()

        registrant = Registrant(event = event,
                                contact = contact,
                                pending = True,
                                discount_code = self.cleaned_data['discount_code'])

        registrant.save()

        return registrant
    def handle(self, *args, **options):
        contact_data = list(csv.DictReader(open(args[0],'rb')))

        # Check first row for List entries and add new lists to db.
        # List entries are prefixed with "List: ", e.g. "List: master"
        list_lkup = get_list_lkup(contact_data[0])

        # Load Contact records
        updated = 0
        for row in contact_data:
            # Create/Update contact
            payload, list_memberships = process_row(row, list_lkup)
            try:
                contact = Contact.objects.get(email_address=payload['email_address'])
                contact.__dict__.update(payload)
            except Contact.DoesNotExist:
                contact = Contact(**payload)
            contact.status = 'active'
            contact.save()
            updated += 1

            # Update Contact's List entries
            lists_added_to = 0
            for contact_list in list_memberships:
                # If Contact/List combo already exists, it will violate
                # a uniqueness constraint and raise an IntegrityError
                try:
                    membership = ListMembership(contact=contact, contact_list=contact_list)
                    membership.save()
                    lists_added_to += 1
                except IntegrityError:
                    pass
            print "Created/Updated: %s with %s lists" % (contact, lists_added_to) 

        print "Created/Updated %s Contacts" % updated
예제 #3
0
파일: views.py 프로젝트: SevenKeys/Invoices
    def form_valid(self,form):
        new_company = form.save(commit=False)
        
        # get from request Contact data
        contact = Contact(phone_number=self.request.POST['phone_number'],
                          email=self.request.POST['email'],
                          street=self.request.POST['street'],
                          city=self.request.POST['city'],
                          postcode=self.request.POST['postcode'],
                          country=self.request.POST['country'],
                          website=self.request.POST['website'])
        contact.save()
        # write user's first and last names
        full_name = self.request.POST['full_user_name']
        register_user = self.request.user
        if len(full_name.split(' '))==2:
            print('name is twofold')
            register_user.first_name = full_name.split(' ')[0] 
            register_user.last_name = full_name.split(' ')[1]
            register_user.save()

        # connect the new company with Contact model
        new_company.contact = contact
        new_company.save()
        # connect data - company, user and contact
        current_user = UserProfile.objects.get(user=register_user)
        current_user.name = full_name
        new_company.userprofile_set.add(current_user)

        contact.userprofile_set.add(current_user)
        return super(AddCompany, self).form_valid(form)
def import_csv(imported_file):
    for i, v in enumerate(imported_file.splitlines()):
        if i == 0:
            continue
        else:
            v = v.split(',')
            contact = Contact(firstName=v[0], lastName=v[1], phone=v[2], email=v[3])
            contact.save()
예제 #5
0
def upload_contacts_csv(request):
    if request.method == 'POST':
        form = ContactCSVUploadForm(request.POST, request.FILES)
        if form.is_valid():
            Contact.insert_contacts_from_csv(request.FILES['file'])
            return HttpResponseRedirect('/admin/contacts/contact/')
    else:
        form = ContactCSVUploadForm()
    return render_to_response('upload.html', {'form': form}, RequestContext(request))
예제 #6
0
 def handle(self, *args, **options):
     Contact.objects.all().delete()
     with open(
             r'C:\Users\flux\programs\class_raccoon\Code\Matthew\django\mysite\contacts\management\commands\contacts.json',
             'r') as f:
         data = f.read()
     data = json.loads(data)
     for data_contact in data['contacts']:
         contact = Contact(**data_contact)
         contact.save()
    def test_contact_needed_detect_not_contacted_at_all(self):
        # GIVEN: new contact without last contact date
        contact = Contact(firstName='Test', lastName='Test', age=33, notificationsFrequency=24, gender=1, isActive=True)
        contact.save()

        # WHEN: run get_contact_needed
        results = StatsView.get_contact_needed()

        # THEN: expect the given contact in the results
        self.assertIn(contact, results)
    def test_contact_needed_postponed_but_active_again(self):
        # GIVEN: new contact without last contact date and postponed in past
        contact = Contact(firstName='Test', lastName='Test', age=33, notificationsFrequency=24, gender=1, isActive=True,
                          postponed=timezone.now()-datetime.timedelta(days=1))
        contact.save()

        # WHEN: run get_contact_needed
        results = StatsView.get_contact_needed()

        # THEN: expect the given contact in the results
        self.assertIn(contact, results)
예제 #9
0
 def test_contact_queryset_is_all_contacts(self):
     """Contact view should show all contacts."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     contacts = self.client.get('/api/texts/')
     self.assertEqual(len(contacts.json()), 0)
     jabba = Contact(name="Jabba", number="+2068675309")
     jabba.save()
     contacts = self.client.get('/api/contacts/list/')
     self.assertEqual(len(contacts.json()), 11)
예제 #10
0
파일: tests.py 프로젝트: rwisecar/Pyphon
 def test_contact_add_view_post_existing_number(self):
     """Test adding a new contact with existing number doesn't create new contact."""
     contact = Contact(name="some name", number='+12345678910')
     contact.save()
     old_contact_count = Contact.objects.count()
     self.client.post(reverse_lazy("new_contact"), {
         "name": "test",
         "number": "+12345678910"
     })
     new_contact_count = Contact.objects.count()
     self.assertEqual(old_contact_count, new_contact_count)
def new(request):
    user_profile = request.user.userprofile_set.filter()[0]
    form_categories = Category.objects.filter(owner=user_profile)

    if request.method == "GET":
        current_user = request.user
        form = ContactForm(current_user=current_user)
        user_profile = request.user.userprofile_set.filter()[0]
        form_categories = Category.objects.filter(owner=user_profile)
        print(len(form_categories))
        return render(request, 'contacts/new_contact_form.html', {
            'form': form,
            'title': "New Contact",
            'categories': form_categories
        })
    else:
        form = ContactForm(data=request.POST, current_user=request.user)

        if form.is_valid():
            try:
                user_profile = get_user_profile(request)
                age = form.cleaned_data['age']
                name = form.cleaned_data['name']
                public = form.cleaned_data['public']
                category_id = form.cleaned_data['category']
                category = Category.objects.filter(id=category_id)[0]
                contact = Contact(age=age,
                                  name=name,
                                  public=public,
                                  owner=user_profile,
                                  category=category)
                contact.save()
                messages.add_message(request, messages.SUCCESS,
                                     "Contact successfully created")
                return redirect('/contacts/')
            except:
                messages.add_message(request, messages.ERROR,
                                     "Contact creation unsuccessful")
                return render(
                    request, 'contacts/new_contact_form.html', {
                        'form': form,
                        'title': "New Contact",
                        'categories': form_categories
                    })
        else:
            messages.add_message(request, messages.ERROR,
                                 "Contact creation unsuccessful")
            return render(
                request, 'contacts/new_contact_form.html', {
                    'form': form,
                    'title': "New Contact",
                    'categories': form_categories
                })
예제 #12
0
 def test_get_contact_by_number_returns_right_contact(self):
     """Should return contact with given number."""
     view = GetContactByNumber.as_view()
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     request = self.request.get('/sf', number='1')
     request.user = user1
     jabba = Contact(name="Jabba the Hutt", number="+2068675309")
     jabba.save()
     response = view(request, number=2068675309)
     self.assertIn('Jabba the Hutt', response.rendered_content.decode())
예제 #13
0
    def setUp(self):
        self.url = "/search/?q={}"

        user = User.objects.create(username="******")
        self.client = APIClient()
        self.client.force_authenticate(user=user)

        self.first_contact = Contact(name="test abc", email="*****@*****.**")
        self.second_contact = Contact(name="admin", email="*****@*****.**")

        self.first_contact.save()
        self.second_contact.save()
예제 #14
0
def AddContact(ten):
    """ taọ một contact mới
    Nếu contact đã tồn tại thì return contact
    ngược lại thì tạo mới và return contact đó
    """
    contacts = Contact.objects.filter(first_name=ten)
    if contacts.count() == 0:
        contact = Contact(first_name=ten)
        contact.save()
        return contact

    else:
        return contacts[0]
예제 #15
0
파일: tests.py 프로젝트: rwisecar/Pyphon
 def test_contact_list_view_returns_contact(self):
     """Test that contact list view returns 200 OK response."""
     user1 = User()
     user1.save()
     jabba = Contact(name="Jabba", number="+1234567890")
     jabba.save()
     view = ContactListView.as_view()
     req = self.request.get(reverse_lazy("contacts"))
     req.user = user1
     contacts = Contact.objects.all()
     response = view(req, {"contacts": contacts})
     contact = response.context_data['contacts'][0]
     self.assertTrue(contact.name == "Jabba")
예제 #16
0
 def test_call_queryset_is_all_calls(self):
     """Call view should show all texts."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 0)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     call1 = Call(contact=jabba, direction="outgoing", status="completed")
     call1.save()
     calls = self.client.get('/api/calls/')
     self.assertEqual(len(calls.json()), 1)
예제 #17
0
 def test_api_contacts_detail_view_status_ok(self):
     """Test api contacts detail view is status ok."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     request = self.request.get(
         reverse_lazy('api_contacts_retrieve', kwargs={"pk": jabba.pk}))
     request.user = user1
     view = ContactViewSet.as_view({'get': 'retrieve'})
     response = view(request, pk=jabba.id)
     self.assertEqual(response.status_code, 200)
예제 #18
0
def contact(request):
    '''Creates a view for adding contact, and saves the new contact to database.'''
    contacts = Contact.objects.all()
    contracts = Contract.objects.all()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            firstname = form.cleaned_data['firstname']
            lastname = form.cleaned_data['lastname']
            email = form.cleaned_data['email']
            options = request.POST.getlist('contract')
            try:
                contact = Contact()
                contact.firstname = firstname
                contact.lastname = lastname
                contact.email = email
                contract_dates = [str(x) for x in options]
                for cd in contract_dates:
                    if cd:
                        cr = Contract.objects.get(from_date=cd)
                        contact.contract = cr
                contact.save()
            except:
                pass

            return HttpResponseRedirect(reverse('index'))

    else:
        form = ContactForm()

    context = {'contacts': contacts, 'contracts': contracts, 'form': form}
    return render(request, 'contacts/contact.html', context)
예제 #19
0
파일: views.py 프로젝트: rwisecar/Pyphon
 def post(self, request, *kwargs):
     parser = FormParser()
     query_dict = parser.parse(request)
     contact = Contact.objects.filter(number=query_dict["From"]).first()
     if not contact:
         contact = Contact(number=query_dict["From"])
         contact.save()
     if contact.number != os.environ["TWILIO_NUMBER"]:
         sender = "them"
     else:
         sender = "you"
     text = Text(sender=sender, contact=contact, body=query_dict["Body"])
     text.save()
     return HttpResponse()
    def test_contact_needed_but_scheduled_not_detected(self):
        # GIVEN: new contact without last contact date but with scheduled message
        contact = Contact(firstName='Test', lastName='Test', age=33, notificationsFrequency=24, gender=1, isActive=True,
                          lastContact=timezone.now())
        contact.save()
        message = Message(type='SMS', recipientName='Test test', contact=contact, recipientPhone="1234", body="test",
                          sendAtDate=timezone.now(), state="QUEUED")
        message.save()

        # WHEN: run get_contact_needed
        results = StatsView.get_contact_needed()

        # THEN: expect the given contact NOT in the results
        self.assertNotIn(contact, results)
예제 #21
0
def contact(request):
    if request.method == 'POST':
        listing_id = request.POST['listing_id']
        listing = request.POST['listing']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        user_id = request.POST['user_id']
        realtor_email = request.POST['realtor_email']

        # check if user has already made an enquiry
        if request.user.is_authenticated:
            user_id = request.user.id
            has_contacted = Contact.objects.all().filter(listing_id=listing_id,
                                                         user_id=user_id)
            if has_contacted:
                messages.error(
                    request,
                    'You have already made an enquiry for this listing')
                return redirect('/listings/' + listing_id)

        contact = Contact(listing=listing,
                          listing_id=listing_id,
                          name=name,
                          email=email,
                          phone=phone,
                          message=message,
                          user_id=user_id)
        contact.save()

        # send mail:
        # panel = """<a
        #             href="127.0.0.1:8000/admin/">panel
        #            </a>
        #         """ work on it!!!!?????????????????????????????????????????????======================-------------!!?????
        send_mail(
            subject='Property Listing Enquiry',
            message='There has been an enquiry for' + listing +
            '.\nSign into the admin panel for more information',
            from_email='*****@*****.**',
            recipient_list=[realtor_email, '*****@*****.**'],
            fail_silently=False)

        messages.success(
            request,
            'Your request has been submitted. \nA realtor will get back to you soon'
        )
        return redirect('/listings/' + listing_id)
예제 #22
0
def contacts_lists(request):
    errors = []
    announcements = Announcement.objects.all()
    users = User.objects.exclude(username=request.user.username)
    conversations = Conversation.objects.filter(users=request.user).order_by('-date_last_message')
    lists = List.objects.filter(is_active=True)
    inactive_lists = List.objects.filter(is_active=False)
    inactive_contacts = Contact.objects.filter(is_active=False)
    groups = GroupPermission.objects.all()

    countries = CmsCountry.objects.all()
    cities = CmsCity.objects.all()
    zip_codes = CmsUSZIPCode.objects.all()
    states = CmsUSState.objects.all()

    if 'btn_delgroup' in request.POST:
        l = List.objects.get(name=request.POST['list'])
        l.delete()
    if 'btn_active' in request.POST:
        List.objects.get(name=request.POST['list']).activate()
    if 'btn_active_contact' in request.POST:
        Contact.objects.get(pk=request.POST['inactive_contact']).activate()
    if 'btn_new_contact' in request.POST:
        Contact.new_contact(request.POST)
    if 'btn_new_list' in request.POST:
        if request.POST['name_list'] == "" or request.POST['desc_list'] == "":
            errors.append("Mandatory fields empty")
        else:
            groups = request.POST.getlist('group_selected[]')
            List.create(name=request.POST['name_list'],
                        description=request.POST['desc_list'],
                        created_by=request.user,
                        groups=groups)

    return render(request,
                  'contacts/lists.html',
                  {'lists': lists,
                   'inactive_lists': inactive_lists,
                   'inactive_contacts': inactive_contacts,
                   "user": request.user,
                   "countries": countries,
                   "cities": cities,
                   "zip_codes": zip_codes,
                   "states": states,
                   "announcements": announcements,
                   "conversations": conversations,
                   "chaters": users,
                   "groups": groups,
                   "errors": errors})
예제 #23
0
def contacts(request):
    if request.method == "POST":

        name = request.POST["name"]
        email = request.POST["email"]
        question = request.POST["question"]
        phone = request.POST["phone"]

        if not is_emtpy_fields(name, email, question):
            # get profession if selected
            profession = get_profession(request)

            contact = Contact(
                name=name,
                email=email,
                phone=phone,
                profession=profession,
                question=question,
            )

            contact.save()

            messages.success(request, "Запит успішно відправленно")

            return redirect('contacts')
        else:

            # tempotary save for fillind form
            request.session['name'] = name
            request.session['email'] = email
            request.session['phone'] = phone
            request.session['question'] = question

            messages.error(
                request,
                "Не вдалося відправити питання. Ви не заповнили обов'язкові поля."
            )

            return redirect('contacts')

    context = {}

    #if this is second try fill values
    if len(request.session.keys()) > 0:
        for key, value in list(request.session.items()):
            context[key] = value
            del request.session[key]

    return render(request, "contacts.html", context)
예제 #24
0
 def test_call_queryset_returns_call_attributes_in_json(self):
     """Test that a call to the calls api contains call attributes."""
     user1 = User()
     user1.save()
     self.client.force_login(user1)
     jabba = Contact(name="Jabba", number="+12068675309")
     jabba.save()
     call1 = Call(contact=jabba, direction="outgoing", status="completed")
     call1.save()
     calls = self.client.get('/api/calls/')
     self.assertTrue("direction" in calls.content.decode())
     self.assertTrue("outgoing" in calls.content.decode())
     self.assertTrue("time" in calls.content.decode())
     self.assertTrue("status" in calls.content.decode())
     self.assertTrue("contact" in calls.content.decode())
예제 #25
0
def contactUs(request):
    entertainments = Entertainment.objects.all().order_by('date')
    business = Business.objects.all()
    context = {
        "entertainments": entertainments,
        "business": business,
    }
    if request.method == 'POST':
        name = request.POST['username']
        email = request.POST['useremail']
        message = request.POST['message']

        contactDetails = Contact(name=name, email=email, message=message)
        contactDetails.save()
    return render(request, 'contact.html', context)
예제 #26
0
def contacts_edit(request, pk):
    Contact = get_object_or_404(Contact, pk=pk)
    if request.method == "POST":
        form = generic_contact_form(request.POST, instance=Contact)
        if form.is_valid():
            Contact = form.save(commit=False)
            Contact.Owner = User
            if not Company and not Last_Name:
                raise forms.ValidationError(
                    'Please include a contact name or company!')
            Contact.save()
            return redirect('contact-detail', pk=Contact.uuid)
    else:
        form = generic_contact_form(instance=Contact)
    return render(request, 'contacts/edit_contact.html', {'form': form})
예제 #27
0
def create_contact(request):
    form = AddContactForm(request.POST)
    if not form.is_valid():
        return render_to_response('contacts/add_contact.html', {'form': form})

    email = form.cleaned_data.get('user_email')
    first_name = form.cleaned_data.get('first_name')
    last_name = form.cleaned_data.get('last_name')
    note = form.cleaned_data.get('note')
    contact_number = form.cleaned_data.get('contact_number')
    dob = form.cleaned_data.get('dob')

    errors = list()

    if len(first_name) < 4:
        errors.append("Firstname is too short")

    if len(last_name) < 4:
        errors.append("Lastname is too short")

    if len(note) < 4:
        errors.append("note is too short")

    if len(contact_number) < 11:
        errors.append("contact_number is too short")

    if len(errors) > 0:
        return render(request, 'contacts/add_contact.html', {
            'form': form,
            'errors': errors
        })

    user_id = request.user.id
    user = User.objects.get(id=user_id)
    contact = Contact(first_name=first_name,
                      last_name=last_name,
                      dob=dob,
                      note=note,
                      user_id=user)
    contact.save()

    email = Email(email=email, contact_id=contact)
    email.save()

    number = Number(number=contact_number, contact_id=contact)
    number.save()

    return HttpResponseRedirect('/user_index/')
예제 #28
0
def contact(request):
    if request.method == 'POST':
        listing_id = request.POST['listing_id']
        listing = request.POST['listing']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        user_id = request.POST['user_id']
        realtor_email = request.POST['realtor_email']

        # if user has made inquiry already
        if request.user.is_authenticated:
            user_id = request.user.id
            has_contacted = Contact.objects.all().filter(listing_id=listing_id,
                                                         user_id=user_id)
            if has_contacted:
                messages.error(
                    request,
                    'You have already made an inquiry for this listing')
                return redirect('/listings/' + listing_id)

        contact = Contact(listing=listing,
                          listing_id=listing_id,
                          name=name,
                          email=email,
                          phone=phone,
                          message=message,
                          user_id=user_id)

        contact.save()

        # send mail

        # send_mail(
        #     'Property Listing Inquiry',
        #     'There has been an inquiry for' + listing + '.Sign into the admin panel for more info',
        #     '*****@*****.**',
        #     [realtor_email, '*****@*****.**'],
        #     fail_silently=False,
        # )

        messages.success(
            request,
            'Your request has been submitted, a realtor will get back to you soon'
        )

        return redirect('/listings/' + listing_id)
예제 #29
0
파일: views.py 프로젝트: IshaiJaffe/yuval
def add(request):
    if request.method == 'GET':
        form = ContactForm()
        return render_to_response('contacts/New_contact.html',
                                  context_instance=RequestContext(
                                      request, {'form': form}))
    else:
        cnt = Contact()
        form = ContactForm(request.POST, request.FILES, instance=cnt)
        if form.is_valid():
            form.save()
            send_mail('new contact', 'there is a new contact',
                      settings.EMAIL_HOST_USER, ['*****@*****.**'])
            return render_to_response('contacts/New_contact.html',
                                      context_instance=RequestContext(
                                          request, {
                                              'form': form,
                                              'status': 'saved'
                                          }))
        else:
            return render_to_response('contacts/New_contact.html',
                                      context_instance=RequestContext(
                                          request, {
                                              'form': form,
                                              'status': 'error'
                                          }))
예제 #30
0
def upload_defaulter_excel_sheet(request):
    response_messages = []
    if request.method == 'POST':
        form = DefaulterUploadForm(request.POST, request.FILES)
        if form.is_valid() and LDAPToken.exists(
        ) and LDAPSearchParameters.exists():
            list_of_defaulter_id = DefaulterAction.extract_defaulter_ids_from_excel(
                request.FILES['file'])
            if not list_of_defaulter_id:
                response_messages.append(
                    "The File format has changed; Upload file with following headers"
                )
                response_messages.append(DefaulterAction.EXCEL_SHEET_HEADER)
            message = request.POST['message']
            from_number = request.POST['from_number']
            defaulter_phone_hash = Contact.get_phone_number_for_defaulters(
                list_of_defaulter_id)
            response_messages += send_sms_to_defaulters(
                request.user, from_number, defaulter_phone_hash, message)
            form = DefaulterUploadForm()
        else:
            if form.is_valid():
                message = "Please check LDAP Token and Search parameters!!"
                response_messages.append(message)
                logger.error(message)
    else:
        form = DefaulterUploadForm()
    return render_to_response('defaulter_upload.html', {
        'form': form,
        'info_messages': response_messages
    }, RequestContext(request))
예제 #31
0
    def test_str(self):
        contact = Contact(first_name='John', last_name='Smith')

        self.assertEquals(
            str(contact),
            'John Smith',
        )
예제 #32
0
    def handle(self, *args, **kwargs):
        for c in range(0, 40):
            contact = Contact(first_name=generate_name(),
                              phone_number=generate_phone_number(),
                              email=generate_email(),
                              category=generate_category(),
                              job=generate_job(),
                              address=generate_address(),
                              city='New York',
                              country='United States',
                              created=generate_date_created(),
                              user=User.objects.get(pk=1))

            contact.save()

        self.stdout.write(self.style.SUCCESS('Data created successfully'))
예제 #33
0
파일: views.py 프로젝트: rwisecar/Pyphon
    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        number = request.POST['number']
        if len(number) > 11 or number.isalpha():
            return self.get(request, *args, **kwargs)
        number = "+" + number
        if Contact.objects.filter(number=number):
            contact = Contact.objects.filter(number=number).first()
        else:
            contact = Contact(number=number)
            contact.save()
        pk = contact.pk
        return redirect(reverse_lazy('contact_detail', kwargs={'pk': pk}))
예제 #34
0
 def test_queryset_deleted(self):
     c = Contact(
         code="1",
         name="contact1",
         email="*****@*****.**"
     )
     c.save()
     Contact.objects.all().delete()
     self.assertEqual(
         len(
             Contact.history.all()
         ),
         1  # created audit only
         # deleted audit is not created
         # use bulk_delete_with_history for deleted audits
     )
예제 #35
0
    def import_contacts(self):
        data = self.__get_data()
        if not isinstance(data, list):
            raise ValueError('Wrong json format')

        created_companies = {}

        new_contacts = []
        for d in data:
            if 'name' not in d or not isinstance(d['name'], str) or len(
                    d['name']) == 0:
                continue
            if 'email' not in d or not isinstance(d['email'], str) or len(
                    d['email']) == 0:
                continue
            if 'company' not in d or not isinstance(d['company'], dict) or 'name' not in d['company'] \
                    or not isinstance(d['company']['name'], str) or len(d['company']['name']) == 0:
                continue
            if d['company']['name'] in created_companies:
                company = created_companies[d['company']['name']]
            else:
                company = Company.objects.get_or_create(
                    name=d['company']['name'])[0]
                created_companies[d['company']['name']] = company

            new_contacts.append(
                Contact(name=d['name'],
                        email=d['email'],
                        company=company,
                        phone=self.__parse_phone(d.get('phone'))))
        Contact.objects.bulk_create(new_contacts)
        print('{0} contacts are created'.format(len(new_contacts)))
예제 #36
0
def contact(request):
    if request.method == 'POST':
        campspot_id = request.POST['campspot_id']
        campme_id = request.POST['campme_id']
        campspot = request.POST['campspot']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        user_id = request.POST['user_id']
        spot_email = request.POST['spot_email']

        #  Check if user has made inquiry already
        if request.user.is_authenticated:
            user_id = request.user.id
            has_contacted = Contact.objects.all().filter(
                campspot_id=campspot_id, user_id=user_id)
            if has_contacted:
                messages.error(
                    request,
                    'You have already made an inquiry for this listing')
                return redirect('/campspots/' + campspot_id)

        contact = Contact(campspot=campspot,
                          campspot_id=campspot_id,
                          name=name,
                          email=email,
                          phone=phone,
                          message=message,
                          user_id=user_id)

        contact.save()

        # Send email
        # send_mail(
        #   'Property Listing Inquiry',
        #   'There has been an inquiry for ' + listing + '. Sign into the admin panel for more info',
        #   '*****@*****.**',
        #   [realtor_email, '*****@*****.**'],
        #   fail_silently=False
        # )

        messages.success(
            request,
            'Your request has been submitted, a campspot will get back to you soon'
        )
        return redirect('/campspots/' + campspot_id)
예제 #37
0
def dashboard(request):
    if user.is_authenticated:
        contacts = Contact.objects().order_by('-contact_date').filter(
            user_id=request.user.id)

        context = {'contacts': contacts}

        return render(request, 'accounts/dashboard.html', context)
예제 #38
0
 def handle(self, *args, **options):
     first_names = ['Jane', 'Joe', 'John', 'Jimmy', 'Job', 'Mark']
     last_names = [
         'Jones', 'Frasier', 'Kringleberry', 'Marsh', 'Bellingham'
     ]
     for i in range(300):
         first_name = random.choice(first_names)
         last_name = random.choice(last_names)
         birthday = datetime.datetime.now() - datetime.timedelta(
             days=random.randint(1000, 10000))
         contact = Contact(first_name=first_name,
                           last_name=last_name,
                           birthday=birthday,
                           email='*****@*****.**',
                           is_cell=random.choice([True, False]),
                           comments='blah blah blah')
         contact.save()
    def handle(self, *args, **options):
        for call in Call.objects.all():
            self.stdout.write("Checking call: {0}".format(call.sid))

            if not call.related_phone_number:
                for number in (call.from_number, call.to_number):
                    result = PhoneNumber.objects.filter(e164=number)

                    if result:
                        self.stdout.write("Related number found: "
                                          "{0}".format(number))
                        call.related_phone_number = \
                            result.latest('date_created')
                        call.save()

            if not call.related_contact:
                for number in (call.from_number, call.to_number):
                    result = Contact.objects.filter(phone_number=number)

                    if result:
                        self.stdout.write("Related contact found: "
                                          "{0}".format(number))
                        call.related_contact = result.latest('date_created')
                        call.save()

                    if not call.related_contact:
                        result = PhoneNumber.objects.filter(e164=number)

                        if not result:
                            self.stdout.write("Creating related contact for "
                                              "{0}".format(number))
                            try:
                                c = Contact(phone_number=number)
                                c.save()

                                c.date_created = call.date_created
                                c.save()

                                lookup_contact.apply_async(args=[c.id])

                                for related in (call.from_number,
                                                call.to_number):
                                    if number is not related:
                                        num = PhoneNumber \
                                            .objects.get(e164=related)
                                        c.related_phone_numbers.add(num)
                                        c.save()
                            except Exception as e:
                                self.stdout.write("Failure creating contact "
                                                  "for {0}: {1}".format(
                                                      number, e))
    def test_state_contact_needed_last_contact_present(self):
        # GIVEN: active contact with last contact older than notification frequency
        contact = Contact(firstName='Test',
                          lastName='Test',
                          lastContact=timezone.now() - datetime.timedelta(hours=36),
                          postponed=timezone.now() - datetime.timedelta(hours=24),
                          email='*****@*****.**',
                          phone='12341234',
                          age=33,
                          gender=1,
                          notificationsFrequency=24,
                          isActive=True,
                          notes='Test notes')
        contact.save()

        # THEN: state should be contact needed
        self.assertEqual(contact.state, 'CONTACT_NEEDED')
    def test_state_disabled(self):
        # GIVEN: disabled contact
        contact = Contact(firstName='Test',
                          lastName='Test',
                          lastContact=timezone.now(),
                          postponed=timezone.now(),
                          email='*****@*****.**',
                          phone='12341234',
                          age=33,
                          gender=1,
                          notificationsFrequency=24,
                          isActive=False,
                          notes='Test notes')
        contact.save()

        # THEN: state should be disabled
        self.assertEqual(contact.state, 'DISABLED')
    def test_state_postponed_past(self):
        # GIVEN: active contact with postponed in past
        contact = Contact(firstName='Test',
                          lastName='Test',
                          lastContact=timezone.now(),
                          postponed=timezone.now() - datetime.timedelta(hours=24),
                          email='*****@*****.**',
                          phone='12341234',
                          age=33,
                          gender=1,
                          notificationsFrequency=24,
                          isActive=True,
                          notes='Test notes')
        contact.save()

        # THEN: state should not be postponed
        self.assertNotEqual(contact.state, 'POSTPONED')
예제 #43
0
def contact(request):
    '''Creates a view for adding contact, and saves the new contact to database.'''
    contacts = Contact.objects.all()
    contracts = Contract.objects.all()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            firstname = form.cleaned_data['firstname']
            lastname = form.cleaned_data['lastname']
            email = form.cleaned_data['email']
            options = request.POST.getlist('contract')
            try:
                contact = Contact()
                contact.firstname = firstname
                contact.lastname = lastname
                contact.email = email
                contract_dates = [str(x) for x in options]
                for cd in contract_dates:
                    if cd:
                        cr = Contract.objects.get(from_date = cd)
                        contact.contract = cr
                contact.save()
            except:
                pass

            return HttpResponseRedirect(reverse('index'))
        
    else:
        form = ContactForm()

    context = {'contacts' : contacts, 'contracts': contracts, 'form' :form}
    return render(request, 'contacts/contact.html', context )
예제 #44
0
파일: views.py 프로젝트: er34/JoomboCRM
def editformprocessor(request):
    logger.debug(request.POST['code'])
    if request.POST['code']:
        nc = Contact.objects.filter(owner=request.user).filter(code=request.POST['code'])[0]
    else:
        nc = Contact(code=GetNewCode(Contact.objects.filter(owner_id = request.user.id)), owner = request.user)
    nc.client = Client.objects.filter(owner_id = request.user.id).filter(code=request.POST['clientid'])[0]
    nc.fio = request.POST['fio']    
    nc.email = request.POST['email']  
    if (request.POST['birthday']):
        stdate = datetime.datetime.strptime(str(request.POST['birthday']), "%Y-%m-%d");
        nc.birthday = stdate    
    nc.position = request.POST['position']    
    nc.phone = request.POST['phone']    
    nc.save();
    return entry(request)
    def test_state_planned_contact(self):
        # GIVEN: active contact with queued message
        contact = Contact(firstName='Test',
                          lastName='Test',
                          lastContact=timezone.now(),
                          postponed=timezone.now() - datetime.timedelta(hours=24),
                          email='*****@*****.**',
                          phone='12341234',
                          age=33,
                          gender=1,
                          notificationsFrequency=24,
                          isActive=True,
                          notes='Test notes')
        contact.save()
        message = Message(type='SMS', recipientName='Test test', contact=contact, recipientPhone="1234", body="test",
                          sendAtDate=timezone.now(), state="QUEUED")
        message.save()

        # THEN: state should be contact planned
        self.assertEqual(contact.state, 'CONTACT_PLANNED')
예제 #46
0
파일: whatsappd.py 프로젝트: josben/mc
def saveWhatsapp(phone, type_message, message):
    try:
        contact = ContactNumber.objects.get(phone=phone)
    except ContactNumber.DoesNotExist:
        # If number phone not exist
        contact = Contact(nickname=phone)
        contact.save()
        contact_number = ContactNumber(contact=contact,
                                       country_code='591',
                                       phone=phone)
        contact_number.save()

    print ('===========')
    print ('type_message')
    print ('===========')

#    if type_message is not 'image' and type_message is not 'video' and type_message is not 'audio':
    if type_message is 'text':
        whatsapp = MessageCenterReceived(contact=contact,
                                         message_received=message)
        whatsapp.save()
예제 #47
0
def contacts(request):
    if request.method == 'GET':
        rec=Contact.objects.all()
        output=[]
        for one in rec:
            output.append(one.json())
        return HttpResponse(json.dumps(output, ensure_ascii=False)) 
    if request.method == 'POST':
        data = json.loads(request.body.decode("utf-8"))
        contact=Contact.mycreate(data)
        contact.save()
        output=contact.json()
        return HttpResponse(json.dumps(output, ensure_ascii=False)) 
예제 #48
0
    def test_creating_a_new_contact_and_save_it_to_db(self):
        #create a new contact
        contact = Contact()
        contact.name = 'Kostyantyn'
        contact.surname = 'Surename'
        contact.birthdate = timezone.now()
        contact.bio = 'My bio'
        
        contact.save()

        all_contacts = Contact.objects.all()
        self.assertEqual(len(all_contacts), 1)
        db_contact = all_contacts[0]
        
        self.assertEqual(db_contact.name, 'Kostyantyn')
        self.assertEqual(db_contact.surname, 'Surename')
        self.assertEqual(db_contact.birthdate, contact.birthdate)
        self.assertEqual(db_contact.bio, 'My bio')
        
        contactdetails = ContactDetail()
        contactdetails.jabber = 'jabber'
        contactdetails.email = '*****@*****.**'
        contactdetails.skype = 'skype'
        contactdetails.other = 'bla-bla-bla'
        
        contactdetails.save()
        contact.contactdetails = contactdetails
        contact.save()
        
        all_contacts = Contact.objects.all()
        self.assertEqual(len(all_contacts), 1)
        db_contact=all_contacts[0]
        
        self.assertEqual(db_contact.contactdetails.jabber, 'jabber')
        self.assertEqual(db_contact.contactdetails.email, '*****@*****.**')
        self.assertEqual(db_contact.contactdetails.skype, 'skype')
        self.assertEqual(db_contact.contactdetails.other, 'bla-bla-bla')
        
예제 #49
0
def new(request):
    user_profile = request.user.userprofile_set.filter()[0]
    form_categories = Category.objects.filter(owner=user_profile)

    if request.method == "GET":
        current_user = request.user
        form = ContactForm(current_user=current_user)
        user_profile = request.user.userprofile_set.filter()[0]
        form_categories = Category.objects.filter(owner=user_profile)
        return render(request, 'contacts/new_contact_form.html', {'form':form,
                                                                  'title':"New Contact",
                                                                  'categories':form_categories})
    else:
        form = ContactForm(data=request.POST, current_user=request.user)

        if form.is_valid():
            try:
                user_profile = get_user_profile(request)
                age = form.cleaned_data['age']
                name = form.cleaned_data['name']
                public = form.cleaned_data['public']
                category_id = form.cleaned_data['category']
                category = Category.objects.filter(id=category_id)[0]
                contact = Contact(age=age, name=name, public=public, owner=user_profile, category=category)
                contact.save()
                messages.add_message(request, messages.SUCCESS, "Contact successfully created" )
                return redirect('/contacts/')
            except:
                messages.add_message(request, messages.ERROR, "Contact creation unsuccessful" )
                return render(request, 'contacts/new_contact_form.html', {'form':form,
                                                                          'title':"New Contact",
                                                                          'categories': form_categories})
        else:
            messages.add_message(request, messages.ERROR, "Contact creation unsuccessful" )
            return render(request, 'contacts/new_contact_form.html', {'form':form,
                                                                      'title':"New Contact",
                                                                      'categories': form_categories})
예제 #50
0
파일: views.py 프로젝트: carriercomm/aspect
def contact_edit(request, abonent_id, contact_id=0):
    if contact_id != '0' :
        message = u'Изменение контактной информации'
        new = False
        contact = Contact.objects.get(pk=contact_id)
    else:
        message = u'Добавление нового контакта'
        new = True
        contact = Contact()

    try:
        abonent = Abonent.objects.get(pk = abonent_id)
    except:
        raise Http404

    if request.method == 'POST':
        form = ContactModelForm(request.POST, instance=contact)
        if form.is_valid():
            form.save(commit=False)
            contact.abonent=abonent
            contact.save()
            return HttpResponseRedirect(reverse('contacts', args=[abonent_id]))
        else:
            print form.errors
    else:
        form = ContactModelForm(instance=contact)

    header = 'Контакт'
    breadcrumbs = [({'url':reverse('contacts', args=[abonent.pk]),'title':'Контакты'})]

    return render_to_response('generic/generic_edit.html', { 
                                'header' : header,
                                'form': form,
                                'breadcrumbs':breadcrumbs,
                                'abonent': abonent,
                                'extend': 'abonent/main.html', },
                                 context_instance = RequestContext(request))
    def test_should_save_a_contact_belonging_to_a_category(self):
        category = Category(name="friend")
        category.save()

        self.assertEqual(1, len(Category.objects.filter()))
        contact = Contact()
        contact.name = "ben"
        contact.email_address = "brainychip.gmail.com"
        contact.category = category
        contact.save()

        self.assertEqual(contact.category, category)


        
예제 #52
0
def upload_defaulter_excel_sheet(request):
    response_messages = []
    if request.method == 'POST':
        form = DefaulterUploadForm(request.POST, request.FILES)
        if form.is_valid() and LDAPToken.exists() and LDAPSearchParameters.exists():
            list_of_defaulter_id = DefaulterAction.extract_defaulter_ids_from_excel(request.FILES['file'])
            if not list_of_defaulter_id:
                response_messages.append("The File format has changed; Upload file with following headers")
                response_messages.append(DefaulterAction.EXCEL_SHEET_HEADER)
            message = request.POST['message']
            from_number = request.POST['from_number']
            defaulter_phone_hash = Contact.get_phone_number_for_defaulters(list_of_defaulter_id)
            response_messages += send_sms_to_defaulters(request.user,from_number,defaulter_phone_hash,message)
            form = DefaulterUploadForm()
        else:
            if form.is_valid():
                message = "Please check LDAP Token and Search parameters!!"
                response_messages.append(message)
                logger.error(message)
    else:
        form = DefaulterUploadForm()
    return render_to_response('defaulter_upload.html', {'form': form,'info_messages': response_messages}, RequestContext(request))
예제 #53
0
def update_contacts(request):
    if request.method == 'POST':
        for i in range(int(request.POST['total_contacts'])):
            try:
                c = Contact()

                c.user = request.user
                c.name = request.POST['name' + str(i)]
                c.email = request.POST['email' + str(i)]

                c.save()
            except Exception:
                print 'none'

        return HttpResponseRedirect(reverse('dashboard'))
    else:
        return HttpResponseRedirect(reverse('accounts'))
예제 #54
0
def issues(request):

    from contacts.models import Contact, ContactGroup

    grupos = ContactGroup.objects.all()

    if request.method == "POST":
        if 'file' in request.FILES:
            import xlrd
            
            from django.conf import settings

            file = request.FILES['file']
            
            wb = xlrd.open_workbook(file_contents=file.read())
            sh = wb.sheet_by_index(0)

            for rownum in range(1,sh.nrows):
                row = sh.row_values(rownum)           
                ctc = Contact()
                ctc.name = row[0]
                ctc.last_name = row[1]
                ctc.email = row[2]
                ctc.grupo = ContactGroup.objects.get(pk=row[3])
                ctc.save()
 
    form = UploadFileForm()
    
    return simple.direct_to_template(
        request,
        'issues.html',
        extra_context = {
            'grupos':grupos,
            'formMass':form,
        }
    )
 def test_should_save_an_invalid_model(self):
     contact = Contact()
     contact.save()
     self.assertTrue(Contact.objects.count(), 1)
예제 #56
0
def view_contact_import(request):
    form = ImportContactsForm()
    message = ''
    errorList = []
    if request.method == 'POST':
        form = ImportContactsForm(request.POST,request.FILES)
        my_file = request.FILES['file']
        if form.is_valid():
            with open('/var/www/yellowpage/media/xls/'+my_file.name, 'wb+') as destination:
                for chunk in my_file.chunks():
                    destination.write(chunk)
            xls = xlrd.open_workbook('/var/www/yellowpage/media/xls/'+my_file.name)
            sheet = xls.sheet_by_index(0)
            completed = 0
            for row_index in range(1, sheet.nrows):
                try:
                    code = sheet.cell_value(row_index,0).capitalize()
                    #if str(code) == "":
                    #    
                    contact = Contact(code=code)
                    contact.surname = sheet.cell_value(row_index,1).capitalize()
                    contact.name = sheet.cell_value(row_index,2).capitalize()
                    contact.street = sheet.cell_value(row_index,3).capitalize()
                    contact.zip = str(sheet.cell_value(row_index,4))
                    contact.city = sheet.cell_value(row_index,5).capitalize()
                    contact.province = Province.objects.get(code=sheet.cell_value(row_index,6))
                    contact.email = sheet.cell_value(row_index,8)
                    contact.phone_number = sheet.cell_value(row_index, 7)
                    contact.birthdate = str(sheet.cell_value(row_index,12))
                    #Settore
                    sectorString = str(sheet.cell_value(row_index, 10))
                    professionString = str(sheet.cell_value(row_index, 9))
                    profession = Work.objects.filter(name=professionString)
                    if not profession:
                        sector = Sector.objects.filter(name=sectorString)
                        if not sector:
                            sector = Sector(name=sectorString)
                            sector.save()
                        #Professione
                        profession = Work(name=professionString, sector=Sector.objects.get(pk=sector.pk))
                        profession.save()
                    else:
                        profession = profession[0]
                    contact.work = Work.objects.get(name=profession.name)
                    contact.save()
                    completed += 1
                    #Certificato
                    cabinet = Cabinet.objects.get(pk=ContactCertFile.CABINET_ID)
                    current_user = request.user
                    file = ContactCertFile(contact=Contact.objects.get(pk=contact.pk))
                    uploadedFile = UploadedFile(title="Certificato Vuoto", cabinet=cabinet, file_ref="/cabinet/cert_empty.pdf", owner=current_user)
                    uploadedFile.save()
                    file.file = uploadedFile
                    file.expiry = str(sheet.cell_value(row_index,11))
                    file.save()
                except Exception as e:
                    print '%s (%s)' % (e.message, type(e))
                    errorList.append(sheet.cell_value(row_index,0).capitalize() + " " + e.message)
            message = 'Report Import: %d contatti importati correttamente. ' % completed

    return render_to_response('admin/contacts/view_contact_import.html',{'form':form, 'message':message, 'errorList': errorList}, context_instance=RequestContext(request))
 def test_should_save_partial_contact(self):
     contact = Contact()
     contact.name = "ben"
     contact.email_address = "brainychip.gmail.com"
     contact.save()
     self.assertEqual(Contact.objects.count(), 1)
def import_json(imported_file):
    for json_contact in json.loads(imported_file):
        contact = Contact(firstName=json_contact['firstName'], lastName=json_contact['lastName'],
                          phone=json_contact['phone'], email=json_contact['email'])
        contact.save()
def import_xml(imported_file):
    raw_xml = xmldict.xml_to_dict(imported_file)['root']['item']
    for item in raw_xml:
        contact = Contact(firstName=item['firstName']['#text'], lastName=item['lastName']['#text'],
                          phone=item['phone']['#text'], email=item['email']['#text'])
        contact.save()
예제 #60
0
def view_main(request):
    contact = Contact.objects.all().filter(owner=request.user)
    provinces = Province.objects.all()
    sectors = Sector.objects.all()
    ref_files = ContactRefFile.objects.filter(contact=contact)
    cert_files = ContactCertFile.objects.filter(contact=contact)
    form = ContactForm()
    today = datetime.datetime.now()
    events = Event.objects.all().filter(date__gte=today,is_public=True).order_by('date')
    iscrizioni = []
    #print contact
    if len(contact)>0:
        iscrizioni = EventSignup.objects.all().filter(contact=contact[0])
    signups = []
    for s in iscrizioni:
        signups.append(s.event)
    #print signups
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if contact and form.is_valid():
            up_contact = Contact.objects.get(code=contact[0].code)
            province = Province.objects.filter(id=form.cleaned_data["province"])[0]
            work = Work.objects.filter(id=form.cleaned_data["work"])[0]
            up_contact.name=form.cleaned_data["name"]
            up_contact.surname=form.cleaned_data["surname"]
            up_contact.street =  form.cleaned_data["street"]
            up_contact.province = province
            up_contact.birthdate =  form.cleaned_data["birthdate"]
            up_contact.city = form.cleaned_data["city"]
            up_contact.zip = form.cleaned_data["zip"]
            up_contact.civic = form.cleaned_data["civic"]
            up_contact.email = form.cleaned_data["email"]
            up_contact.sex = form.cleaned_data["sex"]
            up_contact.phone_number=form.cleaned_data["phone_number"]
            up_contact.work=work
            up_contact.save()
            messages.success(request, "Informazioni Aggiornate!!")
            return HttpResponseRedirect('/frontend/main')
        elif form.is_valid():
            province = Province.objects.filter(id=form.cleaned_data["province"])[0]
            work = Work.objects.filter(id=form.cleaned_data["work"])[0]

            my_contact = Contact(name=form.cleaned_data["name"], surname=form.cleaned_data["surname"], street=form.cleaned_data["street"], province=province,
                                 birthdate = form.cleaned_data["birthdate"],sex = form.cleaned_data["sex"], city=form.cleaned_data["city"], zip=form.cleaned_data["zip"], civic = form.cleaned_data["civic"], email=form.cleaned_data["email"], phone_number=form.cleaned_data["phone_number"], work=work, code = form.cleaned_data["code"], owner = request.user)
            my_contact.save()

    work_str = "0"
    event_files = []

    if contact:
        contact_entry = contact[0]
        work_str = str(contact_entry.work.id)

        # Search for event files
        files = []
        # print "### Searching for contact_id: %s" % contact_entry.code
        for signup in EventSignup.objects.filter(contact=contact_entry, presence=True):
            # print "### Searching for file for event: %s [%d]" % (signup, signup.event_id)
            for file in EventFile.objects.filter(event=signup.event):
                # print "### Found file: %s" % file
                files.append(file)

        # Not sure why EventSignup allow for duplicate signup per event, as result,
        # need to create a unique list of files per user
        # ToDo: Find out why EventSignup allow for duplicate signup and fix it if bug and remove the create of the unique list below
        event_files = set(files)

    return render_to_response(
        'frontend/main.html',
        {
            "contact": contact,
            "form": form,
            "provinces": provinces,
            "sectors": sectors,
            "events": events,
            "signups": signups,
            "work_str": work_str,
            "ref_files": ref_files,
            "event_files": event_files,
            "cert_files": cert_files
        },
        context_instance=RequestContext(request)
    )