# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
# 
#     URL_METHODS = Choices(
#         ('POST', 'POST'),
#         ('GET',  'GET'),
#     )
# 
#     user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
#     name = models.CharField('Имя', max_length=255)
#     secret_key = models.CharField(_('secret key'), max_length=50)
# 
#     result_url = models.URLField(_('result url'))
#     result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
# 
#     success_url = models.URLField(_('success url'))
#     fail_url = models.URLField(_('fail url'))
# 
#     class Meta:
#         verbose_name = 'продавец'
#         verbose_name_plural = 'продавцы'
#         db_table = 'payway_merchants'
# 
# Path: payway/orders/models.py
# class Order(TimeStampedModel):
#     PAYMENT_STATUS = Choices(
#         (False, 'NOT_PAID', _('not paid')),
#         (True,  'PAID', _('paid')),
#     )
#     user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
#     merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant'))
#     uid = models.PositiveIntegerField(unique=False, editable=False)
#     sum = fields.MoneyField(_('sum'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
#     account = models.ForeignKey(Account, related_name='orders', verbose_name=_('account'))
#     description = models.CharField(_('description'), max_length=255, blank=True)
#     is_paid = models.BooleanField(_('payment status'), default=False, choices=PAYMENT_STATUS)
#     objects = ChainableQuerySetManager(ExtendedQuerySet)
# 
#     class Meta:
#         verbose_name = _('order')
#         verbose_name_plural = _('orders')
#         db_table = 'payway_orders'
# 
#     def __init__(self, *args, **kwargs):
#         account = kwargs.get('account') or None
#         if account:
#             kwargs.setdefault('user', account.user)
#         super(Order, self).__init__(*args, **kwargs)
# 
#     def set_paid(self, is_paid=False):
#         self.is_paid = is_paid
# 
#     def __unicode__(self):
#         return 'Order {0}'.format(self.uid)
# 
# Path: payway/orders/tests/mocks.py
# def mock_MerchantHttpClient_success_execute():
# def mock_MerchantHttpClient_fail_execute():
# def set_back_MerchantHttpClient_execute():
#     class ResponseMock(object):
# 
# Path: payway/utils/tests/base.py
# class BaseViewTestCase(AuthorizedViewTestCase):
# 
#     _url = ''
# 
#     def create_new_user_with_account(self):
#         password = 'abc123'
#         self.user = User.objects.create_user(
#             'user',
#             'user@example.com',
#             password,
#         )
#         self.account = self.user.accounts.create(user=self.user, currency='RUB')
#         self.account.add(Money(20, self.account.currency))
#         self.client_login(username=self.user.username, password=password)
# 
#     def assert_url_available(self):
#         response = self.client.get(self._url)
#         self.failUnlessEqual(response.status_code, 200)
# 
#     def assert_redirects(self, expected_url):
#         response = self.client.get(self._url)
#         self.assertRedirects(response, expected_url)
# 
#     def assert_has_message(self, response, message, level):
#         messages_list = CookieStorage(response)._decode(response.cookies['messages'].value)
#         self.assertIn(Message(level, message), messages_list)


from django.core.urlresolvers import reverse
from moneyed.classes import Money
from payway.merchants.models import Merchant
from payway.orders.models import Order
from payway.orders.tests import mocks
from payway.utils.tests.base import BaseViewTestCase

    def test_order_exists(self):
        self.GET['uid'] = 1
        response = self.client.get(reverse('orders_payment'), self.GET)
        self.failUnlessEqual(response.status_code, 200)
        self.assertContainsTextItems(response, self.GET.values() + ['Order is paid'])

    def test_success_order_payment(self):
        mocks.mock_MerchantHttpClient_success_execute()

        initial_balance = self.account.get_balance()
        merchant_init_balance = self.merchant_account.get_balance()

        response = self.client.post(reverse('orders_payment'), self.POST)

        self.failUnlessEqual(response.status_code, 200)
        self.assertContainsTextItems(response, self.POST.values() + [dict(Order.PAYMENT_STATUS).get(Order.PAYMENT_STATUS.PAID)])
        self.assertTrue(Order.objects.get(uid=self.order.uid).is_paid)
        self.assert_balance_decreased(initial_balance)

        # merchant balance should be increased
        self.assertEquals(merchant_init_balance + self.order.sum, self.merchant_account.get_balance())

        # test if already paid
        initial_balance = self.account.get_balance()
        response = self.client.post(reverse('orders_payment'), self.POST)

        self.assertContainsTextItems(response, self.POST.values() + [dict(Order.PAYMENT_STATUS).get(Order.PAYMENT_STATUS.PAID)])
        self.assert_balance_should_be_same(initial_balance)


