Exemplo n.º 1
0
def user(phone_number):
    new_user = User(
        uuid=generate_uuid(),
        email='a@a',
        email_confirmed=True,
        username='******',
        name='bob',
        dob='1/1/1991',
        password_hash=generate_password_hash('pass'),
        secondary_password_hash=generate_password_hash('1234'),
        is_suspended=False,
        phone_id=phone_number.id,
        bank_name='bankbankbank',
        bank_account_number='123-456',
        bank_account_holder='bob',
        balance=1000000,
        pending_commissions=0,
        payable_commissions=0,
        created_at=datetime(2000, 1, 1, 0, 5, 10),
        role=UserRole.HQ,
        partner_name="partner bob",
        partner_referral_code="test123",
    )
    db.session.add(new_user)
    db.session.commit()
    yield new_user
Exemplo n.º 2
0
def user_ru(phone_number_ru, user_f):
    u = User(
        uuid=generate_uuid(),
        email='ru@ru',
        email_confirmed=True,
        username='******',
        name='ruru',
        dob='1/1/1991',
        password_hash=generate_password_hash('pass'),
        secondary_password_hash=generate_password_hash('1234'),
        is_suspended=False,
        referring_user_id=user_f.id,
        phone_id=phone_number_ru.id,
        bank_name='rubonk',
        bank_account_number='654-321',
        bank_account_holder='ru',
        balance=1000000,
        pending_commissions=0,
        payable_commissions=0,
        created_at=datetime(2000, 1, 1, 0, 5, 10),
        role=UserRole.REGULAR_USER,
    )
    db.session.add(user_ru)
    db.session.commit()
    yield user_ru
Exemplo n.º 3
0
def create_template(name, img):
    """Adds this template to the datastore along with a generated
       thumbnail and accompanied dimension metadata"""
    
    thumb = Image(img)
    template_data = Image(img)
    t_img = db.Blob(img)
    width, height = template_data.width, template_data.height

    if width != 500:
        template_data.resize(width=500)
        template_data = template_data.execute_transforms()
        t_data = Image(template_data)
        width, height = t_data.width, t_data.height
        t_img = db.Blob(template_data)

    thumb.resize(height=125)
    thumb = thumb.execute_transforms(quality=75,output_encoding=JPEG)

    t = Template(uid=generate_uuid(16),
                 name=name,
                 img=t_img,
                 thumb=db.Blob(thumb),
                 real_width=width,
                 real_height=height)
    t.put()
Exemplo n.º 4
0
def register(tokens, sender_number):
    """
    Complete user registration.
    Expected msg format: 'register [new pin] [new pin]'
    """
    messages = []
    
    new_pin = tokens[1]
    new_pin_confirm = tokens[2]
    
    if new_pin != new_pin_confirm:
        msg = "the pins entered are not the same. please try again"
        sms = OutgoingMessage(body=msg, receiver=sender_number,
                              timestamp=time.time())
        messages.append(sms)
        return send_sms(messages)
    
    try:
        user = User.objects.get(phone=sender_number)
        user.pin_salt = util.generate_uuid()
        user.pin = hashlib.md5(new_pin + user.pin_salt).hexdigest()
        user.save()
        
        msg = ("Your registration has been completed. Send '[balance] [pin]' to"
               " check your available balance.")
        sms = OutgoingMessage(body=msg, receiver=user.phone,
                              timestamp=time.time(), type='complete_reg')
        messages.append(sms)
        return send_sms(messages)
    
    except User.DoesNotExist:
        return msg_user_does_not_exist(sender_number)
