# Path: zipfelchappe/payment_provider.py
# class BasePaymentProvider(object):
#     """
#     The abstract base class for all payment providers.
#     """
#     def __init__(self, name):
#         self.name = name
# 
#     def __unicode__(self):
#         return 'Base payment provider'
# 
#     def payment_url(self):
#         """
#         :return: The payment URL
#         """
#         raise NotImplementedError()
# 
#     # TODO: use this instead of global urls.
#     def get_provider_url_patterns(self):
#         """
#         Return the local url patterns
#         :return: A list of url instances
#         """
#         raise NotImplementedError
# 
#     def validate_project(self, project, db_instance=None):
#         """
#         A provider can validate a project.
#         :param project: The project instance to validate
#         :param db_instance: The project instance in the database
#         :raise: ValidationError
#         """
#         pass
# 
#     def collect_pledge(self, pledge):
#         """
#         Collects payment for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def refund_pledge(self, pledge):
#         """
#         Frees reserved funds for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def collect_billable_payments(self, project):
#         """
#         Collects billable payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         pledges = project.authorized_pledges.filter(provider=self.name)
#         for pledge in pledges:
#             try:
#                 self.collect_pledge(pledge)
#             except PaymentProviderException as e:
#                 logger.info(e.message)
# 
#     def refund_payments(self, project):
#         """
#         Refunds reserved payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         raise NotImplementedError()
# 
# Path: zipfelchappe/postfinance/tasks.py
# def process_pledge(pledge):
#     """ Collect postfinance payment for exactly one pledge """
#     try:
#         payment = pledge.postfinance_payment
#     except Payment.DoesNotExist:
#         raise PostfinanceException('Payment for pledge %s not found' % pledge.pk)
# 
#     if payment.STATUS == '91':
#         # payment is in processing state, check status
#         result = update_payment(payment.PAYID)
#         if result['STATUS'] == '9':
#             payment.STATUS = result['STATUS']
#             payment.save()
# 
#             payment.pledge.status = Pledge.PAID
#             payment.pledge.save()
#             logger.info('Pledge {0} has been paid.'.format(pledge.pk))
#             return result
#         logger.debug('New status for pledge {0}: {1}:{2}'.format(
#             pledge.pk, payment.STATUS, STATUS_DICT[payment.STATUS]
#         ))
# 
#     elif payment.STATUS == '5':
#         # Payment is authorized, request transaction
#         try:
#             result = request_payment(payment.PAYID)
#         except Exception as e:
#             payment.pledge.mark_failed(e.message)
#             raise PostfinanceException(e.message)
# 
#         if 'STATUS' not in result or result['STATUS'] == '0':
#             raise PostfinanceException('Incomplete or invalid status')
#         else:
#             payment.STATUS = result['STATUS']
#             payment.save()
#             logger.info('Pledge {0} has been paid. Status:{1}'.format(pledge.pk, result['STATUS']))
# 
#         return result
#     else:
#         raise PostfinanceException('Payment is not authorized')
# 
# Path: zipfelchappe/postfinance/app_settings.py
# MAX_BLOCKING_DURATION_DAYS = 29  # maximum duration for funds to be blocked.


from datetime import timedelta
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from ..payment_provider import BasePaymentProvider
from .tasks import process_pledge
from .app_settings import MAX_BLOCKING_DURATION_DAYS
# coding: utf-8
from __future__ import absolute_import, unicode_literals