# Path: payway/merchants/models.py
# class Merchant(RandomUIDAbstractModel):
# 
#     URL_METHODS = Choices(
#         ('POST', 'POST'),
#         ('GET',  'GET'),
#     )
# 
#     user = models.ForeignKey(User, related_name='merchants', verbose_name=_('user'))
#     name = models.CharField('Имя', max_length=255)
#     secret_key = models.CharField(_('secret key'), max_length=50)
# 
#     result_url = models.URLField(_('result url'))
#     result_url_method = models.CharField(_('result url method'), max_length=4, choices=URL_METHODS)
# 
#     success_url = models.URLField(_('success url'))
#     fail_url = models.URLField(_('fail url'))
# 
#     class Meta:
#         verbose_name = 'продавец'
#         verbose_name_plural = 'продавцы'
#         db_table = 'payway_merchants'
# 
# Path: payway/orders/models.py
# class Order(TimeStampedModel):
#     PAYMENT_STATUS = Choices(
#         (False, 'NOT_PAID', _('not paid')),
#         (True,  'PAID', _('paid')),
#     )
#     user = models.ForeignKey(User, related_name='orders', verbose_name=_('user'))
#     merchant = models.ForeignKey(Merchant, related_name='orders', verbose_name=_('merchant'))
#     uid = models.PositiveIntegerField(unique=False, editable=False)
#     sum = fields.MoneyField(_('sum'), max_digits=MAX_MONEY_DIGITS, decimal_places=MAX_MONEY_PLACES)
#     account = models.ForeignKey(Account, related_name='orders', verbose_name=_('account'))
#     description = models.CharField(_('description'), max_length=255, blank=True)
#     is_paid = models.BooleanField(_('payment status'), default=False, choices=PAYMENT_STATUS)
#     objects = ChainableQuerySetManager(ExtendedQuerySet)
# 
#     class Meta:
#         verbose_name = _('order')
#         verbose_name_plural = _('orders')
#         db_table = 'payway_orders'
# 
#     def __init__(self, *args, **kwargs):
#         account = kwargs.get('account') or None
#         if account:
#             kwargs.setdefault('user', account.user)
#         super(Order, self).__init__(*args, **kwargs)
# 
#     def set_paid(self, is_paid=False):
#         self.is_paid = is_paid
# 
#     def __unicode__(self):
#         return 'Order {0}'.format(self.uid)
# 
# Path: payway/orders/tests/mocks.py
# def mock_MerchantHttpClient_success_execute():
# def mock_MerchantHttpClient_fail_execute():
# def set_back_MerchantHttpClient_execute():
#     class ResponseMock(object):
# 
# Path: payway/utils/tests/base.py
# class BaseViewTestCase(AuthorizedViewTestCase):
# 
#     _url = ''
# 
#     def create_new_user_with_account(self):
#         password = 'abc123'
#         self.user = User.objects.create_user(
#             'user',
#             'user@example.com',
#             password,
#         )
#         self.account = self.user.accounts.create(user=self.user, currency='RUB')
#         self.account.add(Money(20, self.account.currency))
#         self.client_login(username=self.user.username, password=password)
# 
#     def assert_url_available(self):
#         response = self.client.get(self._url)
#         self.failUnlessEqual(response.status_code, 200)
# 
#     def assert_redirects(self, expected_url):
#         response = self.client.get(self._url)
#         self.assertRedirects(response, expected_url)
# 
#     def assert_has_message(self, response, message, level):
#         messages_list = CookieStorage(response)._decode(response.cookies['messages'].value)
#         self.assertIn(Message(level, message), messages_list)


# Path: payway/orders/tests/views.py
from django.core.urlresolvers import reverse
from moneyed.classes import Money
from payway.merchants.models import Merchant
from payway.orders.models import Order
from payway.orders.tests import mocks
from payway.utils.tests.base import BaseViewTestCase


    def test_order_exists(self):
        self.GET['uid'] = 1
        response = self.client.get(reverse('orders_payment'), self.GET)
        self.failUnlessEqual(response.status_code, 200)
        self.assertContainsTextItems(response, self.GET.values() + ['Order is paid'])

    def test_success_order_payment(self):
        mocks.mock_MerchantHttpClient_success_execute()

        initial_balance = self.account.get_balance()
        merchant_init_balance = self.merchant_account.get_balance()

        response = self.client.post(reverse('orders_payment'), self.POST)

        self.failUnlessEqual(response.status_code, 200)
        self.assertContainsTextItems(response, self.POST.values() + [dict(Order.PAYMENT_STATUS).get(Order.PAYMENT_STATUS.PAID)])
        self.assertTrue(Order.objects.get(uid=self.order.uid).is_paid)
        self.assert_balance_decreased(initial_balance)

        # merchant balance should be increased
        self.assertEquals(merchant_init_balance + self.order.sum, self.merchant_account.get_balance())

        # test if already paid
        initial_balance = self.account.get_balance()
        response = self.client.post(reverse('orders_payment'), self.POST)

        self.assertContainsTextItems(response, self.POST.values() + [dict(Order.PAYMENT_STATUS).get(Order.PAYMENT_STATUS.PAID)])
        self.assert_balance_should_be_same(initial_balance)


        mocks.set_back_MerchantHttpClient_execute()