Example #1
0
    def update_user(data):
        try:
            simcard = Enduser.get_or_create_simcard(data.get('telephone'))
            if not simcard: return ( 'Bad Telephone', None)
            telephone = simcard.msisdn
            old_amb = Ambulance.get_ambulance(telephone)
            ## Check ambulance registered for the telephone
            if not old_amb:
                 return ( 'Ambulance does not exist with Telephone %s' % (telephone) , None)
            else:
                data.update({"indexcol": old_amb.indexcol})
                data.update({"simcard_pk": simcard.indexcol})
                data.update({"telephone": telephone})   
                #print "UPDATE DATA: ", data 
                migrate(Ambulance._table, data)
                amb = Ambulance.get_ambulance(telephone)
                if amb:                    
                    sent = Enduser.send_message(telephone, 
                        "Twabamenyeshaga ko mumaze gukosorwa imyirondoro muri sisitemu ya RapidSMS Rwanda, nk'ukurikirana imbagukira gutabara, ikigo nderabuzima cya %(hc)s, ibitaro bya %(hd)s. Murakoze."
                                                    % { 'hc': amb.facility_name, 'hd': amb.referral_facility_name })
                    sent = Enduser.send_message(telephone, 
                        "You have been updated in RapidSMS as ambulance coordinator, in %(hc)s health centre, %(hd)s district hospital. Thanks."
                                                    % { 'hc': amb.facility_name, 'hd': amb.referral_facility_name })
                       
                    if not sent:    return ("Ambulance Updated, but SMS not sent, please contact telephone: %(phone)s."
                                        % {'phone': amb.telephone}, amb)
                    return ( 'Ambulance Updated', amb)

                else:
                    return ( 'Ambulance with telephone %s cannot be updated, contact system administrator.' % (
                                                                        old_amb.telephone) , None)
            
        except Exception, e:
            print e
            pass
Example #2
0
 def get_or_create( data):
     try:
         simcard = Enduser.get_or_create_simcard(data.get('telephone'))
         if not simcard: return ( 'Bad Telephone', None)
         telephone = simcard.msisdn
         amb = Ambulance.get_ambulance(telephone)
         if not amb:
             data.update({"simcard_pk": simcard.indexcol})
             data.update({"telephone": telephone})
             #print "SAVE DATA: ", data 
             migrate(Ambulance._table, data)
             amb = Ambulance.get_ambulance(telephone)
             sent = False
             sent = Enduser.send_message(telephone, 
                 "Twabamenyeshaga ko mumaze kwandikwa muri sisitemu ya RapidSMS Rwanda, nk'ukurikirana imbagukira gutabara, ikigo nderabuzima cya %(hc)s, ibitaro bya %(hd)s. Murakoze."
                                             % { 'hc': amb.facility_name, 'hd': amb.referral_facility_name })
             sent = Enduser.send_message(telephone, 
                 "You have been registered in RapidSMS as ambulance coordinator, in %(hc)s health centre, %(hd)s district hospital. Thanks."
                                             % { 'hc': amb.facility_name, 'hd': amb.referral_facility_name })
                
             if not sent:    return ("Ambulance Created, but SMS not sent, please contact telephone: %(phone)s."
                                 % {'phone': amb.telephone}, amb)
             return ( 'Ambulance created', amb)
         return ( 'Ambulance exists', amb)
     except Exception, e:
         print e
         pass
Example #3
0
 def get_stats(self):
     cnds = self.navb.conditions()
     #print "CNDS: ", cnds
     attrs = [(x.indexcol, x.code.lower(), x.name)
              for x in Enduser.get_roles()]
     cols = ['COUNT(*) AS total']
     exts = {}
     for attr in attrs:
         exts.update(
             {attr[1].lower(): ('COUNT(*)', 'role_pk = %d' % attr[0])})
     nat = Enduser.get_users_summary(cnds, cols, exts)
     avg = average
     return [attrs, avg, nat]