class PostfinanceProvider(BasePaymentProvider):
    """
    The Payment Provider Postfinance.
    """
    def __unicode__(self):
        return 'Postfinance'

    def payment_url(self):
        return reverse('zipfelchappe_postfinance_payment')

    def collect_pledge(self, pledge):
        return process_pledge(pledge)

    def validate_project(self, project, db_instance=None):
        """
        A provider can validate a project.
        :param project: The project instance to validate
        :param db_instance: The project instance in the database
        :raise: ValidationError
        """
        if project.start and project.end and \
           project.end - project.start > timedelta(days=MAX_BLOCKING_DURATION_DAYS):
            raise ValidationError(_('Project duration can be max. %(duration) '
                                    'days because of Postfinance rules.'

# Path: zipfelchappe/payment_provider.py
# class BasePaymentProvider(object):
#     """
#     The abstract base class for all payment providers.
#     """
#     def __init__(self, name):
#         self.name = name
# 
#     def __unicode__(self):
#         return 'Base payment provider'
# 
#     def payment_url(self):
#         """
#         :return: The payment URL
#         """
#         raise NotImplementedError()
# 
#     # TODO: use this instead of global urls.
#     def get_provider_url_patterns(self):
#         """
#         Return the local url patterns
#         :return: A list of url instances
#         """
#         raise NotImplementedError
# 
#     def validate_project(self, project, db_instance=None):
#         """
#         A provider can validate a project.
#         :param project: The project instance to validate
#         :param db_instance: The project instance in the database
#         :raise: ValidationError
#         """
#         pass
# 
#     def collect_pledge(self, pledge):
#         """
#         Collects payment for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def refund_pledge(self, pledge):
#         """
#         Frees reserved funds for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def collect_billable_payments(self, project):
#         """
#         Collects billable payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         pledges = project.authorized_pledges.filter(provider=self.name)
#         for pledge in pledges:
#             try:
#                 self.collect_pledge(pledge)
#             except PaymentProviderException as e:
#                 logger.info(e.message)
# 
#     def refund_payments(self, project):
#         """
#         Refunds reserved payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         raise NotImplementedError()
# 
# Path: zipfelchappe/postfinance/tasks.py
# def process_pledge(pledge):
#     """ Collect postfinance payment for exactly one pledge """
#     try:
#         payment = pledge.postfinance_payment
#     except Payment.DoesNotExist:
#         raise PostfinanceException('Payment for pledge %s not found' % pledge.pk)
# 
#     if payment.STATUS == '91':
#         # payment is in processing state, check status
#         result = update_payment(payment.PAYID)
#         if result['STATUS'] == '9':
#             payment.STATUS = result['STATUS']
#             payment.save()
# 
#             payment.pledge.status = Pledge.PAID
#             payment.pledge.save()
#             logger.info('Pledge {0} has been paid.'.format(pledge.pk))
#             return result
#         logger.debug('New status for pledge {0}: {1}:{2}'.format(
#             pledge.pk, payment.STATUS, STATUS_DICT[payment.STATUS]
#         ))
# 
#     elif payment.STATUS == '5':
#         # Payment is authorized, request transaction
#         try:
#             result = request_payment(payment.PAYID)
#         except Exception as e:
#             payment.pledge.mark_failed(e.message)
#             raise PostfinanceException(e.message)
# 
#         if 'STATUS' not in result or result['STATUS'] == '0':
#             raise PostfinanceException('Incomplete or invalid status')
#         else:
#             payment.STATUS = result['STATUS']
#             payment.save()
#             logger.info('Pledge {0} has been paid. Status:{1}'.format(pledge.pk, result['STATUS']))
# 
#         return result
#     else:
#         raise PostfinanceException('Payment is not authorized')
# 
# Path: zipfelchappe/postfinance/app_settings.py
# MAX_BLOCKING_DURATION_DAYS = 29  # maximum duration for funds to be blocked.


# Path: zipfelchappe/postfinance/provider.py
from datetime import timedelta
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from ..payment_provider import BasePaymentProvider
from .tasks import process_pledge
from .app_settings import MAX_BLOCKING_DURATION_DAYS

# coding: utf-8
from __future__ import absolute_import, unicode_literals


class PostfinanceProvider(BasePaymentProvider):
    """
    The Payment Provider Postfinance.
    """
    def __unicode__(self):
        return 'Postfinance'

    def payment_url(self):
        return reverse('zipfelchappe_postfinance_payment')

    def collect_pledge(self, pledge):
        return process_pledge(pledge)

    def validate_project(self, project, db_instance=None):
        """
        A provider can validate a project.
        :param project: The project instance to validate
        :param db_instance: The project instance in the database
        :raise: ValidationError
        """
        if project.start and project.end and \
           project.end - project.start > timedelta(days=MAX_BLOCKING_DURATION_DAYS):
            raise ValidationError(_('Project duration can be max. %(duration) '
                                    'days because of Postfinance rules.'

                                    % {'duration': MAX_BLOCKING_DURATION_DAYS}))