from django.db import transaction
from django.utils import timezone
from apps.finance.models import FinanceEntry
from .models import Contribution
from .providers import get_provider
def initialize_payment(contribution,callback_url):
 provider=get_provider(contribution.provider);data=provider.initialize(contribution,callback_url);contribution.provider_reference=data['provider_reference'];contribution.authorization_url=data['authorization_url'];contribution.provider_payload=data['payload'];contribution.status=Contribution.Status.PROCESSING;contribution.save();return contribution
@transaction.atomic
def verify_payment(contribution):
 data=get_provider(contribution.provider).verify(contribution.provider_reference or contribution.reference);contribution.provider_payload=data['payload'];contribution.status=Contribution.Status.SUCCESS if data['successful'] else Contribution.Status.FAILED
 if data['successful']:
  contribution.paid_at=timezone.now();FinanceEntry.objects.get_or_create(reference=contribution.reference,defaults={'scope':'CAMPUS' if contribution.campus else 'NATIONAL','campus':contribution.campus,'direction':'INCOME','category':'DONATION' if contribution.purpose!='OFFERTORY' else 'OFFERTORY','amount':contribution.amount,'currency':contribution.currency,'transaction_date':timezone.localdate(),'description':contribution.get_purpose_display(),'submitted_by':contribution.member,'approved':True})
 contribution.save();return contribution
