Example #1
0
    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)
Example #2
0
    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])
Example #3
0
    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_exception.DBDuplicateEntry:
            LOG.exception('Duplicated deduct req_id: %s' % data.reqId)
            raise exception.DuplicatedDeduct(req_id=data.reqId)
        except exception.NotAuthorized as e:
            LOG.exception('Fail to deduct the account: %s' % data.accountNum)
            raise exception.NotAuthorized()
        except Exception as e:
            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])
Example #4
0
    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)
Example #5
0
    def get_all(self, user_id=None, limit=None, offset=None,
                sort_key='dispatched,used', sort_dir='asc'):
        """Get all precharges."""
        context = pecan.request.context
        conn = pecan.request.db_conn
        check_policy(context, "account:precharge")

        if limit and limit < 0:
            raise exception.InvalidParameterValue(err="Invalid limit")
        if offset and offset < 0:
            raise exception.InvalidParameterValue(err="Invalid offset")

        try:
            precharges = conn.get_precharges(context,
                                             user_id=user_id,
                                             limit=limit,
                                             offset=offset,
                                             sort_key=sort_key,
                                             sort_dir=sort_dir)
            total_count = conn.get_precharges_count(context, user_id=user_id)
            pecan.response.headers['X-Total-Count'] = str(total_count)
        except Exception as e:
            LOG.exception('Failed to get all precharges')
            raise exception.DBError(reason=e)

        precharges = [models.PreCharge.from_db_model(p) for p in precharges]
        return models.PreCharges.transform(precharges=precharges,
                                           total_count=total_count)
Example #6
0
    def get_all(self,
                user_id=None,
                limit=None,
                offset=None,
                sort_key='dispatched,used',
                sort_dir='asc'):
        """Get all precharges."""
        context = pecan.request.context
        conn = pecan.request.db_conn
        check_policy(context, "account:precharge")

        if limit and limit < 0:
            raise exception.InvalidParameterValue(err="Invalid limit")
        if offset and offset < 0:
            raise exception.InvalidParameterValue(err="Invalid offset")

        try:
            precharges = conn.get_precharges(context,
                                             user_id=user_id,
                                             limit=limit,
                                             offset=offset,
                                             sort_key=sort_key,
                                             sort_dir=sort_dir)
            total_count = conn.get_precharges_count(context, user_id=user_id)
            pecan.response.headers['X-Total-Count'] = str(total_count)
        except Exception as e:
            LOG.exception('Failed to get all precharges')
            raise exception.DBError(reason=e)

        precharges = [models.PreCharge.from_db_model(p) for p in precharges]
        return models.PreCharges.transform(precharges=precharges,
                                           total_count=total_count)
Example #7
0
    def put(self, data):
        """Update salesperson of an account
        """
        context = pecan.request.context
        check_policy(context, 'uos_sales_admin')

        user_id = self.user_id
        conn = pecan.request.db_conn
        conn.set_accounts_salesperson(context, [user_id], data.sales_id)
Example #8
0
    def get(self, user_id=None, type=None, start_time=None,
            end_time=None, limit=None, offset=None,
            sort_key='created_at', sort_dir='desc'):
        """Get all charges of all account."""

        check_policy(request.context, "charges:all")

        if limit and limit < 0:
            raise exception.InvalidParameterValue(err="Invalid limit")
        if offset and offset < 0:
            raise exception.InvalidParameterValue(err="Invalid offset")

        users = {}

        def _get_user(user_id):
            user = users.get(user_id)
            if user:
                return user
            contact = keystone.get_uos_user(user_id) or {}
            user_name = contact.get('name')
            email = contact.get('email')
            real_name = contact.get('real_name')
            mobile = contact.get('mobile_number')
            company = contact.get('company')
            users[user_id] = models.User(user_id=user_id,
                                         user_name=user_name,
                                         email=email,
                                         real_name=real_name,
                                         mobile=mobile,
                                         company=company)
            return users[user_id]

        self.conn = pecan.request.db_conn
        charges = self.conn.get_charges(request.context,
                                        user_id=user_id,
                                        type=type,
                                        limit=limit,
                                        offset=offset,
                                        start_time=start_time,
                                        end_time=end_time,
                                        sort_key=sort_key,
                                        sort_dir=sort_dir)
        charges_list = []
        for charge in charges:
            acharge = models.Charge.from_db_model(charge)
            acharge.actor = _get_user(charge.operator)
            acharge.target = _get_user(charge.user_id)
            charges_list.append(acharge)

        total_price, total_count = self.conn.get_charges_price_and_count(
            request.context, user_id=user_id, type=type,
            start_time=start_time, end_time=end_time)
        total_price = gringutils._quantize_decimal(total_price)

        return models.Charges.transform(total_price=total_price,
                                        total_count=total_count,
                                        charges=charges_list)