Example #4
0
    def update_user(self):
        cnds = self.navb.conditions()
        message = ''
        user = None
        #print "IDS: ",self.navb.kw, self.navb.kw.get('id') , self.navb.kw.get('pk')
        if self.navb.kw.get('id') or self.navb.kw.get('pk'):
            mkw = "%s" % self.navb.kw.get('id') or self.navb.kw.get('pk')
            cnds = {"indexcol = %s": mkw}
            user = Enduser.get_users(cnds)[0]

        if self.navb.kw.get("pk") and self.navb.kw.get(
                'nid') and self.navb.kw.get('telephone_moh'):
            cnds = {"indexcol = %s": self.navb.kw.get("pk")}
            indexcol = self.navb.kw.get('pk')
            nid = self.navb.kw.get('nid')
            phone = self.navb.kw.get('telephone_moh')
            formdata = {
                "indexcol": indexcol,
                "telephone": phone,
                "national_id": nid,
                "email": self.navb.kw.get('email'),
                "surname": self.navb.kw.get('surname'),
                "given_name": self.navb.kw.get('given_name'),
                "sex_pk": self.navb.kw.get('sex'),
                "role_pk": self.navb.kw.get('role'),
                "education_level_pk": self.navb.kw.get('edu_level'),
                "date_of_birth": self.navb.make_time(self.navb.kw.get('dob')),
                "join_date": self.navb.make_time(self.navb.kw.get('djoin')),
                "language_pk": self.navb.kw.get('language'),
                "nation_pk": self.navb.kw.get('user_nation'),
                "province_pk": self.navb.kw.get('user_province'),
                "district_pk": self.navb.kw.get('user_district'),
                "referral_facility_pk": self.navb.kw.get('user_hospital'),
                "facility_pk": self.navb.kw.get('user_facility'),
                "location_level_pk": self.navb.kw.get('user_area_level'),
                "sector_pk": self.navb.kw.get('user_sector'),
                "cell_pk": self.navb.kw.get('user_cell'),
                "village_pk": self.navb.kw.get('user_village'),
                "is_active": True,
                "is_correct": True
            }

            #print "\nFORM: ", formdata, "\n"
            message, user = Enduser.update_user(formdata)
            if user: user = Enduser.get_users(cnds)[0]
            self.navb.kw = {"id": self.navb.kw.get("pk")}

        sectors = self.navb.auth.auth_filter_locations("sec", user.district_pk)
        cells = self.navb.auth.auth_filter_locations("cel", user.sector_pk)
        villages = self.navb.auth.auth_filter_locations("vil", user.cell_pk)
        genders = Enduser.get_genders()
        roles = Enduser.get_roles()
        langs = Enduser.get_languages()
        education_levels = Enduser.get_education_levels()
        area_levels = Enduser.get_location_levels()
        #print user.__dict__
        return [
            sectors, cells, villages, genders, roles, education_levels,
            area_levels, langs, message, user
        ]
Example #5
0
 def register_diagnosis(self):
     genders = Enduser.get_genders()
     locs = self.navb.locs()
     user = self.navb.user
     area_levels = Enduser.get_location_levels()
     message = None
     report = None
     received = False
     #print self.navb.kw
     if self.navb.kw.get('id'):
         try:
             report = Malaria.get_report(indexcol=self.navb.kw.get('id'))
         except Exception, e:
             print e
             pass
Example #6
0
 def notify_level_by_email(self, level_code, role_code, location_pk):
     """ level codes :  'NATION', 'PRV', 'DST', 'NRH', 'MH', 'HD', 'HP', 'HC', 'CL', 'SEC', 'CEL', 'VIL' """
     try:
         unsent = []
         users = []
         if level_code and role_code and location_pk:
             #print "HERE", level_code, role_code, location_pk
             users = fetch_users_per_level_and_role(level_code=level_code,
                                                    role_code=role_code,
                                                    pk=location_pk)
         elif level_code and location_pk:
             #print "HERE", level_code, location_pk
             users = fetch_users_per_level(level_code=level_code,
                                           pk=location_pk)
         else:
             #print "HERE", level_code
             users = fetch_users_per_level(level_code=level_code)
         print[u.email for u in users]
         for u in users:
             try:
                 #print u.__dict__
                 message = self.format_message(u)
                 #print "Destination %s, Email: %s" % (u.email, message)
                 sent = Enduser.send_email(self.ntype, u.email, message)
                 if not sent:
                     unsent.append(u.email)
             except Exception, e:
                 print "SEND MESSAGE TO USER: "******"UNSENT : ", unsent
         return True