Exemplo n.º 5
0
    def __init__(self,uuid=None):
        '''
        @param {_CommitManager} commit_manager --- When we either want
        to commit or backout the changes that the invalidation
        listener makes to its objs_touched, do so through _CommitManager

        @param {uuid} uuid --- If uuid is None, generates a new uuid.
        Otherwise, uses old one.
        '''


        # keeps track of all objects that were read/written to during
        # the course of this event.  we distinguish two types of
        # objects during the course of completing a commit.  The first
        # is a priority object.  We will run complete commit on all of
        # these before running complete commit on the lower priority
        # objects.  The reason for distinguishing objects into high
        # and low priority tiers is that some objects may wrap
        # additional data.  For instance, a folder map object may wrap
        # many files.  At commit time, we want to serialize the
        # changes to a variable so that can replay those changes on
        # the file system.  However, for this to work, we need to
        # ensure that the folder object is complete_commit-ed before
        # any of the subfiles are.
        self.priority_touched_objs = {}        
        self.objs_touched = {}

        self.peered_modified = False
        if uuid == None:
            uuid = util.generate_uuid()
        self.uuid = uuid
Exemplo n.º 6
0
def user_sd(phone_number_sd, user_1):
    u = User(
        uuid=generate_uuid(),
        email='sd@sd',
        email_confirmed=True,
        username='******',
        name='sdsd',
        dob='1/1/1991',
        password_hash=generate_password_hash('pass'),
        secondary_password_hash=generate_password_hash('1234'),
        is_suspended=False,
        referring_user_id=user_1.id,
        phone_id=phone_number_sd.id,
        bank_name='sdbonk',
        bank_account_number='654-321',
        bank_account_holder='sd',
        balance=1000000,
        pending_commissions=0,
        payable_commissions=0,
        created_at=datetime(2000, 1, 1, 0, 5, 10),
        role=UserRole.SOLE_DISTRIBUTOR,
    )
    db.session.add(user_sd)
    db.session.commit()
    yield user_sd
