activate services

This commit is contained in:
deflax 2017-07-16 03:48:18 +03:00
parent 449e88789c
commit 9d930a0450
7 changed files with 74 additions and 50 deletions

View file

@ -129,7 +129,7 @@ def dashboard(user_pid=0):
flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid))) flash('Deploy #{} unreachable. Support is notified'.format(str(cubeid)))
send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid), send_email(current_app.config['MAIL_USERNAME'], 'Cube {} is unreachable'.format(cubeid),
'vmanager/email/adm_unreachable', user=cuser, cubeid=cubeid ) 'vmanager/email/adm_unreachable', user=cuser, cubeid=cubeid )
current_app.logger.info('[ADMIN] {} deployments: {}, services: {}, domains: {}, services: {}'.format(cuser.email, inv_deployments_list, inv_services_list, inv_domains_list, inv_addresses_list )) current_app.logger.warning('[ADMIN] {} deployments: {}, services: {}, domains: {}, services: {}'.format(cuser.email, inv_deployments_list, inv_services_list, inv_domains_list, inv_addresses_list ))
return render_template('main/dashboard.html', rrd=rrd, status=statuses, inv_deployments=inv_deployments, inv_services=inv_services, inv_domains=inv_domains, inv_addresses=inv_addresses, region=regions) return render_template('main/dashboard.html', rrd=rrd, status=statuses, inv_deployments=inv_deployments, inv_services=inv_services, inv_domains=inv_domains, inv_addresses=inv_addresses, region=regions)
@admin.route("/listtransactions", methods=['GET']) @admin.route("/listtransactions", methods=['GET'])

View file

@ -23,7 +23,7 @@ def after_request(response):
def activate(itemid=0): def activate(itemid=0):
if current_user.wallet < 1: if current_user.wallet < 1:
flash('Insufficient Funds') flash('Insufficient Funds')
return redirect(url_for('uinvoice.addfunds')) return redirect(url_for('uinvoice.transactions'))
#work with disabled deploys only #work with disabled deploys only
result = current_user.inv_domains.all() result = current_user.inv_domains.all()
@ -32,9 +32,9 @@ def activate(itemid=0):
inventory.extend([invcls.pid]) inventory.extend([invcls.pid])
if current_user.is_administrator(): if current_user.is_administrator():
current_app.logger.info('[ADMIN] Access override for domain id:{}'.format(itemid)) current_app.logger.warning('[ADMIN] Access override for domain id:{}'.format(itemid))
elif not itemid in inventory: elif not itemid in inventory:
current_app.logger.warning('[{}] Access violation with domain id: {}'.format(current_user.email, itemid)) current_app.logger.error('[{}] Access violation with domain id: {}'.format(current_user.email, itemid))
abort(404) abort(404)
#current_app.logger.info('[{}] Disabled deployments: {}'.format(current_user.email, inventory)) #current_app.logger.info('[{}] Disabled deployments: {}'.format(current_user.email, inventory))

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('Service Period', choices=[('1 Month', 1), ('3 Months', 3), ('6 Months', 6), ('1 Year', 12), ('2 Years', 24)]) period = SelectField('Service Period', choices=[(1, '1 Month'), (3, '3 Months'), (6, '6 Months'), (12, '1 Year'), (24, '2 Years')], coerce=int)
submit = SubmitField('Activate') submit = SubmitField('Activate')

View file

@ -6,10 +6,11 @@ from . import smanager
from .forms import ActivateForm from .forms import ActivateForm
from .. import db from .. import db
from ..email import send_email from ..email import send_email
from ..models import User, Permission, Service from ..models import User, Permission, Service, Transaction
from ..decorators import admin_required, permission_required from ..decorators import admin_required, permission_required
from datetime import datetime, timedelta, date, time from datetime import datetime, timedelta, date, time
from dateutil.relativedelta import relativedelta
@smanager.after_app_request @smanager.after_app_request
def after_request(response): def after_request(response):
@ -21,25 +22,47 @@ def after_request(response):
@smanager.route('/activate/<int:itemid>', methods=['GET', 'POST']) @smanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required @login_required
def activate(itemid=0): def activate(itemid=0):
if current_user.wallet < 1:
flash('Insufficient Funds')
return redirect(url_for('uinvoice.addfunds'))
#work with disabled deploys only
result = current_user.inv_services.all() result = current_user.inv_services.all()
inventory = [] inventory = []
for invcls in result: for invcls in result:
inventory.extend([invcls.pid]) inventory.extend([invcls.pid])
if current_user.is_administrator(): if current_user.is_administrator():
current_app.logger.info('[ADMIN] Access override for service id:{}'.format(itemid)) current_app.logger.warning('[ADMIN] Access override for service id:{}'.format(itemid))
elif not itemid in inventory: elif not itemid in inventory:
current_app.logger.warning('[{}] Access violation with service id: {}'.format(current_user.email, itemid)) current_app.logger.error('[{}] Access violation with service id: {}'.format(current_user.email, itemid))
abort(404) abort(404)
#current_app.logger.info('[{}] Disabled deployments: {}'.format(current_user.email, inventory)) service = Service.query.filter_by(pid=itemid).first()
form = ActivateForm(period=Service.query.filter_by(pid=itemid)) price = float(service.price)
if current_user.confirmed and form.validate_on_submit(): form = ActivateForm(period=int(service.period))
current_app.logger.info('payment')
return render_template('smanager/activate.html', form=form, itemid=itemid) owner = service.owner
if owner.confirmed and form.validate_on_submit():
if owner.wallet < price:
flash('Insufficient Funds')
return redirect(url_for('uinvoice.transactions'))
current_app.logger.info('[{}] Charge service: {}'.format(owner.email, service.description))
today = datetime.utcnow()
expiry = today + relativedelta(today, months=+(form.period.data))
daysleft = expiry - today
extradays = relativedelta(today, days=+(service.daysleft))
service.date_last_charge = today + extradays
service.period = form.period.data
service.daysleft = daysleft.days + extradays.days - 1
service.warning = False
service.enabled = True
db.session.commit()
transaction = Transaction(user_id=int(owner.pid), description='Deployment {} activated for {} month(s)'.format(str(service.description), form.period.data), value=-price)
db.session.add(transaction)
db.session.commit()
owner.wallet = owner.wallet - price
db.session.commit()
if owner.is_administrator:
return redirect(url_for('admin.list_items'))
else:
return redirect(url_for('main.dashboard'))
return render_template('smanager/activate.html', form=form, service=service, total=service.price)