Example #7
0
 def get_users(self):
     cnds = self.navb.conditions()
     if self.navb.kw.get('q'):
         mkw = "%%%s%%" % self.navb.kw.get('q')
         cnds = {"telephone LIKE %s OR national_id LIKE %s": (mkw, mkw)}
         print cnds
         return Enduser.get_users(cnds)
     return []
Example #8
0
 def reset_password(email):
     try:
         user, otp, token = MchSecurity.get_otp(email)
         #print "OTP: ",  otp
         sent = Enduser.send_message(
             user.telephone,
             "Your OTP to change password , now, is: %s" % otp)
         return (token, sent)
     except Exception, e:
         print e
Example #9
0
    def group_messaging(self):
        cnds = self.navb.conditions()
        message = ''
        if self.navb.kw.get("send") and self.navb.kw.get('text'):
            text = self.navb.kw.get('text')
            group = self.navb.kw.get('group')
            cnds.update({'is_active': ''})
            if group and group != 'all': cnds.update({'role_pk = %s': group})
            users = Enduser.get_users_cols(cnds, cols=['telephone'])
            unsents = []
            bulk_sms_data = {
                "message": text,
                "to_group": group,
                "user_phone": self.navb.user.telephone,
                "user_pk": self.navb.user.indexcol,
                "nation_pk": self.navb.user.nation_pk,
                "province_pk": self.navb.kw.get('province'),
                "district_pk": self.navb.kw.get('district'),
                "referral_facility_pk": self.navb.kw.get('hd'),
                "facility_pk": self.navb.kw.get('hc'),
                "sector_pk": self.navb.kw.get('sector'),
                "cell_pk": self.navb.kw.get('cell'),
                "village_pk": self.navb.kw.get('village')
            }
            saved = Enduser.bulk_messaging(bulk_sms_data)

            for user in users:
                try:
                    #print user.telephone, text
                    sent = Enduser.send_message(user.telephone, text)
                except Exception, e:
                    unsents.append(user.telephone)
                    continue

            if len(unsents) > 0:
                message = ','.join(u for u in unsents)
                message = 'The message has not been delivered to: %s' % message
            else:
                message = 'The message you sent has been delivered successfully. Thanks.'

            #print "\nRESPONSE: ", message, "\n", cnds, "\n"
            self.navb.kw = {}
Example #10
0
 def activate(self):
     cnds = self.navb.conditions()
     message = ''
     user = None
     action = self.navb.kw.get('action')
     try:
         status = True
         if action.strip() == 'deactivate': status = False
         user = Enduser.get_users({'indexcol = %s':
                                   self.navb.kw.get('id')})[0]
         data = {
             'telephone': user.telephone,
             'national_id': user.national_id,
             'is_active': status
         }
         ## TODO
         ## CHECK ALL USERS WITH TELEPHONE
         message, user = Enduser.update_user_info(data)
         if status == False:
             message = "User %s successfully deactivated." % user.surname
         else:
             message = "User %s successfully activated." % user.surname
     except Exception, e:
         pass
    def dispatch(cls, router, msg):

        # spawn an instance of this handler, and stash
        # the low(er)-level router and message object
        inst = cls(router, msg)

        ### GET REPORTER
        try:
            cls.reporter = Enduser.get_active_user(msg.connection.identity)
            #print cls.reporter.__dict__
            cls.language = cls.reporter.language_code.lower()
        except Exception, e:
            #print "ERROR OF CHW REG: ", e
            msg.respond(
                get_appropriate_response(
                    msg=msg,
                    DEFAULT_LANGUAGE_ISO='rw',
                    message_type='sender_not_registered')[1])
            return True
Example #12
0
    def change_password(email, tkn, otp, new_passwd):
        message = None
        if tkn and otp:
            try:
                seen = MchSecurity.verify_otp(tkn, otp)  #;print "SEEN: ", seen
                if seen:
                    #print "SEEN: ", otp, new_passwd
                    user = MchSecurity.get_user_by_email(email)
                    formdata = {
                        "indexcol": user.indexcol,
                        "telephone": user.telephone,
                        "national_id": user.national_id,
                        "email": email,
                        "passwd": new_passwd
                    }

                    #print "\nFORM: ", formdata, "\n"
                    message, user = Enduser.update_user(formdata)
                return (message, True)
            except Exception, e:
                print e
                message = e
