예제 #1
0
파일: BaseComp.py 프로젝트: sridwan/meong
 def buildSubTopupSucess(self, param):
     '''Build substitution dictionary for a
        "transaction_successful" message.
        Needed parameters:
             - agent_id
             - reg_protocol
             - product_id
             - order
             - msisdn_destination
             - references
             - deposit
             - sell_price
     '''
     if not isinstance(param, dict):
         return False
     to_sub = {}
     to_sub['product_id'] = self.productIdAndOrder(param['product_id'],
                                                   param['order'])
     to_sub['dest'] = param['msisdn_destination']
     to_sub['ref'] = param['references']
     to_sub['balance'] = thousandSeparator(param['deposit'])
     to_sub['price'] = thousandSeparator(param.get('sell_price', 0))
     to_sub['agent_id'] = param.get('agent_id', '')
     to_sub['name'] = self.am.getAgentData(param['agent_id'])['agent_name']
     to_sub['unit'] = param['product_id']
     return to_sub
예제 #2
0
파일: Sync.py 프로젝트: sridwan/meong
 def _tukarPoin(self, p, ag):
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute('''SELECT SQL_NO_CACHE `point_balance` FROM `point_mutation`
                  WHERE `agent_id`=%s ORDER BY `point_mutation_id` DESC
                 LIMIT 1 FOR UPDATE''', (ag['agent_id'],))
     tmp = c.fetchone()
     if not tmp:
         self.writeNotifyOut(p['protocol'], 'insufficient_point', {
                 'point': 0,
             })
         return
     bal = int(tmp['point_balance']) 
     if  bal < 2000:
         self.writeNotifyOut(p['protocol'], 'insufficient_point', {
                 'point': thousandSeparator(bal),
             })
         return
     sql = '''INSERT INTO `point_mutation` (`timestamp`,`agent_id`,
              `mutation`,`type`,`point_balance`,`comment`) VALUES
              (%s,%s,%s,"D",%s,%s)'''
     c.execute(sql, (datetime.now(), ag['agent_id'], bal, 0, '_tukarPoin'))
     old_bal = self.dm.getBalance(ag['agent_id'])
     new_bal = self.dm.credit(ag['agent_id'], bal*10, '_tukarPoin')
     self.writeNotifyOut(p['protocol'], 'tukar_poin', {
             'point': thousandSeparator(bal),
             'saldo': thousandSeparator(bal*10),
             'before': thousandSeparator(old_bal),
             'after': thousandSeparator(new_bal),
         })
     print '{id}-{name} tukarPoin {poin}, saldo awal={awal}, '\
           'saldo akhir={akhir}'.\
           format(id=ag['agent_id'], name=ag['agent_name'], poin=bal,
                  awal=old_bal, akhir=new_bal)
예제 #3
0
파일: Sync.py 프로젝트: sridwan/meong
 def _tukarBonus(self, p, ag):
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     # c.execute('LOCK TABLES `bonus_mutation` LOW_PRIORITY WRITE')
     c.execute('''SELECT SQL_NO_CACHE `bonus_balance` FROM `bonus_mutation`
                 WHERE `agent_id`=%s ORDER BY `bonus_mutation_id` DESC
                 LIMIT 1 FOR UPDATE''', (ag['agent_id'],))
     tmp = c.fetchone()
     if not tmp:
         self.writeNotifyOut(p['protocol'], 'no_bonus', {})
         return
     bal = int(tmp['bonus_balance']) 
     if  bal == 0:
         self.writeNotifyOut(p['protocol'], 'no_bonus', {})
         return
     sql = '''INSERT INTO `bonus_mutation` (`timestamp`,`agent_id`,
              `mutation`,`type`,`bonus_balance`,`comment`) VALUES
              (%s,%s,%s,"D",%s,%s)'''
     c.execute(sql, (datetime.now(), ag['agent_id'],
               bal, 0, '_tukarBonus'))
     old_bal = self.dm.getBalance(ag['agent_id'])
     new_bal = self.dm.credit(ag['agent_id'], bal, '_tukarBonus')
     # self.dbconn.commit()
     # c.execute('''UNLOCK TABLES''')
     self.writeNotifyOut(p['protocol'], 'tukar_bonus', {
             'bonus': thousandSeparator(bal),
             'before': thousandSeparator(old_bal),
             'after': thousandSeparator(new_bal),
         })
     print '{id}-{name} tukarBonus {bonus}, saldo awal={awal}, '\
           'saldo akhir={akhir}'.\
           format(id=ag['agent_id'], name=ag['agent_name'], bonus=bal,
                  awal=old_bal, akhir=new_bal)
예제 #4
0
파일: Sync.py 프로젝트: sridwan/meong
 def _ticket(self, p, ag):
     '''Request deposit ticket'''
     sql = '''SELECT * FROM `ticket` WHERE `status`=0 AND `agent_id`=%s'''
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute(sql, (ag['agent_id'], ))
     r = c.fetchone()
     if r:
         self.writeNotifyOut(p['protocol'], 'ticket_exist',
                             {
                                 'agent_id': ag['agent_id'],
                                 'name': ag['agent_name'],
                                 'ticket': thousandSeparator(int(r['given_amount'])),
                                 'datetime': r['request_dt'].strftime('%d-%m-%y %H:%M')
                             })
         return
     try:
         amount = int(p['amount'])
         if amount < 0:
             raise Exception('Negative number')
     except:
         amount = 0
     if amount == 0:
         self.writeNotifyOut(p['protocol'], 'amount_not_number',
                             {'amount': p['amount']})
         return
     x = datetime.now()
     if x.hour >= 21:
         self.writeNotifyOut(p['protocol'], 'bank_closed', {})
         return
     salt = 'oimh5oi4yrp,i[jmcvnty98pqmucr'
     reqtime = datetime.now()
     seed = '{0}{1}{2}{3}'.format(salt, reqtime.strftime('%Y%m%d%H%M%S'),
                                  ag['agent_id'], amount)
     x = int(hashlib.md5(seed).hexdigest()[-4:], 16) % 1000
     if x == 0:
         x = 1
     g_amount = amount + x
     sql = '''SELECT * FROM `ticket` WHERE `status`=0 AND `given_amount`=%s'''
     while True:
         c.execute(sql, (g_amount,))
         if c.fetchone():
             g_amount += 1
         else:
             break
     sql = '''INSERT INTO `ticket` (`request_dt`,`checked_dt`,`agent_id`,
              `request_amount`,`given_amount`,`status`) VALUES (%s,%s,%s,%s,%s,0)'''
     c.execute(sql, (reqtime, reqtime, ag['agent_id'], amount, g_amount))
     self.writeNotifyOut(p['protocol'], 'ticket_registered',
                         {
                             'agent_id': ag['agent_id'],
                             'name': ag['agent_name'],
                             'ticket': thousandSeparator(g_amount),
                         })
     print '{0}-{1} Tiket Rp {2}'.\
           format(ag['agent_id'], ag['agent_name'],
                  thousandSeparator(g_amount))
예제 #5
0
파일: admin.py 프로젝트: sridwan/meong
 def depmut_execute(self, agent_id, type, amount, comment, pin):
     result = {
       'success': 0,
       'balance': 0,
     }
     try:
         int(amount)
     except:
         result['message'] = 'AMOUNT NOT VALID'
         return json.dumps(result)
     # agent must exist
     bc = AgentNotifier()
     c_agent = DBCache(const.AGENT_PREFIX, config.DEFAULT_EXPIRE,
                       const.AGENT_SQL)
     c_agent.setConn(bc.dbconn, bc.cacheconn)
     #print c_agent.sGet(agentid)
     ag = c_agent.sGet(agent_id)
     if not ag:
         result['message'] = 'AGENT NOT REGISTERED'
         return json.dumps(result)
     dm = DepositMutation(20, bc.dbconn, bc.cacheconn)
     prev_bal = dm.getBalance(agent_id)
     if type.upper() == 'C':
         balance = dm.credit(agent_id, int(amount), comment)
         bc.writeNotifyOut(ag['default_protocol'], 'deposit_credit', {
                 'mutation': thousandSeparator(amount),
                 'balance_before': thousandSeparator(prev_bal),
                 'balance': thousandSeparator(balance),
             })
     elif type.upper() == 'D':
         balance = dm.debit(agent_id, int(amount), comment)
         bc.writeNotifyOut(ag['default_protocol'], 'deposit_debit', {
                 'mutation': thousandSeparator(amount),
                 'balance_before': thousandSeparator(prev_bal),
                 'balance': thousandSeparator(balance),
             })
     else:
         result['message'] = 'TYPE NOT RECOGNIZED'
         return json.dumps(result)
     if balance == NOT_ENOUGH_BALANCE:
         result['message'] = 'NOT ENOUGH BALANCE'
         return json.dumps(result)
     elif balance == LOCK_FAILED:
         result['message'] = 'SERVER BUSY'
         return json.dumps(result)
     bc.dbconn.commit()
     msg = '{0}-{1} Deposit: Rp. {2} Before: Rp. {3} After: Rp. {4} ({5}) ID:{6}'.\
           format(ag['agent_id'], ag['agent_name'], thousandSeparator(amount),
                  thousandSeparator(prev_bal), thousandSeparator(balance),
                  comment, dm.last_id)
     for prot in ('ym://b_martian','ym://inileonard', 'ym://sridwan981'):
         bc.writeNotifyOut(prot, 'general_message', {'message': msg})
     bc.dbconn.commit()
     result.update({
         'success': 1,
         'message': 'SUCCESS',
         'balance': balance,
         'mutation_id': dm.last_id,
     })
     return json.dumps(result)
예제 #6
0
파일: Sync.py 프로젝트: sridwan/meong
 def _checkDeposit(self, p, ag):
     agent_id = ag['agent_id']
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute('''SELECT SQL_NO_CACHE `bonus_balance` from `bonus_mutation`
                  WHERE `agent_id`=%s ORDER BY `bonus_mutation_id` DESC
                  LIMIT 1''', (agent_id,))
     b = c.fetchone()
     if not b:
         bonus = 0
     else:
         bonus = b['bonus_balance']
     c.execute('''SELECT SQL_NO_CACHE `point_balance` from `point_mutation`
                  WHERE `agent_id`=%s ORDER BY `point_mutation_id` DESC
                  LIMIT 1''', (agent_id,))
     b = c.fetchone()
     if not b:
         poin = 0
     else:
         poin = b['point_balance']
     a = datetime.now()
     day_start = datetime(a.year, a.month, a.day, 0, 0, 0)
     day_end = datetime(a.year, a.month, a.day, 23, 59, 59)
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     sql = '''SELECT SQL_NO_CACHE `sell_price` FROM `transaction`
              WHERE `transaction_datetime` >= %s
              AND `transaction_datetime` <= %s AND `agent_id`=%s
              AND `status`>=%s AND `status`<=%s'''
     total = 0
     c.execute(sql, (day_start, day_end, agent_id, const.TR_EXECUTED,
                     const.TR_POINTED))
     for i in c:
         total += int(i['sell_price'])
     c.close()
     balance = thousandSeparator(self.dm.getBalance(agent_id))
     name = ag['agent_name']
     bonus = thousandSeparator(bonus)
     poin = thousandSeparator(poin)
     total = thousandSeparator(total)
     self.writeNotifyOut(p['protocol'], 'deposit_level',
                         {
                             'agent_id': agent_id,
                             'name': name,
                             'deposit': balance,
                             'bonus': bonus,
                             'poin': poin,
                             'total': total,
                         })
     print '{0}-{1} check deposit. bonus={2}, poin={3}, today trx={4}'.\
           format(agent_id, name, bonus, poin, total)
