def apply(self): if not self.state.is_VOTING: raise exceptions.ApplyBillInWrongStateError(bill_id=self.id) if not self.approved_by_moderator: raise exceptions.ApplyUnapprovedBillError(bill_id=self.id) if self.time_before_voting_end != datetime.timedelta(seconds=0): raise exceptions.ApplyBillBeforeVoteWasEndedError(bill_id=self.id) self.recalculate_votes() self._model.min_votes_percents_required = bills_settings.MIN_VOTES_PERCENT results_text = u'Итоги голосования: %d «за», %d «против» (итого %.1f%% «за»), %d «воздержалось».' % ( self.votes_for, self.votes_against, round(self.votes_for_percents, 3) * 100, self.votes_refrained) self._model.voting_end_at = datetime.datetime.now() self.applyed_at_turn = TimePrototype.get_current_turn_number() if self.is_percents_barier_not_passed: self.state = BILL_STATE.REJECTED self.save() PostPrototype.create(ThreadPrototype(self._model.forum_thread), get_system_user(), u'Законопроект отклонён.\n\n%s' % results_text, technical=True) signals.bill_processed.send(self.__class__, bill=self) return False self.data.apply(self) self.state = BILL_STATE.ACCEPTED with achievements_storage.verify( type=ACHIEVEMENT_TYPE.POLITICS_ACCEPTED_BILLS, object=self.owner): self.save() PostPrototype.create( ThreadPrototype(self._model.forum_thread), get_system_user(), u'Законопроект принят. Изменения вступят в силу в ближайшее время.\n\n%s' % results_text, technical=True) for actor in self.data.actors: if isinstance(actor, PlacePrototype): actor.stability_modifiers.append( (u'закон №%d' % self.id, -self.type.stability)) logic.initiate_actual_bills_update(self._model.owner_id) signals.bill_processed.send(self.__class__, bill=self) return True
def remove_friendship(cls, initiator, friend): request = cls.get_for_bidirectional(initiator, friend) if request is None: return if request.is_confirmed: MessagePrototype.create( get_system_user(), friend, 'игрок %(account_link)s удалил вас из списка друзей' % { 'account_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose) }) else: MessagePrototype.create( get_system_user(), friend, 'игрок %(account_link)s отказался добавить вас в список друзей' % { 'account_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose) }) request.remove() return
def apply(self): if not self.state.is_VOTING: raise exceptions.ApplyBillInWrongStateError(bill_id=self.id) if not self.approved_by_moderator: raise exceptions.ApplyUnapprovedBillError(bill_id=self.id) if self.time_before_voting_end != datetime.timedelta(seconds=0): raise exceptions.ApplyBillBeforeVoteWasEndedError(bill_id=self.id) self.recalculate_votes() self._model.min_votes_percents_required = bills_settings.MIN_VOTES_PERCENT results_text = 'Итоги голосования: %d «за», %d «против» (итого %.1f%% «за»), %d «воздержалось».' % (self.votes_for, self.votes_against, round(self.votes_for_percents, 3)*100, self.votes_refrained) self._model.voting_end_at = datetime.datetime.now() self.applyed_at_turn = TimePrototype.get_current_turn_number() with transaction.atomic(): if self.is_percents_barier_not_passed: self.state = BILL_STATE.REJECTED self.save() PostPrototype.create(ThreadPrototype(self._model.forum_thread), get_system_user(), 'Законопроект отклонён.\n\n%s' % results_text, technical=True) signals.bill_processed.send(self.__class__, bill=self) return False self.data.apply(self) self.state = BILL_STATE.ACCEPTED with achievements_storage.verify(type=ACHIEVEMENT_TYPE.POLITICS_ACCEPTED_BILLS, object=self.owner): self.save() PostPrototype.create(ThreadPrototype(self._model.forum_thread), get_system_user(), 'Законопроект принят. Изменения вступят в силу в ближайшее время.\n\n%s' % results_text, technical=True) for actor in self.data.actors: if isinstance(actor, places_objects.Place): actor.effects.add(effects.Effect(name='закон №{}'.format(self.id), attribute=places_relations.ATTRIBUTE.STABILITY, value=-self.type.stability)) logic.initiate_actual_bills_update(self._model.owner_id) signals.bill_processed.send(self.__class__, bill=self) return True
def portal_day_started(sender, **kwargs): # pylint: disable=W0613 accounts_query = AccountPrototype.live_query().filter( active_end_at__gt=datetime.datetime.now(), ban_game_end_at__lt=datetime.datetime.now(), ban_forum_end_at__lt=datetime.datetime.now(), premium_end_at__lt=datetime.datetime.now()) accounts_number = accounts_query.count() if accounts_number < 1: return account_model = accounts_query[random.randint(0, accounts_number - 1)] account = AccountPrototype(model=account_model) settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY] = str(account.id) environment.workers.accounts_manager.cmd_run_account_method( account_id=account.id, method_name=AccountPrototype.prolong_premium.__name__, data={'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY}) message = ''' Поздравляем! Ваш герой выбран героем дня и Вы получаете %(days)d дней подписки! ''' % { 'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY } MessagePrototype.create(get_system_user(), account, message)
def update(self, form): Vote.objects.filter(bill_id=self.id).delete() VotePrototype.create(self.owner, self, VOTE_TYPE.FOR) self.data.initialize_with_user_data(form) self._model.updated_at = datetime.datetime.now() self._model.caption = form.c.caption self._model.rationale = form.c.rationale self._model.approved_by_moderator = False self._model.chronicle_on_accepted = form.c.chronicle_on_accepted self.recalculate_votes() self.save() ActorPrototype.update_actors(self, self.data.actors) thread = ThreadPrototype(self._model.forum_thread) thread.caption = form.c.caption thread.save() text = u'[url="%s%s"]Законопроект[/url] был отредактирован, все голоса сброшены.' % ( project_settings.SITE_URL, reverse('game:bills:show', args=[self.id])) PostPrototype.create(thread, get_system_user(), self.bill_info_text(text), technical=True) signals.bill_edited.send(self.__class__, bill=self)
def create(cls, author, caption, text): model = models.Post.objects.create(author=author._model, caption=caption, text=text, state=relations.POST_STATE.ACCEPTED, created_at_turn=game_prototypes.TimePrototype.get_current_turn_number(), votes=1) thread = ForumThreadPrototype.create(ForumSubCategoryPrototype.get_by_uid(conf.settings.FORUM_CATEGORY_UID), caption=caption, author=get_system_user(), text=u'обсуждение [url="%s%s"]произведения[/url]' % (project_settings.SITE_URL, reverse('blogs:posts:show', args=[model.id])), markup_method=MARKUP_METHOD.POSTMARKUP) model.forum_thread = thread._model model.save() post = cls(model) VotePrototype.create(post, author) for tag_id in conf.settings.DEFAULT_TAGS: models.Tagged.objects.create(post_id=post.id, tag_id=tag_id) return post
def setUp(self): super(NewNewsTests, self).setUp() create_test_map() self.account_1 = self.accounts_factory.create_account() self.account_2 = self.accounts_factory.create_account() self.account_3 = self.accounts_factory.create_account() self.news = news_logic.create_news(caption='news-caption', description='news-description', content='news-content') news_logic.send_mails(self.news) self.message = MessagePrototype.get_priority_message() # enshure that system user exists accounts_logic.get_system_user()
def process(self): from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype message = PersonalMessagePrototype.get_by_id(self.message_id) if message is None: return True # message can be removed by admins or with removed thread account = message.recipient if not account.personal_messages_subscription: return True if account.id == get_system_user().id or account.is_bot: return True if not account.email: return True subject = u'«Сказка»: личное сообщение' context = {'message': message} html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context) text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context) return logic.send_mail([account], subject, text_content, html_content)
def process(self): from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype from the_tale.accounts.logic import get_system_user accounts_ids = AccountPrototype.live_query().filter( is_fast=False, created_at__lt=datetime.datetime.now() - accounts_settings.RANDOM_PREMIUM_CREATED_AT_BARRIER, active_end_at__gt=datetime.datetime.now(), premium_end_at__lt=datetime.datetime.now()).exclude( id=self.initiator_id).values_list('id', flat=True) if not accounts_ids: return False account = AccountPrototype.get_by_id(random.choice(accounts_ids)) with transaction.atomic(): account.prolong_premium(self.days) account.save() PersonalMessagePrototype.create(get_system_user(), account, self.MESSAGE % {'days': self.days}) self.receiver_id = account.id self.state = relations.RANDOM_PREMIUM_REQUEST_STATE.PROCESSED self.save() return True
def process(self): from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype from the_tale.accounts.logic import get_system_user accounts_ids = AccountPrototype.live_query().filter(is_fast=False, created_at__lt=datetime.datetime.now() - accounts_settings.RANDOM_PREMIUM_CREATED_AT_BARRIER, active_end_at__gt=datetime.datetime.now(), premium_end_at__lt=datetime.datetime.now()).exclude(id=self.initiator_id).values_list('id', flat=True) if not accounts_ids: return False account = AccountPrototype.get_by_id(random.choice(accounts_ids)) with transaction.atomic(): account.prolong_premium(self.days) account.save() PersonalMessagePrototype.create(get_system_user(), account, self.MESSAGE % {'days': self.days}) self.receiver_id = account.id self.state = relations.RANDOM_PREMIUM_REQUEST_STATE.PROCESSED self.save() return True
def remove_old_messages(cls): cls._db_filter(hide_from_sender=True, hide_from_recipient=True).delete() system_user = get_system_user() cls._db_filter(recipient=system_user.id, created_at__lt=datetime.datetime.now() - conf.settings.SYSTEM_MESSAGES_LEAVE_TIME).delete() cls._db_filter(sender=system_user.id, created_at__lt=datetime.datetime.now() - conf.settings.SYSTEM_MESSAGES_LEAVE_TIME).delete()
def process(self): from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype message = PersonalMessagePrototype.get_by_id(self.message_id) if message is None: return True # message can be removed by admins or with removed thread account = message.recipient if not account.personal_messages_subscription: return True if account.id == get_system_user().id or account.is_bot: return True if not account.email: return True subject = '«Сказка»: личное сообщение' context = {'message': message} html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context) text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context) return logic.send_mail([account], subject, text_content, html_content)
def process(self, main_task, storage=None): # pylint: disable=R0911 if self.step.is_UNPROCESSED: account = accounts_prototypes.AccountPrototype.get_by_id(self.account_id) system_user = accounts_logic.get_system_user() if account.is_ban_forum: main_task.comment = 'account is banned' self.state = self.STATE.BANNED return POSTPONED_TASK_LOGIC_RESULT.ERROR accounts = accounts_prototypes.AccountPrototype.get_list_by_id(self.recipients) for recipient in accounts: if recipient.id == system_user.id: main_task.comment = 'system user' self.state = self.STATE.SYSTEM_USER return POSTPONED_TASK_LOGIC_RESULT.ERROR if recipient.is_fast: main_task.comment = 'fast user' self.state = self.STATE.FAST_USER return POSTPONED_TASK_LOGIC_RESULT.ERROR for recipient in accounts_prototypes.AccountPrototype.get_list_by_id(self.recipients): prototypes.MessagePrototype.create(account, recipient, self.message) self.step = self.STEP.PROCESSED return POSTPONED_TASK_LOGIC_RESULT.SUCCESS
def _confirm(self): MessagePrototype.create(get_system_user(), self.friend_1, u'игрок %(account_link)s подтвердил, что вы являетесь друзьями' % {'account_link': u'[url=%s]%s[/url]' % (full_url('http', 'accounts:show', self.friend_2.id), self.friend_2.nick_verbose)}) self._model.is_confirmed = True self.save()
def create(cls, owner, caption, rationale, bill, chronicle_on_accepted): model = Bill.objects.create(owner=owner._model, type=bill.type, caption=caption, rationale=rationale, created_at_turn=TimePrototype.get_current_turn_number(), technical_data=s11n.to_json(bill.serialize()), state=BILL_STATE.VOTING, chronicle_on_accepted=chronicle_on_accepted, votes_for=1) # author always wote for bill bill_prototype = cls(model) text = u'Обсуждение [url="%s%s"]закона[/url]' % (project_settings.SITE_URL, reverse('game:bills:show', args=[model.id]) ) thread = ThreadPrototype.create(SubCategoryPrototype.get_by_uid(bills_settings.FORUM_CATEGORY_UID), caption=caption, author=get_system_user(), text=bill_prototype.bill_info_text(text), technical=True, markup_method=MARKUP_METHOD.POSTMARKUP) model.forum_thread = thread._model model.save() ActorPrototype.update_actors(bill_prototype, bill_prototype.data.actors) VotePrototype.create(owner, bill_prototype, VOTE_TYPE.FOR) signals.bill_created.send(sender=cls, bill=bill_prototype) return bill_prototype
def portal_day_started(sender, **kwargs): # pylint: disable=W0613 accounts_query = AccountPrototype.live_query().filter(active_end_at__gt=datetime.datetime.now(), ban_game_end_at__lt=datetime.datetime.now(), ban_forum_end_at__lt=datetime.datetime.now(), premium_end_at__lt=datetime.datetime.now()) accounts_number = accounts_query.count() if accounts_number < 1: return account_model = accounts_query[random.randint(0, accounts_number-1)] account = AccountPrototype(model=account_model) settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY] = str(account.id) environment.workers.accounts_manager.cmd_run_account_method(account_id=account.id, method_name=AccountPrototype.prolong_premium.__name__, data={'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY}) message = u''' Поздравляем! Ваш герой выбран героем дня и Вы получаете %(days)d дней подписки! ''' % {'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY} MessagePrototype.create(get_system_user(), account, message)
def test_day_started_signal(self): self.assertFalse( portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY in settings) self.assertEqual(MessagePrototype._db_count(), 0) with mock.patch( 'the_tale.accounts.workers.accounts_manager.Worker.cmd_run_account_method' ) as cmd_run_account_method: portal_signals.day_started.send(self.__class__) self.assertEqual(cmd_run_account_method.call_count, 1) self.assertEqual( cmd_run_account_method.call_args, mock.call(account_id=self.account.id, method_name='prolong_premium', data={ 'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY })) self.assertEqual( int(settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY]), self.account.id) self.assertEqual(MessagePrototype._db_count(), 1) message = MessagePrototype._db_get_object(0) self.assertEqual(message.sender_id, get_system_user().id) self.assertEqual(message.recipient_id, self.account.id)
def process(self): from the_tale.accounts.personal_messages import tt_api as pm_tt_api message = pm_tt_api.get_message(self.account_id, message_id=self.message_id) if message is None: return True # message can be removed by admins or with removed thread account = AccountPrototype.get_by_id(self.account_id) if not account.personal_messages_subscription: return True if account.id == get_system_user().id or account.is_bot: return True if not account.email: return True subject = '«Сказка»: личное сообщение' context = {'message': message, 'sender': AccountPrototype.get_by_id(message.sender_id)} html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context) text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context) return logic.send_mail([account], subject, text_content, html_content)
def create(cls, author, caption, text): model = models.Post.objects.create(author=author._model, caption=caption, text=text, state=relations.POST_STATE.ACCEPTED, created_at_turn=turn.number(), votes=1) thread = ForumThreadPrototype.create( ForumSubCategoryPrototype.get_by_uid( conf.settings.FORUM_CATEGORY_UID), caption=caption, author=get_system_user(), text='обсуждение [url="%s%s"]произведения[/url]' % (project_settings.SITE_URL, reverse('blogs:posts:show', args=[model.id])), markup_method=MARKUP_METHOD.POSTMARKUP) model.forum_thread = thread._model model.save() post = cls(model) VotePrototype.create(post, author) for tag_id in conf.settings.DEFAULT_TAGS: models.Tagged.objects.create(post_id=post.id, tag_id=tag_id) return post
def update(self, form): Vote.objects.filter(bill_id=self.id).delete() VotePrototype.create(self.owner, self, VOTE_TYPE.FOR) self._initialize_with_form(form) self.recalculate_votes() self.save() ActorPrototype.update_actors(self, self.actors) thread = ThreadPrototype(self._model.forum_thread) thread.caption = form.c.caption thread.save() text = '[url="%s%s"]Запись[/url] была отредактирована, все голоса сброшены.' % ( project_settings.SITE_URL, reverse('game:bills:show', args=[self.id])) PostPrototype.create(thread, get_system_user(), self.bill_info_text(text), technical=True) signals.bill_edited.send(self.__class__, bill=self)
def test_mail_send__to_system_user(self): from the_tale.accounts.logic import get_system_user task, message = self.create_task_and_message(get_system_user(), 'user_1_new') self.assertEqual(len(mail.outbox), 0) message.process() self.assertTrue(message.state.is_PROCESSED) self.assertEqual(len(mail.outbox), 0)
def test_wait__successed(self): self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) transfer_invoice = self.task.transfer_transaction.get_invoice() transfer_invoice.state = bank_relations.INVOICE_STATE.FROZEN transfer_invoice.save() commission_invoice = self.task.commission_transaction.get_invoice() commission_invoice.state = bank_relations.INVOICE_STATE.FROZEN commission_invoice.save() with self.check_delta( personal_messages_prototypes.MessagePrototype._db_count, 1): self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.SUCCESS) self.assertTrue(self.task.step.is_SUCCESS) self.assertTrue(self.task.state.is_PROCESSED) message = personal_messages_prototypes.MessagePrototype._db_latest() self.assertEqual(message.sender_id, logic.get_system_user().id) self.assertEqual(message.recipient_id, self.recipient.id) self.assertIn(u'some comment string', message.text)
def test_remove_old_messages__system_user(self): system_user = get_system_user() messages = [ MessagePrototype.create(self.account1, self.account2, 'message 1'), MessagePrototype.create(system_user, self.account2, 'message 2'), MessagePrototype.create(self.account1, system_user, 'message 3'), MessagePrototype.create(system_user, system_user, 'message 4'), MessagePrototype.create(self.account1, self.account2, 'message 5'), MessagePrototype.create(system_user, self.account2, 'message 6'), MessagePrototype.create(self.account1, system_user, 'message 7'), MessagePrototype.create(system_user, system_user, 'message 8') ] for message in messages[-4:]: message._model.created_at = datetime.datetime.now( ) - conf.settings.SYSTEM_MESSAGES_LEAVE_TIME message.save() with self.check_delta(MessagePrototype._db_count, -3): MessagePrototype.remove_old_messages() for message in messages[:5]: self.assertNotEqual(MessagePrototype.get_by_id(message.id), None)
def update(self, form): Vote.objects.filter(bill_id=self.id).delete() VotePrototype.create(self.owner, self, VOTE_TYPE.FOR) self.data.initialize_with_user_data(form) self._model.updated_at = datetime.datetime.now() self._model.caption = form.c.caption self._model.rationale = form.c.rationale self._model.approved_by_moderator = False self._model.chronicle_on_accepted = form.c.chronicle_on_accepted self.recalculate_votes() self.save() ActorPrototype.update_actors(self, self.data.actors) thread = ThreadPrototype(self._model.forum_thread) thread.caption = form.c.caption thread.save() text = u'[url="%s%s"]Законопроект[/url] был отредактирован, все голоса сброшены.' % (project_settings.SITE_URL, reverse('game:bills:show', args=[self.id]) ) PostPrototype.create(thread, get_system_user(), self.bill_info_text(text), technical=True) signals.bill_edited.send(self.__class__, bill=self)
def test_close_lot(self): self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) self.assertEqual( self.task.process(self.main_task, storage=self.logic_storage), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) with self.check_delta( personal_messages_prototypes.MessagePrototype._db_count, 1): self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.SUCCESS) self.assertTrue(self.task.state.is_PROCESSED) self.assertTrue(self.task.step.is_SUCCESS) lot = logic.load_lot(self.task.lot_id) self.assertTrue(lot.state.is_CLOSED_BY_TIMEOUT) self.assertTrue(lot.closed_at < datetime.datetime.now()) self.assertEqual(lot.buyer_id, None) personal_message = personal_messages_prototypes.MessagePrototype._db_all( ).latest() self.assertEqual(personal_message.recipient_id, self.account_1.id) self.assertEqual(personal_message.sender_id, accounts_logic.get_system_user().id)
def request_dialog(self, friend): if friend.id == get_system_user().id: return self.auto_error('friends.request_dialog.system_user', u'Вы не можете пригласить в друзья системного пользователя') return self.template('friends/request_dialog.html', {'friend': friend, 'form': RequestForm()})
def request_dialog(self, friend): if friend.id == get_system_user().id: return self.auto_error( "friends.request_dialog.system_user", "Вы не можете пригласить в друзья системного пользователя" ) return self.template("friends/request_dialog.html", {"friend": friend, "form": RequestForm()})
def test_mail_send__to_system_user(self): from the_tale.accounts.logic import get_system_user SubscriptionPrototype.create(get_system_user(), self.thread) self.assertEqual(len(mail.outbox), 0) self.message.process() self.assertTrue(self.message.state.is_PROCESSED) self.assertEqual(len(mail.outbox), 0)
def test_mail_send__to_system_user(self): from the_tale.accounts.logic import get_system_user SubscriptionPrototype.create(get_system_user(), subcategory=self.subcategory) self.assertEqual(len(mail.outbox), 0) self.message.process() self.assertTrue(self.message.state.is_PROCESSED) self.assertEqual(len(mail.outbox), 0)
def process(self, main_task, storage=None): # pylint: disable=R0911 if self.step.is_FREEZE_LOT: lot = logic.load_lot(self.lot_id) if not lot.state.is_ACTIVE: main_task.comment = 'lot is not active, real state is: %s' % lot.state.name self.state = self.STATE.WRONG_LOT_STATE return POSTPONED_TASK_LOGIC_RESULT.ERROR self.account_id = lot.seller_id self.good_type = goods_types.get_type(lot.type) self.good = lot.good lot.state = relations.LOT_STATE.FROZEN logic.save_lot(lot) main_task.extend_postsave_actions( (lambda: environment.workers.supervisor.cmd_logic_task( self.account_id, main_task.id), )) self.step = self.STEP.RETURN_GOOD return POSTPONED_TASK_LOGIC_RESULT.CONTINUE if self.step.is_RETURN_GOOD: hero = storage.accounts_to_heroes[self.account_id] # TODO: save hero after receive item? and after extract too?... self.good_type.insert_good(hero, self.good) storage.save_bundle_data(hero.actions.current_action.bundle_id) main_task.extend_postsave_actions( (lambda: environment.workers.market_manager.cmd_logic_task( self.account_id, main_task.id), )) self.step = self.STEP.CLOSE_LOT return POSTPONED_TASK_LOGIC_RESULT.CONTINUE if self.step.is_CLOSE_LOT: lot = logic.load_lot(self.lot_id) lot.state = relations.LOT_STATE.CLOSED_BY_TIMEOUT lot.closed_at = datetime.datetime.now() logic.save_lot(lot) seller = account_prototypes.AccountPrototype.get_by_id( lot.seller_id) personal_messages_prototypes.MessagePrototype.create( accounts_logic.get_system_user(), seller, good_timeout_message(lot)) self.state = self.STATE.PROCESSED self.step = self.STEP.SUCCESS return POSTPONED_TASK_LOGIC_RESULT.SUCCESS
def remove_friendship(cls, initiator, friend): request = cls.get_for_bidirectional(initiator, friend) if request is None: return if request.is_confirmed: MessagePrototype.create(get_system_user(), friend, u'игрок %(account_link)s удалил вас из списка друзей' % {'account_link': u'[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose)}) else: MessagePrototype.create(get_system_user(), friend, u'игрок %(account_link)s отказался добавить вас в список друзей' % {'account_link': u'[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose)}) request.remove() return
def test_sent_to_system_user(self): self.check_ajax_error( self.post_ajax_json( url('accounts:messages:create'), { 'text': 'test-message', 'recipients': ('%d,%d' % (self.account2.id, get_system_user().id)) }), 'system_user') self.assertEqual(Message.objects.all().count(), 0)
def increment_level(self, send_message=False): self.level += 1 self.add_message('hero_common_journal_level_up', hero=self, level=self.level) self.force_save_required = True if send_message: # TODO: move out logic account = accounts_prototypes.AccountPrototype.get_by_id(self.account_id) message_prototypes.MessagePrototype.create(accounts_logic.get_system_user(), account, text=u'Поздравляем, Ваш герой получил %d уровень!' % self.level)
def test_add_achievement__notify(self): with self.check_delta(GiveItemTaskPrototype._db_count, 2): with self.check_delta(MessagePrototype._db_count, 1): self.account_achievements_1.add_achievement(self.achievement_1, notify=True) message = MessagePrototype._db_get_object(0) self.assertEqual(message.sender_id, get_system_user().id) self.assertEqual(message.recipient_id, self.account_1.id) self.assertTrue((url('accounts:achievements:group', self.achievement_1.group.slug) + ('#a%d' % self.achievement_1.id)) in message.text)
def increment_level(self, send_message=False): self.level += 1 self.add_message('hero_common_journal_level_up', hero=self, level=self.level) self.force_save_required = True if send_message: # TODO: move out logic account = accounts_prototypes.AccountPrototype.get_by_id(self.account_id) message_prototypes.MessagePrototype.create(accounts_logic.get_system_user(), account, text='Поздравляем, Ваш герой получил %d уровень!' % self.level)
def _confirm(self): MessagePrototype.create( get_system_user(), self.friend_1, 'игрок %(account_link)s подтвердил, что вы являетесь друзьями' % { 'account_link': '[url=%s]%s[/url]' % (full_url('http', 'accounts:show', self.friend_2.id), self.friend_2.nick_verbose) }) self._model.is_confirmed = True self.save()
def check_recipients(recipients_form): system_user = accounts_logic.get_system_user() if system_user.id in recipients_form.c.recipients: raise dext_views.ViewError(code='system_user', message='Нельзя отправить сообщение системному пользователю') if accounts_models.Account.objects.filter(is_fast=True, id__in=recipients_form.c.recipients).exists(): raise dext_views.ViewError(code='fast_account', message='Нельзя отправить сообщение пользователю, не завершившему регистрацию') if accounts_models.Account.objects.filter(id__in=recipients_form.c.recipients).count() != len(recipients_form.c.recipients): raise dext_views.ViewError(code='unexisted_account', message='Вы пытаетесь отправить сообщение несуществующему пользователю')
def request_dialog(self, friend): if friend.id == get_system_user().id: return self.auto_error( 'friends.request_dialog.system_user', u'Вы не можете пригласить в друзья системного пользователя') return self.template('friends/request_dialog.html', { 'friend': friend, 'form': RequestForm() })
def check_recipients(recipients_form): system_user = accounts_logic.get_system_user() if system_user.id in recipients_form.c.recipients: raise dext_views.ViewError(code='system_user', message=u'Нельзя отправить сообщение системному пользователю') if accounts_models.Account.objects.filter(is_fast=True, id__in=recipients_form.c.recipients).exists(): raise dext_views.ViewError(code='fast_account', message=u'Нельзя отправить сообщение пользователю, не завершившему регистрацию') if accounts_models.Account.objects.filter(id__in=recipients_form.c.recipients).count() != len(recipients_form.c.recipients): raise dext_views.ViewError(code='unexisted_account', message=u'Вы пытаетесь отправить сообщение несуществующему пользователю')
def remove(self, initiator): self.set_remove_initiator(initiator) self.state = BILL_STATE.REMOVED self.save() thread = ThreadPrototype(self._model.forum_thread) thread.caption = thread.caption + u" [удалён]" thread.save() PostPrototype.create(thread, get_system_user(), u"Законопроект был удалён", technical=True) signals.bill_removed.send(self.__class__, bill=self)
def test_mail_send__to_system_user(self): from the_tale.accounts.logic import get_system_user Message.objects.all().delete() ResetPasswordTaskPrototype.create(get_system_user()) message = MessagePrototype.get_priority_message() self.assertEqual(len(mail.outbox), 0) message.process() self.assertTrue(message.state.is_PROCESSED) self.assertEqual(len(mail.outbox), 0)
def test_sent_to_system_user(self): self.check_ajax_error( self.post_ajax_json( url('accounts:messages:create'), { 'text': 'test-message', 'recipients': ('%d,%d' % (self.account_2.id, get_system_user().id)) }), 'system_user') total, messages = tt_api.get_sent_messages(self.account_1.id) self.assertEqual(total, 0)
def test_add_achievement__notify(self): with self.check_delta(GiveItemTaskPrototype._db_count, 2): with self.check_delta(MessagePrototype._db_count, 1): self.account_achievements_1.add_achievement(self.achievement_1, notify=True) message = MessagePrototype._db_get_object(0) self.assertEqual(message.sender_id, get_system_user().id) self.assertEqual(message.recipient_id, self.account_1.id) self.assertTrue(( url('accounts:achievements:group', self.achievement_1.group.slug) + ('#a%d' % self.achievement_1.id)) in message.text)
def test_remove_lot(self): self.invoice.state = bank_relations.INVOICE_STATE.FROZEN self.invoice.save() self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) self.assertEqual( self.task.process(self.main_task, storage=self.logic_storage), POSTPONED_TASK_LOGIC_RESULT.CONTINUE) with mock.patch( 'the_tale.finances.bank.transaction.Transaction.confirm' ) as confirm: with self.check_delta( bank_prototypes.InvoicePrototype._model_class.objects. count, 1): with self.check_delta( personal_messages_prototypes.MessagePrototype. _db_count, 1): self.assertEqual(self.task.process(self.main_task), POSTPONED_TASK_LOGIC_RESULT.SUCCESS) self.assertEqual(confirm.call_count, 1) self.assertTrue(self.task.state.is_PROCESSED) self.assertTrue(self.task.step.is_SUCCESS) lot = logic.load_lot(self.task.lot_id) self.assertTrue(lot.state.is_CLOSED_BY_BUYER) self.assertTrue(lot.closed_at < datetime.datetime.now()) self.assertEqual(lot.buyer_id, self.account_2.id) personal_message = personal_messages_prototypes.MessagePrototype._db_all( ).latest() self.assertEqual(personal_message.recipient_id, self.account_1.id) self.assertEqual(personal_message.sender_id, accounts_logic.get_system_user().id) commission_ivoice = bank_prototypes.InvoicePrototype._db_latest() self.assertTrue(commission_ivoice.recipient_type.is_GAME_ACCOUNT) self.assertEqual(commission_ivoice.recipient_id, lot.seller_id) self.assertTrue(commission_ivoice.sender_type.is_GAME_LOGIC) self.assertEqual(commission_ivoice.sender_id, 0) self.assertTrue(commission_ivoice.currency.is_PREMIUM) self.assertEqual(commission_ivoice.amount, -lot.commission) self.assertEqual(commission_ivoice.operation_uid, u'market-buy-commission-%s' % lot.type) self.assertTrue(commission_ivoice.state.is_FORCED)
def decline(self, moderator): self.state = relations.POST_STATE.DECLINED self.moderator_id = moderator.id self.save() thread = ForumThreadPrototype(self._model.forum_thread) thread.caption = thread.caption + u' [удалён]' thread.save() ForumPostPrototype.create(thread, get_system_user(), u'Произведение было удалено', technical=True)
def increment_level(self, send_message=False): from the_tale.accounts.prototypes import AccountPrototype from the_tale.accounts.personal_messages.prototypes import MessagePrototype from the_tale.accounts.logic import get_system_user self._model.level += 1 self.add_message('hero_common_journal_level_up', hero=self, level=self.level) self.force_save_required = True if send_message: account = AccountPrototype.get_by_id(self.account_id) MessagePrototype.create(get_system_user(), account, text=u'Поздравляем, Ваш герой получил %d уровень!' % self.level)
def process(self, main_task, storage=None): # pylint: disable=R0911 if self.step.is_FREEZE_LOT: lot = logic.load_lot(self.lot_id) if not lot.state.is_ACTIVE: main_task.comment = 'lot is not active, real state is: %s' % lot.state.name self.state = self.STATE.WRONG_LOT_STATE return POSTPONED_TASK_LOGIC_RESULT.ERROR self.account_id = lot.seller_id self.good_type = goods_types.get_type(lot.type) self.good = lot.good lot.state = relations.LOT_STATE.FROZEN logic.save_lot(lot) main_task.extend_postsave_actions((lambda: environment.workers.supervisor.cmd_logic_task(self.account_id, main_task.id),)) self.step = self.STEP.RETURN_GOOD return POSTPONED_TASK_LOGIC_RESULT.CONTINUE if self.step.is_RETURN_GOOD: hero = storage.accounts_to_heroes[self.account_id] # TODO: save hero after receive item? and after extract too?... self.good_type.insert_good(hero, self.good) storage.save_bundle_data(hero.actions.current_action.bundle_id) main_task.extend_postsave_actions((lambda: environment.workers.market_manager.cmd_logic_task(self.account_id, main_task.id),)) self.step = self.STEP.CLOSE_LOT return POSTPONED_TASK_LOGIC_RESULT.CONTINUE if self.step.is_CLOSE_LOT: lot = logic.load_lot(self.lot_id) lot.state = relations.LOT_STATE.CLOSED_BY_TIMEOUT lot.closed_at = datetime.datetime.now() logic.save_lot(lot) seller = account_prototypes.AccountPrototype.get_by_id(lot.seller_id) personal_messages_prototypes.MessagePrototype.create(accounts_logic.get_system_user(), seller, good_timeout_message(lot)) self.state = self.STATE.PROCESSED self.step = self.STEP.SUCCESS return POSTPONED_TASK_LOGIC_RESULT.SUCCESS
def notify_about_premium_expiration(self): from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype from the_tale.accounts.logic import get_system_user current_time = datetime.datetime.now() message = u''' До окончания подписки осталось: %(verbose_timedelta)s. Вы можете продлить подписку на странице нашего %(shop_link)s. ''' % {'verbose_timedelta': verbose_timedelta(self.premium_end_at - current_time), 'shop_link': u'[url="%s"]магазина[/url]' % full_url('http', 'shop:shop')} PersonalMessagePrototype.create(get_system_user(), self, message)
def recalculate(cls): RatingValues.objects.all().delete() cursor = connection.cursor() sql_request = ''' INSERT INTO %(ratings)s (account_id, might, bills_count, magic_power, physic_power, level, phrases_count, pvp_battles_1x1_number, pvp_battles_1x1_victories, referrals_number, achievements_points, help_count, gifts_returned, politics_power) SELECT %(accounts)s.id AS account_id, %(heroes)s.might AS might, CASE WHEN raw_bills_count IS NULL THEN 0 ELSE raw_bills_count END AS bills_count, %(heroes)s.raw_power_magic AS magic_power, %(heroes)s.raw_power_physic AS physic_power, %(heroes)s.level AS level, CASE WHEN raw_phrases_count IS NULL THEN 0 ELSE raw_phrases_count END AS phrases_count, %(heroes)s.stat_pvp_battles_1x1_number AS pvp_battles_1x1_number, CASE WHEN %(heroes)s.stat_pvp_battles_1x1_number < %(min_pvp_battles)s THEN 0 ELSE CAST(%(heroes)s.stat_pvp_battles_1x1_victories AS FLOAT) / %(heroes)s.stat_pvp_battles_1x1_number END AS pvp_battles_1x1_victories, %(accounts)s.referrals_number as referrals_number, %(achievements)s.points as achievements_points, %(heroes)s.stat_help_count as help_count, %(heroes)s.stat_gifts_returned as gifts_returned, %(heroes)s.stat_politics_multiplier as politics_power FROM %(accounts)s JOIN %(heroes)s ON %(accounts)s.id=%(heroes)s.account_id JOIN %(achievements)s ON %(accounts)s.id=%(achievements)s.account_id LEFT OUTER JOIN ( SELECT %(bills)s.owner_id AS bills_owner_id, COUNT(%(bills)s.owner_id) AS raw_bills_count FROM %(bills)s WHERE %(bills)s.state=%(bill_accepted_state)s GROUP BY %(bills)s.owner_id ) AS bills_subquery ON %(accounts)s.id=bills_owner_id LEFT OUTER JOIN ( SELECT %(phrase_candidates)s.account_id AS phrase_author_id, COUNT(%(phrase_candidates)s.account_id) AS raw_phrases_count FROM %(phrase_candidates)s WHERE %(phrase_candidates)s.type=%(phrase_candidate_type)s GROUP BY %(phrase_candidates)s.account_id ) AS phrases_subquery ON %(accounts)s.id=phrase_author_id WHERE NOT %(accounts)s.is_fast AND NOT %(accounts)s.is_bot AND %(accounts)s.id <> %(system_user_id)s AND %(accounts)s.ban_game_end_at < current_timestamp ''' sql_request = sql_request % {'ratings': RatingValues._meta.db_table, 'accounts': Account._meta.db_table, 'achievements': AccountAchievements._meta.db_table, 'heroes': Hero._meta.db_table, 'bills': bill_models.Bill._meta.db_table, 'bill_accepted_state': bill_relations.BILL_STATE.ACCEPTED.value, 'phrase_candidates': ContributionPrototype._model_class._meta.db_table, 'phrase_candidate_type': CONTRIBUTION_TYPE.TEMPLATE.value, 'min_pvp_battles': heroes_settings.MIN_PVP_BATTLES, 'system_user_id': get_system_user().id} cursor.execute(sql_request)
def process(self): account = AccountPrototype.get_by_id(self.account_id) if account.id == get_system_user().id or account.is_bot: return True subject = '«Сказка»: сброс пароля' context = {'account': account, 'task_uuid': self.task_uuid} html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context) text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context) return logic.send_mail([account], subject, text_content, html_content)
def request_friendship(self, friend): if friend.is_fast: return self.json_error('friends.request_friendship.fast_friend', u'Вы не можете пригласить в друзья игрока не завершившего регистрацию') if friend.id == get_system_user().id: return self.json_error('friends.request_friendship.system_user', u'Вы не можете пригласить в друзья системного пользователя') form = RequestForm(self.request.POST) if not form.is_valid(): return self.json_error('friends.request_friendship.form_errors', form.errors) FriendshipPrototype.request_friendship(self.account, friend, text=form.c.text) return self.json_ok()
def process(self): subject = '«Сказка»: подтвердите email' task = ChangeCredentialsTaskPrototype.get_by_id(self.task_id) if task.account.id == get_system_user().id or task.account.is_bot: return True context = {'task': task} html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context) text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context) return logic.send_mail([(task.account, task.new_email)], subject, text_content, html_content)
def test_process__has_active_accounts(self): AccountPrototype._db_all().update(active_end_at=datetime.datetime.now() + datetime.timedelta(days=1)) self.request.process() self.assertEqual(MessagePrototype._db_count(), 1) message = MessagePrototype._db_get_object(0) self.assertEqual(message.recipient_id, self.account_2.id) self.assertEqual(message.sender_id, get_system_user().id) self.assertEqual(list(AccountPrototype._db_filter(premium_end_at__gt=datetime.datetime.now()).values_list('id', flat=True)), [self.account_2.id]) self.request.reload() self.assertTrue(self.request.state.is_PROCESSED) self.assertEqual(self.request.receiver_id, self.account_2.id)