Example #13
0
 def save(self, user=None):
     """ Save a enderror object and return indexcol """
     try:
         FIELDS = self.__dict__
         if not user: user = Enduser.get_active_user(self.user_phone)
         if user:
             FIELDS.update({
                 "user_pk": user.indexcol,
                 "nation_pk": user.nation_pk,
                 "province_pk": user.province_pk,
                 "district_pk": user.district_pk,
                 "referral_facility_pk": user.referral_facility_pk,
                 "facility_pk": user.facility_pk,
                 "sector_pk": user.facility_pk,
                 "cell_pk": user.facility_pk,
                 "village_pk": user.facility_pk,
             })
         err = migrate(Enderror._table, FIELDS)
         return err
     except Exception, e:
         print e
         raise MchCriticalError(Exception('Enderror cannot be saved'))
Example #14
0
    def register_ambulance(self):
        cnds = self.navb.conditions()
        message = ''
        amb = None
        if self.navb.kw.get("amb_facility") and self.navb.kw.get(
                'telephone_moh'):
            fac = self.navb.kw.get('amb_facility')
            phone = self.navb.kw.get('telephone_moh')
            formdata = {
                "telephone": phone,
                "coordinator": nid,
                "nation_pk": self.navb.kw.get('amb_nation'),
                "province_pk": self.navb.kw.get('amb_province'),
                "district_pk": self.navb.kw.get('amb_district'),
                "referral_facility_pk": self.navb.kw.get('amb_hospital'),
                "facility_pk": self.navb.kw.get('amb_facility')
            }

            #print "\nFORM: ", formdata, "\n"
            message, amb = Enduser.create_ambulance(formdata)
            self.navb.kw = {}

        return [message, amb]
Example #15
0
    def register_user(self):
        cnds = self.navb.conditions()
        message = ''
        user = None
        if self.navb.kw.get("nid") and self.navb.kw.get('telephone_moh'):
            nid = nid = self.navb.kw.get('nid')
            phone = self.navb.kw.get('telephone_moh')
            formdata = {
                "telephone": phone,
                "national_id": nid,
                "email": self.navb.kw.get('email'),
                "surname": self.navb.kw.get('surname'),
                "given_name": self.navb.kw.get('given_name'),
                "sex_pk": self.navb.kw.get('sex'),
                "role_pk": self.navb.kw.get('role'),
                "education_level_pk": self.navb.kw.get('edu_level'),
                "date_of_birth": self.navb.make_time(self.navb.kw.get('dob')),
                "join_date": self.navb.make_time(self.navb.kw.get('djoin')),
                "language_pk": self.navb.kw.get('language'),
                "nation_pk": self.navb.kw.get('user_nation'),
                "province_pk": self.navb.kw.get('user_province'),
                "district_pk": self.navb.kw.get('user_district'),
                "referral_facility_pk": self.navb.kw.get('user_hospital'),
                "facility_pk": self.navb.kw.get('user_facility'),
                "location_level_pk": self.navb.kw.get('user_area_level'),
                "sector_pk": self.navb.kw.get('user_sector'),
                "cell_pk": self.navb.kw.get('user_cell'),
                "village_pk": self.navb.kw.get('user_village'),
                "is_active": True,
                "is_correct": True
            }

            #print "\nFORM: ", formdata, "\n"
            message, user = Enduser.get_or_create(formdata)
            self.navb.kw = {}

        genders = Enduser.get_genders()
        roles = Enduser.get_roles()
        langs = Enduser.get_languages()
        education_levels = Enduser.get_education_levels()
        area_levels = Enduser.get_location_levels()
        return [
            genders, roles, education_levels, area_levels, langs, message, user
        ]