예제 #7
0
파일: admin.py 프로젝트: sridwan/meong
 def bundle(self, name, agent_id, price, pin):
     bc = AgentNotifier()
     c_agent = DBCache(const.AGENT_PREFIX, config.DEFAULT_EXPIRE,
                       const.AGENT_SQL)
     c_agent.setConn(bc.dbconn, bc.cacheconn)
     dm = DepositMutation(20, bc.dbconn, bc.cacheconn)
     ag = c_agent.sGet(agent_id)
     if not ag:
         return json.dumps({'success': 0, 'reason': 'AGENT NOT FOUND'})
     sql = '''SELECT * FROM `bundle` WHERE `bundle_name`=%s'''
     c = bc.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute(sql, (name,))
     cs = c.fetchall()
     if len(cs) == 0:
         return json.dumps({'success': 0, 'reason': 'BUNDLE NOT FOUND'})            
     balance = dm.debit(agent_id, int(price), 'Bundle {0}'.format(name))
     if balance < 0:
         return json.dumps({'success': 0, 'reason': 'NOT ENOUGH DEPOSIT'})
     um = UnitMutation(5, bc.dbconn, bc.cacheconn)
     for r in c:
         um.credit(agent_id, r['product_id'], r['unit'], 0, name)
     msg = 'Add bundle {0} to {1}-{2} Rp {3}'.\
           format(name, agent_id, ag['agent_name'], thousandSeparator(price))
     for prot in ('ym://b_martian','ym://inileonard', 'ym://sridwan981'):
         bc.writeNotifyOut(prot, 'general_message', {'message': msg})
     bc.dbconn.commit()
     return json.dumps({'success': 1, 'reason': ''})            
예제 #8
0
파일: BaseComp.py 프로젝트: sridwan/meong
 def buildSubTopupFail(self, param, precompute):
     '''Build substitution dictionary for a "transaction_fail" message.
        Needed parameters:
             - reg_protocol
             - product_id
             - order
             - msisdn_destination
             - deposit
             - sell_price
             - type
     '''
     if not isinstance(param, dict):
         return False
     to_sub = {}
     to_sub['product_id'] = self.productIdAndOrder(param['product_id'],
                                                   param['order'])
     to_sub['dest'] = param['msisdn_destination']
     to_sub['unit'] = param['product_id']
     if precompute:
         to_sub['balance'] = thousandSeparator(param['deposit'])
     else:
         t = param.get('type', 1)
         if t == 3:
             to_sub['balance'] = int(param['deposit']) + 1
         else:
             to_sub['balance'] = int(param['deposit']) + int(param['sell_price'])
     return to_sub
예제 #9
0
파일: Sync.py 프로젝트: sridwan/meong
 def cekTransferByDate(self, p, ag, dt = None):
     if not dt or not isinstance(dt, datetime):
         dt = datetime.now()
     day_start = datetime(dt.year, dt.month, dt.day, 0, 0, 0)
     day_end = datetime(dt.year, dt.month, dt.day, 23, 59, 59)
     sql = '''SELECT `amount` FROM `deposit_transfer` WHERE `timestamp`>=%s
              AND `timestamp`<=%s AND `agent_id_from`=%s'''
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute(sql, (day_start, day_end, ag['agent_id']))
     transfer_sum = 0
     for i in c:
         transfer_sum += int(i['amount'])
     self.writeNotifyOut(p['protocol'], 'transfer_sum', {
                         'total': thousandSeparator(transfer_sum),
                         'date': dt.strftime('%d-%m-%y')
                     })
     print '{0}-{1} Cek total transfer: Rp {2}'.\
           format(ag['agent_id'], ag['agent_name'],
                  thousandSeparator(transfer_sum))
예제 #10
0
파일: Sync.py 프로젝트: sridwan/meong
 def _checkPrice(self, p, agent_id):
     prod = p['product_id'].upper()
     tmp = self.c_agentprice.get(self.dbconn, self.cacheconn,
         (agent_id, prod))
     if not tmp:
         if prod.isalpha():
             self._checkPriceWildcard(p, agent_id)
             return
         self.writeNotifyOut(p['protocol'], 'prod_not_registered',
             {'product_id': p['product_id']})
         return
     self.writeNotifyOut(p['protocol'], 'product_price',
         {'product_id': prod, 'price': thousandSeparator(tmp['sell_price'])})
