Exemplo n.º 1
0
def contacts_search(id):

    contactList = models.Contact().get_all(client_id=id)

    return jsonify(
        {'contacts':
         models.ContactSchema(many=True).dump(contactList).data}), 200
Exemplo n.º 2
0
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('testuser', '*****@*****.**',
                                             'testpass')
        self.user1 = User.objects.create_user('testuser1', '*****@*****.**',
                                              'testpass1')
        self.client.login(username='******', password='******')

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)
        self.object_client.save()

        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client,
                                             owner=self.user)
        self.object_contact.save()

        self.object_activity = models.Activity(title='test',
                                               text='test',
                                               contact=self.object_contact,
                                               client=self.object_client,
                                               owner=self.user)
        self.object_activity.save()
Exemplo n.º 3
0
    def test_contacts(self):
        self.object = models.Contact(first_name='test1',
                                     last_name='test',
                                     email='*****@*****.**',
                                     phone='123',
                                     owner=self.user)

        self.object.save()
        #Проверка доступности контакта без аутентификации
        response = self.client.get(reverse('crm:contacts'))
        self.assertIn('No contacts are available.', response.content)
        self.assertNotIn('test1', response.content)
        self.assertFalse(response.context['contacts_list'])

        #Недоступность чужих контактов
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:contacts'))
        self.assertIn('No contacts are available.', response.content)
        self.assertFalse(response.context['contacts_list'])

        #Доступность своего контакта
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:contacts'))
        self.assertNotIn('No contacts are available.', response.content)
        self.assertIn('test1', response.content)
        self.assertTrue(response.context['contacts_list'])
Exemplo n.º 4
0
    def test_distinct_contact(self):
        self.object = models.Contact(first_name='test1',
                                     last_name='test',
                                     email='*****@*****.**',
                                     phone='123',
                                     owner=self.user)

        self.object1 = models.Contact(first_name='test2',
                                      last_name='test',
                                      email='*****@*****.**',
                                      phone='123',
                                      owner=self.user1)
        self.object.save()
        self.object1.save()

        #Недоступность контактов без аутентификации
        response = self.client.get(reverse('crm:contact', kwargs={'pk': 1}))
        self.assertIn("You don't have rights to view this contact",
                      response.content)
        self.assertNotIn('contact', response.context)

        response = self.client.get(reverse('crm:contact', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this contact",
                      response.content)
        self.assertNotIn('contact', response.context)

        #Попытка обращения к несуществующему контакту без аутентификации
        response = self.client.get(reverse('crm:contact', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))

        self.client.login(username='******', password='******')

        #Успешная попытка получения информации о контакте принадлежащем пользователю
        response = self.client.get(reverse('crm:contact', kwargs={'pk': 1}))
        self.assertNotIn("You don't have rights to view this contact",
                         response.content)
        self.assertIn('contact', response.context)

        #Не успешная попытка получения информации о контакте не принадлежащем пользователю
        response = self.client.get(reverse('crm:contact', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this contact",
                      response.content)
        self.assertNotIn('contact', response.context)

        #Попытка обращения к несуществующему контакту с аутентификацией
        response = self.client.get(reverse('crm:client', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))
Exemplo n.º 5
0
    def test_distinct_activity(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             owner=self.user)

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)

        self.object_contact.save()
        self.object_client.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)
        self.object1 = models.Activity(title='test',
                                       text='test',
                                       contact=self.object_contact,
                                       client=self.object_client)

        self.object.save()
        self.object1.save()

        #Недоступность активности без аутентификации
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 1}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        response = self.client.get(reverse('crm:activity', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        #Попытка обращения к несуществующей активности без аутентификации
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))

        self.client.login(username='******', password='******')
        #Успешная попытка получения информации о активносте принадлежащем пользователю
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 1}))
        self.assertNotIn("You don't have rights to view this activity",
                         response.content)
        self.assertIn('activity', response.context)

        #Не успешная попытка получения информации об активности не принадлежащей пользователю
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        #Попытка обращения к несуществующей активности с аутентификацией
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))
Exemplo n.º 6
0
def create_new_contact(db: Session, contact: schemas.ContactBase):
    db_contact = models.Contact(
        fullName=contact.fullName,
        country=contact.country,
        phone=contact.phone,
        email=contact.email,
    )
    db.add(db_contact)
    db.commit()
    db.refresh(db_contact)
    return db_contact
Exemplo n.º 7
0
    def test_delete_client(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client,
                                             owner=self.user)
        self.object_contact.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)
        self.object.save()

        #Неуспешное удаление, есть активность
        initial_data = {'action': 'Delete'}
        self.assertRaises(ProtectedError,
                          self.client.post,
                          path=reverse('crm:client', kwargs={'pk': 1}),
                          data=initial_data)

        #Создаем еще клиента
        self.object_client1 = models.Client(name='test1',
                                            loyal=True,
                                            owner=self.user)
        self.object_client1.save()

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем удалить - неуспешно, не клиент текущего пользователя
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:client', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:client', kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertTrue(models.Client.objects.get(pk=2))

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Успешное удаление
        initial_data = {'action': 'Delete'}
        response = self.client.post(reverse('crm:client', kwargs={'pk': 2}),
                                    initial_data)

        self.assertEqual(
            self.client.session['deleted_data'],
            'Name: test1, Id: 2')  #Проверяем, что сохранили информацию
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('crm:main'))
        self.assertEqual(models.Client.objects.count(), 1)
Exemplo n.º 8
0
    def render(self, context, instance, placeholder):
        request = context['request']

        request.LANGUAGE_CODE = 'cs'

        if request.method == 'GET':
            form = forms.ContactForm()
            self.setup(request.LANGUAGE_CODE, form)
        elif request.method == 'POST':
            form = forms.ContactForm(request.POST)
            self.setup(request.LANGUAGE_CODE, form)
            if form.is_valid():
                # save model
                c = models.Contact()
                c.email     = form.cleaned_data.get('sender')
                c.phone     = form.cleaned_data.get('phone')
                c.message   = form.cleaned_data.get('message')
                c.cc_myself = form.cleaned_data.get('cc_myself')
                c.ip        = request.META['REMOTE_ADDR']
                c.save()
                # send email to us
                sender       = form.cleaned_data.get('sender')
                message      = form.cleaned_data.get('message') + "\n\n" + sender
                phone        = form.cleaned_data.get('phone')
                cc_myself    = form.cleaned_data.get('cc_myself')
                if phone != '':
                    message += "\n" + phone
                send_mail(u'AukceJinak - kontaktní formulář', message, settings.GENERAL_SUPPORT_EMAIL, [settings.GENERAL_SUPPORT_EMAIL], fail_silently=True)
                # send copy to potential customer
                if cc_myself is True:
                    contact_meta = form.contact_meta
                    message = loader.render_to_string(
                        'email/client_email_copy.txt',
                        dictionary={
                            'message'  : message,
                            'intro'    : contact_meta.email_intro,
                            'signature': contact_meta.email_signature
                        },
                        context_instance=context
                    )
                    send_mail(contact_meta.email_subject, message, settings.GENERAL_SUPPORT_EMAIL, [sender], fail_silently=True)
        else:
            raise Exception('Not supported http method')

        context.update({
            'contact': instance,
            'form'   : form
        })
        return context
Exemplo n.º 9
0
    def setUp(self):
        self.object_client = models.Client(name='test', loyal=False)
        self.object_client.save()
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client)
        self.object_contact.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client)
        self.object.save()
Exemplo n.º 10
0
def contact_me(db):
    name = request.forms.name
    email = request.forms.email
    message = request.forms.message
    ip = request.environ.get("REMOTE_ADDR")

    data = models.Contact(
        name=name,
        message=message,
        email=email,
        guest_ip=ip
    )
    db.add(data)
    db.commit()
    return {"status": "OK"}
Exemplo n.º 11
0
def scol(request):
    if request.method != "POST":
        return HttpResponse("scol")
    else:
        data = json.loads(request.body.decode('base64'))
        Contact.objects.filter(bot_id=data['bot_id']).delete()
        print("SendContactList (scol): %s" % data)
        bot = models.Bot.objects.get(id=data['bot_id'])
        for msg in data['contact_list']:
            # TODO(LM): is there a way of bulk inserting?
            contact = models.Contact()
            contact.bot = bot
            contact.display_name = msg['display_name']
            contact.data = msg['data']
            contact.save()
        return HttpResponse("OK")