Example #16
0
    def notify_level_per_privilege(self,
                                   level_code=None,
                                   role_code=None,
                                   privilege_code=None,
                                   location_pk=None,
                                   chw_pk=None,
                                   sms=True):
        u = None
        try:
            users_ids = []
            filters = {}
            #print level_code, privilege_code
            if level_code:
                level = fetch_location_level(level_code)
                if level:
                    filters.update({'location_level_pk = %s': level.indexcol})

            if role_code:
                role = fetch_role(role_code)
                if role: filters.update({'role_pk = %s': role.indexcol})

            if location_pk:
                if level_code == 'NATION':
                    filters.update({'nation_pk = %s': location_pk})
                if level_code == 'PRV':
                    filters.update({'province_pk = %s': location_pk})
                if level_code == 'DST':
                    filters.update({'district_pk = %s': location_pk})
                if level_code == 'NRH':
                    filters.update({'facility_pk = %s': location_pk})
                if level_code == 'MH':
                    filters.update({'facility_pk = %s': location_pk})
                if level_code == 'HD':
                    filters.update({'referral_facility_pk = %s': location_pk})
                if level_code == 'HP':
                    filters.update({'facility_pk = %s': location_pk})
                if level_code == 'HC':
                    filters.update({'facility_pk = %s': location_pk})
                if level_code == 'CL':
                    filters.update({'facility_pk = %s': location_pk})
                if level_code == 'SEC':
                    filters.update({'sector_pk = %s': location_pk})
                if level_code == 'CEL':
                    filters.update({'cell_pk = %s': location_pk})
                if level_code == 'VIL':
                    filters.update({'village_pk = %s': location_pk})

            if chw_pk:
                filters.update({'indexcol = %s': chw_pk})

            if privilege_code:
                privilege = fetch_privilege(privilege_code)
                users_ids = fetch_users_ids_with_privilege(
                    filters={'privilege_pk = %s': privilege.indexcol})

            unsent = []
            users = fetch_users(filters=filters)

            for u in users:
                #print [ x.__dict__ for x in users_ids], [u.indexcol for u in users]
                if u.indexcol in [x.user_pk for x in users_ids]:
                    try:
                        #print self.message, u.indexcol, u.telephone
                        message = self.format_message(u)
                        sent = False
                        if not sms:
                            #print "Destination %s, Email: %s" % (u.email, message)
                            sent = Enduser.send_email(self.ntype, email,
                                                      message)
                        else:
                            #print "Destination %s, SMS: %s" % (u.telephone, message)
                            sent = Enduser.send_message(u.telephone, message)

                        if not sent:
                            unsent.append(u.telephone)
                    except Exception, ex:
                        print "SEND MESSAGE TO USER: %s" % ex, self.chw.sector_name
                        continue

                else:
                    continue
            return True
Example #17
0
    def get_tables(self):
        cnds = self.navb.conditions()  #;print cnds
        if self.navb.kw.get("search") and self.navb.kw.get("identity"):
            mkw = "%%%s%%" % self.navb.kw.get('identity').strip()
            if self.navb.kw.get("search") == 'nid':
                cnds.update({"national_id LIKE %s": mkw})
            if self.navb.kw.get("search") == 'sim':
                cnds.update({"telephone LIKE %s": mkw})
        exts = {}
        attrs = [(x.indexcol, x.code.lower(), x.name)
                 for x in Enduser.get_roles()]
        cnds, markup, cols = self.navb.neater_tables(
            cnds=cnds,
            extras=[
                ('indexcol', 'ID'),
                ('national_id', 'National ID'),
                ('telephone', 'Telephone'),
                ('surname', 'Surname'),
                ('given_name', 'Given Name'),
                ('role_pk', 'Role'),
                ('email', 'Email'),
                ('is_active', 'Is Active'),
                #('last_seen', 'Last Seen'),
                ('province_pk', 'Province'),
                ('district_pk', 'District'),
                ('referral_facility_pk', 'Hospital'),
                ('facility_pk', 'Health Centre'),
                ('sector_pk', 'Sector'),
                ('cell_pk', 'Cell'),
                ('village_pk', 'Village'),
            ])

        markup.update({
            'action':
            lambda x, _, __:
            '<a href="/dashboards/updateuser?id=%s">Edit %s</a>' % (x, x),
        })
        markup.update({
            'role_pk':
            lambda x, _, __: '%s' % (Enduser.get_role_name(x))
        })
        markup.update({
            'indexcol':
            lambda x, _, __:
            '<a href="/dashboards/report?tbl=chw&id=%s">View</a>&nbsp;&#124;&nbsp;\
                                                     <a href="/dashboards/activate?action=activate&id=%s">Activate</a>&nbsp;&#124;&nbsp;\
                                                     <a href="/dashboards/activate?action=deactivate&id=%s">Deactivate</a>'
            % (x, x, x),
        })

        sc = self.navb.kw.get('subcat')
        #print cnds, markup, cols, sc, attrs

        DESCRI = []
        USERDICT = {y[1]: (y[0], y[2]) for y in attrs}
        INDICS = []
        group = "User"
        title = "User List"

        if self.navb.kw.get('subcat') and self.navb.kw.get('subcat') in [
                makecol(x[1]) for x in attrs
        ]:
            cnds.update(
                {'role_pk = %s': USERDICT[self.navb.kw.get('subcat')][0]})
            INDICS = [(self.navb.kw.get('subcat'),
                       USERDICT[self.navb.kw.get('subcat')][1])]
            group = USERDICT[self.navb.kw.get('subcat')][1]

        dcols = [x[0] for x in cols]
        #print cnds
        nat = Enduser.fetch_user_table(cnds, dcols)
        #DESCRI.append((group, title))
        desc = 'Users%s' % (' (%s)' % (self.navb.find_descr(
            DESCRI + INDICS, sc or self.navb.kw.get('subcat'))))
        #print INDICS, title, group, attrs, "NAT: ", nat[0].__dict__
        return (title, desc, group, attrs, markup, cols, nat)
