activate item javascript calculator

This commit is contained in:
deflax 2017-07-21 02:30:09 +03:00
parent 9d930a0450
commit 11c5712675
8 changed files with 177 additions and 28 deletions

View file

@ -4,5 +4,5 @@ from wtforms import validators, ValidationError
from wtforms.fields.html5 import EmailField from wtforms.fields.html5 import EmailField
class ActivateForm(FlaskForm): class ActivateForm(FlaskForm):
period = SelectField('Domain Period', choices=[('1 Year', 12), ('2 Years', 24)]) period = SelectField('Domain Period', choices=[(12, '1 Year'), (24, '2 Years'), (36, '3 Years')], coerce=int)
submit = SubmitField('Activate') submit = SubmitField('Activate')

View file

@ -33,13 +33,16 @@ def activate(itemid=0):
abort(404) abort(404)
service = Service.query.filter_by(pid=itemid).first() service = Service.query.filter_by(pid=itemid).first()
price = float(service.price) if service.enabled == True and service.warning == False:
abort(404)
ppm = float(service.price)
form = ActivateForm(period=int(service.period)) form = ActivateForm(period=int(service.period))
owner = service.owner owner = service.owner
if owner.confirmed and form.validate_on_submit(): if owner.confirmed and form.validate_on_submit():
if owner.wallet < price: total = ppm * form.period.data
flash('Insufficient Funds') if owner.wallet < total:
flash('Activation costs {} {}. Insufficient Funds'.format(total, owner.currency))
return redirect(url_for('uinvoice.transactions')) return redirect(url_for('uinvoice.transactions'))
current_app.logger.info('[{}] Charge service: {}'.format(owner.email, service.description)) current_app.logger.info('[{}] Charge service: {}'.format(owner.email, service.description))
today = datetime.utcnow() today = datetime.utcnow()
@ -48,7 +51,7 @@ def activate(itemid=0):
extradays = relativedelta(today, days=+(service.daysleft)) extradays = relativedelta(today, days=+(service.daysleft))
service.date_last_charge = today + extradays service.date_last_charge = today + extradays
service.period = form.period.data service.period = form.period.data
service.daysleft = daysleft.days + extradays.days - 1 service.daysleft = daysleft.days + extradays.days
service.warning = False service.warning = False
service.enabled = True service.enabled = True
db.session.commit() db.session.commit()
@ -64,5 +67,5 @@ def activate(itemid=0):
return redirect(url_for('admin.list_items')) return redirect(url_for('admin.list_items'))
else: else:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
return render_template('smanager/activate.html', form=form, service=service, total=service.price) return render_template('smanager/activate.html', form=form, service=service, ppm=ppm, total=(ppm * service.period))

View file

@ -1,6 +1,29 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Activate service #{{ service.pid }}{% endblock %} {% block head %}
{{ super() }}
<script type="text/javascript">
function getPricePerMonth()
{
var period = 0;
var periodselect = document.getElementById('period');
period = periodselect.value;
return period;
}
function calculateTotal()
{
var period = getPricePerMonth();
var ppm = {{ ppm }};
var total = 0;
total = period * ppm;
var divobj = document.getElementById('totalPrice');
divobj.innerHTML = "Total Price: "+total;
}
</script>
{% endblock %}
{% block title %}Activate service{% endblock %}
{% block page_content %} {% block page_content %}
@ -8,20 +31,20 @@
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-info"> <div class="panel panel-info">
<div class="panel-heading">Activate</div> <div class="panel-heading">Activate service {{ service.description }}</div>
<div class="panel-body"> <div class="panel-body">
<form method="POST" action"{{ url_for('smanager.activate', itemid=service.pid) }}"> <form method="POST" action"{{ url_for('smanager.activate', itemid=service.pid) }}">
<h3> <p>
{{ form.period.label }} {{ form.period }}<br /> {{ form.period.label }} {{ form.period(**{"onchange":"calculateTotal()"}) }}<br />
{% for error in form.period.errors %} {% for error in form.period.errors %}
{{ error }}<br /> {{ error }}<br />
{% endfor %} {% endfor %}
<h3>
---<br /> ---<br />
Total = {{ total }} <div id="totalPrice">Previous Period: {{ total }}</div>
</h3> </h3>
<p>
{{ form.csrf_token() }} {{ form.csrf_token() }}
{{ form.submit }} {{ form.submit }}
</p> </p>

