def esewa_success(request):
    # {u'oid': [u'm_2_2015'], u'amt': [u'150'], u'refId': [u'0000ELD']}
    response = dict(request.GET)
    if not request.user.is_authenticated:
        messages.error(
            request,
            'An error occurred. Please contact us to complete your registration.'
        )
        mail_admins('[MUSCN] Esewa Failure: No user session', str(response))
        return redirect('/')
    user = request.user
    payment_type = 'Renewal' if user.status == 'Expired' else 'Membership'
    amount = response.get('amt')
    if type(amount) == list:
        amount = amount[0]
    amount = float(amount)
    ref_id = response['refId'][0]
    pid = response['oid'][0]
    user_id = int(pid.split('_')[1])
    if request.user.id != user_id:
        messages.error(
            request,
            'An error occurred. Please contact us to complete your registration.'
        )
        mail_admins('[MUSCN] Esewa Failure: Invalid user id in product id',
                    str(response))
        return redirect('/')
    payment = Payment(user=request.user, amount=amount, type=payment_type)
    if payment.amount < MembershipSetting.get_solo().membership_fee:
        messages.error(request, 'You did not pay the full amount.')
    esewa_payment = EsewaPayment(amount=payment.amount, pid=pid, ref_id=ref_id)
    if esewa_payment.verify(unique=True):
        payment.save()
        esewa_payment.payment = payment
        # esewa_payment.get_details()
        esewa_payment.save()
        messages.success(request, 'Thank you for registering to be a member.')
        user.status = 'Pending Approval'
        user.save()
        try:
            cs = CardStatus.objects.get(user=user, season=season())
            messages.success(
                request,
                'You can pickup your package from %s after you are notified of it\'s availability.'
                % cs.pickup_location)
            return redirect(cs.pickup_location.get_absolute_url())
        except CardStatus.DoesNotExist:
            mail_admins('[MUSCN] Esewa Warning: No card pickup location.',
                        str(response))
            return redirect('/')
    else:
        messages.error(request, 'Payment via eSewa failed!')
        return redirect(reverse_lazy('membership_form'))
Exemple #2
0
def save_payment(data):
    payment = Payment()
    payment.save()
    for detail in data['payment_detail']:
        if articles_validator(detail['id_article']):
            article = Article.objects.get(id=detail['id_article'])
            PaymentDetail(id_article=article,
                          id_payment=payment,
                          quantity=detail['quantity'],
                          sub_total=article.price * detail['quantity']).save()
        else:
            continue
    return payment
def renew(request):
    user = request.user
    if not hasattr(user, 'membership'):
        return redirect(reverse_lazy('membership_form'))
    if hasattr(user, 'membership') and not user.membership.payment_id:
        return redirect(reverse_lazy('membership_payment'))
    if user.is_member():
        return redirect(reverse_lazy('home'))
    pending_renewal = Renewal.objects.filter(membership__user=request.user,
                                             payment__verified_by__isnull=True)
    if pending_renewal.exists():
        messages.warning(request,
                         'One of your renewal requests is already pending.')
    membership = user.membership
    bank_deposit_form = BankDepositForm()
    direct_payment_form = DirectPaymentForm()
    if request.POST:
        payment = Payment(user=request.user,
                          amount=MembershipSetting.get_solo().membership_fee,
                          remarks='Renewal')
        if request.POST.get('method') == 'direct':
            direct_payment_form = DirectPaymentReceiptForm(
                request.POST, request.FILES)
            if direct_payment_form.is_valid():
                payment.save()
                direct_payment = direct_payment_form.save(commit=False,
                                                          user=request.user,
                                                          payment=payment)
                # direct_payment.payment = payment
                direct_payment.save()
        elif request.POST.get('method') == 'bank':
            bank_deposit_form = BankDepositForm(request.POST, request.FILES)
            bank_deposit = bank_deposit_form.save(commit=False)
            payment.save()
            bank_deposit.payment = payment
            bank_deposit.save()
        if payment.id:
            renewal = Renewal(membership=membership, payment=payment)
            renewal.save()
            return redirect(reverse('membership_thankyou'))
    bank_accounts = BankAccount.objects.all()
    return render(
        request, 'users/renew.html', {
            'membership': membership,
            'bank_deposit_form': bank_deposit_form,
            'direct_payment_form': direct_payment_form,
            'bank_accounts': bank_accounts,
            'base_template': 'base.html',
        })