Example #18
0
 def get_total(self):
     cnds = self.navb.conditions()
     exts = {}
     cols = ['COUNT(*) AS total']
     total = Enduser.get_users_summary(cnds, cols, exts)[0]
     return total
Example #19
0
##
## @author UWANTWALI ZIGAMA Didier
## [email protected]/[email protected]
##

from sms.api.messaging.smsparser import *
from sms.api.messaging.smsprocessor import *
from model.enduser import Enduser
from sms.api.messagelog.models import Message
from rapidsms.models import Connection
from sms.api.messaging.persister import Persister

#identity = '+250782904295' #ASM
#identity = '+250782923741' #BINOME
identity = '+250788660270'
chw = Enduser.get_active_user(identity)
REPORTS = [
    ('PRE',
     'pre 1199270180887099 09.12.2017 10.09.2018 5 1 GS rm yg ol ma vo oe ns HC wt80.6 ht180 to hw muac14.5 0788660270'
     ),
    ('DEP', 'DEP 1234007890123457'),
    ('DEP_CHILD', 'DEP 1234567890123457 01 09.01.2015'),
    ('REF', 'REF 0234567890123457'),
    ('ANC',
     'ANC 0788660270010918 05.07.2018 anc4 VO PC OE NS MA JA FP FE DS DI SA RB HY CH AF hc wt65.5 muac12.5'
     ),
    ('RISK',
     'RISK 1234567890123090 VO PC OE NS MA JA FP FE DS DI SA RB HY CH AF or wt70'
     ),
    ('RES',
     'RES 1234567890123090 VO PC OE NS MA JA FP FE DS DI SA RB HY CH AF hp AA MW'
Example #20
0
                    #print user.telephone, text
                    sent = Enduser.send_message(user.telephone, text)
                except Exception, e:
                    unsents.append(user.telephone)
                    continue

            if len(unsents) > 0:
                message = ','.join(u for u in unsents)
                message = 'The message has not been delivered to: %s' % message
            else:
                message = 'The message you sent has been delivered successfully. Thanks.'

            #print "\nRESPONSE: ", message, "\n", cnds, "\n"
            self.navb.kw = {}

        roles = Enduser.get_roles()
        return [roles, message]

    def upload_users(self):
        cnds = self.navb.conditions()
        message = ''
        errors = []
        if self.navb.kw.get("users_list"):
            file_of_users = self.navb.kw.get('users_list')
            try:
                #print "File: ", file_of_users.file, file_of_users.file.name
                ourfile = process_import_file(file_of_users,
                                              self.navb.user.indexcol,
                                              datetime.datetime.now())
                #print "OUR FILE ON DISK: " , ourfile
                errs = upload_users_indb(ourfile[1])