def test_publish(self): Tariff.create_tariff(self.localized_name("tariff_for_balance"), "tariff!!!", "rub", None) customer_id = Customer.new_customer("*****@*****.**", "123qwe", self.admin_user.user_id).customer_id db.session.commit() customer = Customer.get_by_id(customer_id) news_id = self.admin_client.news.create(**self.test_news)['news_id'] # check publish news = self.admin_client.news.publish(news_id, publish=True) self.assertTrue(news['published']) self.assertEqual(outbox[0].to, [customer.email]) self.assertIn(self.test_news['subject'], outbox[0].subject) news_id = self.admin_client.news.create(subject='$test_subject', body='test_body')['news_id'] self.admin_client.news.publish(news_id, publish=True) self.assertEqual(len(outbox), 1) # check unpublish news = self.admin_client.news.publish(news_id, publish=False) self.assertFalse(news['published']) self.assertEqual(len(outbox), 1) # check publish deleted news self.admin_client.news.delete(news_id) with self.expect_error(errors.RemovedNews): self.admin_client.news.publish(news_id, publish=True)
def test_publish(self): Tariff.create_tariff(self.localized_name("tariff_for_balance"), "tariff!!!", "rub", None) customer_id = Customer.new_customer( "*****@*****.**", "123qwe", self.admin_user.user_id).customer_id db.session.commit() customer = Customer.get_by_id(customer_id) news_id = self.admin_client.news.create(**self.test_news)['news_id'] # check publish news = self.admin_client.news.publish(news_id, publish=True) self.assertTrue(news['published']) self.assertEqual(outbox[0].to, [customer.email]) self.assertIn(self.test_news['subject'], outbox[0].subject) news_id = self.admin_client.news.create(subject='$test_subject', body='test_body')['news_id'] self.admin_client.news.publish(news_id, publish=True) self.assertEqual(len(outbox), 1) # check unpublish news = self.admin_client.news.publish(news_id, publish=False) self.assertFalse(news['published']) self.assertEqual(len(outbox), 1) # check publish deleted news self.admin_client.news.delete(news_id) with self.expect_error(errors.RemovedNews): self.admin_client.news.publish(news_id, publish=True)
def setUp(self): super().setUp() self.collector = Collector() self.image_size_price = "12.34" self.volume_size_price = "12.37" self.root_disk_price = "2.91" self.nano_price = "3.47" services = [{ "service_id": "storage.image", "price": self.image_size_price }, { "service_id": "storage.volume", "price": self.volume_size_price }, { "service_id": "storage.disk", "price": self.root_disk_price }, { "service_id": self.service_nano_id, "price": self.nano_price }] self.tariff = Tariff.create_tariff( self.localized_name("Tariff for customers"), "tariff!!!", "rub", services=services) self.tariff.mark_immutable() self.tariff.make_default() self.loop = asyncio.get_event_loop()
def aggregate(self, report_id): logbook.info("Get detailed customer usage aggregation for {}", report_id) customer = Customer.get_by_id(report_id.customer_id) if not customer: raise Exception("Customer %s not found" % report_id.customer_id) with timed("get_usage simple"): aggregated_usage = ServiceUsage.get_detailed_usage( customer, report_id.start, report_id.end) tariffs = {} services = set() for usage in aggregated_usage: tariff = Tariff.get_by_id(usage.tariff_id) tariff_report = tariffs.get(usage.tariff_id) if tariff_report is None: tariff_report = self.tariff_report_type(tariff, customer) tariffs[usage.tariff_id] = tariff_report tariff_report.add_usage(usage) total = Counter() for tariff_id, tariff in tariffs.items(): total_tariff, currency = tariff.aggregate() total[currency] += total_tariff for t, value in total.items(): total[t] = decimal_to_string(value) logbook.info("Aggregated {} for {}. Services: {}", total, customer, services) return self.prepare_result(list(tariffs.values()), total, customer, report_id.start, report_id.end)
def test_update_public_flavor_service(self): tariff = self.admin_client.tariff.create( as_json=True, **self.tariff_example("Tariff for update")) self.admin_client.tariff.immutable(tariff["tariff_id"]) tariff = Tariff.get_by_id(tariff["tariff_id"]) tariff.services.append(ServicePrice(self.service_nano_id, 0, True)) db.session.commit() updated = self.admin_client.tariff.update( resource_id=tariff.tariff_id, as_json=True, services=[{ "service_id": str(self.service_nano_id), "price": "11.11" }, { "service_id": str(self.service_medium_id), "price": "100" }]) db.session.add(tariff) self.assertEqual( tariff.services_as_dict()[str(self.service_nano_id)].need_changing, False) self.assertEqual( tariff.services_as_dict()[str(self.service_nano_id)].price, Decimal('11.11')) self.assertEqual( tariff.services_as_dict()[str(self.service_medium_id)].price, Decimal('23.45'))
def aggregate(self, report_id): logbook.info("Get customer usage aggregation for {}", report_id) customer = Customer.get_by_id(report_id.customer_id) if not customer: raise Exception("Customer %s not found" % report_id.customer_id) with timed("get_usage simple"): aggregated_usage = ServiceUsage.get_usage(customer, report_id.start, report_id.end) tariffs = {} services = set() for usage in aggregated_usage: service_id, tariff_id, cost, usage_volume = usage services.add(service_id) if not tariff_id: logbook.error("ServiceUsage {} is not completed. Tariff is not filled", usage) continue tariff = Tariff.get_by_id(tariff_id) tariff_report = tariffs.get(tariff_id) if tariff_report is None: tariff_report = self.tariff_report_type(tariff, customer) tariffs[tariff_id] = tariff_report tariff_report.add_usage(usage) total = Counter() for tariff_id, tariff in tariffs.items(): total_tariff, currency = tariff.aggregate() total[currency] += total_tariff for t, value in total.items(): total[t] = decimal_to_string(value) logbook.info("Aggregated {} for {}. Services: {}", total, customer, services) return self.prepare_result(list(tariffs.values()), total, customer, report_id.start, report_id.end)
def test_tariff_add_service(self): t = Tariff.create_tariff(self.localized_name("tariff_and_services"), "Test tariff with services", "RUB", None) t.update(services=[{"service_id": "m1.small", "price": "12.3456"}]) db.session.commit() tt = Tariff.get_by_id(t.tariff_id) self.assertEqual(len(tt.services), 1) t.update(services=[{"service_id": "m1.small", "price": "23.1"}]) db.session.commit() tt = Tariff.get_by_id(t.tariff_id) self.assertEqual(tt.services_as_dict()["m1.small"].price, Decimal("23.1")) t.update(services=[{"service_id": "m1.micro", "price": "231.333333"}]) db.session.commit() tt = Tariff.get_by_id(t.tariff_id) self.assertEqual(tt.services_as_dict()["m1.micro"].price, Decimal("231.333333")) self.assertEqual(len(tt.services), 1) # m1.small was removed
def test_tariff_update(self): lname = self.localized_name("tariff_update") tariff = Tariff.create_tariff(lname, "Tariff Update", "RUB", None) db.session.commit() tariff.update({"tr": "Tariffo"}) db.session.commit() tariff.update({"en": "Super Tariff"}) tariff.update(description="new description") db.session.commit() t = Tariff.get_by_id(tariff.tariff_id) localizations = {l.language: l for l in t.localized_name} self.assertEqual(localizations["en"].localized_name, "Super Tariff") self.assertEqual(localizations["tr"].localized_name, "Tariffo") self.assertEqual(t.description, "new description")
def test_get(self): with self.expect_error(errors.Unauthorized): self.cabinet_client.get("/lk_api/0/news/", auth_required=False) self.create_news() news_list = self.admin_client.news.list() self.assertEqual(len(news_list['items']), 2) self.assertEqual(news_list['items'][0]['news_id'], 2) news_list = self.admin_client.news.list(visible=False) self.assertEqual(len(news_list['items']), 4) news_list = self.admin_client.news.list(visible=False, published=True) self.assertEqual(len(news_list['items']), 2) # check filtering by creation date hour_ago = utcnow().replace(hours=-1).datetime in_hour = utcnow().replace(hours=+1).datetime filtered_news = self.admin_client.news.list(visible=False, deleted_before=in_hour) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, deleted_before=hour_ago) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, deleted_after=in_hour) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, deleted_after=hour_ago) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, published_before=in_hour) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, published_before=hour_ago) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, published_after=in_hour) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, published_after=hour_ago) self.assertEqual(len(filtered_news['items']), 2) with self.expect_error(errors.BadRequest): self.admin_client.news.list(sort='+published') self.tariff = Tariff.create_tariff(self.localized_name("Tariff for customers"), "tariff!!!", "RUB", None) db.session.commit() password = "******" email = "*****@*****.**" self.cabinet_client.customer.create(email=email, password=password) self.cabinet_client.auth(email, password) self.cabinet_client.get("/lk_api/0/news/")
def get_default(self): """ Get description of default tariff :return dict tariff_info: Returns dict with tariff description. """ tariff = Tariff.get_default().first() if not tariff: raise errors.TariffNotFound() return {"tariff_info": display(tariff)}
def new_customer(cls, email, password, creator_id, detailed_info=None, comment="New customer", withdraw_period=None, make_prod=False, customer_type=None, promo_code=None, locale=None): from model import Tariff, Account, CustomerHistory customer = cls() customer.email = email customer.password = cls.password_hashing(password) if password else "" customer.deleted = None customer.created = utcnow().datetime customer.email_confirmed = False customer.blocked = False customer.customer_mode = cls.CUSTOMER_PRODUCTION_MODE if make_prod else cls.CUSTOMER_TEST_MODE customer.customer_type = customer_type if customer_type else cls.CUSTOMER_TYPE_PRIVATE_PERSON customer.withdraw_period = withdraw_period or conf.customer.default_withdraw_period customer.auto_withdraw_enabled = conf.payments.auto_withdraw_enable customer.auto_withdraw_balance_limit = conf.payments.auto_withdraw_balance_limit customer.auto_withdraw_amount = conf.payments.auto_withdraw_amount customer.locale = locale or conf.customer.default_locale customer.os_dashboard = conf.customer.default_openstack_dashboard default_tariff = Tariff.get_default().first() if not default_tariff: default_tariff = Tariff.query.filter_by(mutable=False).first() or Tariff.query.filter_by().first() if not default_tariff: raise errors.TariffNotFound() customer.tariff_id = default_tariff.tariff_id customer.balance_limit = conf.customer.balance_limits.get(default_tariff.currency, conf.customer.balance_limits.default) db.session.add(customer) db.session.flush() customer.init_subscriptions() template = 'customer' if make_prod else 'test_customer' customer.quota_init(template) customer.accounts.append(Account.create(default_tariff.currency, customer, creator_id, comment)) if promo_code is not None: PromoCode.new_code(promo_code, customer.customer_id) CustomerHistory.new_customer(customer, creator_id, comment) if detailed_info: customer.create_info(customer.customer_type, detailed_info) auto_report_task = ScheduledTask(cls.AUTO_REPORT_TASK, customer.customer_id, customer.withdraw_period) db.session.add(auto_report_task) logbook.info("New customer created: {}", customer) if not make_prod: currency = customer.tariff.currency.upper() initial_balance = conf.customer.test_customer.balance.get(currency) logbook.debug("Initial balance for customer {}: {} {}", customer, initial_balance, currency) if initial_balance: customer.modify_balance(Decimal(initial_balance), currency, None, "Initial test balance") return customer
def new_tariff(self, token, localized_name, description, currency, services=None, parent_id=None, all_parameters=None): """ Create new tariff. Parameters must be sent as json object. :param LocalizedName localized_name: Dict with name localization. en is mandatory key ``{"en": "Name", "ru": "\u0418\u043c\u044f"}`` :param str description: Tariff description :param str currency: Currency code :param TariffId parent_id: Parent tariff id :param list services: List services and its prices **Example of list**:: services: [ { "service_id": "m1.small", "price": "12.23" }, { "service_id": "m1.medium", "price": "21.32" } ] } :return dict tariff_info: Dict as returned by :obj:`GET /0/tariff/\<tariff\>/ <view.GET /0/tariff/\<tariff\>>` """ if parent_id: parent = Tariff.get_by_id(parent_id) if not parent: raise errors.TariffNotFound() if parent.currency != currency: raise errors.ParentTariffCurrency() created = Tariff.create_tariff(**all_parameters) TariffHistory.create(TariffHistory.EVENT_CREATE, token.user_id, created) return {"tariff_info": display(created)}
def test_tariff_history(self): t = Tariff.create_tariff(self.localized_name("tariff_and_services"), "Test tariff with services", "RUB", None) user = User.query.first() TariffHistory.create(TariffHistory.EVENT_CREATE, user.user_id, t) t.update(services=[{"service_id": "m1.small", "price": "12.3456"}]) TariffHistory.create(TariffHistory.EVENT_UPDATE, user.user_id, t) db.session.commit() self.assertEqual(TariffHistory.query.count(), 2) for x in range(10): t.update(services=[{"service_id": "m1.small", "price": "12.3456" + str(x)}]) TariffHistory.create(TariffHistory.EVENT_UPDATE, user.user_id, t) db.session.commit() self.assertEqual(TariffHistory.query.count(), 2)
def setUp(self): super().setUp() self.collector = Collector() self.image_size_price = "12.34" self.volume_size_price = "12.37" self.root_disk_price = "2.91" self.nano_price = "3.47" services = [{"service_id": "storage.image", "price": self.image_size_price}, {"service_id": "storage.volume", "price": self.volume_size_price}, {"service_id": "storage.disk", "price": self.root_disk_price}, {"service_id": self.service_nano_id, "price": self.nano_price} ] self.tariff = Tariff.create_tariff(self.localized_name("Tariff for customers"), "tariff!!!", "rub", services=services) self.tariff.mark_immutable() self.tariff.make_default() self.loop = asyncio.get_event_loop()
def test_tariff_history(self): t = Tariff.create_tariff(self.localized_name("tariff_and_services"), "Test tariff with services", "RUB", None) user = User.query.first() TariffHistory.create(TariffHistory.EVENT_CREATE, user.user_id, t) t.update(services=[{"service_id": "m1.small", "price": "12.3456"}]) TariffHistory.create(TariffHistory.EVENT_UPDATE, user.user_id, t) db.session.commit() self.assertEqual(TariffHistory.query.count(), 2) for x in range(10): t.update(services=[{ "service_id": "m1.small", "price": "12.3456" + str(x) }]) TariffHistory.create(TariffHistory.EVENT_UPDATE, user.user_id, t) db.session.commit() self.assertEqual(TariffHistory.query.count(), 2)
def update_tariff(self, new_tariff_id, user_id, comment=None): from model import Tariff, CustomerHistory from task.customer import change_flavors if self.deleted: raise errors.CustomerRemoved() new_tariff = Tariff.get_by_id(new_tariff_id) if new_tariff.mutable: raise errors.AssignMutableTariff() if new_tariff.deleted: raise errors.RemovedTariff() if self.tariff.currency != new_tariff.currency: # TODO implement logic pass logbook.info("Change tariff from {} to {} for customer {}", self.tariff, new_tariff, self) self.tariff_id = new_tariff_id if self.os_tenant_id: change_flavors.delay(self.os_tenant_id, new_tariff.flavors()) CustomerHistory.tariff_changed(self, user_id, comment)
def test_update_public_flavor_service(self): tariff = self.admin_client.tariff.create(as_json=True, **self.tariff_example("Tariff for update")) self.admin_client.tariff.immutable(tariff["tariff_id"]) tariff = Tariff.get_by_id(tariff["tariff_id"]) tariff.services.append(ServicePrice(self.service_nano_id, 0, True)) db.session.commit() updated = self.admin_client.tariff.update( resource_id=tariff.tariff_id, as_json=True, services=[ {"service_id": str(self.service_nano_id), "price": "11.11"}, {"service_id": str(self.service_medium_id), "price": "100"} ] ) db.session.add(tariff) self.assertEqual(tariff.services_as_dict()[str(self.service_nano_id)].need_changing, False) self.assertEqual(tariff.services_as_dict()[str(self.service_nano_id)].price, Decimal('11.11')) self.assertEqual(tariff.services_as_dict()[str(self.service_medium_id)].price, Decimal('23.45'))
def setUp(self): super().setUp() self.tariff = Tariff.create_tariff(self.localized_name("Tariff for customers"), "tariff!!!", "RUB", None) db.session.commit()
def setUp(self): super().setUp() self.tariff = Tariff.create_tariff( self.localized_name("Tariff for customers"), "tariff!!!", "RUB", None) db.session.commit()
def check_default_tariff(): from model import Tariff return bool(Tariff.get_default().first())
def test_tariff_create(self): lname = self.localized_name("tariff1") Tariff.create_tariff(lname, "tariff!!!", "RUB", None) db.session.commit() with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(lname, "tariff!!!", "RUB", None) db.session.rollback() Tariff.create_tariff({ "en": "tt", "ru": "tt" }, "tariff!!!", "RUB", None) name = lname.copy() name["en"] = "xxxx" with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(name, "tariff!!!", "RUB", None) db.session.rollback() name = lname.copy() name["ru"] = "xxxx" with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(name, "tariff!!!", "RUB", None) db.session.rollback() name["ru"] = lname["en"] name["en"] = lname["ru"] Tariff.create_tariff(name, "tariff!!!", "RUB", None)
def test_get(self): with self.expect_error(errors.Unauthorized): self.cabinet_client.get("/lk_api/0/news/", auth_required=False) self.create_news() news_list = self.admin_client.news.list() self.assertEqual(len(news_list['items']), 2) self.assertEqual(news_list['items'][0]['news_id'], 2) news_list = self.admin_client.news.list(visible=False) self.assertEqual(len(news_list['items']), 4) news_list = self.admin_client.news.list(visible=False, published=True) self.assertEqual(len(news_list['items']), 2) # check filtering by creation date hour_ago = utcnow().replace(hours=-1).datetime in_hour = utcnow().replace(hours=+1).datetime filtered_news = self.admin_client.news.list(visible=False, deleted_before=in_hour) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, deleted_before=hour_ago) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, deleted_after=in_hour) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, deleted_after=hour_ago) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, published_before=in_hour) self.assertEqual(len(filtered_news['items']), 2) filtered_news = self.admin_client.news.list(visible=False, published_before=hour_ago) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, published_after=in_hour) self.assertEqual(len(filtered_news['items']), 0) filtered_news = self.admin_client.news.list(visible=False, published_after=hour_ago) self.assertEqual(len(filtered_news['items']), 2) with self.expect_error(errors.BadRequest): self.admin_client.news.list(sort='+published') self.tariff = Tariff.create_tariff( self.localized_name("Tariff for customers"), "tariff!!!", "RUB", None) db.session.commit() password = "******" email = "*****@*****.**" self.cabinet_client.customer.create(email=email, password=password) self.cabinet_client.auth(email, password) self.cabinet_client.get("/lk_api/0/news/")
def test_tariff_create(self): lname = self.localized_name("tariff1") Tariff.create_tariff(lname, "tariff!!!", "RUB", None) db.session.commit() with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(lname, "tariff!!!", "RUB", None) db.session.rollback() Tariff.create_tariff({"en": "tt", "ru": "tt"}, "tariff!!!", "RUB", None) name = lname.copy() name["en"] = "xxxx" with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(name, "tariff!!!", "RUB", None) db.session.rollback() name = lname.copy() name["ru"] = "xxxx" with self.assertRaises(errors.TariffAlreadyExists): Tariff.create_tariff(name, "tariff!!!", "RUB", None) db.session.rollback() name["ru"] = lname["en"] name["en"] = lname["ru"] Tariff.create_tariff(name, "tariff!!!", "RUB", None)
def fetch_list(self, all_parameters, name=None, description=None, currency=None, deleted_before=None, deleted_after=None, created_before=None, created_after=None, modified_before=None, modified_after=None, parent=_sentinel, visibility=Visibility.DEFAULT, page=1, limit=conf.api.pagination.limit, sort=None, show_used=False): """ Returns paginated filtered tariff list. :param str name: Match tariff name :param str description: Match tariff description :param str currency: Match by currency :param TariffId parent: Match by parent tariff The following values are possible: - Valid tariff id: Returns list of children tariffs; - 0: Returns list of tariffs without parents. :param str visibility: The following values are possible: - visible: returns all not archived tariffs - deleted: returns only archived tariffs - all: returns all tariffs By default "visible" is used :param int page: Page :param int limit: Numbers of items per page. :param bool show_used: include field "used" in the reply which means how many customers are assigned to this tariff :param str or List sort: Sorting field name. Ascending ordering is default. For descending ordering use "-" before. :return list tariff_list: List of tariff info dictionaries (dict as in :obj:`GET /0/tariff/\<tariff\>/ <view.GET /0/tariff/\<tariff\>>`) **Example**:: { "tariff_list": { "items": [ { ... }, { ... } ] "total": 2, "limit": 200, "offset": 0 } } """ all_parameters.pop("show_used", None) query = Tariff.query extract_by_id = False if parent is not _sentinel: if parent: query = query.filter_by(parent_id=parent) else: query = query.filter_by(parent_id=None) if name: query = query.join(Tariff.localized_name).\ filter(TariffLocalization.localized_name.ilike("%{}%".format(name))) extract_by_id = True # noinspection PyUnresolvedReferences all_parameters.setdefault("limit", limit) # noinspection PyUnresolvedReferences all_parameters.setdefault("page", page) query = Tariff.api_filter(all_parameters, exact={"currency"}, query=query, extract_by_id=extract_by_id, visibility=visibility) short_display = [] if show_used else False return {"tariff_list": self.paginated_list(query, short_display=short_display)}