Conversion_Kitchen_Code/kitchen_counter/payment/views.py

2298 lines
91 KiB
Python
Executable File

# from turtle import home
from auto_email.views import sendmail
import calendar
import datetime
import email
import json
import os
import random
from datetime import date, timedelta
from urllib.request import urlopen
from users.models import Institutional_user
import razorpay
import requests
import stripe
from bson import json_util
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import EmailMessage, EmailMultiAlternatives, message
from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse
from django.shortcuts import HttpResponse, redirect, render
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.html import strip_tags
from django.views.decorators.csrf import csrf_exempt
# from forex_python.converter import CurrencyRates
from geopy.distance import geodesic
from geopy.geocoders import Nominatim
from pymongo import MongoClient
from rest_framework import status, viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.authentication import JWTAuthentication
from twilio.rest import Client
# from blockchain.contractInteraction import upload_subscription_to_blockchain
#from ideamall.views import commissionpayment
#from ideamall.views import payment as ideamall_script_payment
from lpp.models import MNFLPPDDatabase
# from MNF.email import mnfnsendemail, poster
from MNF.settings import RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, BasePath
from mnfapp.models import PaymentData, centralDatabase
from mnfapp.views import *
# from relationshipmanager.models import RMDatabase
from users.models import ReferUser
# from mnfapp.views import PaymentDetails
from .models import (LifeMember, PromoCode, Refund, gift, privilegedUser,
privilegedUser1, refer)
from .serializers import PaymentDataSerializer, RefundSerializer
from centralizePayment.models import CentralPayment
User = get_user_model()
# Initialize Nominatim API
geolocator = Nominatim(user_agent="http")
from_email = settings.EMAIL_HOST_USER
#MongoDBUrl = "mongodb+srv://MNF:root@cluster0.gbkxi.gcp.mongodb.net/DB?retryWrites=true&w=majority"
#client = MongoClient(MongoDBUrl)
# script_id = id
#db = client["DB"]
#title = db["college_DB"].find()
#college_emaillist = []
#for i in title:
# college_emaillist.append(i["college_email"])
# Create your views here.
# Create your views here.
# This is your real test secret API key.
# stripe.api_key = "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"
# stripe.api_key = "sk_test_51JT8ahSF9vzGWnggJT1M69LDT0Q8tCqvHzuWd9Fih5YO2guIpMpUd58swbDrJYocpQZAn3nY8k3Ymyw8QZ8dLeEF00VxfBmMWI"
stripe.api_key = settings.STRIPE_SECRET_KEY
STRIPE_PUB_KEY = settings.STRIPE_PUBLISHABLE_KEY
# keyID= "rzp_live_ZCKOJ4oKnyYgjf"
# keySecret = "exix5pSVMUhpyOYeNAqoYuS5"
# keyID = "rzp_test_6U9A7gZuno8Qz1"
# keySecret = "SrhczTH4dmrxW8SrzeqOdBSP"
# keyID = settings.RAZORPAY_KEY_ID
# keySecret = settings.RAZORPAY_KEY_SECRET
def set_payment_token(request):
if request.user.is_superuser:
request.session["keyID"] = settings.T_RAZORPAY_KEY_ID
request.session["keySecret"] = settings.T_RAZORPAY_KEY_SECRET
else:
request.session["keyID"] = settings.RAZORPAY_KEY_ID
request.session["keySecret"] = settings.RAZORPAY_KEY_SECRET
def get_total_months(start_date, end_date):
months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
return months
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
client = Client(account_sid, auth_token)
# from flask import Flask, render_template, jsonify, request
# for USD
def student(request):
return render(request, "payments/student.html")
def valid(request):
return render(request, "payments/validate.html")
def studentregis(request):
# register as previlegeduser1 and redirect to homepage
y = privilegedUser1()
cd = centralDatabase.objects.get(user_id=request.user)
cd.priviledgedMember = True
cd.save()
# lifeData = privilegedUser1.objects.filter(is_active='yes')
# # left = 25
# desc = ''
# thisMonth = datetime.datetime.now().strftime('%B')
# if lifeData:
# for i in lifeData:
# if datetime.datetime.now().month == i.dateSubscribed.month:
# left -= 1
if request.method == "POST" and student_valid(request):
plan = request.POST.get("plan")
y.user = request.user
y.is_active = "yes"
if plan == "Monthly student":
amount = "1"
y.memberType = "normal"
desc = "Privileged"
y.months = 1
y.student = True
y.save()
return redirect("/members-home")
def get_vistor_latlon(visitor_ip):
ip_address = visitor_ip
# visitor_ip_address(request)
# URL to send the request to
request_url = 'https://geolocation-db.com/jsonp/' + ip_address
# Send request and decode the result
response = requests.get(request_url)
result = response.content.decode()
# Clean the returned string so it just contains the dictionary data for the IP address
result = result.split("(")[1].strip(")")
# Convert this data into a dictionary
result = json.loads(result)
l_result = list(result.items())
l_lat2 = l_result[4]
latitude2 = l_lat2[1]
l_lon2 = l_result[5]
longitude2 = l_lon2[1]
return latitude2, longitude2
@csrf_exempt
@login_required(login_url='/')
def payment(request):
# print('In payment function')
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
left = 25
lifeData = privilegedUser1.objects.filter(
is_active="yes",
dateSubscribed__year=datetime.datetime.now().year,
memberType="Life Member",
)
desc = ""
if lifeData:
for i in lifeData:
if datetime.datetime.now().month == i.dateSubscribed.month:
left -= 1
if left < 0:
left = 0
context["life_disable"] = True
break
context = {}
context["monthly_member"] = settings.MONTHLY_MEMBER
context["employ_discount"] = settings.EMPLOY_DISCOUNT
context["yearly_member"] = settings.YEARLY_MEMBER
context["yearly_member_additional"] = settings.YEARLY_MEMBER_ADDITIONAL
context["life_member_additional"] = settings.LIFE_MEMBER_ADDITIONAL
context["life_member_year"] = settings.LIFE_MEMBER_YEAR
context["life_member"] = settings.LIFE_MEMBER
context["employ_yearly_member"] = int(
context["yearly_member"] * context["employ_discount"] / 100
)
context["employ_life_member"] = int(
context["life_member"] * context["employ_discount"] / 100
)
thisMonth = datetime.datetime.now().strftime("%B")
prev = 0
if privilegedUser1.objects.filter(user=request.user).exists():
delta = datetime.datetime.now(
datetime.timezone.utc) - datetime.timedelta(days=2)
privilegedUser1.objects.filter(
user=request.user, is_active="no", dateSubscribed__lt=delta
).delete()
# privilegedUser1.objects.filter(
# user=request.user, is_active='no').delete()
if privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
x = privilegedUser1.objects.get(user=request.user, is_active="yes")
# x.id = privilegedUser1.objects.all().count()
# date_now = timezone.now()
# tmp = relativedelta(date_now, x.dateSubscribed)
# tmp = relativedelta(today_date,x.dateSubscribed)
# prev = tmp.years * 12 + tmp.months
today_date = date.today()
prev = get_total_months(today_date,x.dateSubscribed)
else:
prev = 0
if privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
y = privilegedUser1.objects.get(user=request.user, is_active="yes")
if y.memberType == "Life Member":
context["monthly_disable"] = True
context["yearly_disable"] = True
context["life_disable"] = True
elif y.memberType == "yearly":
context["monthly_disable"] = True
context["yearly_disable"] = True
context["life_member"] = (context["life_member"] - context["monthly_member"] * prev)
elif y.memberType == "normal":
context["monthly_disable"] = True
context["life_member"] = context["life_member"] - \
context["monthly_member"]
context["yearly_member"] = (
context["yearly_member"] - context["monthly_member"]
)
context["employ_yearly_member"] = int(
context["yearly_member"] * context["employ_discount"] / 100
)
context["employ_life_member"] = int(
context["life_member"] * context["employ_discount"] / 100
)
if request.method == "GET":
user_obj = privilegedUser1.objects.get(user=request.user,is_active='yes') if privilegedUser1.objects.filter(user=request.user,is_active='yes').exists() else None
if user_obj:
expiry = user_obj.dateSubscribed + relativedelta(months=user_obj.months)
context['expiry'] = expiry
context['memberType'] = user_obj.memberType
context["left"] = left
context["thisMonth"] = thisMonth
context["desc"] = desc
context["prev"] = prev
return render(request, "Privilege/index.html", context)
# return render(request, "payments/payment1.html", context)
if request.method == "POST":
# we are taking plan wich user has selected to decide amount and description
plan = request.POST.get("plan")
response = {"id": "123"}
# deciding amount and desc on the basis of plan
if plan == "Monthly plan":
amount = str(context["monthly_member"])
desc = "Privileged"
if plan == "yearly":
amount = str(context["yearly_member"])
desc = "Privileged"
if plan == "Monthly special":
amount = str(context["monthly_member"])
desc = "Privileged"
if plan == "yearly special":
amount = str(context["employ_yearly_member"])
desc = "Privileged"
if plan == "Life":
if request.user.is_staff:
amount = str(context["employ_life_member"])
else:
amount = str(context["life_member"])
desc = "Life"
if Institutional_user.objects.filter(user=request.user, status="verified").exists():
# print("caseIMdonenow")
if plan != "Life":
# print("caseIMdonen")
amount = float(
amount) - (float(settings.IM_DISCOUNT) * float(amount) / 100)
# print("caseIMdone")
# request.session["PrivilegedID"] = json.loads(json_util.dumps(x.id))
# passing plan to session for further process
request.session["plan_purchased"] = plan
with open(f"{basepath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
# c = CurrencyRates()
# rate = c.get_rate("USD", str(currency.upper()))
except Exception as e:
# print("checkout error", e)
rate = 80
amtINR = round(float(int(amount) * rate), 2)
# print('Country Name :::::::', request.POST.get("country"))
# if User Country is INDIA payment will done through razorpay
if request.POST.get("country") == "IN":
# print('Country India::::::')
client = razorpay.Client(auth=(keyID, keySecret))
payment_intent = client.order.create(
{
"amount": int(int(amount) * 100 * rate),
"currency": "INR",
"payment": {
"capture": "automatic",
"capture_options": {"refund_speed": "normal"},
},
}
)
pid = payment_intent["id"]
context["desc"] = desc
context["amount"] = amount
context["pid"] = pid
context["pk"] = keyID
context["amtINR"] = amtINR
context["payment_intent"] = payment_intent
context["subPlan"] = plan
# passing amount in indian rupees, rate and months (on the basis of plan) through session
request.session["amtINR_card_razorpay"] = amtINR
request.session["rate"] = rate
if plan == "Monthly plan":
request.session["months_card_razorpay"] = 1
if plan == "yearly":
request.session["months_card_razorpay"] = 12
if plan == "Monthly special":
request.session["months_card_razorpay"] = 1
if plan == "yearly special":
request.session["months_card_razorpay"] = 12
if plan == "Life":
request.session["months_card_razorpay"] = settings.LIFE_MEMBER_YEAR * 12
# shehzeen
request.session['stage'] = "1"
payobj = PaymentData()
payobj.user_id = request.user
payobj.stage = request.session['stage']
payobj.save()
request.session['payment_uuid'] = str(payobj.uuid)
# shehzeen
# Sending Mail
# print('Helloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo')
return render(request, "payments/checkout_razorpay.html", context)
# if User Country is other than INDIA payment will done through stripe
else:
customer = stripe.Customer.create(
email=request.user.email,
)
payment_intent = stripe.PaymentIntent.create(
amount=int(int(amount) * 100 * rate),
currency="INR",
# payment_method_types=["card"],
automatic_payment_methods={'enabled': True},
customer=customer.id,
# payment_method_types=['card', 'Apple Pay', 'Google Pay']
# automatic_payment_methods= {"enabled": True}
)
pid = payment_intent.id
context["pk"] = STRIPE_PUB_KEY
context["amtINR"] = amtINR
context["pid"] = pid
# This is commented for temprary usage
context['secret_key'] = payment_intent.client_secret
context["STRIPE_PUBLISHABLE_KEY"] = (stripe.api_key,)
context["response"] = response
context["left"] = left
context["desc"] = desc
context["thisMonth"] = thisMonth
context["amount"] = amount
context["subPlan"] = plan
# passing payment id , payment type, rate and months (on the basis of plan) through session
request.session["pid"] = pid
request.session["ptype"] = 'subscription'
request.session["rate"] = rate
if plan == "Monthly plan":
request.session["months_stripe_paymentdone"] = 1
if plan == "yearly":
request.session["months_stripe_paymentdone"] = 12
if plan == "Monthly special":
request.session["months_stripe_paymentdone"] = 1
if plan == "yearly special":
request.session["months_stripe_paymentdone"] = 12
if plan == "Life":
request.session["months_stripe_paymentdone"] = settings.LIFE_MEMBER_YEAR * 12
# sending mail
# subject = "Previledge MEMBER " + str(x.dateSubscribed) + "."
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Date": x.dateSubscribed,
# "Name": x.user.email,
# }
# html_content = render_to_string(
# "payments/event_email_template.html", context_2
# ) # render with dynamic value
# Strip the html tag. So people can see the pure text at least.
# text_content = strip_tags(html_content)
# create the email, and attach the HTML version as well.
# msgs = EmailMultiAlternatives(subject, text_content, from_email, [to])
# msgs.attach_alternative(html_content, "text/html")
# msgs.send()
# sendmail(to_email = [x.user.email],email_code = "GT6")
request.session['stage'] = "1"
payobj = PaymentData()
payobj.user_id = request.user
payobj.stage = request.session['stage']
payobj.save()
request.session['payment_uuid'] = str(payobj.uuid)
return render(request, "payments/checkout.html", context)
def student_valid(request):
if privilegedUser1.objects.filter(user=request.user).exists():
return False
temp_email = str(request.user.email).split("@")
if temp_email[1] in college_emaillist:
return True
def Gift(request):
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
x = gift()
if request.method == "POST":
listG = ""
name = request.POST.get("Name")
name = name[:-3]
listN = name.split("@#$")
email = request.POST.get("Email")
email = email[:-3]
listL = email.split("@#$")
phone = request.POST.get("Phone")
phone = phone[:-3]
listP = phone.split("@#$")
counting = request.POST.get("counts")
# print("counting", counting)
# print("typecounting", type(counting))
# print("intcounting", int(counting))
# listL.remove("")
for i in range(len(listL)):
x = gift()
x.user = request.user
x.name = listN[i]
x.email = listL[i]
x.PhoneNumber = listP[i]
x.gift_id = str(random.randint(111111, 999999))
x.plan = "deactivated"
x.token = "MNF_" + str(random.randint(11111111, 99999999))
x.save()
listG += str(x.id) + "@#$"
# amount = 0.8 * int(len(listL))
amount = 0.8 * int(counting)
request.session['gift_amount'] = amount
with open(f"{basepath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
# c = CurrencyRates()
# rate = c.get_rate("USD", str(currency.upper()))
except Exception as e:
# print("checkout error", e)
rate = 80
amtINR = round(float(amount * rate), 2)
if request.POST.get("country") == "IN":
# if False:
client = razorpay.Client(auth=(keyID, keySecret))
payment_intent = client.order.create(
{
"amount": int(amtINR * 100),
"currency": "INR",
"payment": {
"capture": "automatic",
"capture_options": {"refund_speed": "normal"},
},
}
)
pid = payment_intent["id"]
context = {
"pk": keyID,
"giftId": listG,
"amount": amount,
"amtINR": amtINR,
"pid": pid,
"payment_intent": payment_intent,
}
request.session["giftamtINR_card_razorpay"] = amtINR
return render(request, "payments/checkout_razorpay.html", context)
else:
# print("htest1")
customer = stripe.Customer.create(
email=request.user.email,
)
payment_intent = stripe.PaymentIntent.create(
amount=int(amtINR * 100), currency="INR", automatic_payment_methods={'enabled': True}, customer=customer.id
)
pid = payment_intent.id
request.session["pid"] = pid
request.session["ptype"] = "gift"
request.session["giftId"] = listG
context = {
"pk": STRIPE_PUB_KEY,
"giftId": listG,
"amount": amount,
"amtINR": amtINR,
"pid": pid,
"secret_key": payment_intent.client_secret,
"STRIPE_PUBLISHABLE_KEY": stripe.api_key,
}
return render(request, "payments/checkout.html", context)
return redirect("/members-home")
@login_required(login_url='/')
def pcard(request):
# print("CARDCHECKINGG1")
if request.method == 'POST':
# print("CARDCHECKINGG2")
payment_intent_id = request.POST["payment_intent_id"]
payment_method_id = request.POST["payment_method_id"]
sub_plan = request.POST["subPlan"]
pType = request.POST["type"]
giftId = request.POST["giftId"]
if giftId == "":
giftId = None
else:
giftId = giftId
customer = stripe.Customer.create(
email=request.user.email,
payment_method=payment_method_id,
invoice_settings={"default_payment_method": payment_method_id},
)
# subscription=stripe.Subscription.create(
# customer = customer.id,
# items = [
# {
# 'plan' : plan_id
# }
# ]
# )
stripe.PaymentIntent.modify(
payment_intent_id, payment_method=payment_method_id, customer=customer.id
)
ret = stripe.PaymentIntent.confirm(payment_intent_id)
pi = stripe.PaymentIntent.retrieve(payment_intent_id)
# ret = stripe.Subscription.confirm(
# sub.id
# )
if ret.status == "requires_action":
context = {
"pk": STRIPE_PUB_KEY,
"payment_intent_secret": pi.client_secret,
"id": pi.id,
"sid": "sid",
"pType": pType,
"giftId": giftId,
}
return render(request, "payments/3dsec.html", context)
return render(request, "payments/paymentdone.html")
def getip(request):
adr = request.META.get('HTTP_X_FORWARDED_FOR')
if adr:
ip = adr.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
@login_required(login_url='/')
def card_razorpay(request):
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
# print("request.POST", request.POST)
razorpay_order_id = request.POST.get("razorpay_order_id")
razorpay_payment_id = request.POST["razorpay_payment_id"]
razorpay_signature = request.POST["razorpay_signature"]
# print("---------------------------------------")
# print("---------------------------------------")
# print('razorpay_order_id--> ',razorpay_order_id)
# print('razorpay_payment_id--> ',razorpay_payment_id)
# print('razorpay_signature--> ',razorpay_signature)
sub_plan = request.POST["subPlan"]
pType = request.POST["type"]
giftId = request.POST["giftId"]
client = razorpay.Client(auth=(keyID, keySecret))
params_dict = {
"razorpay_order_id": razorpay_order_id,
"razorpay_payment_id": razorpay_payment_id,
"razorpay_signature": razorpay_signature,
}
if giftId:
giftId = giftId[:-3]
gid = giftId.split("@#$")
try:
client.utility.verify_payment_signature(params_dict)
# print("giftId->", gid)
# print(4 * "######thecountis->", len(gid))
# ------Adding details to PaymentData--------
paydetail = client.payment.fetch(razorpay_payment_id)
user_id = request.user
payment_id = razorpay_payment_id
services_used = 'Gift Subscription'
# script_info =
total_amount = request.session["giftamtINR_card_razorpay"]
discount = 0
amount_charged = request.session["giftamtINR_card_razorpay"]
# to convert from paise to rupees
gateway_fee = paydetail['fee'] / 100
currency = paydetail['currency']
pay_method = paydetail['method']
payment_status = 'Success'
payment_gateway = 'RazorPay'
PaymentData.objects.create(
user_id=user_id,
payment_id=payment_id,
services_used=services_used,
amount_charged=amount_charged,
total_amount=total_amount,
discount=discount,
currency=currency,
gateway_fee=gateway_fee,
pay_method=pay_method,
payment_status=payment_status,
payment_gateway=payment_gateway,
)
for i in list(gid):
x = gift.objects.get(id=int(i))
x.transactionID = razorpay_payment_id
x.chargeID = razorpay_order_id
x.receipt = razorpay_signature
x.payment_id = razorpay_payment_id
x.order_id = razorpay_order_id
x.is_paid = "yes"
x.save()
if x.PhoneNumber:
try:
client = Client(account_sid, auth_token)
message = client.messages.create(
body="Hi "
+ str(x.name)
+ ",\n "
+ str(request.user.email).capitalize()
+ " has gifted you an MNF one month Subscription.\n"
+ str(request.user.email).capitalize()
+ " wants you to join MNF and enjoy our film making services.\nPlease apply this coupon code to activate your subscription.\n"
+ x.token
+ "\n Happy Filming \n MyNextFilm",
from_=settings.TWILIO_PHONE_NUMBER,
to=x.PhoneNumber,
)
except:
pass
subject1 = "Someone is generous to you"
from_email = settings.EMAIL_HOST_USER
to1 = x.email
context1 = {
"username": x.name,
"sender": request.user.username,
"token": x.token,
}
sendmail(to_email = [to1],email_code="GT14",key_value=context1)
##### to sender ###
subject2 = (
"Thank you for gifting MyNextFilm subscription to " + str(x.name) + ".")
from_email = settings.EMAIL_HOST_USER
to2 = request.user.email
context2 = {
"username": x.name,
"User": request.user.username,
"token": x.token,
}
# sendmail(to_email=["himanshub166@gmail.com"],email_code = "IM102")
print("###################################222222222222222222222222###########################################")
sendmail(to_email=[to2],email_code="GT1",key_value=context2)
# mnfnsendemail(
# to2, subject2, "payment/templates/payments/MR15.html", context2, from_email)
return render(request, "payments/giftsuccess.html", {})
except:
subject = "Something really went wrong"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Name": request.user.email,
"service_name": "Gift Purchase",
}
sendmail(to_email=[request.user.email], email_code="PM4")
return render(request, "payments/failed.html")
else:
# try:
# shehzeen
request.session['stage'] = "2"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.save()
# shehzeen
# client.utility.verify_payment_signature() is likely being used to verify the payment signature in the Razorpay API.
client.utility.verify_payment_signature(params_dict)
# print('signature:::', client.utility.verify_payment_signature(params_dict))
# print('param dict:::', params_dict)
# request.session['razorpay_signature']
updateprivilege(request)
x = privilegedUser1.objects.get(pk=request.session["PrivilegedID"])
# x = privilegedUser1.objects.find_one({"_id":"request.session['PrivilegedID']"})
x.chargeId = razorpay_order_id
x.transactionId = razorpay_payment_id
x.razorpaySign = razorpay_signature
x.save()
# shehzeen
request.session['stage'] = "5"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.save()
# shehzeen
# ----------Adding details to PaymentData------
paydetail = client.payment.fetch(razorpay_payment_id)
# shehzeen
request.session['stage'] = "6"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.save()
# shehzeen
if request.session["months_card_razorpay"] == 1:
total_amount = round(
(settings.MONTHLY_MEMBER * request.session["rate"]), 2)
services_used = "Monthly Subscription"
# subject = "ONLY A FEW IN THE WORLD ARE PRIVILEGED"
# from_email = settings.EMAIL_HOST_USER
to = request.user.email
# manoj code for poster
context_2 = {
"Date": x.dateSubscribed,
"Name": x.user.email,
"member_type": x.memberType,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR2.html", context_2, from_email)
sendmail(to_email=[to],email_code = "GT7",key_value=context_2)
elif request.session["months_card_razorpay"] == 12:
total_amount = round(
(settings.YEARLY_MEMBER * request.session["rate"]), 2)
services_used = "Yearly Subscription"
subject = "THE BONDING IS NOW CLOSER"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Date": x.dateSubscribed,
"Name": x.user.email,
"member_type": x.memberType,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR3.html", context_2, from_email)
sendmail(to_email=[to],email_code = "GT2",key_value=context_2)
else:
total_amount = round(
(settings.LIFE_MEMBER * request.session["rate"]), 2)
services_used = "Life Member Subscription"
# print("testp2")
'''
#manoj
#Add rm details to life member database
x = LifeMemberForm()
x.email = request.user
x.save()
Add lifemember details to rm database
'''
c = RMDatabase.objects.filter(is_accepted=True)
if len(c) > 1:
mindistance = []
for j in c:
# rm latitude and longitude
latitude1 = j.latitude
longitude1 = j.longitude
ip = getip(request)
# lifemember latitude and longitude
latitude2, longitude2 = get_vistor_latlon(ip)
cust_loc = (latitude1, longitude1)
club_loc = (latitude2, longitude2)
distance = geodesic(cust_loc, club_loc).km
mindistance.append([distance, j])
mindistance = sorted(mindistance, key=lambda x: x[0])
rmuser = mindistance[0][1]
name = rmuser.firstName + " " + rmuser.lastName
whatsapp = rmuser.contact
Email = rmuser.email
rmid = rmuser.id
elif len(c) == 1:
name = c[0].firstName + " " + c[0].lastName
whatsapp = c[0].contact
Email = c[0].email
rmuser = c[0]
rmid = rmuser.id
x = privilegedUser1.objects.get(
pk=request.session["PrivilegedID"])
# x.rmuser = rmuser.id
x.save()
# manoj mail
# to lifemember
subject = "Friendships are for lifetime."
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"UserName": x.user.email,
# "RMName": name,
"RMEmail": x.user.email,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR4.html", context_2, from_email)
sendmail(to_email=[to],email_code="GT3",key_value=context_2)
# to rm
subject = "You have a new lifetime friend."
from_email = settings.EMAIL_HOST_USER
to = x.user.email
context_2 = {
"RMName": x.user.email,
"lifememberName": list(request.user.email.split('@'))[0],
"lifememberEmail": request.user.email,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR5.html", context_2, from_email)
sendmail(to_email=[to],email_code = "GT4",key_value=context_2)
user_id = request.user
payment_id = razorpay_payment_id
# script_info =
amount_charged = request.session["amtINR_card_razorpay"]
discount = round((total_amount - amount_charged), 2)
# to convert from paise to rupees
gateway_fee = paydetail['fee'] / 100
currency = paydetail['currency']
pay_method = paydetail['method']
payment_status = 'Success'
payment_gateway = 'RazorPay'
# print('shehzeen 857', type(total_amount), total_amount)
# shehzeen
request.session['stage'] = "Final Stage"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.payment_id = payment_id
p.services_used = services_used
p.discount = discount
p.total_amount = total_amount
p.amount_charged = amount_charged
p.gateway_fee = gateway_fee
p.currency = currency
p.pay_method = pay_method
p.payment_status = payment_status
p.payment_gateway = payment_gateway
# p.save()
#
# shehzeen
# PaymentData.objects.create(
# user_id=user_id,
# payment_id=payment_id,
# services_used=services_used,
# discount=discount,
# total_amount=total_amount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# currency=currency,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# manoj - code to update data on blockchain
data = privilegedUser1.objects.get(
pk=request.session["PrivilegedID"])
# manoj - send a confirmation mail to user who referred his/her friend to join mnf when his/her friend takes membership
x = refer.objects.all()
for i in x:
if i.refer_email1 == request.user.email:
subject = "Your dividend is on the way"
from_email = settings.EMAIL_HOST_USER
to = i.refer_user.email
context_2 = {
"Name": i.refer_user.email,
"referredpeople": i.refer_email1,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR22.html", context_2, from_email)
sendmail(to_email = [to],email_code="GT5",key_value=context_2)
# print('YOU plan is::::', request.session["months_card_razorpay"])
x = privilegedUser1.objects.get(user=request.user, is_active='yes')
expiryDate = x.dateSubscribed + relativedelta(months=x.months)
return render(
request,
"payments/success.html",
{"pId": razorpay_payment_id, "rSign": "hello",
'expiry': expiryDate, 'isSubscription': True},
)
# except (razorpay.errors.SignatureVerificationError, Exception) as E:
# with open("/home/user/mnf/project/MNF/subtitling3/error_check.txt","a") as f:
# f.write('line 955 -->'+"\n")
# print("----manoj786", E)
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Membership",
# }
# paydetail = client.payment.fetch(razorpay_payment_id)
# if request.session["months_card_razorpay"] == 1:
# total_amount = round(
# (settings.MONTHLY_MEMBER * request.session["rate"]), 2)
# services_used = "Monthly Subscription"
# elif request.session["months_card_razorpay"] == 12:
# total_amount = round(
# (settings.YEARLY_MEMBER * request.session["rate"]), 2)
# services_used = "Yearly Subscription"
# else:
# total_amount = round(
# (settings.LIFE_MEMBER * request.session["rate"]), 2)
# services_used = "Life Member Subscription"
# user_id = request.user
# payment_id = razorpay_payment_id
# # script_info =
# amount_charged = request.session["amtINR_card_razorpay"]
# discount = round((total_amount - amount_charged), 2)
# # to convert from paise to rupees
# gateway_fee = paydetail['fee'] / 100
# currency = paydetail['currency']
# pay_method = paydetail['method']
# payment_status = 'Failed'
# payment_gateway = 'RazorPay'
# # obj = payment.objects.get(id = request.session["payment_id"])
# # shehzeen
# request.session['stage'] = 'Faild Stage'
# p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
# p.stage = request.session['stage']
# p.payment_id = payment_id
# p.services_used = services_used
# p.discount = discount
# p.total_amount = total_amount
# p.amount_charged = amount_charged
# p.gateway_fee = gateway_fee
# p.currency = currency
# p.pay_method = pay_method
# p.payment_status = payment_status
# p.payment_gateway = payment_gateway
# p.save()
# # shehzeen
# # PaymentData.objects.create(
# # user_id=user_id,
# # payment_id=payment_id,
# # services_used=services_used,
# # discount=discount,
# # total_amount=total_amount,
# # amount_charged=amount_charged,
# # gateway_fee=gateway_fee,
# # currency=currency,
# # pay_method=pay_method,
# # payment_status=payment_status,
# # payment_gateway=payment_gateway,
# # )
# # mnfnsendemail(to,subject,"payment/templates/payments/MR24.html",context_2,from_email)
# return render(request, "payments/failed.html")
@login_required(login_url='/')
@csrf_exempt
def paymentDone(request):
print('running')
payment_intent_id = request.session["pid"]
# subscription = request.POST["sid"]
pType = request.session["ptype"]
# print('ptype:::::', pType)
print('payment_intent_id ',payment_intent_id)
pi = stripe.PaymentIntent.retrieve(payment_intent_id)
print('payments details', pi)
if pType == "subscription":
if pi.status == "succeeded":
# print("htest3")
# stripe.Subscription.modify(
# subscription,
# metadata = {"status":'active'}
# )
updateprivilege(request)
x = privilegedUser1.objects.get(
pk=request.session["PrivilegedID"])
x.transactionId = pi.id
x.chargeId = pi.latest_charge
x.currency = pi.currency
x.status = pi.status
# x.receipt_url = pi.charges.data[0].get("receipt_url")
x.amount_captured = pi.amount
x.save()
# ------Email--
y = privilegedUser1.objects.get(
user=request.user, is_active="yes")
if y.months == 1:
subject = "ONLY A FEW IN THE WORLD ARE PRIVILEGED"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Date": x.dateSubscribed,
"Name": x.user.email,
"member_type": x.memberType,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR2.html", context_2, from_email)
elif y.months == 12:
subject = "THE BONDING IS NOW CLOSER"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Date": x.dateSubscribed,
"Name": x.user.email,
"member_type": x.memberType,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR3.html", context_2, from_email)
else:
c = RMDatabase.objects.filter(is_accepted=True)
if len(c) > 1:
mindistance = []
for j in c:
# rm latitude and longitude
latitude1 = j.latitude
longitude1 = j.longitude
ip = getip(request)
# lifemember latitude and longitude
latitude2, longitude2 = get_vistor_latlon(ip)
cust_loc = (latitude1, longitude1)
club_loc = (latitude2, longitude2)
distance = geodesic(cust_loc, club_loc).km
mindistance.append([distance, j])
mindistance = sorted(mindistance, key=lambda x: x[0])
rmuser = mindistance[0][1]
name = rmuser.firstName + " " + rmuser.lastName
whatsapp = rmuser.contact
Email = rmuser.email
rmid = rmuser.id
# print("-------manoj728")
# print("harsh55544")
# print(name)
# print(whatsapp)
# print(Email)
elif len(c) == 1:
name = c[0].firstName + " " + c[0].lastName
whatsapp = c[0].contact
Email = c[0].email
rmuser = c[0]
rmuser = c[0]
rmid = rmuser.id
x = privilegedUser1.objects.get(
pk=request.session["PrivilegedID"])
# x.rmuser = rmuser.id
x.save()
# manoj mail
# to lifemember
subject = "Friendships are for lifetime."
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"UserName": x.user.email,
# "RMName": name,
# "RMEmail": Email,
#"RMwhatsapp": whatsapp,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR4.html", context_2, from_email)
# to rm
subject = "You have a new lifetime friend."
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"RMName": request.user.username,
"lifememberName": list(request.user.email.split('@'))[0],
"lifememberEmail": request.user.email,
}
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR5.html", context_2, from_email)
# -----------Adding Details to payment Details--------------------------
if request.session["months_stripe_paymentdone"] == 1:
total_amount = round(
(settings.MONTHLY_MEMBER * request.session["rate"]), 2)
services_used = "Monthly Subscription"
elif request.session["months_stripe_paymentdone"] == 12:
total_amount = round(
(settings.YEARLY_MEMBER * request.session["rate"]), 2)
services_used = "Yearly Subscription"
else:
total_amount = round(
(settings.LIFE_MEMBER * request.session["rate"]), 2)
services_used = "Life Member Subscription"
user_id = request.user
payment_id = pi["id"]
amount_charged = pi["amount"] / 100
discount = round(total_amount - amount_charged, 2)
gateway_fee = pi["application_fee_amount"]
currency = pi["currency"]
pay_method = "Card"
payment_status = "Success"
payment_gateway = "Stripe"
#PaymentData.objects.create(
# user_id=user_id,
# services_used=services_used,
# pay_method=pay_method,
#payment_id=payment_id,
# total_amount=total_amount,
# discount=discount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# payment_gateway=payment_gateway,
# currency=currency,
# payment_status=payment_status,
#)
# manoj - code to update data on blockchain
data = privilegedUser1.objects.get(
pk=request.session["PrivilegedID"])
# manoj - send a confirmation mail to user who referred his/her friend to join mnf when his/her friend takes membership
xy = refer.objects.all()
for i in xy:
if i.refer_email1 == request.user.email:
subject = "Your dividend is on the way"
from_email = settings.EMAIL_HOST_USER
to = i.refer_user.email
context_2 = {
"Name": i.refer_user.email,
"referredpeople": i.refer_email1,
}
mnfnsendemail(
to, subject, "payment/templates/payments/MR22.html", context_2, from_email)
request.session['paystatus'] = pi.status
# request.session['razorpay_signature'] = razorpay_signature
# request.session['razorpay_order_id'] = razorpay_order_id
request.session['paymentId'] = payment_id
request.session['amount'] = amount_charged
request.session['payment_gateway'] = payment_gateway
updatepaymentstatus(request)
return render(
request,
"payments/success.html",
{"pId": x.transactionId, "rSign": "hello"},
)
else:
request.session['paystatus'] = payment_status
# request.session['razorpay_signature'] = razorpay_signature
# request.session['razorpay_order_id'] = razorpay_order_id
request.session['paymentId'] = pi["id"]
request.session['amount'] = pi["amount"] / 100
request.session['payment_gateway'] = "Stripe"
updatepaymentstatus(request)
return render(request, "payments/failed.html")
elif pType == "gift":
# print("htest4")
giftId = request.session["giftId"]
giftId = giftId[:-3]
gid = giftId.split("@#$")
# print("giftIdforstripe->", gid)
if pi.status == "succeeded":
# -----------Adding Details to payment Details--------------------------
user_id = request.user
payment_id = pi["id"]
services_used = "Gift Subscription"
total_amount = pi["amount"] / 100
discount = 0
amount_charged = pi["amount"] / 100
gateway_fee = pi["application_fee_amount"]
currency = pi["currency"]
pay_method = "Card"
payment_status = "Success"
payment_gateway = "Stripe"
PaymentData.objects.create(
user_id=user_id,
services_used=services_used,
pay_method=pay_method,
payment_id=payment_id,
amount_charged=amount_charged,
discount=discount,
gateway_fee=gateway_fee,
payment_gateway=payment_gateway,
currency=currency,
payment_status=payment_status,
total_amount=total_amount,
)
for i in list(gid):
x = gift.objects.get(id=int(i))
x.transactionID = pi.charges.data[0].get(
"balance_transaction")
x.chargeID = pi.charges.data[0].get("id")
x.receipt = pi.charges.data[0].get("receipt_url")
x.is_paid = "yes"
x.save()
### to reciever ###
subject1 = "Someone is generous to you"
from_email = settings.EMAIL_HOST_USER
to1 = x.email
context1 = {
"username": x.name,
"first_name": request.user.username,
"token": x.token,
}
mnfnsendemail(
to1, subject1, "payment/templates/payments/MR16.html", context1, from_email)
##### to sender ###
subject2 = (
"Thank you for gifting MyNextFilm subscription to " + str(x.name) + ".")
from_email = settings.EMAIL_HOST_USER
to2 = request.user.email
context2 = {
"username": x.name,
"first_name": request.user.username,
"token": x.token,
}
mnfnsendemail(
to2, subject2, "payment/templates/payments/MR15.html", context2, from_email)
return render(request, "payments/giftsuccess.html", {})
else:
return render(request, "payments/failed.html")
# except:
# return render(request, "payments/failed.html")
def pricingCalculator(request):
context = {}
# conversion
context["conversion_per_page"] = settings.CONVERSION_PER_PAGE
context["lpp_per_page"] = settings.LPP_PER_PAGE
# narration
context["ONE_PAGER"] = settings.ONE_PAGER
context["LINE_BY_LINE"] = settings.LINE_BY_LINE
context["ELEVATOR_PITCH"] = settings.ELEVATOR_PITCH
context["SCREENPLAY_ANALYSIS1"] = settings.SCREENPLAY_ANALYSIS1
context["SCREENPLAY_ANALYSIS2"] = settings.SCREENPLAY_ANALYSIS2
context["SCREENPLAY_ANALYSIS3"] = settings.SCREENPLAY_ANALYSIS3
context["SCREENPLAY_ANALYSIS4"] = settings.SCREENPLAY_ANALYSIS4
context["CHARACTER_INTRODUCTION"] = settings.CHARACTER_INTRODUCTION
context["CHARACTERWISE_NARATION"] = settings.CHARACTERWISE_NARATION
# project center
context["SCHEDULING"] = settings.SCHEDULING
context["BUDGETING"] = settings.BUDGETING
amount = 0
if request.method == "POST":
service = request.POST.get("choose_service")
if service == "Conversion":
conservice = request.POST.get("conversion_sub")
numOfPage = int(request.POST.get("page"))
if conservice == "without-llp":
amount = context["conversion_per_page"]*numOfPage
else:
amount = (context["conversion_per_page"] +
context["lpp_per_page"])*numOfPage
context["serviceurl"] = "conversion"
context["serviceurl_name"] = "Convert your script"
elif service == "Narration":
total = 0
numOfPage = int(request.POST.get("page"))
narrateservice = request.POST.getlist("narration_sub")
for i in narrateservice:
if i == "SCREENPLAY_ANALYSIS":
if numOfPage <= 15:
total += context[i+"1"]
elif numOfPage <= 30:
total += context[i+"2"]
elif numOfPage <= 100:
total += context[i+"3"]
else:
total += context[i+"4"]
else:
total = total + context[i]
amount = total*numOfPage
context["serviceurl"] = "Pitchnarrate1"
context["serviceurl_name"] = "Narrate your script"
elif service == "ProjectCenter":
project_center_submenu = request.POST.get("project_center_name")
# print('NAME:::::', project_center_submenu)
num = int(request.POST.get("page"))
# print('NUMBER:::::::', num)
if project_center_submenu == "Scheduling":
# print('we are in scheduling')
if num < 20:
amount = 10
else:
amount = num * context["SCHEDULING"]
context["checkurl"] = "true"
context["serviceurl"] = "/projectcenter"
context["serviceurl_name"] = "Schedule your film"
elif project_center_submenu == "Budgeting":
# print('we are in budgeting')
if num < 10:
amount = 10
else:
amount = num * context["BUDGETING"]
context["checkurl"] = "true"
context["serviceurl"] = "/projectcenter"
context["serviceurl_name"] = "Budget your film"
# print('leaving budgeting')
elif service == "Ideamall":
ideamallSubmenu = request.POST.get("idea_sub")
if ideamallSubmenu == "auction":
project_status = request.POST.get("showcase_status")
start_date = request.POST.get("auctionstartdate")
end_date = request.POST.get("auctionstopdate")
price_currency = request.POST.get("reservepricecurrency")
price_amount = int(request.POST.get("reservepriceamount"))
file_size = int(request.POST.get("filesize"))
amount = ideamall_script_payment(
price_currency, project_status, price_amount, start_date, end_date, int(file_size))
context["serviceurl"] = "showcase"
context["serviceurl_name"] = "Setup your auction"
elif ideamallSubmenu == "script":
project_status = request.POST.get("commisioning_status")
price_currency = request.POST.get("payforassignmentcurrent")
price_amount = request.POST.get("payforassignmentamount")
project_duration = int(request.POST.get("duration1"))
publishmyproject = request.POST.get(
"publishmyproject", "False")
script_purchased = request.POST.get("howmanyscriptpurchased")
# print("manoj1180erer")
# print(price_currency, project_duration,
# project_status, price_amount, publishmyproject)
if publishmyproject == "on":
publishmyproject = "True"
amount = commissionpayment(
price_currency, project_duration, project_status, price_amount, publishmyproject)
context["serviceurl"] = "commssioningpage"
context["serviceurl_name"] = "Commission your script"
# discount part by manoj
total_discount_in_percentage = 0
discount = request.POST.getlist("discount")
additional_discount = request.POST.getlist("extra-discount")
message = []
if not request.user.is_anonymous:
for disc in discount:
if disc == "staff":
if request.user.is_staff:
if total_discount_in_percentage + 50 > 100:
total_discount_in_percentage = 100
else:
total_discount_in_percentage += 50
else:
message.append("You are not a staff member")
elif disc == "partner":
if MNFLPPDDatabase.objects.filter(user_id=request.user).exists():
if total_discount_in_percentage + 5 > 100:
total_discount_in_percentage = 100
else:
total_discount_in_percentage += 5
else:
message.append("Your are not a Language Pair Partner")
elif disc == "student":
message.append("You are not a Student")
elif disc == "messiah":
if RMDatabase.objects.filter(user_id=request.user).exists():
if total_discount_in_percentage + 5 > 100:
total_discount_in_percentage = 100
else:
total_discount_in_percentage += 5
else:
message.append("Your are not a MNF Messiah")
for ad_disc in additional_discount:
if ad_disc == "life":
if privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
y = privilegedUser1.objects.get(
user=request.user, is_active="yes")
if y.memberType == "Life Member":
if total_discount_in_percentage + 20 > 100:
total_discount_in_percentage = 100
else:
total_discount_in_percentage += 20
else:
message.append("Your are not a life member")
elif ad_disc == "annual":
if privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
y = privilegedUser1.objects.get(
user=request.user, is_active="yes")
if y.memberType == "yearly":
if total_discount_in_percentage + 10 > 100:
total_discount_in_percentage = 100
else:
total_discount_in_percentage += 10
else:
message.append("Your are not a yearly member")
else:
if discount or additional_discount:
message.append(
"Please login to avail discount on final amount.")
context["message"] = message
with open(f"{basepath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
amtINR = round(float(amount * rate), 2)
# shehzeen
if total_discount_in_percentage > 0: # chechking whether user has clicked for discount or not
context['isDiscount'] = True
total_discount_amount = round(
(amount/100) * total_discount_in_percentage, 2)
total_discount_amount_INR = round(
float(total_discount_amount * rate), 2)
final_amount = round(amount - total_discount_amount, 2)
final_amount_INR = round(float(final_amount * rate), 2)
# shehzeen
context["amount"] = amount # amount in different currencies
context["amtINR"] = amtINR # amount in indian rupee
# shehzeen
context["totalDiscount"] = total_discount_amount
context["totalDiscountINR"] = total_discount_amount_INR
context["finalAmount"] = final_amount
context["finalAmountINR"] = final_amount_INR
# shehzeen
# print('Shehzeen1292')
# print(total_discount_amount, total_discount_amount_INR,
# final_amount, final_amount_INR)
context["service"] = service
# print('&&&&&&&&&&&&&&&&&&&&&&', context)
# print('shehzeen1298')
return render(request, "payments/pricingCalculator.html", context)
def email_test(request):
subject = "You Got a MyNextFilm gift Subscription"
from_email = "mnfrendezvous@gmail.com"
to = "followasad@gmail.com"
context = {"username": "Asad", "first_name": "Param", "token": "53241"}
html_content = render_to_string(
"payments/email_template1.html", context
) # render with dynamic value
# Strip the html tag. So people can see the pure text at least.
text_content = strip_tags(html_content)
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
# print("sent successfully")
def updatepaymentstatus(request):
y = privilegedUser()
y.user = request.user
y.paymentId = request.session['paymentId']
y.amount = 100
y.orderId = request.session['razorpay_order_id'] if 'razorpay_order_id' in request.session else ""
y.razorpaySign = request.session['razorpay_signature'] if 'razorpay_signature' in request.session else ""
y.save()
'''
save privilegedUser()
y = privilegedUser()
y.user = request.user
y.paymentId = request.session['paymentId']
y.amount = request.session['amount']
y.orderId = request.session['orderId']
y.razorpaySign = request.session['razorpaySign']
y.memberType= request.session['memberType']
y.save()
'''
pass
return
def updateprivilege(request):
# this function update privilege user's information or create new privillage user into database and returns nothing.
# Payment success object is_active='no'
# shehzeen
print('line 1553 --> ',request.session.items())
request.session['stage'] = "3"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.save()
# shehzeen
context = {}
context["life_member_year"] = settings.LIFE_MEMBER_YEAR
plan = request.session["plan_purchased"]
cd = centralDatabase.objects.get(user_id=request.user)
cd.priviledgedMember = True
cd.save()
# make a dictionary to indicate plans name and there number of days repectively
dic = {
"normal": 1,
"yearly": 12,
"Life Member": 120
}
'''
There are few thing we need to keep track of
1. check whether the user is already registered or not and is_active = 'yes' in our database
1.1: if user exists and is_active = 'yes' then set the member type and months
1.2 : if user already has a plan, make sure that current plan should not be less than previous plan. eg(if user is already yearly member of mnf and he wants to buy one month plan also than user member type will remain same as previous one which is yearly but onlt 1 moth will be added to his 12 months pla , 12+1 = 13 moths , that mean now user has 13 moths of subscription plan, similarly for life memeber also.)
1.3 : after making changes update these changes into database.
2. if user doest not exists or not active memeber
2.1 : register user in dtabase with his plan, membertype and number of months
'''
if privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
x = privilegedUser1.objects.get(user=request.user, is_active="yes")
if plan == "Monthly plan":
if dic[x.memberType] < 1:
x.memberType = "normal"
x.months = 1 + x.months
sendmail([request.user.email], "PM2")
if plan == "yearly":
if dic[x.memberType] < 12:
x.memberType = "yearly"
x.months = 12 + x.months
sendmail([request.user.email], "PM3")
if plan == "Monthly special":
if dic[x.memberType] < 1:
x.memberType = "normal"
x.months = 1 + x.months
if plan == "yearly special":
if dic[x.memberType] < 12:
x.memberType = "yearly"
x.months = 12 + x.months
if plan == "Life":
x.memberType = "Life Member"
x.months = context["life_member_year"] * 12 + x.months
sendmail([request.user.email], "PM1")
request.session["PrivilegedID"] = json.loads(json_util.dumps(x.id))
x.save()
else:
x = privilegedUser1()
if privilegedUser1.objects.exists():
lasto = privilegedUser1.objects.last()
x.id = int(lasto.id) + 1
else:
x.id = 1
x.user = request.user
x.is_active = "yes"
if plan == "Monthly plan":
x.memberType = "normal"
x.months = 1
sendmail([request.user.email], "PM2")
if plan == "yearly":
x.memberType = "yearly"
x.months = 12
sendmail([request.user.email], "PM3")
if plan == "Monthly special":
x.memberType = "normal"
x.months = 1
if plan == "yearly special":
x.memberType = "yearly"
x.months = 12
if plan == "Life":
x.memberType = "Life Member"
x.months = context["life_member_year"] * 12
sendmail([request.user.email], "PM1")
request.session["PrivilegedID"] = json.loads(json_util.dumps(x.id))
x.save()
# shehzeen
request.session['stage'] = "4"
p = PaymentData.objects.get(uuid=request.session['payment_uuid'])
p.stage = request.session['stage']
p.save()
# shehzeen
return
def unsubscribe(request):
# keyID= "rzp_live_ZCKOJ4oKnyYgjf"
# keySecret = "exix5pSVMUhpyOYeNAqoYuS5"
keyID = "rzp_test_6U9A7gZuno8Qz1"
keySecret = "SrhczTH4dmrxW8SrzeqOdBSP"
client = razorpay.Client(auth=(keyID, keySecret))
if request.method == "POST":
x = privilegedUser1.objects.get(user=request.user)
client.subscription.cancel(x.subId, {"cancel_at_cycle_end": "1"})
return render(request, "payments/cancelSuccess.html", {})
def referexists(request):
already = []
if request.method == "POST":
for i in [
request.POST.get("mytext1"),
request.POST.get("mytext2"),
request.POST.get("mytext3"),
request.POST.get("mytext4"),
request.POST.get("mytext5"), ]:
if i is not None and i != "undefined":
if User.objects.filter(email=i).exists():
# print("refer if condition", i)
already.append(i)
val = {"context": already}
return JsonResponse(val)
def Refer(request):
# from inside - after login
if request.user.is_authenticated:
if ReferUser.objects.filter(user=request.user).exists():
rId = ReferUser.objects.get(user=request.user)
# print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
# print(rId)
else:
y = ReferUser()
rId = str(random.randint(111111, 999999))
print(rId)
y.user = request.user
# y.user = ""
y.referId = rId
y.save()
# else:
# rId = ReferUser.objects.get(user=request.user)
if request.method == "POST":
listofuser = []
exists = []
for i in [
request.POST.get("mytext1"),
request.POST.get("mytext2"),
request.POST.get("mytext3"),
request.POST.get("mytext4"),
request.POST.get("mytext5"), ]:
if refer.objects.filter(refer_email1=str(i)).exists():
exists.append(i)
if i is not None and i != "undefined" and i not in exists:
refer.objects.create(
refer_user=request.user, refer_email1=str(i))
listofuser.append(i)
subject3 = "Someone trusts you"
# from_email = settings.EMAIL_HOST_USER
to3 = i
if request.user.first_name and request.user.last_name:
sender = (
str(request.user.first_name)
+ " "
+ str(request.user.last_name)
)
else:
sender = request.user.email
context3 = {
"sender": sender,
"user": i.split("@")[0],
"referid": rId,
}
# mnfnsendemail(
# to3, subject3, "payment/templates/payments/MR19.html", context3, from_email)
sendmail(to_email=[to3],email_code = "GT8",key_value = context3)
else:
print('You are already exists', i)
# sending mail to refer sender
# print("sheehzeen1418op")
# print(listofuser)
context = {}
if listofuser:
# print("sheehzeen1420op")
subject3 = "You have a big heart !!"
from_email = settings.EMAIL_HOST_USER
to3 = request.user.email
context3 = {
"sender": request.user.username,
"listofuser": ",".join(listofuser)
}
if len(listofuser) > 1:
subject3 = "You are really marvellous"
# mnfnsendemail(
# to3, subject3, "payment/templates/payments/MR20.html", context3, from_email)
sendmail(to_email=[to3],email_code="GT9",key_value= context3)
else:
# mnfnsendemail(
# to3, subject3, "payment/templates/payments/MR18.html", context3, from_email)
sendmail(to_email=[to3],email_code="GT10",key_value= context3)
context["alreadyreferred"] = "True"
return JsonResponse(context)
else:
context["alreadyreferred"] = "False"
context["dataitems"] = exists
return JsonResponse(context)
else:
if request.method == "POST":
for i in [
request.POST.get("mytext1"),
request.POST.get("mytext2"),
request.POST.get("mytext3"),
request.POST.get("mytext4"),
request.POST.get("mytext5"),
]:
if i is not None and i != "undefined":
subject3 = "One of your friend has referred you to join MyNextFilm"
from_email = settings.EMAIL_HOST_USER
to3 = i
context3 = {
"sender1": "A friend of yours",
"sender2": "Your friend",
"user1": i.split("@")[0],
"referid": rId,
}
# if y.user == "Anonmouys":
# context3['sender'] = "Anonmouys"
# html_content3 = render_to_string(
# "payments/referred_email.html", context3
# ) # render with dynamic value
# Strip the html tag. So people can see the pure text at least.
# text_content3 = strip_tags(html_content3)
# create the email, and attach the HTML version as well.
# msg3 = EmailMultiAlternatives(
# subject3, text_content3, from_email, [to3]
# )
# msg3.attach_alternative(html_content3, "text/html")
# msg3.send()
sendmail(to_email=[to3],email_code="GT11",key_value=context3)
return render(
request,
"mnfapp/landing.html",
{
"messageR": "thanks for refering your friends. You will get extra one month of our services for every 3 joinings from your referal link"
},
)
# return base(request)
# return base(request, message=True)
return render(request, "mnfapp/landing.html", {})
# return base(request)
def refer_landing_page(request):
return render(
request,
"mnfapp/landing.html",
{
"messageR": "thanks for refering your friends. You will get extra one month of our services for every 3 joinings from your referal link"
},
)
def verifyToken(request):
if request.method == "POST":
# Yameen Vinchu
# Remove whiteSpace from token
_token = request.POST["token"]
strip_token = _token.strip(' ')
print(strip_token, 'strip_token')
print('db',gift.objects.filter(token=strip_token))
if gift.objects.filter(token=strip_token).exists():
x = gift.objects.get(token=request.POST["token"])
print('working --> ',x)
if x.email == request.user.email and x.plan == "deactivated":
x.plan = "activated"
x.save()
if privilegedUser1.objects.filter(user=request.user).exists():
y = privilegedUser1.objects.get(user=request.user)
y.months += 1
y.is_active = "yes"
y.save()
else:
y = privilegedUser1()
y.id = int(privilegedUser1.objects.all().last().id)+1
y.months = 1
y.user = request.user
y.is_active = "yes"
y.save()
cd = centralDatabase.objects.get(user_id=request.user)
cd.priviledgedMember = True
cd.save()
subject = "A pledge is redeemed"
sender_email = x.user.email
context = {
"Name": sender_email,
"claimName": x.name
}
# mnfnsendemail(sender_email, subject,
# "payment/templates/payments/MR17.html", context)
sendmail(to_email=[sender_email],email_code="GT12",key_value=context)
# (whomtosend,titleofmail, email_template, context,from_email=settings.EMAIL_HOST_USER)
request.session["message"] = "Gift Token Applied Successfully"
# return render(request, 'payments/verifytoken.html', {'message': 'Gift Token Verified Successfully'})
return redirect("base")
else:
return render(
request, "Privilege/index.html", {
"message2": "Invalid Token"}
)
else:
return render(
request, "Privilege/index.html", {
"message2": "Invalid Token"}
)
return render(request, "Privilege/index.html", {})
def verifyToken2(request):
if request.method == "POST":
# Yameen Vinchu
# Remove whiteSpace from token
_token = request.POST["token"]
strip_token = _token.strip(' ')
# print(strip_token, 'strip_token')
if gift.objects.filter(token=strip_token).exists():
x = gift.objects.get(token=request.POST["token"])
# print(x)
if x.email == request.user.email and x.plan == "deactivated":
x.plan = "activated"
x.save()
if privilegedUser1.objects.filter(user=request.user).exists():
y = privilegedUser1.objects.get(user=request.user)
y.months += 1
y.is_active = "yes"
y.save()
else:
y = privilegedUser1()
y.id = int(privilegedUser1.objects.all().last().id) + 1
y.months = 1
y.user = request.user
y.is_active = "yes"
y.save()
cd = centralDatabase.objects.get(user_id=request.user)
cd.priviledgedMember = True
cd.save()
subject = "A pledge is redeemed"
sender_email = x.user.email
context = {
"Name": sender_email,
"claimName": x.name
}
# mnfnsendemail(sender_email, subject,
# "payment/templates/payments/MR17.html", context)
sendmail(to_email=[sender_email], email_code="GT12", key_value=context)
# (whomtosend,titleofmail, email_template, context,from_email=settings.EMAIL_HOST_USER)
request.session["message"] = "Gift Token Applied Successfully"
# return render(request, 'payments/verifytoken.html', {'message': 'Gift Token Verified Successfully'})
return redirect("base")
else:
return render(
request, "payments/verifytoken.html", {
"message2": "Invalid Token"}
)
else:
return render(
request, "payments/verifytoken.html", {
"message2": "Invalid Token"}
)
return render(request, "payments/verifytoken2.html", {})
def cancel(request):
return render(request, "payments/cancel.html", {})
def sendMail(request):
x = privilegedUser1.objects.filter(is_active="yes")
date_limitB = timezone.now() + relativedelta(days=7) # 7 days later date
date_limitA = timezone.now() # today's date
for i in x:
if (i.dateSubscribed + relativedelta(months=i.months)) <= date_limitB:
# email_message = EmailMessage(
# "Membership Expiry Warning",
# "Hi "+str(i.user.first_name) + " "+str(i.user.last_name)+",\nYour subscription for MNF Privileged Membership will be expired on "+str(i.dateSubscribed + relativedelta(months=i.months)
# )+".\nPlease renew your subscription of MNF Privileged Membership or Get MNF Life Membership to enjoy our services without any interuption.\nHappy Filming \n MyNextFilm",
# settings.EMAIL_HOST_USER,
# [i.user.email]
# )
# email_message.send()
subject = "Membership Expiry Warning" + "."
from_email = settings.EMAIL_HOST_USER
to = i
context = {
"Name": i,
}
# html_content = render_to_string(
# "payments/email.html", context
# ) # render with dynamic value
# # Strip the html tag. So people can see the pure text at least.
# text_content = strip_tags(html_content)
# # create the email, and attach the HTML version as well.
# msg = EmailMultiAlternatives(
# subject, text_content, from_email, [to])
# msg.attach_alternative(html_content, "text/html")
# msg.send()
sendmail(to_email=[to],email_code="GT13",key_value=context)
return HttpResponse("Mails has been sent successfully.")
# x=privilegedUser.objects.get(user = request.user, is_active = 'yes')
# expiryDate = x.dateSubscribed + relativedelta(months=x.months)
# context['expiry'] = expiryDate
# if timezone.now() > expiryDate:
# x.months = 0
# x.dateSubscribed = x.dateSubscribed
# x.is_active = 'no'
# x.save()
# context['dataP3'] = None
# from payment.models import PromoCode
def Promo(request):
# print("PROMORCODERUNNING")
PCall = PromoCode.objects.filter(status="Activated")
for i in PCall:
if i.ValidTill < timezone.now():
i.status = "Deactivated"
i.save()
if request.method == "POST":
code = request.POST["code"]
subPlan = request.POST["subPlan"]
payment_intent_id = request.POST["pid"]
amount = round(float(request.POST["amount"]), 1)
amtINR = round(float(request.POST["amtINR"]), 1)
# secret_key = request.POST["secret_key"]
desc = request.POST["desc"]
if PromoCode.objects.filter(
PromoCode=code, MembershipType=subPlan, status="Activated"
).exists():
PC = PromoCode.objects.get(
PromoCode=code, MembershipType=subPlan, status="Activated"
)
discount_factor = 1 - ((PC.Discount) / 100)
amount = discount_factor * amount
amtINR = round(discount_factor * amtINR, 2)
pId = stripe.PaymentIntent.modify(
payment_intent_id,
amount=int(amtINR * 100),
)
pid = pId.id
context = {
"pk": STRIPE_PUB_KEY,
"PCid": PC.id,
"amtINR": amtINR,
"pid": pid,
# 'secret_key': pId.client_secret,
"STRIPE_PUBLISHABLE_KEY": stripe.api_key,
"desc": desc,
"amount": amount,
"subPlan": subPlan,
"promo_message": "promo code applied sucessfully",
"green": True,
}
return render(request, "payments/checkout.html", context)
else:
context = {
"pk": STRIPE_PUB_KEY,
"amtINR": amtINR,
"pid": payment_intent_id,
# 'secret_key': secret_key,
"STRIPE_PUBLISHABLE_KEY": stripe.api_key,
"desc": desc,
"amount": amount,
"subPlan": subPlan,
"promo_message": "invalid promo code",
}
return render(request, "payments/checkout.html", context)
basepath = BasePath()
def custom_conversion_rate():
url = "https://openexchangerates.org/api/latest.json?app_id=2fd4530bcb1146a9970d586e81b89a95"
response = urlopen(url)
data_json = json.loads(response.read())
conversionRates = open(
rf"{basepath}/MNF/json_keys/conversionRates.json", "w")
conversionRates.write(json.dumps(data_json))
conversionRates.close()
# print("doneRate23")
# use this function to get latest conversion rate
def get_custom_conversion_rate(request):
conversionRates = open(
rf"{basepath}/MNF/json_keys/conversionRates.json", "r")
rate_json = json.load(conversionRates)
return HttpResponse(rate_json["rates"]["INR"])
def eventsMembers_paymentList(request):
monthly_member = settings.MONTHLY_MEMBER
yearly_member = settings.YEARLY_MEMBER
life_member = settings.LIFE_MEMBER
im_discount = settings.IM_DISCOUNT
e_discount = settings.EMPLOY_DISCOUNT
# yearly_member_add = settings.YEARLY_MEMBER_ADDITIONAL
# life_member_add = settings.LIFE_MEMBER_ADDITIONAL
monthly_emp = monthly_member - (monthly_member * e_discount / 100)
yearly_emp = yearly_member - (yearly_member * e_discount / 100)
life_emp = life_member - (life_member * e_discount / 100)
monthly_im = monthly_member - (monthly_member * im_discount / 100)
yearly_im = yearly_member - (yearly_member * im_discount / 100)
monthly_im_emp = monthly_emp - (monthly_emp * monthly_im / 100)
yearly_im_emp = yearly_emp - (yearly_emp * yearly_im / 100)
dict = {
"monthly_member": monthly_member,
"yearly_member": yearly_member,
"life_member": life_member,
"monthly_emp": monthly_emp,
"yearly_emp": yearly_emp,
"life_emp": life_emp,
"monthly_im": monthly_im,
"yearly_im": yearly_im,
"monthly_im_emp": monthly_im_emp,
"yearly_im_emp": yearly_im_emp
}
# print("test25", dict)
# pricesfile = open(rf"{basepath}/MNF/relationshipmanager/templates/relationshipmanager/prices.json","w")
# pricesfile.write(json.dumps(dict))
# pricesfile.close()
return HttpResponse("Testing completed")
def refund(request):
if request.user.is_staff:
# detailslist = PaymentData.objects.all().order_by('-date')[:1]
detailslist = PaymentData.objects.all().order_by('-date')
serializeddata = PaymentDataSerializer(detailslist, many=True).data
context = {
"list": serializeddata,
}
# return render(request, "payments/refund.html", context)
return JsonResponse(context)
else:
return HttpResponse("You are not allowed to access this resource.")
class Refunds(viewsets.ReadOnlyModelViewSet):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
pagination_class = PageNumberPagination
pagination_class.page_size = 15
queryset = Refund.objects.all().order_by("-created")
serializer_class = RefundSerializer
class Stripe_Refund_Accept_View(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def put(self, request, pk=None):
# print("Running")
refund_obj = Refund.objects.get(r_id=pk)
# stripe.api_key="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"
stripe.api_key = settings.STRIPE_SECRET_KEY
try:
refund = stripe.Refund.create(charge=refund_obj.payment_id)
if refund.status == 'succeeded':
refund_obj.status = "Accept"
refund_obj.save()
context = {
"message": "Refund Success!"
}
return Response(context, status=status.HTTP_200_OK)
else:
refund_obj.status = "Failed"
refund_obj.save()
context = {
"message": "Refund Failed!"
}
return Response(context, status=status.HTTP_200_OK)
except Exception as error:
return Response(status=status.HTTP_502_BAD_GATEWAY)
class Stripe_Refund_Reject_View(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def put(self, request, pk=None):
refund_obj = Refund.objects.get(r_id=pk)
refund_obj.status = "Reject"
refund_obj.save()
context = {
"message": "Success!"
}
return Response(context, status=status.HTTP_200_OK)
class RazorPay_Refund_Accept_View(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def put(self, request, pk):
refund_obj = Refund.objects.get(r_id=pk)
client = razorpay.Client(
auth=(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET))
amount = float(refund_obj.amount) # Example decimal amount
amount_in_cents = str(int(amount * 100))
# print(refund_obj.payment_id)
refund = client.payment.refund(refund_obj.payment_id, {
'amount': amount_in_cents})
if refund.get('status') == 'processed':
refund_obj.status = "Accept"
refund_obj.save()
context = {"message": "Refund Success!"}
return Response(context, status=status.HTTP_200_OK)
else:
refund_obj.status = "Failed"
refund_obj.save()
context = {"message": "Refund Failed!"}
return Response(context, status=status.HTTP_200_OK)
class RazorPay_Refund_Reject_View(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def put(self, request, pk):
refund_obj = Refund.objects.get(r_id=pk)
refund_obj.status = "Reject"
refund_obj.save()
context = {"message": "Success!"}
# return Response(context, status=status.HTTP_200_OK)
return JsonResponse(context)
def create(request):
user = User.objects.get(id=16)
# print(user)
Refund.objects.create(
payment_method="Razorpay",
payment_id="ececececececec",
service_name="Subtitle",
service_id="ececececececec",
claimed_user=user,
amount=200,
reason="jfjkfhejf"
)
return HttpResponse("Ok")
@login_required
def refund_admin(request, id):
if request.user.is_superuser:
payment_object = CentralPayment.objects.get(id=id)
if payment_object.payment_status == "refunded":
return redirect('refpdadmin')
try:
gateway = payment_object.payment_gateway
if gateway == "razorPay":
RAZOR_KEY = settings.RAZORPAY_KEY_ID
RAZOR_SECRET = settings.RAZORPAY_KEY_SECRET
client = razorpay.Client(auth=(RAZOR_KEY, RAZOR_SECRET))
razorpay_payment_instance = client.payment.fetch(payment_object.payment_id)
amount = float(razorpay_payment_instance["amount"])
# amount_in_cents = str(int(amount * 100))
refund = client.payment.refund(payment_object.payment_id)
if refund.get('status') == 'processed':
print("Refund Done", refund)
payment_object.payment_status = "refunded"
payment_object.save()
return redirect('refpdadmin')
else:
print("Refund Not Done", refund)
payment_object.payment_status = "refunded-rejected"
payment_object.save()
return redirect('refpdadmin')
elif gateway == "Stripe":
amount = float(payment_object.amount_charged)
amount_in_cents = str(int(amount * 100))
refund = stripe.Refund.create(payment_intent=payment_object.payment_id, amount=amount_in_cents)
if refund.status == 'succeeded':
print("Refund Done", refund)
payment_object.payment_status = "refunded"
payment_object.save()
return redirect('refpdadmin')
else:
print("Refund Not Done", refund)
payment_object.payment_status = "refunded-rejected"
payment_object.save()
return redirect('refpdadmin')
else:
return redirect('refpdadmin')
except Exception as error:
print("Error is:", error)
return redirect('refpdadmin')
def ForSomeWork(request):
return render(request, 'payments/for_some_work.html')