def membership_form(request):
    user = request.user
    if user.status == 'Pending Approval':
        messages.warning(request,
                         'Your membership request is pending approval.')
        return redirect('/')
    if user.status == 'Member':
        messages.warning(request, 'You are already a member.')
        return redirect('/')
    membership_setting = MembershipSetting.get_solo()
    if membership_setting.enable_esewa:
        tab = 'esewa'
    else:
        tab = 'receipt'
    direct_payment_form = ReceiptPaymentForm()
    bank_deposit_form = BankPaymentForm()
    if request.POST:
        data = request.POST
        valid = False
        form = MembershipForm(data, request.FILES, instance=user)
        if form.is_valid():
            form.save()
            payment_type = 'Renewal' if user.status == 'Expired' else 'Membership'
            payment = Payment(user=user,
                              amount=float(membership_setting.membership_fee),
                              type=payment_type)
            if data.get('esewa.x') and not (data.get('esewa.x') == '0'
                                            and data.get('esewa.y') == '0'):
                return redirect(reverse_lazy('esewa_form'))
            elif data.get('receipt_no') or (data.get('esewa')
                                            and data.get('esewa.x') == '0'
                                            and data.get('esewca.y') == '0'):
                direct_payment_form = ReceiptPaymentForm(data)
                tab = 'receipt'
                valid = False
                receipt_no = data.get('receipt_no')
                if not receipt_no:
                    direct_payment_form.errors[
                        'receipt_no'] = 'Receipt number is required.'
                elif not receipt_no.isdigit():
                    direct_payment_form.errors[
                        'receipt_no'] = 'Invalid receipt number.'
                elif not ReceiptData.objects.filter(
                        active=True,
                        from_no__lte=receipt_no,
                        to_no__gte=receipt_no).exists():
                    direct_payment_form.errors[
                        'receipt_no'] = 'Invalid receipt number.'
                elif DirectPayment.objects.filter(
                        receipt_no=receipt_no,
                        payment__verified_by__isnull=False).exists():
                    direct_payment_form.errors[
                        'receipt_no'] = 'Invalid receipt number.'
                else:
                    payment.save()
                    DirectPayment.objects.create(payment=payment,
                                                 receipt_no=receipt_no)
                    valid = True
            elif data.get('deposit'):
                bank_deposit_form = BankPaymentForm(data, request.FILES)
                tab = 'bank'
                valid = False
                if not request.FILES.get('voucher_image'):
                    bank_deposit_form.errors[
                        'voucher_image'] = 'Voucher image is required.'
                else:
                    payment.save()
                    BankDeposit.objects.create(
                        payment=payment,
                        voucher_image=request.FILES.get('voucher_image'),
                        bank=BankAccount.objects.first())
                    valid = True
            else:
                tab = 'receipt'
                direct_payment_form = ReceiptPaymentForm(data)
                direct_payment_form.errors[
                    'receipt_no'] = 'Receipt number is required.'

        if valid:
            user.status = 'Pending Approval'
            user.save()
            messages.success(request,
                             'Thank you for registering to be a member.')
            if data.get('pickup_location'):
                partner = Partner.objects.get(id=data.get('pickup_location'))
                messages.success(
                    request,
                    'You can pickup your package from %s after you are notified of it\'s availability.'
                    % partner)
                return redirect(
                    reverse_lazy('view_partner', kwargs={'slug':
                                                         partner.slug}))
    else:
        form = MembershipForm(instance=user)
    bank_accounts = BankAccount.objects.all()
    return render(
        request, 'membership_form.html', {
            'form': form,
            'base_template': 'base.html',
            'tab': tab,
            'bank_deposit_form': bank_deposit_form,
            'direct_payment_form': direct_payment_form,
            'bank_accounts': bank_accounts,
        })
Exemple #5
0
 def create_payment(self):
     return Payment().save()
Exemple #6
0
    def membership(self, request):
        if request.method == 'GET':
            if request.user.is_authenticated:
                data = UserSerializer(self.request.user, many=False).data
                data['membership_fee'] = MembershipSetting.get_solo().membership_fee
                data['pickup_locations'] = PartnerSer(Partner.objects.filter(pickup_location=True), many=True).data
                return Response(data)
            return Response({'status': 'error', 'detail': 'Not authenticated.'}, 401)
        if request.method == 'POST':
            user = request.user
            if not user.is_authenticated:
                return Response({'status': 'error', 'detail': 'Not authenticated.'}, 401)
            data = request.data
            if user.status == 'Pending Approval':
                raise APIException('Your membership request in pending approval.')
            if user.status == 'Member':
                raise APIException('You are already a member.')
            membership_setting = MembershipSetting.get_solo()
            if not data.get('full_name'):
                raise APIException('Full name is required.')
            if not data.get('mobile'):
                raise APIException('Mobile number is required.')
            if not data.get('pickup_location'):
                raise APIException('Pickup Location is required')
            user.full_name = data.get('full_name')
            user.mobile = data.get('mobile')
            user.save()
            CardStatus.objects.update_or_create(user=user, season=season(), defaults={'status': 'Awaiting Approval',
                                                                                      'pickup_location_id': data.get(
                                                                                          'pickup_location')})
            payment_type = 'Renewal' if user.status == 'Expired' else 'Membership'
            payment = Payment(user=user, amount=float(membership_setting.membership_fee), type=payment_type, channel='Android')
            if data.get('esewa'):
                response = json.loads(data.get('esewa_response'))
                if float(response['totalAmount']) < float(payment.amount):
                    raise APIException('You did not pay the full amount.')
                esewa_payment = EsewaPayment(amount=payment.amount, pid=response['productId'],
                                             ref_id=response['transactionDetails']['referenceId'])
                if esewa_payment.verify():
                    payment.save()
                    esewa_payment.payment = payment
                    esewa_payment.get_details()
                    esewa_payment.save()
                else:
                    raise APIException('Payment via eSewa failed!')

            elif data.get('receipt'):
                receipt_no = data.get('receipt_no')
                if not receipt_no:
                    raise APIException('Receipt number is required.')
                elif not receipt_no.isdigit():
                    raise APIException('Invalid receipt number.')
                elif not ReceiptData.objects.filter(active=True, from_no__lte=receipt_no, to_no__gte=receipt_no).exists():
                    raise APIException('Invalid receipt number.')
                elif DirectPayment.objects.filter(receipt_no=receipt_no, payment__verified_by__isnull=False).exists():
                    raise APIException('Invalid receipt number.')
                else:
                    payment.save()
                    DirectPayment.objects.create(payment=payment, receipt_no=receipt_no)
            elif data.get('deposit'):
                if not request.data.get('voucher_image'):
                    raise APIException('Voucher image is required.')
                else:
                    payment.save()
                    bd = BankDeposit.objects.create(payment=payment, voucher_image=request.data.get('voucher_image'),
                                                    bank=BankAccount.objects.first())
                    if not bd.voucher_image:
                        payment.delete()
                        raise APIException('Could not save voucher image.')
            else:
                raise APIException('No payment method specified.')
            user.status = 'Pending Approval'
            user.save()
            data = UserSerializer(user, many=False).data
            return Response(data)