View file

@ -48,9 +48,6 @@ var myChart = new Chart(ctx, {
<div class="row"> <div class="row">
<div class="col-md-4">
{% include "/settings/acc_avatar.html" %}
</div>
<div class="col-md-8"> <div class="col-md-8">
<div class="panel panel-info"> <div class="panel panel-info">
@ -59,6 +56,11 @@ var myChart = new Chart(ctx, {
<canvas id="transchart" height="80"></canvas> <canvas id="transchart" height="80"></canvas>
</div></div></div> </div></div></div>
<div class="col-md-4">
{% include "/settings/acc_avatar.html" %}
</div>
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-info"> <div class="panel panel-info">
<div class="panel-heading">Transactions</div> <div class="panel-heading">Transactions</div>

View file

@ -1,6 +1,29 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Activatei deployment #{{ deploy.machine_id }}{% endblock %} {% block head %}
{{ super() }}
<script type="text/javascript">
function getPricePerMonth()
{
var period = 0;
var periodselect = document.getElementById('period');
period = periodselect.value;
return period;
}
function calculateTotal()
{
var period = getPricePerMonth();
var ppm = {{ ppm }};
var total = 0;
total = period * ppm;
var divobj = document.getElementById('totalPrice');
divobj.innerHTML = "Total Price: "+total;
}
</script>
{% endblock %}
{% block title %}Activate deployment{% endblock %}
{% block page_content %} {% block page_content %}
@ -8,20 +31,20 @@
<div class="col-md-12"> <div class="col-md-12">
<div class="panel panel-info"> <div class="panel panel-info">
<div class="panel-heading">Activate</div> <div class="panel-heading">Activate deployment {{ deploy.machine_alias }}</div>
<div class="panel-body"> <div class="panel-body">
<form method="POST" action"{{ url_for('vmanager.activate', itemid=deploy.machine_id) }}"> <form method="POST" action"{{ url_for('vmanager.activate', itemid=deploy.machine_id) }}">
<h3> <h3>
CPU x {{ deploy.machine_cpu }} cores = {{ cpu_cost }}<br /> CPU: {{ deploy.machine_cpu }} cores<br />
Memory x {{ deploy.machine_mem }} MB = {{ mem_cost }}<br /> Memory: {{ deploy.machine_mem }} MB<br />
Storage x {{ deploy.machine_hdd }} GB = {{ hdd_cost }}<br /> Storage: {{ deploy.machine_hdd }} GB<br />
{{ form.period.label }} {{ form.period }}<br /> {{ form.period.label }} {{ form.period(**{"onchange":"calculateTotal()"}) }}<br />
{% for error in form.period.errors %} {% for error in form.period.errors %}
{{ error }}<br /> {{ error }}<br />
{% endfor %} {% endfor %}
---<br /> ---<br />
Total = {{ total }} <div id="totalPrice">Previous Period: {{ total }}</div>
</h3> </h3>
<p> <p>

View file

@ -97,7 +97,8 @@ def deploy(product_id=None):
'vps_cpu': form.cpu.data, 'vps_cpu': form.cpu.data,
'vps_mem': form.mem.data, 'vps_mem': form.mem.data,
'vps_hdd': form.hdd.data, 'vps_hdd': form.hdd.data,
'vps_ipv4': form.ipv4.data } 'vps_ipv4': form.ipv4.data,
'vps_mac': form.mac.data }
try: try:
query = contact_proxmaster(data, 'vmcreate') query = contact_proxmaster(data, 'vmcreate')
@ -106,7 +107,7 @@ def deploy(product_id=None):
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
if query is not None: if query is not None:
deployment = Deployment(user_id=client_id, product_id=product_id, machine_alias=form.servername.data, machine_id=query['cube'], machine_cpu=form.cpu.data, machine_mem=form.mem.data, machine_hdd=form.hdd.data, date_expire=(datetime.utcnow() + timedelta(days=30)), enabled=True) deployment = Deployment(user_id=client_id, product_id=product_id, machine_alias=form.servername.data, machine_id=query['cube'], machine_cpu=form.cpu.data, machine_mem=form.mem.data, machine_hdd=form.hdd.data, enabled=True)
db.session.add(deployment) db.session.add(deployment)
db.session.commit() db.session.commit()
@ -132,16 +133,19 @@ def activate(itemid=0):
abort(404) abort(404)
deploy = Deployment.query.filter_by(machine_id=itemid).first() deploy = Deployment.query.filter_by(machine_id=itemid).first()
if deploy.enabled == True and deploy.warning == False:
abort(404)
cpu_cost = deploy.machine_cpu * current_app.config['CPU_RATIO'] cpu_cost = deploy.machine_cpu * current_app.config['CPU_RATIO']
mem_cost = ( deploy.machine_mem / 1024 ) * current_app.config['MEM_RATIO'] mem_cost = ( deploy.machine_mem / 1024 ) * current_app.config['MEM_RATIO']
hdd_cost = deploy.machine_hdd * current_app.config['HDD_RATIO'] hdd_cost = deploy.machine_hdd * current_app.config['HDD_RATIO']
total = round(cpu_cost + mem_cost + hdd_cost,2) ppm = round(cpu_cost + mem_cost + hdd_cost)
form = ActivateForm(period=int(deploy.period)) form = ActivateForm(period=int(deploy.period))
owner = deploy.owner owner = deploy.owner
if owner.confirmed and form.validate_on_submit(): if owner.confirmed and form.validate_on_submit():
total = ppm * form.period.data
if owner.wallet < total: if owner.wallet < total:
flash('Insufficient Funds') flash('Activation costs {} {}. Insufficient Funds'.format(total, owner.currency))
return redirect(url_for('uinvoice.transactions')) return redirect(url_for('uinvoice.transactions'))
current_app.logger.info('[{}] Charge deployment: {}'.format(owner.email, deploy.machine_id)) current_app.logger.info('[{}] Charge deployment: {}'.format(owner.email, deploy.machine_id))
today = datetime.utcnow() today = datetime.utcnow()
@ -150,7 +154,7 @@ def activate(itemid=0):
extradays = relativedelta(today, days=+(deploy.daysleft)) extradays = relativedelta(today, days=+(deploy.daysleft))
deploy.date_last_charge = today + extradays deploy.date_last_charge = today + extradays
deploy.period = form.period.data deploy.period = form.period.data
deploy.daysleft = daysleft.days + extradays.days - 1 deploy.daysleft = daysleft.days + extradays.days
deploy.warning = False deploy.warning = False
deploy.enabled = True deploy.enabled = True
db.session.commit() db.session.commit()
@ -161,11 +165,13 @@ def activate(itemid=0):
owner.wallet = owner.wallet - total owner.wallet = owner.wallet - total
db.session.commit() db.session.commit()
flash('Deployment {} activated for {} month(s)'.format(str(deploy.machine_alias), form.period.data))
if owner.is_administrator: if owner.is_administrator:
return redirect(url_for('admin.list_items')) return redirect(url_for('admin.list_items'))
else: else:
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
return render_template('vmanager/activate.html', form=form, deploy=deploy, cpu_cost=cpu_cost, mem_cost=mem_cost, hdd_cost=hdd_cost, total=total) return render_template('vmanager/activate.html', form=form, deploy=deploy, cpu_cost=cpu_cost, mem_cost=mem_cost, hdd_cost=hdd_cost, ppm=ppm, total=(ppm * deploy.period))
@vmanager.route('/<cmd>/<int:vmid>') @vmanager.route('/<cmd>/<int:vmid>')
@login_required @login_required

86
config.py.dist Normal file
View file

@ -0,0 +1,86 @@
import os
import random
import hashlib
import time
basedir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig(object):
#DATABASE
SQLALCHEMY_DATABASE_URI = 'postgresql://proxadmin:CHANGEME@localhost/proxdb'
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
SQLALCHEMY_RECORD_QUERIES = True
SLOW_DB_QUERY_TIME = 0.5
SQLALCHEMY_TRACK_MODIFICATIONS = True
#SQLALCHEMY_ECHO = True
#MAIL
MAIL_SERVER = 'mail.server.tld'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get('MAIL_USERNAME') or 'admin@server.tld'
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') or 'CHANGEME'
MAIL_SUBJECT_PREFIX = '[admin]'
MAIL_SENDER = 'Virtual Office <admin@server.tld>'
MAIL_ADMIN = os.environ.get('MAIL_ADMIN') or 'Proxadmin'
#API
PROXMASTER_URL='https://api.example.tld'
APIKEY='CHANGEME'
ADMIN_EMAIL='adminuser@example.tld'
ADMIN_PREFIX='admin123456'
#MISC
SUPPORTED_LOCALES = ['en']
#SECURITY
SECRET_KEY = 'CHANGEME'
CSRF_ENABLED = True
WTF_CSRF_ENABLED = True
WTF_CSRF_TIME_LIMIT = 180
#SESSION_COOKIE_DOMAIN = "www.example.tld"
#SESSION_COOKIE_SECURE = True
RECAPTCHA_PUBLIC_KEY = "CHANGEME"
RECAPTCHA_PRIVATE_KEY = "CHANGEME"
RECAPTCHA_DATA_ATTRS = {'theme': 'dark'}
#FACEBOOK
FB_APP_ID = 'CHANGEME'
FB_APP_SECRET = 'CHANGEME'
FB_PAGE_ID = 'CHANGEME'
#GOOGLEOAUTH2
GOOGLE_CLIENT_ID = ('CHANGEME'
'.apps.googleusercontent.com')
GOOGLE_CLIENT_SECRET= '6XScleYPVEY5Vvd_GvZ_RHlB'
REDIRECT_UTL = 'https://www.example.tld/auth/oauth2callback'
AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
USER_INFO = 'https://www.googleapis.com/userinfo/v2/me'
REGISTER_BONUS = 5.0
# EXAMPLE DATA
REGIONS = [ ('region1', 'Region1'),
('region2', 'Region2') ]
CPU_RATIO = 4.7
MEM_RATIO = 3.0
HDD_RATIO = 0.4
@staticmethod
def init_app(app):
pass
class ProductionConfig(BaseConfig):
DEBUG = False
class DevelopmentConfig(BaseConfig):
DEBUG = True
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'default': ProductionConfig
}

View file

@ -98,6 +98,9 @@ def autowarn():
print('Deployment "' + deploy.machine_alias + '" is ' + str(daysleft.days) + ' days until expiration. Last charged: ' + lastcharge.strftime('%c') + ' expiry date: ' + expiry.strftime('%c')) print('Deployment "' + deploy.machine_alias + '" is ' + str(daysleft.days) + ' days until expiration. Last charged: ' + lastcharge.strftime('%c') + ' expiry date: ' + expiry.strftime('%c'))
deploy.warning = True deploy.warning = True
db.session.commit() db.session.commit()
else:
deploy.warning = False
db.session.commit()
services_ena = Service.query.filter_by(enabled=True).all() services_ena = Service.query.filter_by(enabled=True).all()
for service in services_ena: for service in services_ena:
@ -111,6 +114,9 @@ def autowarn():
print('Service "' + service.description + '" is ' + str(daysleft.days) + ' days until expiration. Last charged: ' + lastcharge.strftime('%c') + ' expiry date: ' + expiry.strftime('%c')) print('Service "' + service.description + '" is ' + str(daysleft.days) + ' days until expiration. Last charged: ' + lastcharge.strftime('%c') + ' expiry date: ' + expiry.strftime('%c'))
service.warning = True service.warning = True
db.session.commit() db.session.commit()
else:
service.warning = False
db.session.commit()
domains_ena = Domain.query.filter_by(enabled=True).all() domains_ena = Domain.query.filter_by(enabled=True).all()
for domain in domains_ena: for domain in domains_ena: