Example #1
0
    def test_contact_attributes(self):
        source = Source.objects.get(slug="test")

        attributes = {
                'procedure' : 'test',
                'procedures_long' : 'long',
                'contact_by' : 'June 12',
                'best_call_time' : '12am',
                'hear_about_us' : 'magazine',
                'date_contacted' : 'july 1',
                'call_message' : 'hey there',
                'location' : 'none'
            }

        contact_params = {
                'name' : 'test',
                'address' : '123 fake st.',
                'city' : 'test city',
                'state' : 'state',
                'zip_code' : 'zip_code',
                'phone' : 'phone',
                'email' : 'email',
                'message' : 'test',
                'source' : source,
                'attributes' : simplejson.dumps(attributes)
                }

        contact = Contact(**contact_params)
        contact.save()


        assert contact.json_attributes == attributes, True

        assert contact.get_attribute("procedure") == "test", True
        assert contact.get_attribute("procedures_long") == "long", True
Example #2
0
def send_invitation(invitation):
  """
  """
  try:
    user = User.objects.get(email=invitation.email)
    message = "{0} added you to his contacts".format(
        invitation.sender.username)
    contact = Contact(owner=invitation.sender, user=user)
    contact.save()
    invitation.delete()
    return HttpResponseRedirect(contact.get_absolute_url())
  except User.DoesNotExist:
    message = """
{0} Invites you to join his contacts.
You can register on http://{1}/user/create_account/ \
if you want to accept his invitation""".format(
        invitation.sender.username,
        Site.objects.get_current().domain
        )
  send_mail('An invitation sent to you',
             message,
             invitation.sender,
             [invitation.email],
             fail_silently=False
             )
  return HttpResponseRedirect(invitation.get_absolute_url())
    def setUp(self):
        # Set up Google App Engine testbed
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_app_identity_stub()

        self.contactNumber = "+16135551234"

        # Set up some handy constants
        self._APP_ID = app_identity.get_application_id()
        self.MAIL_SUFFIX = "@" + self._APP_ID + ".appspotmail.com"
        self.XMPP_SUFFIX = "@" + self._APP_ID + ".appspotchat.com"

        self.ownerPhoneNumber = "+16135554444"
        self.ownerJid = "*****@*****.**"
        self.ownerEmailAddress = "*****@*****.**"
        self.owner = Owner(self.ownerPhoneNumber, self.ownerJid, self.ownerEmailAddress)
        self.xmppvoicemail = XmppVoiceMail(self.owner)
        self.communications = self.xmppvoicemail._communications = CommunicationsFixture()

        # Subscribe the default sender.
        defaultSender = Contact.getDefaultSender()
        defaultSender.subscribed = True
        Contact.update(defaultSender)
Example #4
0
 def test_encoding_is_proper(self):
     # test_str = unicode("✄", "utf-8")
     test_str = u"✄"
     name = Contact(first_name=test_str)
     name.save()
     name2 = Contact.objects.get(first_name=test_str)
     self.assertEqual(name.first_name, name2.first_name)
Example #5
0
def upload_contacts(request):
  if not request.user.is_authenticated():
    return HttpResponse('You are not logged in')
  if request.FILES.__contains__('csv'):
    rows = csv.reader(request.FILES['csv'])
    count = 0
    for row in rows:
      if count > 0 and len(row) == 11:
        contactExists = Contact.objects.filter(email=row[4]).count()
        if not contactExists:
          contact = Contact(
            first_name = row[0],
            last_name = row[1],
            phone = row[2],
            mobile = row[3],
            email = row[4],
            address = row[5],
            colony = row[6],
            city = row[7],
            zip_code = row[8],
            birth_date = row[10] if row[10] != '' else '1988-11-16',
            amount = '',
            period = '',
            payment = '',
            tax_info = ''
          )
          contact.save()
          if len(row[9]) > 0:
            for group in Group.objects.filter(id__in=row[9].split(' ')):
              contact.group.add(group)
          contact.save()
      count+=1
    return HttpResponseRedirect('/admin/impulso/contact/')
  return render('admin/upload.html', {}, context_instance = RequestContext(request))
Example #6
0
 def setUp(self):
     u = User(username='******',email_address='*****@*****.**')
     u.save()
     ct = Contact(first_name='tom',last_name='salfield',organisation='the-hub',email_address='*****@*****.**',location='islington',apply_msg='about me', find_out='through the grapevine',invited_by=u)
     ct.save()
     self.u = u
     self.ct = ct
     return
Example #7
0
 def new(self, name, phone=None, fax=None):
     contact = Contact(
         name=name,
         phone=phone,
         fax=fax
     )
     contact.save()
     return serialize(contact, excludes=[re.compile(r'^datetime_'),])
 def createContact(self, subscribed):
     # Create a known contact
     c = Contact(
         name="mrtest",
         phoneNumber=self.contactNumber,
         normalizedPhoneNumber=phonenumberutils.toNormalizedNumber(self.contactNumber),
         subscribed=subscribed,
     )
     Contact.update(c)
Example #9
0
 def test_model_contact(self):
     """Test Contact model"""
     type = ContactType(name='Test', slug='test')
     type.save()
     obj = Contact(name='Test', contact_type=type)
     obj.save()
     self.assertEquals('Test', obj.name)
     self.assertNotEquals(obj.id, None)
     obj.delete()
Example #10
0
def contactlist(id):
	contact = Contact.find_first('where id=?',id)
	if contact is None:
		raise notfound()
	contactlist = Contact.find_by('where groupid=?',contact.groupid)
	if contactlist:
		return dict(contactlist=contactlist,group=contact.groupid)
	else:
		raise APIResourceNotFoundError(contact.groupid,'failed')
Example #11
0
def create_task():
    contact = Contact(
        firstName = request.json['firstName'],
        lastName = request.json['lastName'],
        bday = request.json['bday'],
        zodiac = request.json['zodiac']
    )
    contact.put()
    return redirect(url_for('index'))
Example #12
0
def contacts(request):
	if request.method == "GET":
		contacts = Contact.objects.all()
		return HttpResponse(format_contacts(contacts), mimetype="application/json")
	elif request.method == "POST":
		contact = Contact()
		data = json.loads(request.raw_post_data)
		contact.fromRaw(data)
		contact.save()
		return HttpResponse(format_contacts([contact]), mimetype="application/json")
    def done(self, form_list, **kwargs):

        new = Contact()
        #new.user = self.request.user
        for form in form_list:
            for k, v in form.cleaned_data.iteritems():
                setattr(new, k, v)
        new.save()

        return redirect('/users/')
Example #14
0
def add_contact(data, instance_id=""):
    if instance_id:
        contact = Contact.get_by_id(int(instance_id))
    else:
        contact = Contact()

    if data["name"]:
        contact.name = data["name"]

    if data["contacts"]:
        if contact.contacts:
            contact.contacts.append(data["contacts"])
        else:
            contact.contacts = data["contacts"]

    if data["email"]:
        contact.email = data["email"]

    if data["facebook"]:
        contact.facebook = data["facebook"]

    if data["twitter"]:
        contact.twitter = data["twitter"]

    contact.put()
    return contact
Example #15
0
def create():
    form = ContactForm()
    if form.validate_on_submit():
        new_contact = Contact()
        new_name = Name()
        new_contact.email = form.email.data
        new_name.first_name = form.first_name.data
        new_name.last_name = form.last_name.data
        new_contact.name = new_name
        new_contact.group = form.group.data
        new_contact.known_from = form.known_from.data
        new_contact.general_comment = form.general_note.data
        new_contact.current_status = form.status.data
        for language in form.languages.data:
            if language:
                new_contact.tags.append(language)
        other_tags = form.other_tags.data.replace(', ', ',').split(',')
        for tag in other_tags:
            new_contact.tags.append(tag)
        try:
            new_contact.save()
            flash_string = '<a href=\"/{}\">{} {}</a> was added to the database.'
            flash_string = flash_string.format(new_contact.email, new_contact.name.first_name,
                                               new_contact.name.last_name)
            flash(Markup(flash_string))
            update_p_dict()
            return redirect(url_for('index'))
        except NotUniqueError:
            msg = "That email address is already in use.  <a href=\"/" + form.email.data + "\">View Entry.</a>"
            form.email.errors.append(Markup(msg))
        except Exception as e:
            flash("There were database-raised errors in the form.  Specifically, " + e.message)

    return render_template('create_contact.html', form=form)
Example #16
0
 def getDisplayNameAndContact(self, number):
     displayName = toPrettyNumber(number)
     
     # Find the XMPP user to send this from
     contact = Contact.getByPhoneNumber(number)
     if contact:
         displayName = contact.name
     else:
         contact = Contact.getDefaultSender()
         
     return (displayName, contact)
Example #17
0
def auth():
	i = ctx.request.input(phoneid='')
	phoneid = i.phoneid.strip()
	contact = Contact.find_first('where tel=?',phoneid)
	contact1 = Contact.find_first('where work_tel=?',phoneid)
	if contact:
		return dict(contact)
	elif contact1:
		return dict(contact1)
	else :
		raise APIResourceNotFoundError(phoneid,'failed')
Example #18
0
    def post(self, request):
        try:
            print "Here about to create an add request"
            user_id = request.data["id"]
            user = User.objects.get(pk=user_id)
            Contact.create_add_request(from_user=request.user, for_user = user)

            return JSONResponse([], status=200)
        except Exception as e:
            beam(e, request)
            return JSONResponse(ERROR_MESSAGE, status=400)
Example #19
0
def contactlist(id):
    contact = Contact.find_first("where id=?", id)
    if contact is None:
        raise notfound()
    contactlist = Contact.find_by("where groupid=? and year=? order by headman desc", contact.groupid, contact.year)
    print("------++++++--")
    if contactlist:
        print("----------------")
        return dict(contactlist=contactlist, group=contact.groupid)
    else:
        print("+++++++++++++++++")
        raise APIResourceNotFoundError(contact.groupid, "failed")
Example #20
0
def createContact(request):#POST
    if request.method != 'POST':
        return JsonError( 'invalid message' ) 

    json_data = request.POST['contacts']
    data = json.loads(json_data)
    newContact = Contact()
    try:
        newContact.jsonToClass(data)
        newContact.save()
        return JsonSuccess( { 'message': 'Ok' } )
    except:
        return JsonError( 'Error on saving contact' )
Example #21
0
 def handleIncomingCall(self, fromNumber, callStatus):
     """Handle an incoming call.
     """
     displayFrom = toPrettyNumber(fromNumber)
     
     # Find the XMPP user to send this from
     contact = Contact.getByPhoneNumber(fromNumber)
     if contact:
         displayFrom = contact.name
     else:
         contact = Contact.getDefaultSender()
         
     self.sendMessageToOwner("Call from: " + displayFrom + " status:" + callStatus, contact, fromNumber)
Example #22
0
class TnycntTestCase(TestCase):
    """
    Create a sample contact form
    """
    def setUp(self):
        self.sample_user = User.objects.create_user(username='******', password='******',
                           email='*****@*****.**')
        self.sample_contact_form = Contact(title='Sample Form',
                                      description='Sample description',
                                      is_active=True,
                                      user=self.sample_user,)
        self.sample_contact_form.save()                              
        self.client.login(username='******', password='******')
Example #23
0
    def test_signal_processor(self):
        contact = Contact(
            first_name='Igor_test',
            last_name='Kucher_test',
            birth_date='1990-01-10',
            email='*****@*****.**',
            jabber='*****@*****.**',
            skype='skype_test',
            other_contacts='other_test',
            bio='bio_test'
        )
        contact.save()

        contact_object_name = ContentType.objects.get_for_model(contact).model

        log_entry = ModelsChangeLog.objects.latest()
        self.assertEqual(log_entry.model, contact_object_name.title())
        self.assertEqual(log_entry.action, ModelsChangeLog.CREATE)
        self.assertEqual(log_entry.object_id, contact.pk)

        contact.first_name = 'Igor_test_edit'
        contact.save()
        log_entry = ModelsChangeLog.objects.latest()
        self.assertEqual(log_entry.model, contact_object_name.title())
        self.assertEqual(log_entry.action, ModelsChangeLog.EDIT)
        self.assertEqual(log_entry.object_id, contact.pk)

        contact_pk = contact.pk
        contact.delete()
        log_entry = ModelsChangeLog.objects.latest('created')
        self.assertEqual(log_entry.model, contact_object_name.title())
        self.assertEqual(log_entry.action, ModelsChangeLog.DELETE)
        self.assertEqual(log_entry.object_id, contact_pk)
Example #24
0
def mail_sended_cb(sender, **kwargs):
    """
    Callback function to add email to contacts.
    """
    
    user = kwargs['user']
    email = kwargs['email']

    try:
        Contact.objects.get(user_email=user, contact_email=email)
        # Already in contacts list, pass.
    except Contact.DoesNotExist:
        # Add new contact
        c = Contact(user_email=user, contact_email=email)
        c.save()
Example #25
0
    def get(self):
        answer = []

        # Always put the default sender at the top.
        defaultSender = Contact.getDefaultSender()
        answer.append(defaultSender.toDict())

        contacts = Contact.all()
        contacts.filter('__key__ !=', defaultSender.key())
        
        for contact in contacts:
            answer.append(contact.toDict())
            
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(answer))
Example #26
0
 def post(self):
     form = ContactForm(self)
     params = {
         'form': form,
     }
     self.response.write(form.validate())
     if form.validate():
         contact = Contact(
             name=self.request.get('name'),
             email=self.request.get('email'),
             subject=self.request.get('subject'),
             body=self.request.get('body'),
         )
         contact.put()
     self.render_response('contact.html', **params)
Example #27
0
def main():
    routes = [
        (r'/recording', PostRecording),
        (r'/call', CallHandler),
        (r'/sms', SMSHandler),
        
        (r'/api/login', LoginHandler),
        (r'/api/admin/contacts', AdminContactsHandler),
        (r'/api/admin/contacts/(.*)', AdminContactsHandler),
        (r'/api/admin/log', AdminLogHandler),
        (r'/api/invite', InviteHandler),
        (r'/api/sendSms', SendSmsHandler),
        
        (r'/_ah/xmpp/message/chat/', XMPPHandler),
        (r'/_ah/xmpp/presence/(available|unavailable)/', XmppPresenceHandler),
        (r'/_ah/xmpp/subscription/(subscribe|subscribed|unsubscribe|unsubscribed)/', XmppSubscribeHandler),
        
        MailHandler.mapping(),
    ]

    webapp2Config = {}
    webapp2Config['webapp2_extras.sessions'] = {
        'secret_key': config.SESSION_SECRET_KEY,
    }
            
    app = webapp2.WSGIApplication(routes=routes, debug=True, config=webapp2Config)
    app.error_handlers[404] = handle_404
    app.error_handlers[500] = handle_500

    # Send an invite for the default sender if the default sender is not subscribed.
    defaultSender = Contact.getDefaultSender()
    if not defaultSender.subscribed:
        xmppVoiceMail.sendXmppInvite(defaultSender.name)
       
    return app
Example #28
0
    def post(self, subscriptionType):
        sender = self.request.get('from').split('/')[0]
        to = self.request.get('to').split('/')[0]

        contactName = to.split('@')[0]
        
        contact = Contact.getByName(contactName)
        if not contact:
            logging.error("Got subscription type " + subscriptionType + " for unknown contact " + to)
        else:
            logging.info("Got subscription type " + subscriptionType + " from " + sender + " to " + to)        
            if subscriptionType.startswith("un"):
                contact.subscribed = False
            else:
                contact.subscribed = True
            Contact.update(contact)
Example #29
0
 def delete(self, contactIdStr):
     contact = Contact.getByIdString(contactIdStr)
     if contact:
         if contact.isDefaultSender():
             raise errors.ValidationError("Cannot delete default sender.")
         logging.info("Deleting contact " + contact.name)
         contact.delete()
Example #30
0
def send_contact_mail(self):
    contacts = Contact.query(Contact.sent != True)
    count = contacts.count()
    if count:
        datetime_handler = lambda obj: obj.isoformat() \
            if isinstance(obj, datetime) else None
        message = json.dumps(
            [contact.to_dict() for contact in contacts],
            default=datetime_handler,
            indent=4
        )

        mail.send_mail(
            sender="Getmewrite.com Support <*****@*****.**>",
            to="Mona <*****@*****.**>",
            subject="You have {0} new contact(s)".format(count),
            body=message
        )

        self.response.write(message)
        logger.info(
            'Send daily mail success, {0} new contacts'.format(count))

        put_list = []
        for contact in contacts:
            contact.sent = True
            put_list.append(contact)

        ndb.put_multi(put_list)
Example #31
0
 def get(self, contact_id):
     contact = Contact.get_by_id(int(contact_id))
     params = {"contact": contact}
     return self.render_template("contact_delete.html", params=params)
Example #32
0
def create(date, name, phone, team_id):
    # Create
    new_contact = Contact(date=date, name=name, phone=phone, team_id=team_id)
    db.session.add(new_contact)
    db.session.commit()
Example #33
0
    #%% Loop
    print('Start iterating dataset ...')
    data = []
    for i in stazioni.itertuples():
        geolocator = Nominatim(user_agent="me")
        tempLoc = ''
        tempLoc += str(i.geometry.y) + ',' + str(i.geometry.x)
        rawData = geolocator.reverse(tempLoc)
        location = Location(rawData.latitude, rawData.longitude, None)
        address = Address(
            rawData.raw['address']['state'], rawData.raw['address']['city'],
            rawData.raw['address']['road'] + ',' +
            rawData.raw['address']['suburb']
            if 'suburb' in rawData.raw['address'] else '',
            rawData.raw['address']['house_number']
            if 'house_number' in rawData.raw['address'] else None,
            rawData.raw['address']['postcode']
            if 'postcode' in rawData.raw['address'] else None, location)
        contact = Contact(phone=None, email=None, website=None)
        facility = Facility('RailwayStation', None, contact, None, address,
                            None)
        data.append(facility.toJSON())
    print('finished Iterating Dataset.')
    #%%
    # print(os.getcwd())

    ds_out_path = '../../dataset/Formal Modeling/data/stazioni.json'
    with open(ds_out_path, 'w') as ds_out_file:
        json.dump(data, ds_out_file)
    print('finished dumping json and saved file.')
Example #34
0
from common import db
from models import Contact

# Ici on souhaite créer un petit script qui va supprimer les données existantes, recréer les bases nécessaires, et ajouter des valeurs "de test"

# 1. Supprimer toutes les tables existantes
# 2. Creer toutes les tables nécessaire
db.drop_all()
db.create_all()

# 3. Créer des objets Contact "de test" (par exemple Alice, Bob, Charlie) en utilisant des données fictives
alice = Contact(name="Alice", email="*****@*****.**", phone="1234567")
bob = Contact(name="Bob", email="*****@*****.**", phone="5837293")
charlie = Contact(name="Charlie", email="*****@*****.**", phone="0918375")

# 4. Ajouter (et commiter) ces nouveaux objets dans la base
db.session.add(alice)
db.session.add(bob)
db.session.add(charlie)
db.session.commit()
Example #35
0
 def new(self, name, phone=None, fax=None):
     contact = Contact(name=name, phone=phone, fax=fax)
     contact.save()
     return serialize(contact, excludes=[
         re.compile(r'^datetime_'),
     ])
Example #36
0
def contacts(id = None):
    if request.method == 'GET':
        if id is not None:
            contact = Contact.query.get(id)
            if contact:
                return jsonify(contact.serialize()), 200
            else:
                return jsonify({"msg": "Contact not found"}), 404
        else:
            contacts = Contact.query.all()
            contacts = list(map(lambda contact: contact.serialize(), contacts))

        return jsonify(contacts), 200
    if request.method == 'POST':
        name = request.json.get('name')
        phone = request.json.get('phone')

        contact = Contact()
        contact.name = name
        contact.phone = phone
        contact.save()
        
        return jsonify(contact.serialize()), 201
    if request.method == 'PUT':
        name = request.json.get('name')
        phone = request.json.get('phone')

        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact not found"}), 404

        contact.name = name
        contact.phone = phone
        contact.update()

        return jsonify(contact.serialize()), 200
    if request.method == 'DELETE':
        contact = Contact.query.get(id)
        if not contact:
            return jsonify({"msg": "Contact not found"}), 404
        contact.delete()

        return jsonify({"success": "Contact deleted"}), 200
Example #37
0
fake = Factory.create()
# Spanish
#fake = Factory.create('es_ES')
# Reload tables
db.drop_all()
db.create_all()
# Make 100 fake contacts
for num in range(50):
    fullname = fake.name().split()
    name = fullname[0]
    surname = ' '.join(fullname[1:])
    email = fake.email()
    phone = fake.phone_number()
    # Save in database
    mi_contacto = Contact(uid=secrets.token_urlsafe(8),
                          name=name,
                          surname=surname,
                          email=email,
                          phone=phone)
    db.session.add(mi_contacto)

db.session.commit()

contacts = Contact.query.order_by(Contact.name).all()
for contact in contacts:
    for i in range(5):
        new_remark = Note(rid=secrets.token_urlsafe(8),
                          to=contact.uid,
                          text=fake.sentence())
        db.session.add(new_remark)
db.session.commit()
Example #38
0
async def contact_create(request):
    new_contact = Contact(**await request.json())
    session.add(new_contact)
    session.commit()

    return web.json_response({'success': True, 'id': new_contact.id})
Example #39
0
def scrape_contacts(group, phone_number=None):
    if phone_number is None:
        free_accounts = session.query(TelegramAccount).filter(
            TelegramAccount.active == True,
            TelegramAccount.task == None).all()
        account = random.choice(free_accounts)
        if not account:
            active_accounts = session.query(TelegramAccount).filter(
                TelegramAccount.active == True).all()
            account = random.choice(active_accounts)
            if not account:
                for adm in config.ADMIN_IDS:
                    bot.send_message(
                        adm, f'No available accounts for scrapping. '
                        f'Add an account at first.')
                return
    else:
        account = session.query(TelegramAccount).filter(
            TelegramAccount.phone_number == phone_number, ).first()
    try:
        proxy = session.query(Proxy).first()
        client = TelegramClient(os.path.join(config.TELETHON_SESSIONS_DIR,
                                             account.phone_number),
                                config.TELEGRAM_API_ID,
                                config.TELEGRAM_API_HASH,
                                proxy=(socks.HTTP, proxy.ip, proxy.port, True,
                                       proxy.username, proxy.password))
        client.connect()
        if isinstance(group, int):
            group_link = group
        else:
            group_link = group.lower()
        account_id = client.get_me().id
        group = client.get_entity(group_link)
        participants = client.get_participants(group, aggressive=True)
        last_messages = client.get_messages(group, 1000)
        last_active_users_ids = set([msg.from_id for msg in last_messages])
        if client.get_me().id not in [i.id for i in participants]:
            client(JoinChannelRequest(group))
        channel_admins = client.get_participants(
            group, filter=ChannelParticipantsAdmins)
        admins_list = list()
        for i in channel_admins:
            admins_list.append(i)
        admins_ids = [i.id for i in admins_list]
        client.disconnect()
        filtered_participants = [
            p for p in list(participants) if not p.bot
            and p.id not in admins_ids and p.id != account_id and p.username
        ]
        contacts = [
            Contact(tg_id=user.id,
                    source_group=group_link,
                    username=user.username,
                    source_group_name=group.title,
                    priority=Contact.PRIORITY_HIGH if user.id
                    in last_active_users_ids else Contact.PRIORITY_LOW)
            for user in filtered_participants
        ]
        session.add_all(contacts)
        session.commit()
        for adm in config.ADMIN_IDS:
            bot.send_message(
                adm,
                f'Scrapped {len(filtered_participants)} from {group.title}.\n'
                f'Skipped {abs(len(filtered_participants)-len(participants))} '
                f'admins, bots and users without usernames.')
    except Exception as e:
        for adm in config.ADMIN_IDS:
            bot.send_message(adm, str(e))
Example #40
0
 def get(self):
     return Contact.return_all()
Example #41
0
def contact_builder(name, number):
    """ Build and return an instance of Contact """
    urns = [urns_parser(number)]
    contact = Contact(name, urns)
    return contact
Example #42
0
 def test_add_contact(self):
     """Adds new contact and checks if it exists in database."""
     new_contact = Contact("New", "Contact", "123456789", "*****@*****.**")
     self.test_db.add_contact(new_contact)
     self.assertIn(new_contact.get_fields(),
                   self.__fetch_all_contacts_from_db())
from models import db, Contact
from faker import Factory

fake = Factory.create()

# Reload tables
db.drop_all()
db.create_all()
# Make 100 fake contacts
for num in range(100):
    fullname = fake.name().split()
    name = fullname[0]
    surname = ' '.join(fullname[1:])
    email = fake.email()
    phone = fake.phone_number()
    adress = fake.adress()
    # Save in database
    mi_contacto = Contact(name=name, surname=surname,
                          email=email, phone=phone, adress=adress)
    db.session.add(mi_contacto)