View file

@ -172,14 +172,13 @@ addEventListener("DOMContentLoaded", function() {
<button class="command command-vmstart btn btn-default btn-success" value="vmstart" vmid="{{ deploy.machine_id }}"><span class="glyphicon glyphicon-play" aria-hidden="true"></span> Start</button> <button class="command command-vmstart btn btn-default btn-success" value="vmstart" vmid="{{ deploy.machine_id }}"><span class="glyphicon glyphicon-play" aria-hidden="true"></span> Start</button>
{% endif %}</td> {% endif %}</td>
<td data-title="Remote">{% if status[deploy.machine_id] == 'running' %} <td data-title="Remote">{% if status[deploy.machine_id] == 'running' %}
<button class="btn btn-default btn-info" onclick="window.open('/vmanager/vmvnc/{{ deploy.machine_id }}', '_blank');"><span class="glyphicon glyphicon-console" aria-hidden="true"></span> Console</button> <button class="btn btn-default btn-info" onclick="window.open('/vmanager/vmvnc/{{ deploy.machine_id }}', '_blank');"><span class="glyphicon glyphicon-console" aria-hidden="true"></span> Console</button>{% endif %}
{% if deploy.warning == True %} {% if deploy.warning == True %}
<td data-title="Time Left"><button class="btn btn-default btn-success" onclick="window.open('/vmanager/activate/{{ deploy.machine_id }}');"><span class="glyphicon glyphicon-bell" aria-hidden="true"></span> Renew ({{ deploy.daysleft }} days left)</button></td> <td data-title="Time Left"><button class="btn btn-default btn-success" onclick="window.open('/vmanager/activate/{{ deploy.machine_id }}');"><span class="glyphicon glyphicon-bell" aria-hidden="true"></span> Renew ({{ deploy.daysleft }} days left)</button></td>
{% else %} {% else %}
<td data-title="Time Left">{{ deploy.daysleft }} day(s)</td> <td data-title="Time Left">{{ deploy.daysleft }} day(s)</td>
{% endif %} {% endif %}
</td>
{% endif %}</td>
</tr> </tr>
{% endif %} {% endif %}
{% endfor %} {% endfor %}

View file

@ -1,6 +1,6 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block title %}Activate{% endblock %} {% block title %}Activate service #{{ service.pid }}{% endblock %}
{% block page_content %} {% block page_content %}
@ -11,12 +11,16 @@
<div class="panel-heading">Activate</div> <div class="panel-heading">Activate</div>
<div class="panel-body"> <div class="panel-body">
<form method="POST" action"{{ url_for('smanager.activate', itemid=itemid) }}"> <form method="POST" action"{{ url_for('smanager.activate', itemid=service.pid) }}">
<p>{{ form.period.label }}<br />{{ form.period }}<br /> <h3>
{{ form.period.label }} {{ form.period }}<br />
{% for error in form.period.errors %} {% for error in form.period.errors %}
{{ error }}<br /> {{ error }}<br />
{% endfor %} {% endfor %}
</p> ---<br />
Total = {{ total }}
</h3>
<p> <p>
{{ form.csrf_token() }} {{ form.csrf_token() }}
{{ form.submit }} {{ form.submit }}

View file

@ -121,15 +121,14 @@ def deploy(product_id=None):
@vmanager.route('/activate/<int:itemid>', methods=['GET', 'POST']) @vmanager.route('/activate/<int:itemid>', methods=['GET', 'POST'])
@login_required @login_required
def activate(itemid=0): def activate(itemid=0):
#work with disabled deploys only
result = current_user.inv_deployments.all() result = current_user.inv_deployments.all()
inventory = [] inventory = []
for invcls in result: for invcls in result:
inventory.extend([invcls.machine_id]) inventory.extend([invcls.machine_id])
if current_user.is_administrator(): if current_user.is_administrator():
current_app.logger.info('[ADMIN] Access override for deployment id:{}'.format(itemid)) current_app.logger.warning('[ADMIN] Access override for deployment id:{}'.format(itemid))
elif not itemid in inventory: elif not itemid in inventory:
current_app.logger.warning('[{}] Access violation with deployment id: {}'.format(current_user.email, itemid)) current_app.logger.error('[{}] Access violation with deployment id: {}'.format(current_user.email, itemid))
abort(404) abort(404)
deploy = Deployment.query.filter_by(machine_id=itemid).first() deploy = Deployment.query.filter_by(machine_id=itemid).first()
@ -139,44 +138,43 @@ def activate(itemid=0):
total = round(cpu_cost + mem_cost + hdd_cost,2) total = round(cpu_cost + mem_cost + hdd_cost,2)
form = ActivateForm(period=int(deploy.period)) form = ActivateForm(period=int(deploy.period))
if current_user.confirmed and form.validate_on_submit(): owner = deploy.owner
if current_user.wallet < total: if owner.confirmed and form.validate_on_submit():
if owner.wallet < total:
flash('Insufficient Funds') flash('Insufficient Funds')
return redirect(url_for('uinvoice.transactions')) return redirect(url_for('uinvoice.transactions'))
current_app.logger.info('[{}] Charge deployment: {}'.format(current_user.email, deploy.machine_id)) current_app.logger.info('[{}] Charge deployment: {}'.format(owner.email, deploy.machine_id))
today = datetime.utcnow() today = datetime.utcnow()
current_app.logger.info(form.period.data) expiry = today + relativedelta(today, months=+(form.period.data))
daysleft = expiry - today
daysleft = relativedelta(today, months=+(form.period.data)) extradays = relativedelta(today, days=+(deploy.daysleft))
deploy.date_last_charge = today + extradays
deploy.date_last_charge = today
deploy.period = form.period.data deploy.period = form.period.data
deploy.daysleft = form.period.data * daysleft.days deploy.daysleft = daysleft.days + extradays.days - 1
deploy.warning = False deploy.warning = False
deploy.enabled = True deploy.enabled = True
db.session.commit() db.session.commit()
transaction = Transaction(user_id=int(current_user.pid), description='Deployment {} activated for {} month(s)'.format(str(deploy.machine_alias), form.period.data), value=-total) transaction = Transaction(user_id=int(owner.pid), description='Deployment {} activated for {} month(s)'.format(str(deploy.machine_alias), form.period.data), value=-total)
db.session.add(transaction) db.session.add(transaction)
db.session.commit() db.session.commit()
current_user.wallet = current_user.wallet - total owner.wallet = owner.wallet - total
db.session.commit() db.session.commit()
if owner.is_administrator:
return redirect(url_for('admin.list_items'))
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, total=total)
@vmanager.route('/<cmd>/<int:vmid>') @vmanager.route('/<cmd>/<int:vmid>')
@login_required @login_required
def command(cmd=None, vmid=0): def command(cmd=None, vmid=0):
valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop', 'vmvnc']
#checks whether this is a valid command #checks whether this is a valid command
valid_commands = ['vmstatus', 'vmstart', 'vmshutdown', 'vmstop', 'vmvnc']
if not cmd in valid_commands: if not cmd in valid_commands:
current_app.logger.warning(cmd + ' is not a valid command!') current_app.logger.warning(cmd + ' is not a valid command!')
abort(404) abort(404)
#if cmd == 'vmstart' and current_user.wallet < 3.0:
# flash('Недостатъчно средства в сметката за тази операция')
# return redirect(url_for('uinvoice.addfunds'))
#work with enabled deploys only #work with enabled deploys only
result = current_user.inv_deployments.filter_by(enabled=True) result = current_user.inv_deployments.filter_by(enabled=True)
@ -185,14 +183,14 @@ def command(cmd=None, vmid=0):
inventory.extend([invcls.machine_id]) inventory.extend([invcls.machine_id])
if current_user.is_administrator(): if current_user.is_administrator():
current_app.logger.info('[ADMIN] Access override for cube id:{}'.format(vmid)) current_app.logger.warning('[ADMIN] Access override for cube id:{}'.format(vmid))
db_result = contact_proxmaster({}, cmd, vmid) db_result = contact_proxmaster({}, cmd, vmid)
if cmd == 'vmvnc': if cmd == 'vmvnc':
return redirect(db_result['url']) return redirect(db_result['url'])
else: else:
#checks if current user owns this vmid #checks if current user owns this vmid
if not vmid in inventory: if not vmid in inventory:
current_app.logger.warning('[{}] Access violation with cube id: {}'.format(current_user.email, vmid)) current_app.logger.error('[{}] Access violation with cube id: {}'.format(current_user.email, vmid))
#TODO: log ips #TODO: log ips
else: else:
db_result = contact_proxmaster({}, cmd, vmid) db_result = contact_proxmaster({}, cmd, vmid)