Example #9
0
    def put(self, data):
        """Update salesperson of an account
        """
        context = pecan.request.context
        check_policy(context, 'uos_sales_admin')

        user_id = self.user_id
        conn = pecan.request.db_conn
        conn.set_accounts_salesperson(context, [user_id], data.sales_id)
Example #10
0
    def get(self, user_id=None, type=None, start_time=None,
            end_time=None, limit=None, offset=None,
            sort_key='created_at', sort_dir='desc'):
        """Get all charges of all account."""

        check_policy(request.context, "charges:all")

        if limit and limit < 0:
            raise exception.InvalidParameterValue(err="Invalid limit")
        if offset and offset < 0:
            raise exception.InvalidParameterValue(err="Invalid offset")

        users = {}

        def _get_user(user_id):
            user = users.get(user_id)
            if user:
                return user
            contact = kunkka.get_uos_user(user_id) or {}
            user_name = contact.get('name')
            email = contact.get('email')
            real_name = contact.get('real_name')
            mobile = contact.get('phone')
            company = contact.get('company')
            users[user_id] = models.User(user_id=user_id,
                                         user_name=user_name,
                                         email=email,
                                         real_name=real_name,
                                         mobile=mobile,
                                         company=company)
            return users[user_id]

        self.conn = pecan.request.db_conn
        charges = self.conn.get_charges(request.context,
                                        user_id=user_id,
                                        type=type,
                                        limit=limit,
                                        offset=offset,
                                        start_time=start_time,
                                        end_time=end_time,
                                        sort_key=sort_key,
                                        sort_dir=sort_dir)
        charges_list = []
        for charge in charges:
            acharge = models.Charge.from_db_model(charge)
            acharge.actor = _get_user(charge.operator)
            acharge.target = _get_user(charge.user_id)
            charges_list.append(acharge)

        total_price, total_count = self.conn.get_charges_price_and_count(
            request.context, user_id=user_id, type=type,
            start_time=start_time, end_time=end_time)
        total_price = gringutils._quantize_decimal(total_price)

        return models.Charges.transform(total_price=total_price,
                                        total_count=total_count,
                                        charges=charges_list)
Example #11
0
    def post(self, data):
        """Create a new account."""
        check_policy(request.context, "account:post")

        conn = pecan.request.db_conn
        try:
            account = db_models.Account(**data.as_dict())
            return conn.create_account(request.context, account)
        except Exception:
            LOG.exception('Fail to create account: %s' % data.as_dict())
            raise exception.AccountCreateFailed(user_id=data.user_id,
                                                domain_id=data.domain_id)
Example #12
0
    def post(self, data):
        """Create a new account."""
        check_policy(request.context, "account:post")

        conn = pecan.request.db_conn
        try:
            account = db_models.Account(**data.as_dict())
            return conn.create_account(request.context, account)
        except Exception:
            LOG.exception('Fail to create account: %s' % data.as_dict())
            raise exception.AccountCreateFailed(user_id=data.user_id,
                                                domain_id=data.domain_id)
Example #13
0
    def delete(self):
        """Delete the precharge. Actually set the deleted status as True"""
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        try:
            conn.delete_precharge(context, self.code)
        except exception.PreChargeNotFound:
            raise
        except Exception as e:
            msg = 'Failed to delete precharge:%s, for reason:%s' % \
                (self.code, e)
            LOG.error(msg)
            raise exception.PreChargeException()