예제 #11
0
 def _expired(self, ticket):
     if (ticket['request_dt'] + timedelta(hours=1)) >= datetime.now():
         return False
     sql = '''UPDATE `ticket` SET `status`=2 WHERE `id`=%s'''
     self.execSQL(None, sql, (ticket['id'],))
     c_agent = DBCache(const.AGENT_PREFIX, config.DEFAULT_EXPIRE,
                       const.AGENT_SQL)
     ag = c_agent.get(self.dbconn, self.cacheconn, ticket['agent_id'])
     if not ag:
         return True
     self.writeNotifyOut(ag['default_protocol'], 'ticket_expired', {
                             'agent_id': ag['agent_id'],
                             'name': ag['agent_name'],
                             'ticket': thousandSeparator(ticket['given_amount']),
                             'datetime': ticket['request_dt'].strftime('%d-%m-%y %H:%M'),
                         })
     c_agent = None
     return True
예제 #12
0
파일: Sync.py 프로젝트: sridwan/meong
 def _checkDepositDownline(self, p, agent_id):
     try:
         agent_to = self._mapToAgentID(p['agent_id'])
         result = self.agent.verifyAgent(agent_to, 'xxxx', strict=False)
     except:
         self.writeNotifyOut(p['protocol'], 'agent_not_reg',
                             {'agent_id': p['agent_id']})
         return
     if result['code'] == agent.AGST_NOTFOUND:
         self.writeNotifyOut(p['protocol'], 'agent_not_reg',
                             {'agent_id': p['agent_id']})
         return
     if not self.verifyDownline(agent_id, agent_to):
         self.writeNotifyOut(p['protocol'], 'agent_not_downline',
                             {'agent_id': p['agent_id']})
         return
     balance = thousandSeparator(self.dm.getBalance(agent_to))
     name = self.agent.getAgentData(agent_to)['agent_name']
     self.writeNotifyOut(p['protocol'], 'downline_deposit_level',
         {'agent_id': agent_to, 'name': name, 'deposit': balance})
     print 'Cek deposit downline ({dl_id}-{name}) oleh upline {upline}'.\
             format(dl_id=agent_to, name=name, upline=agent_id)
예제 #13
0
 def productError(self, prot, pcode, agent_id, params):
     if not re.match('^[A-Za-z]+\d+$', pcode):
         self.writeNotifyOut(prot, 'command_invalid', {})
         print 'invalid command by {0}'.format(agent_id)
         return
     dest = params
     print 'params=', params
     if isinstance(params, str):
         dest = params
     elif len(params) == 2:
         dest = params[1]
     elif len(params) == 3:
         dest = '{0}.{1}'.format(params[1], params[2])
     self.writeNotifyOut(prot, 'transaction_fail_msg', {
             'product_id': pcode,
             'dest': dest,
             'message': 'Produk gangguan / Stok tidak tersedia',
             'balance': thousandSeparator(self.dm.getBalance(agent_id)),
         })
     print 'Reject {pcode}.{dest} from {agent_id}, produk ditutup'.\
           format(pcode=pcode, dest=dest, agent_id=agent_id)
     self.log.info('Reject {pcode}.{dest} from {agent_id}, produk ditutup'.\
                   format(pcode=pcode, dest=dest, agent_id=agent_id))