Exemplo n.º 7
0
def cashout(tokens, sender_number):
    """
    Generate cashout ticket
    Expected Format: 'cashout [amount] [pin]'
    """
    messages = []
    try:
        amount = float(tokens[1])
        pin = tokens[2]
        
        user = User.objects.get(phone=sender_number)
        if not account_activated(user):
            return msg_account_not_activated(user.phone)
        
        if not validate_pin(user, pin):
            return msg_invalid_pin(user.phone)
        
        # check account balance
        if amount > (user.balance - 100):
            msg = ("You do not have enough balance to cashout.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), 
                                  type='insufficient_balance')
            messages.append(sms)
            return send_sms(messages)
        
        if amount > 3000:
            msg = ("You cannot cashout above NGN3,000 in one transaction."
                   " Please try again.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), type='excess_cashout')
            messages.append(sms)
            return send_sms(messages)
        
        transaction = Transaction(
            id=util.generate_uuid()[0:12], sender=user.phone, 
                receiver=user.phone, timestamp=time.time(), amount=amount,
                type='user_cashout')
        
        # return message to confirm transaction
        msg = ("transaction-id: %s, amount: %s, type: cashout. Please"
               " reply this message with 'confirm' to confirm this"
               " transaction." % (transaction.id, transaction.amount))
        sms = OutgoingMessage(body=msg, receiver=sender_number,
                              timestamp=time.time(), meta=transaction,
                              type='confirm_transaction')
        messages.append(sms)
        return send_sms(messages)
        
    except User.DoesNotExist:
        return msg_user_does_not_exist(sender_number)
    
    except IndexError:
        expected_format = ("Unkown message format. Expected message format:"
                           " 'cashout [amount] [pin]'")
        return  msg_unknown_format(expected_format, sender_number)
    return None
Exemplo n.º 8
0
    def __init__(self,waldo_classes,host_uuid,conn_obj,global_var_store):
        '''
        @param {dict} waldo_classes --- Contains common utilities
        needed by emitted code, such as WaldoNumVariable
        
        @param {uuid} host_uuid --- The uuid of the host this endpoint
        lives on.
        
        @param {ConnectionObject} conn_obj --- Used to write messages
        to partner endpoint.

        @param {_VariableStore} global_var_store --- Contains the
        peered and endpoint global data for this endpoint.  Will not
        add or remove any peered or endpoint global variables.  Will
        only make calls on them.
        '''
        self._uuid = util.generate_uuid()

        self._endpoint_uuid_str = str(self._uuid)
        
        self._waldo_classes = waldo_classes
        
        self._act_event_map = waldoActiveEventMap._ActiveEventMap(self)
        self._conn_obj = conn_obj
        
        # whenever we create a new _ExecutingEvent, we point it at
        # this variable store so that it knows where it can retrieve
        # variables.
        self._global_var_store = global_var_store

        self._endpoint_service_thread = waldoEndpointServiceThread._EndpointServiceThread(self)
        self._endpoint_service_thread.start()

        self._host_uuid = host_uuid

        self._signal_queue = Queue.Queue()
        
        # When go through first phase of commit, may need to forward
        # partner's endpoint uuid back to the root, so the endpoint
        # needs to keep track of its partner's uuid.  FIXME: right
        # now, manually setting partner uuids in connection object.
        # And not checking to ensure that the partner endpoint is set
        # before doing additional work. should create a proper
        # handshake instead.
        self._partner_uuid = None

        
        # both sides should run their onCreate methods to entirety
        # before we can execute any additional calls.
        self._ready_lock_ = threading.Lock()
        self._this_side_ready_bool = False
        self._other_side_ready_bool = False

        self._ready_waiting_list_mutex = threading.Lock()
        self._ready_waiting_list = []

        self._conn_obj.register_endpoint(self)
Exemplo n.º 9
0
def run_test():
    start = time.time()
    for i in range(0,NUM_ITERATIONS):
        # u = buuid.uuid4()
        u = util.generate_uuid()

    elapsed = time.time() - start
    print '\n\n'
    print elapsed
    print '\n\n'        
Exemplo n.º 10
0
def run_test():
    start = time.time()
    for i in range(0, NUM_ITERATIONS):
        # u = buuid.uuid4()
        u = util.generate_uuid()

    elapsed = time.time() - start
    print '\n\n'
    print elapsed
    print '\n\n'
Exemplo n.º 11
0
def add_user():
    """
    添加用户
    :return:
    """
    user_uid = generate_uuid('user')
    print(111111111111111)
    kv = request.get_json(force=True)
    print(kv)
    kv['user_uid'] = user_uid
    ticket.add_user(**kv)
Exemplo n.º 12
0
 def __init__(self,host_uuid,peered,init_val,version_obj):
     '''
     @param {bool} peered --- True if this variable is a piece of
     sequence local data.  False if it's just a regular-old local
     variable.
     '''
     self.host_uuid = host_uuid
     self.uuid = util.generate_uuid()
     self.val = init_val
     self.version_obj = version_obj        
     self.peered = peered
Exemplo n.º 13
0
    def simulate(self, max_turns=None, verbose=False):
        '''
        Simulate a dialogue.
        '''
        self.events = []
        self.max_turns = max_turns
        time = 0
        num_turns = 0
        game_over = False
        self.describe_scenario()
        if random.random() < 0.5:
            first_speaker = 0
        else:
            first_speaker = 1
        while not game_over:
            for agent, session in enumerate(self.sessions):
                if num_turns == 0 and agent != first_speaker:
                    continue
                event = session.send()
                time += 1
                if not event:
                    continue

                event.time = time
                self.event_callback(event)
                self.events.append(event)

                if verbose:
                    print('agent=%s: session=%s, event=%s' %
                          (agent, type(session).__name__, event.to_dict()))
                else:
                    action = event.action
                    data = event.data
                    event_output = data if action == 'message' else "Action: {0}, Data: {1}".format(
                        action, data)
                    print('agent=%s, event=%s' % (agent, event_output))
                num_turns += 1
                if self.game_over() or (max_turns and num_turns >= max_turns):
                    game_over = True
                    break

                for partner, other_session in enumerate(self.sessions):
                    if agent != partner:
                        other_session.receive(event)

        uuid = generate_uuid('E')
        outcome = self.get_outcome()
        if verbose:
            print('outcome: %s' % outcome)
            print('----------------')
        # TODO: add configurable names to systems and sessions
        agent_names = {'0': self.session_names[0], '1': self.session_names[1]}
        return Example(self.scenario, uuid, self.events, outcome, uuid,
                       agent_names)
Exemplo n.º 14
0
def add_subway_line(subway_line_name):
    if line_exist(subway_line_name, "name"):
        raise STPHTTPException("subway line %s has been exist." %
                               subway_line_name,
                               403,
                               10200)

    uuid = util.generate_uuid(uuid_type="upper")
    db.line.add_subway_line(uuid, subway_line_name)

    new_line = compute.line.Line(uuid=uuid, name=subway_line_name)
    compute.line.lines[subway_line_name] = new_line
    return
Exemplo n.º 15
0
 def update_model(self, form, model):
     form_data = form.data
     try:
         original_model_json = model.to_json()
         # referring_user can't be in the column_editable_list because it's not supported for inline edits.
         for editable_column in self.column_editable_list + ['referring_user', 'username']:
             if editable_column in form_data:
                 setattr(model, editable_column, form_data[editable_column])
         if form.role.data != UserRole.FRANCHISEE.value:
             assert model.owned_promotion is None and form_data['owned_promotion'] is None
         # TODO: check to make sure a promotion isn't being taken away from another user
         if form.password.data != '':  # reset password if new password entered
             assert isinstance(form.password.data, str), form.password.data
             model.uuid = generate_uuid()  # log the user out of all existing sessions
             model.password_hash = generate_password_hash(form.password.data)
             logger.info(f'User update by admin {auth_get_current_username()} was a password reset for {model}')
         if form.secondary_password.data != '':  # reset secondary password if new secondary password entered
             assert isinstance(form.secondary_password.data, str), form.secondary_password.data
             model.uuid = generate_uuid()  # log the user out of all existing sessions
             model.secondary_password_hash = generate_password_hash(form.secondary_password.data)
             logger.info(f'User update by admin {auth_get_current_username()} was a secondary password reset for {model}')
         if form.is_suspended.data != model.is_suspended:  # user suspended or unsuspended
             assert isinstance(form.is_suspended.data, bool), form.is_suspended.data
             model.uuid = generate_uuid()  # log the user out of all existing sessions
         if form.owned_promotion.data:
             model.owned_promotion_id = form.owned_promotion.data.id
         model.assert_hierarchy()
         self.session.add(model)
         self.session.commit()
         caching.set_user(model)
         logger.info(f'User updated by admin {auth_get_current_username()}: {original_model_json} -> {model.to_json()}')
     except Exception as ex:
         self.session.rollback()
         flash(f'Failed to update user. {str(ex)}', 'error')
         logger.exception(f'User update by admin {auth_get_current_username()} raised exception')
         return False
     return True
Exemplo n.º 16
0
    def __init__(self,uuid=None):
        '''
        @param {_CommitManager} commit_manager --- When we either want
        to commit or backout the changes that the invalidation
        listener makes to its objs_touched, do so through _CommitManager

        @param {uuid} uuid --- If uuid is None, generates a new uuid.
        Otherwise, uses old one.
        '''        
        self.objs_touched = {}

        self.peered_modified = False
        if uuid == None:
            uuid = util.generate_uuid()
        self.uuid = uuid
Exemplo n.º 17
0
    def __init__(
        self,host_uuid,peered,init_val,version_obj,
        dirty_element_constructor):

        self.host_uuid = host_uuid
        self.uuid = util.generate_uuid()
        self.version_obj = version_obj
        self.peered = peered
        
        self.val = init_val
        self.dirty_element_constructor = dirty_element_constructor

        self.notification_map = waldoNotificationMap._NotificationMap(
            self.uuid,self.host_uuid)
        
        # keys are uuids.  values are dirty values of each object.
        self._dirty_map = {}
        self._mutex = threading.Lock()
Exemplo n.º 18
0
def change_pin(tokens, sender_number):
    """
    Change user pin number
    Expected message format: 'change pin [old pin] [new pin] [new pin]'
    """
    messages = []
    try:
        old_pin = tokens[2]
        new_pin = tokens[3]
        new_pin_confirm = tokens[4]
        user = User.objects.get(phone=sender_number)
        
        
        if not account_activated(user):
            return msg_account_not_activated(user.phone)
        
        if not validate_pin(user, old_pin):
            return msg_invalid_pin(user.phone)
        
        if new_pin != new_pin_confirm:
            msg = ("The pin entered are not the same. please try again."
                   " Format: 'change pin [old pin] [new pin] [new pin]'")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time())
            messages.append(sms)
            return send_sms(messages)
        
        user.pin_salt = util.generate_uuid()
        user.pin = hashlib.md5(new_pin + user.pin_salt).hexdigest()
        user.save()
        
        msg = ("Your pin has been successfully changed.")
        sms = OutgoingMessage(body=msg, receiver=sender_number,
                              timestamp=time.time(), type='change_pin')
        messages.append(sms)
        return send_sms(messages)
        
    except User.DoesNotExist:
        return msg_user_does_not_exist(sender_number)
    
    except IndexError:
        expected_format = ("Unknow message format. Expected format. 'change pin" 
                           "[old pin] [new pin] [new pin]'")
        return msg_unknown_format(expected_format, sender_number)