Example #14
0
    def get(self, accountNum):

        check_policy(request.context, "deduct:account_get")
        self.conn = pecan.request.db_conn

        try:
            account = self.conn.get_account(request.context, accountNum)
        except Exception as e:
            LOG.error('account %s not found' % accountNum)
            raise exception.AccountNotFound(user_id=accountNum)

        return models.GetBalanceResponse(code="0",
                                         total="1",
                                         message="OK",
                                         data=[models.GetBalance(money=account.balance)])
Example #15
0
    def delete(self):
        """Delete the account including the projects that belong to it."""
        # only admin can delete account
        check_policy(request.context, "account:delete")

        try:
            self.conn = pecan.request.db_conn
            self.conn.delete_account(request.context, self._id)
        except (exception.NotFound):
            msg = _('Could not find account whose user_id is %s' % self._id)
            raise exception.NotFound(msg)
        except Exception as e:
            msg = _("failed to delete account whose user_id is %s." % self._id)
            LOG.warn(msg)
            raise exception.DBError(reason=e)
Example #16
0
    def delete(self):
        """Delete the precharge. Actually set the deleted status as True"""
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        try:
            conn.delete_precharge(context, self.code)
        except exception.PreChargeNotFound:
            raise
        except Exception as e:
            msg = 'Failed to delete precharge:%s, for reason:%s' % \
                (self.code, e)
            LOG.error(msg)
            raise exception.PreChargeException()
Example #17
0
    def delete(self):
        """Delete the account including the projects that belong to it."""
        # only admin can delete account
        check_policy(request.context, "account:delete")

        try:
            self.conn = pecan.request.db_conn
            self.conn.delete_account(request.context, self._id)
        except (exception.NotFound):
            msg = _('Could not find account whose user_id is %s' % self._id)
            raise exception.NotFound(msg)
        except Exception as e:
            msg = _("failed to delete account whose user_id is %s." % self._id)
            LOG.warn(msg)
            raise exception.DBError(reason=e)
