diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..41ea1fc --- /dev/null +++ b/Pipfile @@ -0,0 +1,16 @@ +[[source]] +name = "pypi" +verify_ssl = true +url = "https://pypi.org/simple" + +[packages] +django = "==1.11" +gunicorn = "*" +whitenoise = "*" +dj-database-url = "*" +africastalking = "*" + +[dev-packages] + +[requires] +python_version = "3.5.2" diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..2099144 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn ussd_app.wsgi --log-file - \ No newline at end of file diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/admin.py b/core/admin.py new file mode 100644 index 0000000..2514f8b --- /dev/null +++ b/core/admin.py @@ -0,0 +1,6 @@ +from django.contrib import admin +from .models import Transaction, WL_Account +# Register your models here. + +admin.site.register(Transaction) +admin.site.register(WL_Account) diff --git a/core/apps.py b/core/apps.py new file mode 100644 index 0000000..26f78a8 --- /dev/null +++ b/core/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + name = 'core' diff --git a/core/migrations/__init__.py b/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/models.py b/core/models.py new file mode 100644 index 0000000..e3f9904 --- /dev/null +++ b/core/models.py @@ -0,0 +1,88 @@ +from django.db import models + +# Create your models here. +class WL_Account(models.Model): + phone_number = models.CharField(max_length=25) + #credit + balance = models.DecimalField(default=0, max_digits=10, decimal_places=2) + #owing + debt = models.DecimalField(default=0, max_digits=10, decimal_places=2) + bank_name = models.CharField(max_length=30, blank=True) + bank_code = models.IntegerField(null=True) + account_name = models.CharField(max_length=60, blank=True) + account_number = models.CharField(max_length=10, blank=True) + reg_data = models.DateField(auto_now_add=True) + + @classmethod + def get_wl_account(cls, phone_number): + try: + customer = cls.objects.get(phone_number=phone_number) + except: + customer = None + return customer + + def get_last_transaction(self, status): + if status == Transaction.PENDING: + transaction_instance = self.transactions.filter(status=Transaction.PENDING).last() + else: + transaction_instance = self.transaction.last() + return transaction_instance + + def repay_debts(self): + if self.balance > self.debt: + self.balance -= self.debt + self.debt = 0 + self.save() + return "END your debt has been successfully cleared" + + if self.debt == 0: + return "END You don't have any outstanding debts" + + if self.balance < self.debt: + return "END You don't have sufficient money to repay your loan. Try depositing money" + + def __str__(self): + return "{}".format(self.phone_number) + +class Transaction(models.Model): + LOAN = 'loan' + DEPOSIT = 'deposit' + PENDING = 'pending' + APPROVED = 'approved' + CONCLUDED = 'concluded' + PAYED = 'payed' + NOT_PAYED = 'not_paid' + DECLINED = 'declined' + + TRANSACTION_TYPES = ( + (LOAN, 'Loan'), + (DEPOSIT, 'Deposit') + ) + + STATUS_TYPE = ( + (PENDING, 'Pending'), + (CONCLUDED, 'Concluded'), + (PAYED, 'Payed'), + (NOT_PAYED, 'Not Payed'), + (DECLINED, 'Declined'), + (APPROVED, 'Approved') + ) + + transaction_id = models.CharField(max_length=255) + status=models.CharField(max_length=30,null=True, choices=STATUS_TYPE) + type = models.CharField(max_length=30, null=True, choices=TRANSACTION_TYPES) + amount = models.DecimalField(null=True, max_digits=10, decimal_places=2) + transaction_fee = models.DecimalField(null=True, max_digits=10, decimal_places=2) + date=models.DateField(auto_now_add=True) + account = models.ForeignKey(WL_Account, related_name="transactions") + + def mark_as_paid(self, **kwargs): + self.status = self.CONCLUDED + self.save() + self.account.balance += self.amount + self.account.save() + return self.account.balance + + def update_debt_balance(self, amount): + self.account.debt += amount + self.account.save() \ No newline at end of file diff --git a/core/tests.py b/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/core/utils/ATutils.py b/core/utils/ATutils.py new file mode 100644 index 0000000..7a5a2e8 --- /dev/null +++ b/core/utils/ATutils.py @@ -0,0 +1,326 @@ +import os +from ..models import WL_Account, Transaction + +import africastalking + +START_TEXT = "" +CURRENCY = "NGN" +PRODUCT_NAME = "wazobia_loans" + +# MENU +MY_COOPERATIVE = "1" +WAZOBIA_LOANS = "2" +AGBETUNTUN = "3" +REQUEST_CALL = "4" + +# SUBMENU + +# MYCOOPERATIVE +MC_CHECK_BALANCE = "1*1" +MC_REQUEST_LOAN = "1*2" +MC_DEPOSIT = "1*3" + +# WAZOBIA_LOANS +WL_REGISTER = "2*1" +WL_REPAY_LOAN = "2*2" +WL_DEPOSIT = "2*3" +WL_REQUEST_LOAN = "2*4" +WL_REQUEST_CALL = "2*5" + +MENU_RESPONSES = { + START_TEXT: """ + CON Welcome, Select your service \r + 1. My Cooperative \r + 2. Wazobia Loans \r + 3. Join Agbetuntun \r + 4. Request a Call \r + """, + + MY_COOPERATIVE: """ + CON What service will you like to use in your Cooperative account. \r + 1. Check Balance \r + 2. Accept Loan \r + 3. Make Deposit \r + """, + + WAZOBIA_LOANS: """ + CON Welcome to Wazobia Loans, Kindly choose a service \r + 1. Register \r + 2. Repay Loan \r + 3. Make Deposit \r + 4. Request Loan \r + 5. Request a call \r + """, + AGBETUNTUN: "END Coming Soon", + +} + +MENU_2_RESPONSES = { + WL_REGISTER: """ + CON Enter your account details in the form => Kanu James, 2034568902, 1 \r + 1. FCMB Nigeria \r + 2. Zenith Nigeria \r + 3. Access Nigeria \r + 4. Providus Nigeria \r + 5. Sterling Nigeria \r + """, + + WL_DEPOSIT: """ + CON You currently owe {}, How much will you like to deposit? \r + """, + + WL_REQUEST_LOAN: """ + CON How much loan do you need? \r + """, + + WL_REQUEST_CALL: """ + END This feature will be available soon + """, + + MC_CHECK_BALANCE: """ + END This feature will be available soon + """, + + MC_DEPOSIT: """ + END This feature will be available soon + """, + + MC_REQUEST_LOAN: """ + END This feature will be available soon + """, +} + + +BANKS_LIST = { + "1": {"name": "FCMB Nigeria", "code": 234001}, + "2": {"name": "Zenith Nigeria", "code": 234002}, + "3": {"name": "Access Nigeria", "code": 234003}, + "4": {"name": "Providus Nigeria", "code": 234007}, + "5": {"name": "Sterling Nigeria", "code": 234010}, +} + + +class ATutils: + def __init__(self, **kwargs): + self.username = "sandbox" + self.api_key = os.environ.get('API_KEY') + self.phone_number = kwargs.get('phoneNumber', [None])[0] + self.caller_number = kwargs.get('callerNumber', [None])[0] + self.session_id = kwargs.get('sessionId', [None])[0] + self.service_code = kwargs.get('serviceCode', [None])[0] + self.text = kwargs.get('text', [""])[0] + self.level = len(self.text.split('*')) + + #voice parameters + self.is_active = kwargs.get('isActive', [None])[0] + self.voice_duration = kwargs.get('durationInSeconds', [None])[0] + + + self.customer = WL_Account.get_wl_account( + phone_number=self.phone_number) + + africastalking.initialize(username=self.username, api_key=self.api_key) + self.payment = africastalking.Payment + self.voice = africastalking.Voice + + def handle_calls(self, **kwargs): + duration = self.voice_duration + try: + if self.is_active == '1': #make the call when isActive is 1 + + caller_number = self.caller_number or self.phone_number + + # Compose the response + response = '' + response += '' + response += 'Thanks for calling :) Good bye!' + response += '' + return response + else: + currencyCode = CURRENCY + return "END Call has been initiated, An agent will call soonest" + + except: + print ('exception', duration) + + def register_wl_customer(self, *args, **kwargs): + # get account name and number seperated by phone numbers + account_details = self.text.split('*')[2].split(',') + + if len(account_details) != 3: + return "END You inputted invalid values, Try again!" + + account_name, account_number, bank_short_code = account_details + + print(account_details) + + if bank_short_code.strip(" ") not in ["1", "2", "3", "4", "5"]: + return "END You selected an invalid bank, Try again!" + + # check if number already exists in db + customer, created = WL_Account.objects.get_or_create( + phone_number=self.phone_number, + ) + + if created: + customer.account_name = account_name + customer.account_number = account_number.strip(" ") + customer.bank_code = BANKS_LIST[bank_short_code.strip(" ")]["code"] + customer.bank_name = BANKS_LIST[bank_short_code.strip(" ")]["name"] + customer.save() + return "END {}, your account has been successfully created :) !".format(account_name.split(' ')[0]) + + return "END {}, your account already exists !!!".format(account_name.split(' ')[0]) + + def handle_wl_deposit(self): + deposit_amount = self.text.strip(WL_DEPOSIT + "*") + narration = "Deposit from {} - {}".format( + self.customer.account_name, self.customer.phone_number) + + account_details = { + 'accountNumber': self.customer.account_number, + 'bankCode': self.customer.bank_code, + 'accountName': self.customer.account_name + } + + transaction_id = self.payment.bank_checkout( + product_name=PRODUCT_NAME, + currency_code=CURRENCY, + amount=deposit_amount, + narration=narration, + bank_account=account_details + ) + + print("transaction id =>", transaction_id) + if not transaction_id: + return "END Your deposit was not successful" + + trans_instance = Transaction.objects.create( + account=self.customer, + type=Transaction.DEPOSIT, + transaction_id=transaction_id, + status=Transaction.PENDING, + amount=deposit_amount + ) + + return "CON Please enter OTP sent to your phone,\r\n" + + def pay_loan(self): + loan_amount = self.text.split('*')[2] + recipients = [ + {"bankAccount": { + "accountNumber": self.customer.account_number, + "accountName": self.customer.account_name, + "bankCode": self.customer.bank_code + }, + "currencyCode": CURRENCY, + "amount": loan_amount, + "narration": "Loan to {} - {}".format(self.customer.account_name, self.customer.phone_number), + "metadata": {} + } + ] + result = self.payment.bank_transfer( + product_name=PRODUCT_NAME, recipients=recipients)["entries"][0] + + print(result) + + if "errorMessage" in result.keys(): + return "END {}".format(result["errorMessage"]) + + if result.status in ['InvalidRequest', 'NotSupported', 'Failed']: + return "END An error occured when paying the loan, try again later" + + trans_instance = Transactions.objects.create( + account=self.customer, + transaction_id=result["transactionId"], + status=Transaction.PENDING, + type=Transaction.LOAN, + amount=loan_amount, + transaction_fee=result["transactionFee"] + ) + + #update debt balance + self.customer.update_debt_balance(loan_amount) + + return "END Your request has been processed. you will recieve your loan shortly" + + def confirm_wl_deposit(self): + otp = self.text.split('*')[3] + transaction_amount = self.text.split('*')[2] + last_transaction = self.customer.get_last_transaction( + status=Transaction.PENDING) + + validate = self.payment.validate_bank_checkout( + transaction_id=last_transaction.transaction_id, otp=otp) + + if validate: + new_balance = last_transaction.mark_as_paid( + amount=transaction_amount) + response = """ + END Your deposit of {} was successfuly completed,\r\n + New Balance=> {}\r\n + """.format(transaction_amount, new_balance) + else: + response = "END Your deposit was not successful, Try again later \r" + + return response + + def get_ussd_response(self, *args, **kwargs): + # main menu + print(self.text) + + # return menu reponses (Level 1) + if self.level == 1: + if self.text in MENU_RESPONSES.keys(): + response = MENU_RESPONSES[self.text] + return response + + if self.text == REQUEST_CALL: + response = self.handle_calls() + return response + + # return sub menu responses (Level 2) + if self.level == 2: + if self.text in MENU_2_RESPONSES or self.text == WL_REPAY_LOAN: + + if self.text == WL_REGISTER: + if self.customer: + return "END {}, your account already exists !!!".format(self.customer.account_name.split(' ')[0]) + + # only registered users can make use of service + if self.text in [WL_DEPOSIT, WL_REPAY_LOAN, WL_REQUEST_LOAN]: + if not self.customer: + return "CON Sorry but you can't make use of this service till you register" + + if self.text == WL_REPAY_LOAN: + response = self.customer.repay_debts() + return response + + return MENU_2_RESPONSES[self.text].format(self.customer.debt) + + response = MENU_2_RESPONSES[self.text] + return response + + if self.level == 3: + # WAZOBIA LOANS + if self.text.startswith(WL_REGISTER): + response = self.register_wl_customer() + return response + + if self.text.startswith(WL_DEPOSIT): + response = self.handle_wl_deposit() + return response + + if self.text.startswith(WL_REQUEST_LOAN): + response = self.pay_loan() + return response + + if self.level == 4: + if self.text.startswith(WL_DEPOSIT): + response = self.confirm_wl_deposit() + return response + + if self.text.startswith(WL_REQUEST_LOAN): + return + + return "END You entered an invalid option" diff --git a/core/utils/__init__.py b/core/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/views.py b/core/views.py new file mode 100644 index 0000000..71aef59 --- /dev/null +++ b/core/views.py @@ -0,0 +1,26 @@ +from django.shortcuts import render +from django.views.decorators.csrf import csrf_exempt +from django.http import HttpResponse +from core.utils.ATutils import ATutils +# Create your views here. + +@csrf_exempt +def handle_ussd(request): + if request.method == "POST": + print(dict(request.POST)) + api_instance = ATutils(**request.POST) + response = api_instance.get_ussd_response() + print(response) + return HttpResponse(response) + + return HttpResponse(status=200) + +@csrf_exempt +def handle_voice(request): + if request.method == 'POST': + api_instance = ATUtils(**request.POST) + response = api_instance.handle_calls() + else: + response = 'Ooops, sorry... #wink' + + return HttpResponse(response, content_type='application/xml') \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..827b3c0 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ussd_app.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8e48309 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +dj-database-url==0.5.0 +Django==1.11 +gunicorn==19.9.0 +pytz==2018.5 +whitenoise==3.3.1 diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..5f61493 --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.5.2 \ No newline at end of file diff --git a/ussd_app/__init__.py b/ussd_app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ussd_app/settings.py b/ussd_app/settings.py new file mode 100644 index 0000000..7b2e004 --- /dev/null +++ b/ussd_app/settings.py @@ -0,0 +1,121 @@ +""" +Django settings for ussd_app project. + +Generated by 'django-admin startproject' using Django 1.11. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'z(ehi@ww8z@#us2t(%aa^+l9xa0u3q$cokq+o-8w9#w()o(jgn' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'core', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'ussd_app.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'ussd_app.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/ussd_app/urls.py b/ussd_app/urls.py new file mode 100644 index 0000000..4380a0f --- /dev/null +++ b/ussd_app/urls.py @@ -0,0 +1,24 @@ +"""ussd_app URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import url, include +from django.contrib import admin +from core import views + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + url(r'^ussd/$', views.handle_ussd ), + url(r'^voice/$', views.handle_voice ), +] diff --git a/ussd_app/wsgi.py b/ussd_app/wsgi.py new file mode 100644 index 0000000..3684ca1 --- /dev/null +++ b/ussd_app/wsgi.py @@ -0,0 +1,19 @@ +""" +WSGI config for ussd_app project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application +from whitenoise.django import DjangoWhiteNoise + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ussd_app.settings") + +application = get_wsgi_application() + +# application = DjangoWhiteNoise(application) \ No newline at end of file