Exemplo n.º 19
0
def init_user():
    engine, cursor = db.engine.get_engine()
    sql = """
        create table if not exists user(
        uuid        char(27) not null,
        email       varchar(30),
        username    varchar(24) default "subway user",
        password    varchar(18) not null,
        token       char(10) not null,
        user_type   enum("admin", "user") not null default "user",
        create_time datetime not null,
        status      enum("active", "down", "lock") not null default "active",
        image       varchar(100),
        primary key(email)
        ) charset utf8
        """
    cursor.execute(sql)
    logger.info("Setup user finished.")

    # add admin user
    conf_path = util.get_root_path() + "/conf/platform.conf"
    deploy_conf = ConfigParser()
    deploy_conf.read([conf_path])
    uuid = util.generate_uuid()
    admin_user = deploy_conf.get("deploy", "admin_user")
    admin_pwd = deploy_conf.get("deploy", "admin_pwd")
    email = deploy_conf.get("deploy", "admin_email")
    image = "/root/image/localhost/default.jpeg"
    try:
        get_user_detail(email)
    except DBError:
        now = util.get_time_string_format()
        token = util.general_token()
        user_type = "admin"
        sql = "insert into user " \
              "values(%s, %s, %s, %s, %s, %s, %s, default, %s)"
        val = (uuid, email, admin_user, admin_pwd, token, user_type, now,
               image)
        cursor.execute(sql, val)
        logger.info("Init default admin user success.")
    engine.commit()
    engine.close()
    return