예제 #14
0
파일: Sync.py 프로젝트: sridwan/meong
 def _checkPriceWildcard(self, p, agent_id):
     prod = p['product_id'].upper()
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute('''SELECT `product_id`,`sell_price` FROM `agent_price`
                  WHERE `agent_id`=%s AND `product_id`
                  RLIKE "^{0}[[:digit:]]+"'''.\
                 format(prod), (agent_id,))
     msg = ''
     no_product = True
     for r in c:
         no_product = False
         prod_id, price = r['product_id'], r['sell_price']
         msg = '{msg}{prod}={price}, '.format(msg=msg, prod=prod_id,
                                             price=thousandSeparator(price))
     if no_product:
         self.writeNotifyOut(p['protocol'], 'prod_not_registered',
             {'product_id': p['product_id']})
     else:
         msg = msg[:-2]
         self.writeNotifyOut(p['protocol'], 'general_message',
                             {'message': msg})
         print 'agent {0} _checkPriceWildcard: {1}'.\
               format(agent_id, p['product_id'])
예제 #15
0
 def loadBalance(self):
     sql = """SELECT SQL_NO_CACHE `transaction_id`,`reg_protocol`,`agent_id`,
              `product_id`,`operator_id`,`msisdn_destination`,`sell_price`,
              `order`,`deposit` FROM `transaction`
              WHERE `status`={0} and `method`='CH' LIMIT 100"""
     cursor = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     cursor.execute(sql.format(const.TR_AUTHORIZED))
     rows = cursor.fetchall()
     if len(rows) == 0:
         cursor.close()
         return False
     for tran in rows:
         tr_id = tran["transaction_id"]
         self.last_tr_id = tr_id
         self.last_tr_data = dict(tran)
         dest_num = tran["msisdn_destination"]
         print "Topup id {2}, product {0} untuk nomor {1}".format(
             tran["product_id"], tran["msisdn_destination"], tran["transaction_id"]
         )
         self.log.info(
             "<loadBalance>Topup id {2}, product {0} untuk nomor {1}".format(
                 tran["product_id"], tran["msisdn_destination"], tran["transaction_id"]
             )
         )
         prod = self.c_product.sGet(tran["product_id"])
         if not prod:
             self.log.error(
                 '<loadBalance>Not found row in table "Product" ' "with product_id={0}".format(tran["product_id"])
             )
             continue
         op_id = prod["operator_id"]
         op_type = self.operator[op_id]["type"]
         opprod_list = self._extractOperatorProduct(prod)
         if op_type == "G":  # GSM
             result = self._executeTopupGSM(tr_id, op_id, opprod_list, dest_num)
             self.log.info(
                 "<loadBalance>Operator Product {1}\nTopup GSM {0}\nResult={2}".format(prod, opprod_list, result)
             )
         elif op_type == "C":  # CDMA
             result = self._executeTopupCDMA(tr_id, op_id, opprod_list, dest_num)
             self.log.info(
                 "<loadBalance>Operator Product {1}\nTopup CDMA {0}\nResult={2}".format(prod, opprod_list, result)
             )
         protocol = tran["reg_protocol"]
         if result == ET_SUCCESS:
             self._transactionInProgress(tr_id)
             if protocol[:3].lower() == "sms":
                 continue
             self.writeNotifyOut(
                 protocol, "transaction_in_progress", {"product_id": tran["product_id"], "dest": dest_num}
             )
             continue
         elif result == ET_CHANGE_METHOD:
             self._moveToNextMethod(tr_id, self.change_method)
             continue
         next_method = self._getNextMethod(prod)
         if next_method:
             self._moveToNextMethod(tr_id, next_method)
         elif result == ET_HLR_NOT_SUPPORTED:
             self._transactionResult(tr_id, const.TR_FAILED_HLR)
             self.writeNotifyOut(protocol, "hlr_not_supported", {"dest": dest_num})
         elif result == ET_OUT_OF_STOCK:
             self._transactionResult(tr_id, const.TR_OUT_OF_STOCK)
             agent_bal = int(tran["sell_price"]) + self.dm.getBalance(tran["agent_id"])
             self.writeNotifyOut(
                 protocol,
                 "out_of_stock",
                 {"product_id": tran["product_id"], "balance": thousandSeparator(agent_bal)},
             )
     cursor.close()
     self.dbconn.commit()
     return True