Example #18
0
    def delete(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.codes == wsme.Unset:
            data.codes = []
        for code in data.codes:
            if not code:
                continue
            try:
                conn.delete_precharge(context, code)
            except Exception as e:
                msg = 'Failed to delete precharge:%s, for reason:%s' % \
                    (code, e)
                LOG.exception(msg)
Example #19
0
    def level(self, level):
        """Update the account's level."""
        check_policy(request.context, "account:level")

        if not isinstance(level, int) or level < 0 or level > 9:
            raise exception.InvalidParameterValue(err="Invalid Level")

        self.conn = pecan.request.db_conn
        try:
            account = self.conn.change_account_level(request.context, self._id,
                                                     level)
        except Exception as e:
            LOG.exception('Fail to change the account level of: %s' % self._id)
            raise exception.DBError(reason=e)

        return models.UserAccount.from_db_model(account)
Example #20
0
    def get(self, accountNum):

        check_policy(request.context, "deduct:account_get")
        self.conn = pecan.request.db_conn

        try:
            account = self.conn.get_account(request.context, accountNum)
        except Exception:
            LOG.error('account %s not found' % accountNum)
            raise exception.AccountNotFound(user_id=accountNum)

        return models.GetBalanceResponse(
            code="0",
            total="1",
            message="OK",
            data=[models.GetBalance(money=account.balance)])
Example #21
0
    def delete(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.codes == wsme.Unset:
            data.codes = []
        for code in data.codes:
            if not code:
                continue
            try:
                conn.delete_precharge(context, code)
            except Exception as e:
                msg = 'Failed to delete precharge:%s, for reason:%s' % \
                    (code, e)
                LOG.exception(msg)
Example #22
0
    def level(self, level):
        """Update the account's level."""
        check_policy(request.context, "account:level")

        if not isinstance(level, int) or level < 0 or level > 9:
            raise exception.InvalidParameterValue(err="Invalid Level")

        self.conn = pecan.request.db_conn
        try:
            account = self.conn.change_account_level(
                request.context, self._id, level)
        except Exception as e:
            LOG.exception('Fail to change the account level of: %s' % self._id)
            raise exception.DBError(reason=e)

        return models.UserAccount.from_db_model(account)
Example #23
0
    def put(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.codes == wsme.Unset:
            data.codes = []
        if data.remarks == wsme.Unset:
            data.remarks = None

        for code in data.codes:
            if not code:
                continue
            try:
                conn.dispatch_precharge(context, code, data.remarks)
            except Exception as e:
                LOG.error('Fail to dispatch precharge(%s), for reason: %s' %
                          (code, e))
Example #24
0
    def put(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.codes == wsme.Unset:
            data.codes = []
        if data.remarks == wsme.Unset:
            data.remarks = None

        for code in data.codes:
            if not code:
                continue
            try:
                conn.dispatch_precharge(context, code, data.remarks)
            except Exception as e:
                LOG.error('Fail to dispatch precharge(%s), for reason: %s' %
                          (code, e))
Example #25
0
    def post(self, data):
        context = pecan.request.context
        check_policy(context, "account:precharge")

        conn = pecan.request.db_conn
        if data.expired_at == wsme.Unset:
            data.expired_at = datetime.datetime.utcnow() + \
                datetime.timedelta(days=365)
        if data.remarks == wsme.Unset:
            data.remarks = None

        try:
            conn.create_precharge(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()
Example #26
0
    def post(self, data):
        context = pecan.request.context
        check_policy(context, "account:precharge")

        conn = pecan.request.db_conn
        if data.expired_at == wsme.Unset:
            data.expired_at = datetime.datetime.utcnow() + \
                datetime.timedelta(days=365)
        if data.remarks == wsme.Unset:
            data.remarks = None

        try:
            conn.create_precharge(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()
Example #27
0
    def dispatched(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.remarks == wsme.Unset:
            data.remarks = None

        try:
            precharge = conn.dispatch_precharge(context,
                                                self.code,
                                                remarks=data.remarks)
        except exception.PreChargeNotFound:
            LOG.error('The precharge %s not found' % self.code)
            raise exception.PreChargeNotFound(precharge_code=self.code)
        except Exception as e:
            LOG.error('Fail to dispatch precharge(%s), for reason: %s' %
                      (self.code, e))
            raise exception.PreChargeException()

        return models.PreCharge.from_db_model(precharge)
Example #28
0
    def dispatched(self, data):
        conn = pecan.request.db_conn
        context = pecan.request.context
        check_policy(context, "account:precharge")

        if data.remarks == wsme.Unset:
            data.remarks = None

        try:
            precharge = conn.dispatch_precharge(context,
                                                self.code,
                                                remarks=data.remarks)
        except exception.PreChargeNotFound:
            LOG.error('The precharge %s not found' % self.code)
            raise exception.PreChargeNotFound(precharge_code=self.code)
        except Exception as e:
            LOG.error('Fail to dispatch precharge(%s), for reason: %s' %
                      (self.code, e))
            raise exception.PreChargeException()

        return models.PreCharge.from_db_model(precharge)
Example #29
0
    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)
Example #30
0
    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)])
Example #31
0
    def get(self, reqId):

        check_policy(request.context, "deduct:check_req")
        self.conn = pecan.request.db_conn

        status = "0"
        try:
            deduct = self.conn.get_deduct(request.context, reqId)
        except exception.DeductNotFound:
            LOG.warn('Deduct Req: %s not found' % reqId)
            status = "-1"
        except exception.NotAuthorized as e:
            LOG.exception('Fail to get the deduct req: %s' % reqId)
            raise exception.NotAuthorized()
        except Exception as e:
            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)])
Example #32
0
    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)
Example #33
0
    def put(self, data):
        context = pecan.request.context
        policy.check_policy(context, 'uos_sales_admin')

        conn = pecan.request.db_conn
        conn.set_accounts_salesperson(context, data.user_ids, self.sales_id)
Example #34
0
    def put(self, data):
        context = pecan.request.context
        policy.check_policy(context, 'uos_sales_admin')

        conn = pecan.request.db_conn
        conn.set_accounts_salesperson(context, data.user_ids, self.sales_id)
Example #35
0
    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)
Example #36
0
    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)
Example #37
0
    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)
Example #38
0
    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)