Exemplo n.º 20
0
    def add_entry(self, data_entry): 
        #import pdb; pdb.set_trace()
        date = datetime.date.fromtimestamp(eval(data_entry['time_in']))
        query = {'camera_id' : data_entry['camera_id'],
                 'date_in'   : str(date),
                 'item_name' : data_entry['item_name']}
        same_entry = entriesdb.find_entry(query)

        document = query

        if same_entry == None:
            print document
            document['count'] = data_entry['count'] if data_entry.has_key('count')  else 1
            document['id'] = util.generate_uuid()
            document['time_in'] = data_entry['time_in']
            entriesdb.insert_entry(document)
        else:
            same_entry['count'] += data_entry['count'] if data_entry.has_key('count') else 1
            entriesdb.update_entry({'id' : same_entry['id']}, same_entry)
Exemplo n.º 21
0
    def simulate(self, max_turns=100):
        '''Simulate the dialogue.'''
        self.events = []
        time = 0
        self.selections = [None, None]
        self.reward = 0
        num_turns = 0
        timeup = False
        while True:
            for agent, session in enumerate(self.sessions):
                event = session.send()
                time += 1
                if not event:
                    continue
                event.time = time
                self.events.append(event)

                if event.action == 'select':
                    self.selections[agent] = event.data

                print 'agent=%s: session=%s, event=%s' % (
                    agent, type(session).__name__, event.to_dict())
                num_turns += 1
                if num_turns >= max_turns:
                    timeup = True
                for partner, other_session in enumerate(self.sessions):
                    if agent != partner:
                        other_session.receive(event)

                # Game is over when the two selections are the same
                if self.game_over():
                    self.reward = 1
                    break
            if self.game_over() or timeup:
                break

        uuid = generate_uuid('E')
        outcome = {'reward': self.reward}
        print 'outcome: %s' % outcome
        return Example(self.scenario, uuid, self.events, outcome, uuid, None)