예제 #16
0
파일: Sync.py 프로젝트: sridwan/sd
 def _sd_transfer(self, p, ag, prod='t'):
     try:
         am = int(p['amount'])
     except:
         self.writeNotifyOut(p['protocol'], 'amount_not_number',
                             {'amount': p['amount']})
         return
     min_am = 1
     if prod == 't':
         min_am = 10000
     if am < min_am or am > 100000000:
         self.writeNotifyOut(p['protocol'], 'amount_not_number',
                             {'amount': p['amount']})
         return
     msisdn = sanitizeMSISDN(p['msisdn'])
     if 'order' not in p:
         p['order'] = 1
     sql = '''SELECT `rs`.`msisdn`,`rs`.`status`,`sd`.`device_id` FROM `rs`
              INNER JOIN `sd` ON `sd`.`sd_id` = `rs`.`sd_id`
              WHERE `rs`.`msisdn`=%s'''
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     c.execute(sql, (msisdn,))
     ch = c.fetchone()
     if not ch:
         self.writeNotifyOut(p['protocol'], 'rs_not_registered',
                             {'msisdn': msisdn})
         return
     if int(ch['status']) == 9:
         self.writeNotifyOut(p['protocol'], 'rs_not_registered',
                             {'msisdn': msisdn})
         return
     if int(ch['status']) == 0:
         self.writeNotifyOut(p['protocol'], 'rs_suspended',
                             {'msisdn': msisdn})
         return
     sd_dev = self.c_device.get(self.dbconn, self.cacheconn, ch['device_id'])
     if not sd_dev:
         self.writeNotifyOut(p['protocol'], 'topup_fail', {})
         print 'INVALID DEVICE_ID'
         return
     if prod == 't':
         prod_id = 'S#{0}'.format(thousandSeparator(am))
     else:
         prod_id = '{0}#{1}'.format(prod.upper(), am)
         am = self.price[prod] * am
     if self.checkTrx(p['protocol'], ag['agent_id'], prod_id, p['order'], msisdn):
         return
     cur_bal = self.dm.getBalance(ag['agent_id'])
     if cur_bal < am:
         self.writeNotifyOut(p['protocol'], 'agent_not_enough_balance', 
                             {'product_id': am, 'dest': msisdn, 'balance': cur_bal,})
         return
     new_deposit = self.dm.debit(ag['agent_id'], am,
                                 'transfer ke {0}'.format(msisdn))
     sql = '''INSERT INTO `transaction` (`method`,`agent_id`,`agent_name`,
              `reg_protocol`,`deposit`,`base_price`,`sell_price`,`profit`,
              `product_id`,`operator_product_id`,`hlr_id`,`operator_id`,
              `msisdn_destination`,`order`,`transaction_datetime`,`device_id`,
              `status`) VALUES (%(method)s,%(agent_id)s,%(agent_name)s,
              %(reg_protocol)s,%(deposit)s,%(base_price)s,%(sell_price)s,%(profit)s,
              %(product_id)s,%(operator_product_id)s,%(hlr_id)s,%(operator_id)s,
              %(msisdn_destination)s,%(order)s,%(transaction_datetime)s,%(device_id)s,
              %(status)s)'''
     c.execute(sql, {
             'method': 'CH',
             'agent_id': ag['agent_id'],
             'agent_name': ag['agent_name'],
             'reg_protocol': p['protocol'],
             'deposit': new_deposit,
             'base_price': am,
             'sell_price': am,
             'profit': 0,
             'product_id': prod_id,
             'operator_product_id': prod_id,
             'hlr_id': 0,
             'operator_id': 4,
             'msisdn_destination': msisdn,
             'order': p['order'],
             'transaction_datetime': datetime.now(),
             'device_id': sd_dev['device_id'],
             'status': const.TR_INPROGRESS,
         })
     template = self.tran_parse[prod]
     msg = template.format(msisdn=msisdn, amount=p['amount'],
                        pin=sd_dev['pin'], device_id=sd_dev['device_id'])
     leaf_server = '{0}@{2}/{1}'.format(config.LEAFSERVER, sd_dev['server_id'],
                                        config.MSG_SERVER)
     self.sendMessage(leaf_server, 'JBDV', msg, commit=False)
