def get(self, offset=None, limit=None): """Get the accounts of this sales person.""" context = pecan.request.context if not acl.limit_to_sales(context, self.sales_id): raise exception.NotAuthorized() if limit and limit < 0: raise exception.InvalidParameterValue(err="Invalid limit") if offset and offset < 0: raise exception.InvalidParameterValue(err="Invalid offset") conn = pecan.request.db_conn accounts_number, sales_amount = conn.get_salesperson_amount( context, self.sales_id) accounts = conn.get_salesperson_customer_accounts( context, self.sales_id, offset, limit) account_list = [] for account in accounts: user = kunkka.get_uos_user(account.user_id) account_list.append( models.SalesPersonAccount(user_id=account.user_id, user_name=user['name'], user_email=user.get('email', ''), real_name=user.get('real_name', ''), mobile_number=user.get('phone', ''), company=user.get('company', ''), balance=account.balance, consumption=account.consumption, owed=account.owed)) return models.SalesPersonAccounts(total_count=accounts_number, accounts=account_list)
def get(self): """Return salesperson of an account """ context = pecan.request.context user_id = self.user_id conn = pecan.request.db_conn account = conn.get_account(context, user_id) sales_id = account.sales_id if not sales_id: # Only allow sales admin to know that an account # belongs to no salesperson. check_policy(context, 'uos_sales_admin') return models.SalesPerson() # Only allow salesperson to get account that # belongs to himself/herself. if not acl.limit_to_sales(context, sales_id): raise exception.NotAuthorized() try: sales_user = keystone.get_uos_user(sales_id) return models.SalesPerson( user_id=sales_id, user_name=sales_user['name'], user_email=sales_user.get('email', ''), real_name=sales_user.get('real_name', ''), mobile_number=sales_user.get('mobile_number', ''), company=sales_user.get('company', '')) except (exception.NotFound): msg = _('Could not find salesperson %s of account %s' ' from keystone' % (sales_id, user_id)) LOG.error(msg) raise exception.NotFound(msg)
def put(self, data): check_policy(request.context, "deduct:account_pay") if data.reqId == wsme.Unset or data.money == wsme.Unset or \ data.accountNum == wsme.Unset or data.extData == wsme.Unset or \ data.extData.order_id == wsme.Unset: raise exception.InvalidDeductParameter() data.money = gringutils._quantize_decimal(data.money) self.conn = pecan.request.db_conn try: deduct = self.conn.deduct_account(request.context, data.accountNum, **data.as_dict()) except db_exc.DBDuplicateEntry: LOG.exception('Duplicated deduct req_id: %s' % data.reqId) raise exception.DuplicatedDeduct(req_id=data.reqId) except exception.NotAuthorized: LOG.exception('Fail to deduct the account: %s' % data.accountNum) raise exception.NotAuthorized() except Exception: msg = "Fail to deduct the account: %s, charge value: %s" % ( data.accountNum, data.money) LOG.exception(msg) raise exception.DBError(reason=msg) pay = models.Pay(transactionNum=deduct.deduct_id, money=deduct.money, createDate=deduct.created_at) return models.PayResponse(code="0", total="1", message="OK", data=[pay])
def put(self): context = pecan.request.context if not context.is_admin: raise exception.NotAuthorized() user_id = context.user_id key = str("gring-precharge-limit-%s" % user_id) cache = _get_cache() cache.delete(key)
def post(self, data): """Transfer money from one account to another. And only the domain owner can do the operation. """ is_domain_owner = acl.context_is_domain_owner(request.headers) if not is_domain_owner: raise exception.NotAuthorized() conn = pecan.request.db_conn conn.transfer_money(request.context, data)
def put(self, data): """Charge the account """ # Check the charge value if data.value < -100000 or data.value > 100000: raise exception.InvalidChargeValue(value=data.value) self.conn = pecan.request.db_conn try: charge, _ = self.conn.update_account(request.context, None, project_id=self._id, **data.as_dict()) has_bonus = False if cfg.CONF.enable_bonus and data['type'] != 'bonus': data['type'] = 'bonus' data['come_from'] = 'system' value = gringutils.calculate_bonus(data['value']) if value > 0: data['value'] = value bonus, _ = self.conn.update_account(request.context, None, project_id=self._id, **data.as_dict()) has_bonus = True self.conn.set_charged_orders(request.context, None, project_id=self._id) except exception.NotAuthorized as e: LOG.exception('Fail to charge the account:%s due to not authorization' % \ self._id) raise exception.NotAuthorized() except Exception as e: LOG.exception('Fail to charge the account:%s, charge value: %s' % \ (self._id, data.value)) raise exception.DBError(reason=e) else: # Notifier account if cfg.CONF.notify_account_charged and charge['type'] != 'bonus': account = self.conn.get_account(request.context, None, project_id=self._id).as_dict() contact = keystone.get_uos_user(account['user_id']) self.notifier = notifier.NotifierService( cfg.CONF.checker.notifier_level) self.notifier.notify_account_charged( request.context, account, contact, data['type'], charge.value, bonus=bonus.value if has_bonus else 0) return models.Charge.from_db_model(charge)
def amount(self): """Get the sales amount of this sales person.""" context = pecan.request.context if not acl.limit_to_sales(context, self.sales_id): raise exception.NotAuthorized() conn = pecan.request.db_conn accounts_number, sales_amount = conn.get_salesperson_amount( context, self.sales_id) return models.SalesPersonAmount(sales_amount=sales_amount, accounts_number=accounts_number)
def post(self, data): conn = pecan.request.db_conn if data.expired_at == wsme.Unset: data.expired_at = datetime.datetime.utcnow() + datetime.timedelta(days=365) try: conn.create_precharge(pecan.request.context, **data.as_dict()) except exception.NotAuthorized as e: LOG.exception('Fail to create precharges') raise exception.NotAuthorized() except Exception as e: LOG.exception('Fail to create precharges: %s, for reason: %s' % (data.as_dict(), e)) raise exception.PreChargeException()
def get_all(self, owed=None, limit=None, offset=None, duration=None): """Get all accounts.""" check_policy(request.context, "account:all") if limit and limit < 0: raise exception.InvalidParameterValue(err="Invalid limit") if offset and offset < 0: raise exception.InvalidParameterValue(err="Invalid offset") self.conn = pecan.request.db_conn duration = gringutils.normalize_timedelta(duration) if duration: active_from = datetime.datetime.utcnow() - duration else: active_from = None try: accounts = self.conn.get_accounts(request.context, owed=owed, limit=limit, offset=offset, active_from=active_from) count = self.conn.get_accounts_count(request.context, owed=owed, active_from=active_from) pecan.response.headers['X-Total-Count'] = str(count) except exception.NotAuthorized as e: LOG.exception('Failed to get all accounts') raise exception.NotAuthorized() except Exception as e: LOG.exception('Failed to get all accounts') raise exception.DBError(reason=e) accounts = [ models.AdminAccount.from_db_model(account) for account in accounts ] return models.AdminAccounts(total_count=count, accounts=accounts)
def get(self, reqId): check_policy(request.context, "deduct:check_req") self.conn = pecan.request.db_conn status = "0" try: self.conn.get_deduct(request.context, reqId) except exception.DeductNotFound: LOG.warn('Deduct Req: %s not found' % reqId) status = "-1" except exception.NotAuthorized: LOG.exception('Fail to get the deduct req: %s' % reqId) raise exception.NotAuthorized() except Exception: msg = "Fail to get the deduct req: %s" % reqId LOG.exception(msg) raise exception.DBError(reason=msg) return models.CheckReqResponse(code="0", total="1", message="OK", data=[models.CheckReq(status=status)])
def get_all(self, owed=None, limit=None, offset=None): """Get all accounts """ self.conn = pecan.request.db_conn try: accounts = self.conn.get_accounts(request.context, owed=owed, limit=limit, offset=offset) count = self.conn.get_accounts_count(request.context, owed=owed) pecan.response.headers['X-Total-Count'] = str(count) except exception.NotAuthorized as e: LOG.exception('Fail to get all accounts') raise exception.NotAuthorized() except Exception as e: LOG.exception('Fail to get all accounts') raise exception.DBError(reason=e) return [ models.AdminAccount.from_db_model(account) for account in accounts ]
def get_auth_headers(self, **kwargs): if self.auth_token is None: raise exception.NotAuthorized( 'Current authorization does not have a token') return {'X-Auth-Token': self.auth_token}
def require_domain_context(ctxt): if not ctxt.is_admin and not ctxt.is_domain_owner: raise exception.NotAuthorized()
def require_admin_context(ctxt): if not ctxt.is_admin: raise exception.NotAuthorized()
def get_all(self, user_id=None, owed=None, limit=None, offset=None, sort_key='created_at', sort_dir='desc'): check_policy(request.context, "account:all") if limit and limit < 0: raise exception.InvalidParameterValue(err="Invalid limit") if offset and offset < 0: raise exception.InvalidParameterValue(err="Invalid offset") self.conn = pecan.request.db_conn try: accounts = self.conn.get_accounts(request.context, user_id=user_id, owed=owed, limit=limit, offset=offset, sort_key=sort_key, sort_dir=sort_dir) count = self.conn.get_accounts_count(request.context, owed=owed, user_id=user_id) pecan.response.headers['X-Total-Count'] = str(count) except exception.NotAuthorized as e: LOG.exception('Failed to get all accounts') raise exception.NotAuthorized() except Exception as e: LOG.exception('Failed to get all accounts') raise exception.DBError(reason=e) results = [] user_ids = [] for account in accounts: user_ids.append(account.user_id) if account.sales_id: user_ids.append(account.sales_id) if cfg.CONF.external_billing.enable: try: external_balance = \ self.external_client.get_external_balance( account.user_id)['data'][0]['money'] external_balance = \ gringutils._quantize_decimal( external_balance) account.balance = external_balance except exception.GetExternalBalanceFailed: msg = _('Fail to get %s\'s external balance' % (account.user_id)) LOG.warn(msg) price_per_day, remaining_day = \ self._estimate_per_day(account.user_id, account.balance) result = models.AdminAccountInDetail( user=None, user_id=account.user_id, salesperson=None, sales_id=account.sales_id, balance=account.balance, consumption=account.consumption, level=account.level, project_id=account.project_id, domain_id=account.domain_id, owed=owed, inviter=account.inviter, created_at=account.created_at, price_per_day=price_per_day, remaining_day=remaining_day) results.append(result) users = keystone.get_users_by_user_ids(user_ids) for result in results: user = users.get(result.user_id) salesperson = users.get(result.sales_id) if user: result.user = models.UserInDetail(**user) if salesperson: result.salesperson = models.UserInDetail(**salesperson) return models.AdminAccountsInDetail(total_count=count, accounts=results)
def put(self, data): """Charge the account.""" check_policy(request.context, "account:charge") # check uos_bill_account_charge_limited charge value if "uos_bill_account_charge_limited" in request.context.roles: lscv = int(cfg.CONF.limited_support_charge_value) if data.value < -lscv or data.value > lscv: raise exception.InvalidChargeValue(value=data.value) else: # check accountant charge value lacv = int(cfg.CONF.limited_accountant_charge_value) if data.value < -lacv or data.value > lacv: raise exception.InvalidChargeValue(value=data.value) remarks = data.remarks if data.remarks != wsme.Unset else None operator = request.context.user_id self.conn = pecan.request.db_conn try: charge, is_first_charge = self.conn.update_account( request.context, self._id, operator=operator, **data.as_dict()) has_bonus = False if cfg.CONF.enable_bonus and data['type'] != 'bonus': value = gringutils.calculate_bonus(data['value']) if value > 0: bonus, _ = self.conn.update_account(request.context, self._id, type='bonus', value=value, come_from='system', operator=operator, remarks=remarks) has_bonus = True if cfg.CONF.enable_invitation and is_first_charge: _account = self._account() min_charge_value = gringutils._quantize_decimal( cfg.CONF.min_charge_value) reward_value = gringutils._quantize_decimal( cfg.CONF.reward_value) if _account.inviter \ and data.value >= min_charge_value \ and reward_value > 0: self.conn.update_account( request.context, _account.inviter, type='bonus', value=reward_value, come_from='system', operator=operator, remarks="reward because of invitation", invitee=self._id) if cfg.CONF.notify_account_charged: inviter = self.conn.get_account( request.context, _account.inviter).as_dict() contact = keystone.get_uos_user(inviter['user_id']) self.notifier = notifier.NotifierService( cfg.CONF.checker.notifier_level) self.notifier.notify_account_charged( request.context, inviter, contact, 'bonus', reward_value, bonus=0, operator=operator, operator_name=request.context.user_name, remarks="reward because of invitation") self.conn.set_charged_orders(request.context, self._id) except exception.NotAuthorized as e: LOG.exception('Fail to charge the account:%s ' 'due to not authorization' % self._id) raise exception.NotAuthorized() except Exception as e: LOG.exception('Fail to charge the account:%s, ' 'charge value: %s' % (self._id, data.value)) raise exception.DBError(reason=e) else: # Notifier account if cfg.CONF.notify_account_charged: account = self.conn.get_account(request.context, self._id).as_dict() contact = keystone.get_uos_user(account['user_id']) country_code = contact.get("country_code") or "86" language = "en_US" if country_code != '86' else "zh_CN" self.notifier = notifier.NotifierService( cfg.CONF.checker.notifier_level) self.notifier.notify_account_charged( request.context, account, contact, data['type'], charge.value, bonus=bonus.value if has_bonus else 0, operator=operator, operator_name=request.context.user_name, remarks=remarks, language=language) return models.Charge.from_db_model(charge)
def get_endpoint(self): if self.management_url is None: raise exception.NotAuthorized( 'Current authorization does not have a known billing management url') return self.management_url