Exemplo n.º 22
0
 def create_model(self, form):
     form_data = form.data
     try:
         if form.password.data == '':
             raise Exception('Password cannot be empty')
         if form.secondary_password.data == '':
             raise Exception('Secondary password cannot be empty')
         if not isinstance(form.phone.data, PhoneNumber):
             raise Exception('Phone field must be a PhoneNumber object')
         model = User(
             uuid=generate_uuid(),
             username=form.username.data,
             phone_id=form.phone.data.id,
             password_hash=generate_password_hash(form.password.data),
             email_confirmed=True,
             agree_receive_email=True,
             agree_receive_text=True,
             pending_commissions=0,
             payable_commissions=0,
             secondary_password_hash=generate_password_hash(form.secondary_password.data),
             referring_user_id=form.referring_user.data.id if form.referring_user.data else None,
             owned_promotion_id=form.owned_promotion.data.id if form.owned_promotion.data else None,
         )
         for editable_column in self.column_editable_list:
             if editable_column in form_data:
                 setattr(model, editable_column, form_data[editable_column])
         # auto confirm email for partners
         if model.role != UserRole.REGULAR_USER.value:
             model.email_confirmed = True
         model.assert_hierarchy()
         self.session.add(model)
         self.session.commit()
         caching.set_user(model)
         logger.info(f'User create by admin {auth_get_current_username()}: {model.to_json()}')
     except Exception as ex:
         self.session.rollback()
         flash(f'Failed to create user. {str(ex)}', 'error')
         logger.exception(f'User create by admin {auth_get_current_username()} raised exception')
         return False
     return True
Exemplo n.º 23
0
 def __init__(self):
     self._mutex = threading.Lock()
     self._uuid = util.generate_uuid()
     self._stopped = False
Exemplo n.º 24
0
    ]
    issue_jrds_trace(16000, u_activity_id, 0, cloud_trace_format)


def issue_jrds_trace(event_id, activity_id, log_type, arg_array):
    jrds_client.set_log(event_id, activity_id, log_type, map(str, arg_array))


def dict_to_str(input_dict):
    output_str = ""
    for key, value in input_dict.iteritems():
        output_str = output_str + "[" + str(key) + "=" + str(value) + "]"
    return output_str


u_activity_id = util.generate_uuid()

COMPONENT_SANDBOX = "Sandbox"
COMPONENT_WORKER = "Worker"

KEYWORD_DEBUG = "Debug"
KEYWORD_INFO = "Info"
KEYWORD_ERROR = "Error"
KEYWORD_WARNING = "Warning"
KEYWORD_STARTUP = "Startup"
KEYWORD_ROUTINE = "Routine"
KEYWORD_JOB = "Job"
KEYWORD_RUNTIME = "Runtime"
KEYWORD_CONFIGURATION = "Configuration"
KEYWORD_TELEMETRY = "Telemetry"
Exemplo n.º 25
0
                          message]
    issue_jrds_trace(16000, activity_id, 0, cloud_trace_format)


def issue_jrds_trace(event_id, activity_id, log_type, arg_array):
    jrds_client.set_log(event_id, activity_id, log_type, map(str, arg_array))


def dict_to_str(input_dict):
    output_str = ""
    for key, value in input_dict.iteritems():
        output_str = output_str + "[" + str(key) + "=" + str(value) + "]"
    return output_str