예제 #17
0
파일: Sync.py 프로젝트: sridwan/sd
 def _3sakti_t(self, p, ag):
     try:
         am = int(p['amount'])
     except:
         self.writeNotifyOut(p['protocol'], 'amount_not_number',
                             {'amount': p['amount']})
         return        
     c = self.dbconn.cursor(MySQLdb.cursors.DictCursor)
     sql = '''SELECT * FROM `devices` WHERE `operator_id`=13 LIMIT 1'''
     c.execute(sql)
     sd_dev = c.fetchone()
     # sd_dev = self.c_device.get(self.dbconn, self.cacheconn, ch['device_id'])
     if not sd_dev:
         self.writeNotifyOut(p['protocol'], 'topup_fail', {})
         print 'INVALID DEVICE_ID'
         return
     if am < 10000 or am > 100000000:
         self.writeNotifyOut(p['protocol'], 'amount_not_number',
                             {'amount': p['amount']})
     msisdn = sanitizeMSISDN(p['msisdn'])
     if 'order' not in p:
         p['order'] = 1
     prod_id = '3S*{0}'.format(thousandSeparator(am))
     if self.checkTrx(p['protocol'], ag['agent_id'], prod_id, p['order'], msisdn):
         return
     cur_bal = self.dm.getBalance(ag['agent_id'])
     if cur_bal < am:
         self.writeNotifyOut(p['protocol'], 'agent_not_enough_balance', 
                             {'product_id': am, 'dest': msisdn, 'balance': cur_bal,})
         return
     new_deposit = self.dm.debit(ag['agent_id'], am,
                                 'transfer ke {0}'.format(msisdn))
     # new_deposit = 999
     sql = '''INSERT INTO `transaction` (`method`,`agent_id`,`agent_name`,
              `reg_protocol`,`deposit`,`base_price`,`sell_price`,`profit`,
              `product_id`,`operator_product_id`,`hlr_id`,`operator_id`,
              `msisdn_destination`,`order`,`transaction_datetime`,`device_id`,
              `status`) VALUES (%(method)s,%(agent_id)s,%(agent_name)s,
              %(reg_protocol)s,%(deposit)s,%(base_price)s,%(sell_price)s,%(profit)s,
              %(product_id)s,%(operator_product_id)s,%(hlr_id)s,%(operator_id)s,
              %(msisdn_destination)s,%(order)s,%(transaction_datetime)s,%(device_id)s,
              %(status)s)'''
     c.execute(sql, {
             'method': 'CH',
             'agent_id': ag['agent_id'],
             'agent_name': ag['agent_name'],
             'reg_protocol': p['protocol'],
             'deposit': new_deposit,
             'base_price': am,
             'sell_price': am,
             'profit': 0,
             'product_id': prod_id,
             'operator_product_id': prod_id,
             'hlr_id': 0,
             'operator_id': 13,
             'msisdn_destination': msisdn,
             'order': p['order'],
             'transaction_datetime': datetime.now(),
             'device_id': sd_dev['device_id'],
             'status': const.TR_INPROGRESS,
         })
     template = '{device_id},0,sms://089611223344,trf.{msisdn}.{amount}.{pin}'
     msg = template.format(msisdn=msisdn, amount=p['amount'],
                        pin=sd_dev['pin'], device_id=sd_dev['device_id'])
     leaf_server = '{0}@{2}/{1}'.format(config.LEAFSERVER, sd_dev['server_id'],
                                        config.MSG_SERVER)
     self.sendMessage(leaf_server, 'JBDV', msg, commit=False)
     print msg
예제 #18
0
파일: Authorizer.py 프로젝트: sridwan/meong
 def notEnoughBalance(self, prot, prodid, balance, dest):
     self.writeNotifyOut(
         prot,
         "agent_not_enough_balance",
         {"product_id": prodid, "balance": thousandSeparator(balance), "dest": dest},
     )