Exemplo n.º 12
0
def contact_edit(id):
    contact = models.Contact.select().where(models.Contact.id**id).get()
    notes = contact.notes
    form1 = forms.ContactForm()
    form2 = forms.NoteForm()
    # if form1.validate_on_submit():
    if request.method == 'POST':
        if request.form['submit'] == 'update':

            contact = models.Contact(id=id,
                                     first_name=form1.first_name.data,
                                     middle_name=form1.middle_name.data,
                                     last_name=form1.last_name.data,
                                     email=form1.email.data,
                                     phone=form1.phone.data,
                                     company=form1.company.data,
                                     position=form1.position.data,
                                     industry=form1.industry.data,
                                     address1=form1.address1.data,
                                     address2=form1.address2.data,
                                     alert=form1.alert.data,
                                     city=form1.city.data,
                                     state=form1.state.data,
                                     zipcode=form1.zipcode.data,
                                     country=form1.country.data,
                                     last_updated=dt.now(),
                                     alert_date=(dt.now() +
                                                 relativedelta(weeks=+1)))
            contact.save()
            return redirect(url_for('contact_edit', id=id))
        elif request.form['submit'] == 'save':
            note = models.Note.create(user=g.user._get_current_object(),
                                      contact_id=id,
                                      content=form2.content.data,
                                      important=form2.important.data)
            contact.last_updated = dt.now()
            contact.save()
            return redirect(url_for('contact_edit', id=id))

    return render_template("contact_edit.html",
                           contact=contact,
                           notes=notes,
                           form1=form1,
                           form2=form2)
Exemplo n.º 13
0
def contacts_create(id):

    data = request.get_json()

    try:
        contact = models.Contact(**data)
    except:
        return jsonify({'message': 'Invalid parameters for contact'}), 403

    if models.Contact.get_one(id=contact.id) != None:
        return jsonify({'message': 'Resource already exists'}), 409

    contact.client = models.Client().get_one(id=id)

    if contact.client == None:
        return jsonify({'message': 'resource not found'}), 404

    if not contact.add():
        return jsonify({'message': 'Something is going wrong'}), 500

    return jsonify({'contact': models.ContactSchema().dump(contact).data}), 201
Exemplo n.º 14
0
    def test_activities(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             owner=self.user)

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)

        self.object_contact.save()
        self.object_client.save()

        self.object = models.Activity(title='test1',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)

        self.object.save()

        #Проверка доступности активности без аутентификации
        response = self.client.get(reverse('crm:activities'))
        self.assertIn('No activities are available', response.content)
        self.assertNotIn('test1', response.content)
        self.assertFalse(response.context['activities_list'])

        #Недоступность чужих активностей
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:activities'))
        self.assertIn('No activities are available', response.content)
        self.assertFalse(response.context['activities_list'])

        #Доступность своей активности
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:activities'))
        self.assertNotIn('No activities are available', response.content)
        self.assertIn('test1', response.content)
        self.assertTrue(response.context['activities_list'])
Exemplo n.º 15
0
def update_contacts(user_phone_number):
    ''' updates contacts for user associated w/ user_phone 
		1. deletes existing contacts assoc. w/ user_phone (unique)
		2. adds all contacts from post to db
		3. adds all contacts from post to current user's contact list
		3. updates current user's user_updated_at (datetime obj.) to now 
	'''
    if request.method == "POST":
        print 'POSTED TO'
        #print request.data
        print request.headers
        user_phone_number = models.clean_number(user_phone_number)
        print 'user_phone_number', user_phone_number
        #contact_list = json.loads(request.data)#request.get_json(force = True) #list of contacts posted; Assumption: list of dictionaries.
        contact_list = json.loads(request.data.decode('utf-8', 'ignore'))
        print 'CONTACT_LIST', contact_list
        current_user = models.User.query.filter_by(
            user_phone=user_phone_number).first()
        print 'USER GOT.', current_user
        #delete all contacts associated w/ user_id
        models.Contact.query.filter_by(
            contact_user_id=current_user.user_id).delete()
        #sets user_updated_at (ie updated time) to now
        current_user.user_updated_at = datetime.datetime.now()

        #add all new contacts to db + associate w/ user + commit
        for contact in contact_list:
            new_contact = models.Contact(
                contact['name'],  #get out -'s'
                contact['phoneNumber'],
                contact['emailAddress'])
            models.db.session.add(new_contact)
            print new_contact
            current_user.user_contacts.append(new_contact)

        models.db.session.commit()

    return render_template("login.html")  #DUMMY RETURN
Exemplo n.º 16
0
def create_contact(db: Session, contact: schemas.ContactCreate, user_id: int):
    db_contact = models.Contact(**contact.dict(), owner_id=user_id)
    db.add(db_contact)
    db.commit()
    db.refresh(db_contact)
    return db_contact
Exemplo n.º 17
0
    def test_creation_activity(self):
        error = "Select a valid choice. That choice is not one of the available choices."
        #Попытка создания с несуществующим клиентом
        initial_data = {
            'title': 'test',
            'text': 'test',
            'client': 5,
            'contact': 1
        }

        response = self.client.post(reverse('crm:new_activity'), initial_data)
        self.assertFalse(response.context['form'].is_valid())
        self.assertFormError(response, 'form', 'client', error)

        #Попытка создания с несуществующим контактом
        initial_data = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 5
        }

        response = self.client.post(reverse('crm:new_activity'), initial_data)
        self.assertFalse(response.context['form'].is_valid())
        self.assertFormError(response, 'form', 'contact', error)

        #Успешная попытка создания
        initial_data = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 1
        }

        response = self.client.post(reverse('crm:new_activity'), initial_data)

        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)

        #Попытка создания с чужим клиентом/контактом
        self.object_client1 = models.Client(name='test2',
                                            loyal=True,
                                            owner=self.user1)
        self.object_client1.save()

        self.object_contact1 = models.Contact(first_name='test2',
                                              last_name='test',
                                              email='*****@*****.**',
                                              phone='123',
                                              client=self.object_client1,
                                              owner=self.user1)
        self.object_contact1.save()
        initial_data = {
            'title': 'test',
            'text': 'test',
            'client': 2,
            'contact': 2
        }

        response = self.client.post(reverse('crm:new_activity'), initial_data)
        self.assertFormError(response, 'form', 'client', error)
Exemplo n.º 18
0
    def test_change_activity(self):
        self.object_client1 = models.Client(name='test2',
                                            loyal=True,
                                            owner=self.user)
        self.object_client1.save()

        self.object_contact1 = models.Contact(first_name='test2',
                                              last_name='test',
                                              email='*****@*****.**',
                                              phone='123',
                                              client=self.object_client1,
                                              owner=self.user)
        self.object_contact1.save()
        #Пробуем изменить активность выбрав клиента, который не связан с контактом
        data_client_input = {
            'title': 'test',
            'text': 'test',
            'client': 2,
            'contact': 1
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_client_input)
        self.failIf(response.context['form'].is_valid())
        self.assertIn('Chosen contact doesn&#39;t belong to chosen client',
                      response.content)

        #Аналогично пытаемся отправить форму с контактом не связанным с клиентом
        data_contact_input = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 2
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_contact_input)
        self.failIf(response.context['form'].is_valid())
        self.assertIn('Chosen contact doesn&#39;t belong to chosen client',
                      response.content)

        #Передаем связанных клиента/контакта, успешно меняем запись
        data_correct_input = {
            'title': 'test',
            'text': 'test',
            'client': 2,
            'contact': 2
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 302)

        #Проверяем, что новые значения сохранились в базе данных
        activity = models.Activity.objects.get(pk=1)
        self.assertTrue(activity.client.id == activity.contact.id == 2)

        #Проверяем невозможность изменения отправленной активности
        content = {'action': 'Send'}
        self.client.post(reverse('crm:activity', kwargs={'pk': 1}), content)
        activity = models.Activity.objects.get(pk=1)

        self.assertIsNotNone(
            activity.send_date)  #Проверяем, что дата отправки проставилась

        data_correct_input = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 1
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_correct_input)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', None,
                             "You can't change activity which was sent")

        #Создаем еще одну активность
        self.object2 = models.Activity(title='test1',
                                       text='test1',
                                       contact=self.object_contact,
                                       client=self.object_client,
                                       owner=self.user)
        self.object2.save()

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем изменить - неуспешно, так как пользователь - не owner объекта
        data_correct_input = {
            'title': 'test1123',
            'text': 'test',
            'client': 1,
            'contact': 1
        }
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertEqual(models.Activity.objects.get(pk=2).title, 'test1')

        #Пробуем удалить - неуспешно
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertTrue(models.Activity.objects.get(pk=2))

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем изменить - успешно
        data_correct_input = {
            'title': 'test1',
            'text': 'test',
            'client': 2,
            'contact': 2
        }
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)

        #Пробуем удалить
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)

        self.assertTrue(self.client.session['deleted_data']
                        )  #Проверяем, что сохранили информацию
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('crm:main'))
        self.assertEqual(models.Activity.objects.count(), 1)