u_activity_id = util.generate_uuid()

COMPONENT_SANDBOX = "Sandbox"
COMPONENT_WORKER = "Worker"

KEYWORD_DEBUG = "Debug"
KEYWORD_INFO = "Info"
KEYWORD_ERROR = "Error"
KEYWORD_WARNING = "Warning"
KEYWORD_STARTUP = "Startup"
KEYWORD_ROUTINE = "Routine"
KEYWORD_JOB = "Job"
KEYWORD_RUNTIME = "Runtime"
KEYWORD_RUNBOOK = "Runbook"
KEYWORD_CONFIGURATION = "Configuration"
KEYWORD_TELEMETRY = "Telemetry"
Exemplo n.º 26
0
import util
import waldoConnectionObj
from util import Queue
import wVariables
import waldoCallResults
import waldoEndpoint
import waldoExecutingEvent
import waldoVariableStore
import shim.get_math_endpoint
import waldoReferenceBase

StoppedException = util.StoppedException


_host_uuid = util.generate_uuid()
_threadsafe_stoppable_cleanup_queue = Queue.Queue()

_waldo_classes = {
    # waldo variables
    'WaldoNumVariable': wVariables.WaldoNumVariable,
    'WaldoTextVariable': wVariables.WaldoTextVariable,
    'WaldoTrueFalseVariable': wVariables.WaldoTrueFalseVariable,
    'WaldoMapVariable': wVariables.WaldoMapVariable,
    'WaldoListVariable': wVariables.WaldoListVariable,
    'WaldoUserStructVariable': wVariables.WaldoUserStructVariable,
    'WaldoFunctionVariable': wVariables.WaldoFunctionVariable,
    
    'WaldoEndpointVariable': wVariables.WaldoEndpointVariable,
    'WaldoExtNumVariable': wVariables.WaldoExtNumVariable,
    'WaldoExtTrueFalseVariable': wVariables.WaldoExtTrueFalseVariable,
Exemplo n.º 27
0
def transfer_funds(tokens, sender_number):
    """
    Transfer funds to user or non-user
    Expected format: 'transfer [amount] [receiver] [pin]'
    
    transaction limit: NGN3,000
    daily transaction limit: NGN30,000
    """
    messages = []
    try:
        amount = float(tokens[1])
        receiver_number = tokens[2]
        pin = tokens[3]
        
        user = User.objects.get(phone=sender_number)
        if not validate_pin(user, pin):
            return msg_invalid_pin(user.phone)
        
        if not account_activated(user):
            return msg_account_not_activated(user.phone)
        
        # check account balance
        if amount > (user.balance - 100):
            msg = ("You do not have enough balance to make this transfer.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), 
                                  type='insufficient_balance')
            messages.append(sms)
            return send_sms(messages)
        
        if amount > 3000:
            msg = ("You cannot transfer above NGN3,000 in one transaction."
                   " Please try again.")
            sms = OutgoingMessage(body=msg, receiver=sender_number,
                                  timestamp=time.time(), type='excess_transfer')
            messages.append(sms)
            return send_sms(messages)
        
        # add restriction of daily limit of 3ok
        
        # validate receiver exists
        #     if not generate cash out ticket instead
        transaction = Transaction(
            id=util.generate_uuid()[0:12], sender=user.phone, 
            receiver=receiver_number, timestamp=time.time(), amount=amount)
        try:
            User.objects.get(phone=receiver_number)
            transaction.type = 'user_to_user_transfer'
        except User.DoesNotExist:
            transaction.type = 'user_to_guest_transfer'
            
        transaction.save()
        
        # return message to confirm transaction
        msg = ("transaction-id: %s, amount: %s, receiver: %s. Please"
               " reply this message with 'confirm' to confirm this"
               " transaction." 
               % (transaction.id, transaction.amount, transaction.receiver))
        sms = OutgoingMessage(body=msg, receiver=sender_number,
                              timestamp=time.time(), meta=transaction,
                              type='confirm_transaction')
        messages.append(sms)
        return send_sms(messages)
        
    except User.DoesNotExist:
        return msg_user_does_not_exist(sender_number)
    
    except IndexError:
        expected_format = ("Unknown message format. Expeted format: transfer"
                           " [amount] [receiver] [pin]. Please try again.")
        return msg_unknown_format(expected_format, sender_number)
Exemplo n.º 28
0
def confirm_transaction(transaction):
    messages = []
    if transaction.type == 'user_to_user_transfer':
        receiver = User.objects.get(phone=transaction.receiver)
        sender = User.objects.get(phone=transaction.sender)
        
        receiver.balance = receiver.balance + transaction.amount
        sender.balance = sender.balance - transaction.amount
        
        transaction.status = 'complete'
        receiver.save()
        sender.save()
        transaction.save()
        
        # send confirmation to both parties
        # receiver's notification
        msg = ("NGN%s has been successfully transferred from the account "
               " of %s to you. Your new balance is NGN%s. Thank you for using Mopay."
               % (transaction.amount, transaction.sender, receiver.balance))
        sms = OutgoingMessage(body=msg, receiver=transaction.receiver,
                              timestamp=time.time(), 
                              type='transfer_notif_receiver_completed')
        messages.append(sms)
        
        # sender's notification
        msg = ("You have successfully transferred NGN%s to %s. Your new" 
               " balance is NGN%s. Thank you for using Mopay." 
               % (transaction.amount, transaction.receiver, sender.balance))
        sms = OutgoingMessage(body=msg, receiver=transaction.sender, 
                              timestamp=time.time(),
                              type='transfer_notif_sender_completed')
        messages.append(sms)
        return send_sms(messages)
    
    elif transaction.type == 'user_to_guest_transfer':
        sender = User.objects.get(phone=transaction.sender)
        sender.balance = sender.balance - transaction.amount
        
        cashout_ticket = CashoutTicket(
            id=util.generate_uuid()[0:15],sender=sender.phone,
            receiver=transaction.receiver,transaction=transaction,
            timestamp=time.time())
        
        cashout_ticket.save()
        
        transaction.status = 'generated_guest_cashout'
        sender.save()
        transaction.save()
        
        # send notifications
        # receiver's notification.
        msg = ("NGN%s has been sent to you from the account of %s via mopay."
               " Ticket-ID: %s. Please go to the nearest mopay agent to"
               " retrieve." 
               % (transaction.amount, transaction.sender, cashout_ticket.id))
        sms = OutgoingMessage(body=msg, receiver=transaction.receiver,
                              timestamp=time.time(),
                              type='notif_receiver_transfer_cashout')
        messages.append(sms)
        
        # sender's notificationDoesNotExist
        msg = ("You have sent NGN%s to %s. Thank you for using mopay."
               % (transaction.amount, transaction.receiver))
        sms = OutgoingMessage(body=msg, receiver=transaction.sender,
                              timestamp=time.time(),
                              type='notif_sender_cashout_gen')
        messages.append(sms)
        return send_sms(messages)
    
    elif transaction.type == 'user_cashout':
        sender = User.objects.get(phone=transaction.sender)
        sender.balance = sender.balance - transaction.amount
        
        cashout_ticket = CashoutTicket(
            id=util.generate_uuid()[0:15],sender=sender.phone,
            receiver=transaction.receiver,transaction=transaction,
            timestamp=time.time())
        
        cashout_ticket.save()
        transaction.status = 'cashout_ticket_generated'
        sender.save()
        transaction.save()
        
        msg = ("NGN%s been deducted from your account for a cashout ticket."
               " Ticket-ID: %s. Please go to the nearest mopay agent to"
               " retrieve." % (transaction.amount, cashout_ticket.id))
        sms = OutgoingMessage(body=msg, receiver=transaction.receiver,
                              timestamp=time.time(),
                              type='notif_receiver_transfer_cashout')
        messages.append(sms)
        return send_sms(messages)