db.session.commit()
Example #44
0
def sms_maama_report():
    doc = SimpleDocTemplate(
        "qc/static/qc/reports/sms_maama_weekly_report_{end_date}.pdf",
        pagesize=letter,
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=18)
    report = []
    logo = "qc/static/images/logo.jpg"
    logo2 = "qc/static/images/sms_maama_logo.jpg"
    project_name = "SMS MAAMA Project"
    report_title = "SMS Maama Weekly Report"
    prepared_by = "Faith Nassiwa"
    groups = Group.get_sms_maama_groups()
    contacts = Contact.get_sms_maama_weekly_contacts()
    sms_maama_contacts = Contact.get_sms_maama_contacts()
    sent_messages = Message.get_sms_maama_sent_messages()
    delivered_messages = Message.get_sms_maama_delivered_messages()
    failed_messages = Message.get_sms_maama_failed_messages()
    failed_messages_count = Message.get_sms_maama_failed_messages_count()
    contacts_count = Contact.get_sms_maama_contacts_count()
    weekly_contacts_count = Contact.get_sms_maama_weekly_contacts_count()
    messages_count = Message.get_sms_maama_sent_messages_count()
    read_messages_count = Message.get_sms_maama_read_messages_count()
    hanging_messages_count = Message.get_sms_maama_hanging_messages_count()
    hanging_messages = Message.get_sms_maama_hanging_messages()
    flow_responses_weekly = Message.get_sms_maama_weekly_flow_responses()
    flow_responses_count = Message.get_sms_maama_flow_responses_count()
    baby_responses = Message.get_sms_maama_flow_responses_baby()
    baby_responses_count = Message.get_sms_maama_flow_responses_baby_count()
    stops = Message.get_sms_maama_opted_out()
    stops_count = Message.get_sms_maama_opted_out_count()
    screening_responses = Value.sms_maama_contact_flows_screening_values()
    antenatal_responses = Value.sms_maama_contact_flows_antenatal_values()
    enrollments = Message.get_sms_maama_flow_responses_enrollment()
    concerning = Message.get_concerning_messages()
    start_date = datetime.date.today() - datetime.timedelta(days=7)
    end_date = datetime.date.today() - datetime.timedelta(days=1)
    this_day = datetime.datetime.now(
        pytz.timezone('Africa/Kampala')).strftime('%Y-%m-%d %H:%M %Z')

    im = Image(logo, 2 * inch, 1 * inch)
    im2 = Image(logo2, 2 * inch, 1 * inch)
    tabele_data = [[im, im2]]
    t = Table(tabele_data)
    report.append(t)
    report.append(Spacer(1, 12))
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
    ptext = '<font size=14><b>%s</b></font>' % report_title
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    ptext = '<font size=12>Date: %s</font>' % this_day
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    ptext = '<font size=12> Report Date: %s - %s</font>' % (start_date,
                                                            end_date)
    report.append(Paragraph(ptext, styles["Normal"]))
    ptext = '<font size=12> Prepared By: %s</font>' % prepared_by
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    ptext = '<font size=12> <b>All SMS Maama Contacts.</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    all_sms_maama_contact_titles = [
        'Phone Number', 'Name', 'Points', 'Enrolled On', 'Week Enrolled'
    ]
    data = [all_sms_maama_contact_titles]
    colwidths = (100, 120, 40, 120, 80)
    for i, contact in enumerate(sms_maama_contacts):
        data.append([
            contact.urns, contact.name, contact.points,
            contact.sms_maama_enrollment_date, contact.number_of_weeks
        ])

    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])

    report.append(t)
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b>SMS Maama Week of Pregnancy Upon Enrollment Status</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    groups_titles = ['SMS Maama Week', 'Number of Participants']
    data = [groups_titles]
    colwidths = (230, 230)
    for i, group in enumerate(groups):
        data.append([group.name, group.count])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    ptext = '<font size=12> <center>Total Participants: %s</center></font>' % contacts_count
    report.append(Paragraph(ptext, styles["Normal"]))

    report.append(Spacer(1, 12))
    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly Enrolled Contacts</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    contacts_titles = ['Phone Number', 'Created On', 'Enrolled On', 'Language']
    data = [contacts_titles]
    colwidths = (100, 120, 120, 100)
    for i, weekly_contact in enumerate(contacts):
        data.append([
            weekly_contact.urns,
            localtime(weekly_contact.created_on).strftime("%Y-%m-%d %H:%M"),
            weekly_contact.sms_maama_enrollment_date, weekly_contact.language
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    ptext = '<font size=12> <center>Total Weekly Participants: %s</center></font>' % weekly_contacts_count
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b>Weekly Message Count Summary</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    ptext = '<font size=12> <center>Total Messages Sent: %s</center></font>' % messages_count
    report.append(Paragraph(ptext, styles["Normal"]))
    ptext = '<font size=12> <center>Total Messages Delivered: %s</center></font>' % read_messages_count
    report.append(Paragraph(ptext, styles["Normal"]))
    ptext = '<font size=12> <center>Total Messages Hanging(No delivery receipt): %s</center></font>' \
            % hanging_messages_count
    report.append(Paragraph(ptext, styles["Normal"]))
    ptext = '<font size=12> <center>Total Failed to Send Messages: %s</center></font>' % failed_messages_count
    report.append(Paragraph(ptext, styles["Normal"]))
    ptext = '<font size=12> <center>Total Weekly Responses: %s</center></font>' % flow_responses_count
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly Baby, Post-Partum Initiations </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    baby_responses_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [baby_responses_titles]
    colwidths = (100, 130, 100, 130)
    for i, baby_response in enumerate(baby_responses):
        data.append([
            baby_response.urn,
            Paragraph(baby_response.text, styles["BodyText"]),
            baby_response.status,
            localtime(baby_response.sent_on).strftime('%Y-%m-%d %H:%M')
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    ptext = '<font size=12> <center>Total Weekly Baby Responses: %s</center></font>' % baby_responses_count
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly Terminations </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    stops_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [stops_titles]
    colwidths = (100, 130, 100, 130)
    for i, stop in enumerate(stops):
        data.append([
            stop.urn,
            Paragraph(stop.text, styles["BodyText"]), stop.status,
            localtime(stop.sent_on).strftime('%Y-%m-%d %H:%M')
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    ptext = '<font size=12> <center>Total Weekly Terminations: %s</center></font>' % stops_count
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12><b>Responses to Screening Questions</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    flow_responsess_titles = [
        'Phone Number', 'Screening', 'Question Sent On', 'Response',
        'Response Sent On'
    ]
    data = [flow_responsess_titles]
    colwidths = (100, 100, 100, 60, 100)
    for screening_response in screening_responses:
        data.append([
            screening_response.run.contact.urns,
            Paragraph(screening_response.run.flow.name, styles["BodyText"]),
            localtime(
                screening_response.run.created_on).strftime('%Y-%m-%d %H:%M'),
            Paragraph(screening_response.value, styles["BodyText"]),
            localtime(screening_response.time).strftime('%Y-%m-%d %H:%M')
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)

    report.append(Spacer(1, 12))
    report.append(Spacer(1, 12))
    ptext = '<font size=12><b>Responses to Antenatal Reminders</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    antenatal_responses_titles = [
        'Phone Number', 'Appointment Reminder', 'Reminder Sent On', 'Response',
        'Response Sent On'
    ]
    data = [antenatal_responses_titles]
    colwidths = (85, 130, 95, 55, 95)
    if antenatal_responses.count() >= 1:
        for antenatal_response in antenatal_responses:
            data.append([
                antenatal_response.run.contact.urns,
                Paragraph(antenatal_response.run.flow.name,
                          styles["BodyText"]),
                localtime(antenatal_response.run.created_on).strftime(
                    '%Y-%m-%d %H:%M'),
                Paragraph(antenatal_response.value, styles["BodyText"]),
                localtime(antenatal_response.time).strftime('%Y-%m-%d %H:%M')
            ])
        t = Table(data,
                  colwidths,
                  style=[
                      ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                      ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                      ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                      ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                      ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
                  ])
        report.append(t)
    else:
        ptext = '<font size=12>No responses to Antenatal Reminders yet. </font>'
        report.append(Paragraph(ptext, styles["Normal"]))
        report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    report.append(Spacer(1, 12))
    ptext = '<font size=12><b>TMCG Call Interactions</b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    ptext = '<font size=12>No TMCG voice call interactions yet. </font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly Responses </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    flow_responses_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [flow_responses_titles]
    colwidths = (100, 130, 100, 130)
    for i, flow_response in enumerate(flow_responses_weekly):
        data.append([
            flow_response.urn,
            Paragraph(flow_response.text, styles["BodyText"]),
            flow_response.status,
            localtime(flow_response.sent_on).strftime('%Y-%m-%d %H:%M')
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    report.append(Spacer(1, 12))

    ptext = '<font size=12> <b> Weekly failed to send messages </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    failed_messages_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [failed_messages_titles]
    colwidths = (100, 160, 100, 100)
    for i, failed_message in enumerate(failed_messages):
        data.append([
            failed_message.urn,
            Paragraph(failed_message.text, styles["BodyText"]),
            failed_message.status,
            localtime(failed_message.sent_on).strftime('%Y-%m-%d %H:%M')
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)

    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly hanging messages </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    read_messages_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [read_messages_titles]
    colwidths = (100, 160, 100, 100)
    for i, message in enumerate(hanging_messages):
        data.append([
            message.urn,
            Paragraph(message.text, styles["BodyText"]), message.status,
            localtime(message.sent_on).strftime("%Y-%m-%d %H:%M")
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)

    report.append(Spacer(1, 12))

    report.append(Spacer(1, 12))
    ptext = '<font size=12> <b> Weekly read/delivered messages </b></font>'
    report.append(Paragraph(ptext, styles["Normal"]))
    report.append(Spacer(1, 12))
    read_messages_titles = ['Phone Number', 'Message', 'Status', 'Sent On']
    data = [read_messages_titles]
    colwidths = (100, 160, 100, 100)
    for i, delivered_message in enumerate(delivered_messages):
        data.append([
            delivered_message.urn,
            Paragraph(delivered_message.text, styles["BodyText"]),
            delivered_message.status,
            localtime(delivered_message.sent_on).strftime("%Y-%m-%d %H:%M")
        ])
    t = Table(data,
              colwidths,
              style=[
                  ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                  ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                  ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                  ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
              ])
    report.append(t)
    report.append(Spacer(1, 12))

    doc.build(report)
Example #45
0
 def test_update_contact_should_return_zero_if_id_does_not_exist(self):
     contactToUpdate = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", True, 22.9)
     res = self.contactDAO.update(contactToUpdate)
     self.assertEqual(
         res, 0, "updating a non existant contact id does not return 0")
Example #46
0
class MyPDFView(View):
    template = 'qcreports/test.html'  # the template
    groups = Group.get_sms_maama_groups()
    contacts = Contact.get_sms_maama_weekly_contacts()
    sms_maama_contacts = Contact.get_sms_maama_contacts()
    sent_messages = Message.get_sms_maama_sent_messages()
    delivered_messages = Message.get_sms_maama_delivered_messages()
    failed_messages = Message.get_sms_maama_failed_messages()
    failed_messages_count = Message.get_sms_maama_failed_messages_count()
    contacts_count = Contact.get_sms_maama_contacts_count()
    weekly_contacts_count = Contact.get_sms_maama_weekly_contacts_count()
    messages_count = Message.get_sms_maama_sent_messages_count()
    read_messages_count = Message.get_sms_maama_read_messages_count()
    unread_messages = Message.get_sms_maama_unread_messages()
    flow_responses_count = Message.get_sms_maama_flow_responses_count()
    baby_responses = Message.get_sms_maama_flow_responses_baby()
    baby_responses_count = Message.get_sms_maama_flow_responses_baby_count()
    stops = Message.get_sms_maama_opted_out()
    stops_count = Message.get_sms_maama_opted_out_count()
    flows = Run.sms_maama_contact_flows()
    antenatal_responses = Run.sms_maama_contact_flows_antenatal()
    start_date = datetime.datetime.now() - datetime.timedelta(days=7)
    end_date = datetime.datetime.now()
    this_day = now()
    context = {
        'groups': groups,
        'contacts': contacts,
        'sms_maama_contacts': sms_maama_contacts,
        'sent_messages': sent_messages,
        'delivered_messages': delivered_messages,
        'failed_messages': failed_messages,
        'failed_messages_count': failed_messages_count,
        'contacts_count': contacts_count,
        'weekly_contacts_count': weekly_contacts_count,
        'messages_count': messages_count,
        'read_messages_count': read_messages_count,
        'unread_messages': unread_messages,
        'flow_responses_count': flow_responses_count,
        'baby_responses': baby_responses,
        'baby_responses_count': baby_responses_count,
        'stops': stops,
        'stops_count': stops_count,
        'flows': flows,
        'antenatal_responses': antenatal_responses,
        'start_date': start_date,
        'end_date': end_date,
        'this_day': this_day
    }  # data that has to be renderd to pdf templete

    def get(self, request):
        response = PDFTemplateResponse(
            request=request,
            template=self.template,
            filename="sms_maama_weekly_report.pdf",
            context=self.context,
            show_content_in_browser=False,
            # cmd_options={'margin-top': 10,
            #              "zoom": 1,
            #              "viewport-size": "1366 x 513",
            #              'javascript-delay': 1000,
            #              'footer-center': '[page]/[topage]',
            #              "no-stop-slow-scripts": True},
        )
        return response
Example #47
0
def contacts(id=None):
    if request.method == 'GET':
        if id is not None:
            contact = Contact.query.get(id)
            if contact:
                return jsonify(contact.serialize()), 200
            else:
                return jsonify({"msg": "Contact doesn't exist"}), 404
        else:
            contacts = Contact.query.all()
            contacts = list(map(lambda contact: contact.serialize(), contacts))
            return jsonify(contacts), 200

    if request.method == 'POST':
        name = request.json.get('name', None)
        email = request.json.get('email', None)
        phone = request.json.get('phone', "")
        address = request.json.get('address', "")

        if not name:
            return jsonify({"msg": "name is required"}), 400
        if not email:
            return jsonify({"msg": "email is required"}), 400

        contact = Contact()
        contact.name = name
        contact.email = email
        contact.phone = phone
        contact.address = address

        contact.save()

        return jsonify(contact.serialize()), 201

    if request.method == 'PUT':
        name = request.json.get('name', None)
        email = request.json.get('email', None)
        phone = request.json.get('phone', "")
        address = request.json.get('address', "")

        if not name:
            return jsonify({"msg": "name is required"}), 400
        if not email:
            return jsonify({"msg": "email is required"}), 400

        # SELECT * FROM contacts WHERE id = 1
        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact doesn't exist"}), 404

        contact.name = name
        contact.email = email
        contact.phone = phone
        contact.address = address

        # UPDATE contacts SET name=name, email=email ... WHERE id = 1
        contact.update()

        return jsonify(contact.serialize()), 200

    if request.method == 'DELETE':
        contact = Contact.query.get(id)
        if not contact:
            return jsonify({"msg": "Contact doesn't exist"}), 404
        
        # DELETE FROM contacts WHERE id = 1
        contact.delete()
        return jsonify({"succes", "Contact deleted"}), 200
Example #48
0
def add_to_Contact(client_id, user_id, tel, contact_person, post):  # в Contact
    contact_insert = Contact(client_id, user_id, tel, contact_person, post)
    db.session.add(contact_insert)
    db.session.commit()
Example #49
0
def init(db):
    try:
        db.session.query(SensorType).delete()
        db.session.query(Device).delete()
        db.session.query(Sensor).delete()
        db.session.query(Contact).delete()
        db.session.query(Relay).delete()
    except:
        pass

    st_t = SensorType(unit=u'°C',
                      description=u'Temperatura',
                      name='temperature')
    st_h = SensorType(unit=u'%', description=u'Vlažnost', name='humidity')
    st_b = SensorType(unit=u'V', description=u'Baterija', name='battery')

    d_zg = Device(description='Zgoraj')
    d_sp = Device(description='Spodaj')

    zgt = Sensor(sensor_code='ZGT',
                 description='Temperatura (zgoraj)',
                 max_possible_value=40,
                 max_warning_value=33,
                 min_possible_value=-10,
                 min_warning_value=20,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=True,
                 device=d_zg,
                 type=st_t,
                 emit_every=5)

    zgb = Sensor(sensor_code='ZGB',
                 description='Baterija (zgoraj)',
                 max_possible_value=6,
                 min_possible_value=0,
                 min_warning_value=3.3,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=True,
                 device=d_zg,
                 type=st_b,
                 emit_every=10)

    spb = Sensor(sensor_code='SPB',
                 description='Baterija (spodaj)',
                 max_possible_value=6,
                 min_possible_value=0,
                 min_warning_value=3.3,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=True,
                 device=d_sp,
                 type=st_b,
                 emit_every=10)

    spt = Sensor(sensor_code='SPT',
                 description='Temperatura (spodaj)',
                 max_possible_value=40,
                 max_warning_value=34,
                 min_possible_value=-10,
                 min_warning_value=20,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=True,
                 device=d_sp,
                 type=st_t,
                 emit_every=5)

    zgh = Sensor(sensor_code='ZGH',
                 description=u'Vlažnost (zgoraj)',
                 max_possible_value=100,
                 max_warning_value=90,
                 min_possible_value=0,
                 min_warning_value=10,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=False,
                 device=d_zg,
                 type=st_h,
                 emit_every=5)

    sph = Sensor(sensor_code='SPH',
                 description=u'Vlažnost (spodaj)',
                 max_possible_value=100,
                 max_warning_value=90,
                 min_possible_value=0,
                 min_warning_value=10,
                 observable_measurements=3,
                 observable_alarming_measurements=2,
                 enable_warnings=False,
                 device=d_sp,
                 type=st_h,
                 emit_every=5)

    c = Contact(name='Admin', phone='+123456789', email='admin')
    user = User(email='admin')
    user.password = '******'
    user.ping()

    for l in ['A', 'B']:
        for i in range(8):
            code = '%s%d' % (l, i)
            description = 'Rele %s' % code
            db.session.add(
                Relay(description=description,
                      switch_on_text='ON',
                      switch_off_text='OFF'))

    db.session.add(zgt)
    db.session.add(spt)
    db.session.add(zgh)
    db.session.add(sph)
    db.session.add(spb)
    db.session.add(zgb)
    db.session.add(c)
    db.session.add(user)

    db.session.commit()
Example #50
0
def create_contact_query(email, phone):
    new_contact = Contact(email=email, phone=phone)
    db.session.add(new_contact)
    db.session.flush()
    db.session.commit()
    return new_contact.id
Example #51
0
 def post(self, contact_id):
     contact = Contact.get_by_id(int(contact_id))
     contact.key.delete()
     return self.redirect_to('contacts')
Example #52
0
def init():
    db.drop_all()
    db.create_all()

    # Create roles
    user_datastore.create_role(name='admin',
                               description='System administrator')
    user_datastore.create_role(name='user', description='Conference user')
    admin = user_datastore.create_user(
        username='******', password=utils.encrypt_password('admin'))
    user = user_datastore.create_user(username='******',
                                      password=utils.encrypt_password('user'))
    user_datastore.add_role_to_user(admin, 'admin')
    user_datastore.add_role_to_user(user, 'user')

    contacts = [
        ('1010', gettext('John Smith')),
        ('1020', gettext('Sam Brown')),
    ]
    for c in contacts:
        rec = Contact(phone=c[0], name=c[1], user=admin)
        db.session.add(rec)

    guest_user_profile = ParticipantProfile(name=gettext('Guest'),
                                            startmuted=True)
    db.session.add(guest_user_profile)
    marked_user_profile = ParticipantProfile(name=gettext('Marker'),
                                             marked=True)
    db.session.add(marked_user_profile)
    admin_user_profile = ParticipantProfile(name=gettext('Administrator'),
                                            admin=True)
    db.session.add(admin_user_profile)

    conf_profile = ConferenceProfile(name=gettext('Default'))
    db.session.add(conf_profile)

    conf = Conference(
        number=100,
        name=gettext('Test Conference'),
        conference_profile=conf_profile,
        public_participant_profile=guest_user_profile,
        is_public=True,
        user=admin,
    )
    db.session.add(conf)

    p1 = Participant(conference=conf,
                     profile=admin_user_profile,
                     phone='1001',
                     user=admin)
    p2 = Participant(conference=conf,
                     profile=guest_user_profile,
                     phone='1002',
                     user=admin)
    p3 = Participant(conference=conf,
                     profile=marked_user_profile,
                     phone='1003',
                     user=admin)
    db.session.add(p1)
    db.session.add(p2)
    db.session.add(p3)

    db.session.commit()
Example #53
0
 def create_contact(self, name, email_address, phone_number):
     contact = Contact(name, email_address, phone_number)
     self.contacts.append(contact)
Example #54
0
 def get(self, id):
     abort_if_user_doesnt_exist(id)
     return Contact.get_one(id)
Example #55
0
 def delete(self, id):
     abort_if_user_doesnt_exist(id)
     Contact.delete_one(id)
     return '', 204
Example #56
0
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()


if __name__ == '__main__':
    database.connect()

    if not database.get_tables():
        Contact.create_table()
        SMS.create_table()
        Phone.create_table()

    me = Contact.get_or_create(name=settings.OWNER_NAME)
    me.save()
    for phone in settings.OWNER_PHONES:
        p = Phone.get_or_create(phone=phone, contact=me)
        p.save()

    gv_to_db(me)
    database.close()
Example #57
0
 def execute(self):
     contact = Contact.get_by_user_and_unique_id(self.user, self.unique_id)
     contact.key.delete()
     return self.unique_id
Example #58
0
def contacts(id=None):
    if request.method == 'GET':
        if id is not None:
            contact = Contact.query.get(id)
            if contact:
                return jsonify(contact.serialize()), 200
            else:
                return jsonify({"msg": "Contact not found"}), 404
        else:
            contacts = Contact.query.all()
            contacts = list(map(lambda contact: contact.serialize(), contacts))
            return jsonify(contacts), 200

    if request.method == 'POST':
        name = request.json.get('name', None)
        phone = request.json.get('phone', None)

        if not name:
            return jsonify({"msg": "name is required"}), 422
        if not phone:
            return jsonify({"msg": "phone is required"}), 422

        contact = Contact()
        contact.name = name
        contact.phone = phone

        db.session.add(contact)
        db.session.commit()

        return jsonify(contact.serialize()), 201

    if request.method == 'PUT':

        name = request.json.get('name', None)
        phone = request.json.get('phone', None)

        if not name:
            return jsonify({"msg": "name is required"}), 422
        if not phone:
            return jsonify({"msg": "phone is required"}), 422

        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact not found"}), 404

        contact.name = name
        contact.phone = phone

        db.session.commit()

        return jsonify(contact.serialize()), 200

    if request.method == 'DELETE':
        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact not found"}), 404

        db.session.delete(contact)
        db.session.commit()

        return jsonify({"msg": "Contact deleted"}), 200
Example #59
0
    def post(self, request, format=None):
        data = json.loads(request.body)
        print('--------------------')
        print(data['firstName'])
        print(data['lastName'])
        print(data['owner'])
        print(data['accountNumber'])
        print(data['routingNumber'])
        print(data['accountType'])
        print('--------------------')
        firstName = data.get('firstName', None)
        lastName = data.get('lastName', None)
        owner = data.get('owner', None)
        accountNumber = data.get('accountNumber', None)
        routingNumber = data.get('routingNumber', None)
        accountType = data.get('accountType', None)

        headers = {'Content-Type': 'application/json'}
        if (firstName == None or lastName == None or owner == None \
                or accountNumber == None or routingNumber == None or accountType == None):
            return Response(
                {
                    'status': 'Not acceptable',
                    'message': 'Cannot find request parameters!'
                },
                headers=headers,
                status=status.HTTP_406_NOT_ACCEPTABLE)

        # validate the contact should not exist in the record
        try:
            result = Contact.objects.get(owner=owner,
                                         accountNumber=accountNumber)
            return Response(
                {
                    'status':
                    'Precondition invalid',
                    'message':
                    'This account has already existed in your contacts list!'
                },
                headers=headers,
                status=status.HTTP_428_PRECONDITION_REQUIRED)
        except Contact.DoesNotExist:
            # first check whether this contact exist in the accountinfo table
            try:
                result = AccountInfo.objects.get(firstName=firstName, \
                                                 lastName=lastName, accountNumber=accountNumber, \
                                                 accountType=accountType, routingNumber=routingNumber)
                # the result do exist in the contact list.
                newContact = Contact(owner=owner, firstName=firstName, lastName=lastName, \
                                     accountNumber=accountNumber, routingNumber=routingNumber, accountType=accountType)
                newContact.save()
                return Response(
                    {
                        'status': 'Success',
                        'message':
                        'Your new contact has been added successfully!'
                    },
                    headers=headers,
                    status=status.HTTP_200_OK)
            except AccountInfo.DoesNotExist:
                return Response(
                    {
                        'status': 'Not found',
                        'message': 'We do not have record of this contact!'
                    },
                    headers=headers,
                    status=status.HTTP_404_NOT_FOUND)
Example #60
0
def contacts(id=None, name=None):
    if request.method == 'GET':
        if name is not None:
            #contact = Contact.query.filter_by(name="Paul Guzmán").first()
            #contacts = Contact.query.filter(Contact.name.like("%"+name+"%")).all()
            #print(contact)
            return jsonify(contact.serialize()), 200
        if id is not None:
            contact = Contact.query.get(id)
            if contact:
                return jsonify(contact.serialize()), 200
            else:
                return jsonify({"msg": "Contact not found"}), 404
        else:
            contacts = Contact.query.all()
            contacts = list(map(lambda contact: contact.serialize(), contacts))
            return jsonify(contacts), 200

    if request.method == 'POST':
        name = request.json.get("name", None)
        phone = request.json.get("phone", None)

        if not name:
            return jsonify({"msg": "Name is required"}), 400
        if not phone:
            return jsonify({"msg": "Phone is required"}), 400

        contact = Contact()
        contact.name = name
        contact.phone = json.dumps(phone)
        contact.save()

        return jsonify(contact.serialize()), 201

    if request.method == 'PUT':
        name = request.json.get("name", None)
        phone = request.json.get("phone", None)

        if not name:
            return jsonify({"msg": "Name is required"}), 400
        if not phone:
            return jsonify({"msg": "Phone is required"}), 400

        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact not found"}), 404

        contact.name = name
        contact.phone = json.dumps(phone)
        contact.update()

        return jsonify(contact.serialize()), 200

    if request.method == 'DELETE':
        contact = Contact.query.get(id)

        if not contact:
            return jsonify({"msg": "Contact not found"}), 404

        contact.delete()

        return jsonify({"success": "Contact was deleted"}), 200