260 lines
9.2 KiB
Python
260 lines
9.2 KiB
Python
# This file is part of Tryton. The COPYRIGHT file at the top level of
|
|
# this repository contains the full copyright notices and license terms.
|
|
from __future__ import with_statement
|
|
from datetime import datetime, timedelta, date
|
|
|
|
from trytond.model import Workflow, ModelView, ModelSQL, fields
|
|
from trytond.report import Report
|
|
from trytond.pyson import Eval, If, In, Get, Bool
|
|
from trytond.transaction import Transaction
|
|
from trytond.pool import Pool
|
|
from trytond.wizard import Wizard, StateTransition
|
|
from trytond.backend.postgresql.database import LoggingCursor
|
|
import psycopg2
|
|
from psycopg2 import Error
|
|
import os
|
|
from .exceptions import DisableDatabaseWarning
|
|
from trytond.i18n import gettext
|
|
from . import queries
|
|
|
|
STATES = {
|
|
'readonly': Eval('state') != 'draft',
|
|
}
|
|
|
|
|
|
class Database(Workflow, ModelSQL, ModelView):
|
|
'Database'
|
|
__name__ = 'vps.databases'
|
|
_rec_name = 'name'
|
|
vps = fields.Many2One('vps.server', 'Server',
|
|
required=True, )
|
|
price_plan = fields.Many2One('vps.price_plan', 'Price Plan',)
|
|
name = fields.Char('Name Database', required=True,)
|
|
state = fields.Selection([
|
|
('enable', 'Enable'),
|
|
('disable', 'Disable'),
|
|
], 'State', readonly=True, required=True,)
|
|
customer = fields.Many2One('party.party', 'Customer')
|
|
invoices_expiration = fields.Function(fields.Integer('Invoices Expiration'),
|
|
'get_invoices_expiration')
|
|
electronic_invoice = fields.Boolean('Electronic Invoicing' )
|
|
finish_date_certificate = fields.Date('Finish Date Certificate', states={
|
|
'required': Bool(Eval('electronic_invoice')),
|
|
'invisible': ~Bool(Eval('electronic_invoice'))
|
|
})
|
|
sended_email = fields.Boolean('Sended Email')
|
|
|
|
@classmethod
|
|
def __setup__(cls):
|
|
super(Database, cls).__setup__()
|
|
cls._order = [
|
|
('name', 'DESC'),
|
|
]
|
|
cls._transitions |= set((
|
|
('disable', 'enable'),
|
|
('enable', 'disable'),
|
|
))
|
|
cls._buttons.update({
|
|
'disable': {
|
|
'invisible': Eval('state') != 'enable',
|
|
},
|
|
'enable': {
|
|
'invisible': Eval('state') != 'disable',
|
|
},
|
|
})
|
|
|
|
@staticmethod
|
|
def default_state():
|
|
return 'enable'
|
|
|
|
@classmethod
|
|
@ModelView.button
|
|
@Workflow.transition('disable')
|
|
def disable(cls, records):
|
|
pool = Pool()
|
|
Warning = pool.get('res.user.warning')
|
|
for record in records:
|
|
warning_key = 'disable_vps'
|
|
if Warning.check(warning_key):
|
|
raise DisableDatabaseWarning(warning_key, gettext('vps.msg_disable_warning'))
|
|
record.allow_connections_database(False)
|
|
pass
|
|
|
|
@classmethod
|
|
def search_rec_name(cls, name, clause):
|
|
_, operator, value = clause
|
|
if operator.startswith('!') or operator.startswith('not '):
|
|
bool_op = 'AND'
|
|
else:
|
|
bool_op = 'OR'
|
|
domain = [
|
|
bool_op,
|
|
('name', operator, value),
|
|
('customer.name', operator, value),
|
|
('vps.name', operator, value),
|
|
]
|
|
return domain
|
|
|
|
@classmethod
|
|
@ModelView.button
|
|
@Workflow.transition('enable')
|
|
def enable(cls, records):
|
|
for record in records:
|
|
record.allow_connections_database(True)
|
|
|
|
def allow_connections_database(self, allow):
|
|
connection = None
|
|
name= self.name
|
|
try:
|
|
connection = self.get_connection_database('postgres')
|
|
cursor = connection.cursor()
|
|
if allow:
|
|
allow_conection = queries.allow_connection.format(name=name, option='true')
|
|
connection_limit = queries.connection_limit.format(name=name, option=-1)
|
|
self.write([self], {'state': 'enable'})
|
|
else:
|
|
allow_conection = queries.allow_connection.format(name=name, option='false')
|
|
connection_limit = queries.connection_limit.format(name=name, option=0)
|
|
self.write([self], {'state': 'disable'})
|
|
|
|
cursor.execute(allow_conection)
|
|
cursor.execute(connection_limit)
|
|
|
|
connection.commit()
|
|
print("process successfully in PostgreSQL ")
|
|
except (Exception, psycopg2.DatabaseError) as error:
|
|
print ("Error while executed process", error)
|
|
finally:
|
|
#closing database connection.
|
|
if(connection):
|
|
cursor.close()
|
|
connection.close()
|
|
print("PostgreSQL connection is closed")
|
|
|
|
def get_connection_database(self, database):
|
|
connection = connection = psycopg2.connect(user = self.vps.user,
|
|
password = self.vps.password,
|
|
host = self.vps.ip_address,
|
|
port = self.vps.port,
|
|
database = database,
|
|
cursor_factory= LoggingCursor,
|
|
)
|
|
return connection
|
|
|
|
# os.popen("sudo systemctl restart strytond.service", 'w').write('12345678')
|
|
|
|
def get_invoices_expiration(self, name):
|
|
Invoice = Pool().get('account.invoice')
|
|
Configuration = Pool().get('vps.configuration')
|
|
config = Configuration(1)
|
|
InvoicePaymentTermLineDelta = Pool().get('account.invoice.payment_term.line.delta')
|
|
|
|
invoices = Invoice.search([
|
|
('party', '=', self.customer),
|
|
('state', 'in', ['validated', 'posted']),
|
|
])
|
|
now = date.today()
|
|
|
|
invoices_expired = 0
|
|
if config and config.limit_days_expired:
|
|
for invoice in invoices:
|
|
invoice_payment_term_line_delta = InvoicePaymentTermLineDelta.search([
|
|
('line.payment', '=', invoice.payment_term),
|
|
])
|
|
if invoice.invoice_date and invoice_payment_term_line_delta:
|
|
d_expired = int((now - invoice.invoice_date).days)
|
|
d_expired = int(d_expired - invoice_payment_term_line_delta[0].days)
|
|
if d_expired <= 0:
|
|
invoices_expired += 0
|
|
else:
|
|
if d_expired >= config.limit_days_expired:
|
|
invoices_expired += 1
|
|
# setattr(invoice, 'days_expired', days_expired)
|
|
return invoices_expired
|
|
|
|
def notification_resolution():
|
|
pool = Pool()
|
|
Database = pool.get('vps.databases')
|
|
Template = pool.get('email.template')
|
|
start_date = date.today()
|
|
config = pool.get('account.configuration')(1)
|
|
date_1 = start_date+timedelta(days=30)
|
|
date_2 = start_date+timedelta(days=15)
|
|
date_3 = start_date+timedelta(days=8)
|
|
date_4 = start_date+timedelta(days=2)
|
|
databases = Database.search([
|
|
('state', '=', 'enable'),
|
|
('electronic_invoice', '=', 'True'),
|
|
])
|
|
if databases:
|
|
for database in databases:
|
|
if database.finish_date_certificate in [date_1 , date_2, date_3, date_4]:
|
|
email = database.customer.email
|
|
response = Template.send(config.template_email_confirm, database, email)
|
|
if response.status_code == 202:
|
|
Database.write([database], {'sended_email': True})
|
|
|
|
|
|
class Server(ModelSQL, ModelView):
|
|
'Vps Server'
|
|
__name__ = 'vps.server'
|
|
_rec_name = 'name'
|
|
supplier = fields.Many2One('vps.supplier', 'Supplier', ondelete='RESTRICT', required=True)
|
|
active = fields.Boolean('Active')
|
|
name = fields.Char('Name', required=True,)
|
|
user = fields.Char('User', required=True, )
|
|
ip_address = fields.Char('IP Address', required=True,)
|
|
port = fields.Char('Port', required=True,)
|
|
password = fields.Char('Password', required=True,)
|
|
# route = fields.Char('Route', states=STATES)
|
|
databases = fields.One2Many('vps.databases', 'vps', 'Databases',)
|
|
state = fields.Selection([
|
|
('stop', 'Stop'),
|
|
('execution', 'Execution'),
|
|
], 'State', required=True,)
|
|
location = fields.Char('Location')
|
|
|
|
@staticmethod
|
|
def default_state():
|
|
return 'draft'
|
|
|
|
@staticmethod
|
|
def default_active():
|
|
return True
|
|
|
|
@classmethod
|
|
def disable_databases(cls):
|
|
Database = Pool().get('vps.databases')
|
|
databases = Database.search([
|
|
('state', '=', 'enable'),
|
|
('vps.active', '=', True),
|
|
])
|
|
for db in databases:
|
|
if db.price_plan and db.price_plan.kind != 'free' and db.invoices_expiration >= 1:
|
|
db.allow_connections_database(False)
|
|
|
|
|
|
class PricePlan(ModelSQL, ModelView):
|
|
'Price Plan'
|
|
__name__ = 'vps.price_plan'
|
|
_rec_name = 'name'
|
|
name = fields.Char('Name', required=True,)
|
|
kind = fields.Selection([
|
|
('free', 'Free'),
|
|
('payment', 'Payment'),
|
|
], 'Kind', required=True,)
|
|
|
|
|
|
class DocumentElectronic(ModelSQL, ModelView):
|
|
'Document Electronic'
|
|
__name__ = 'vps.document_electronic'
|
|
|
|
period = fields.Date('Period')
|
|
document_support = fields.Integer('Document Support', states={'readonly': True})
|
|
invoice = fields.Integer('Invoice', states={'readonly': True})
|
|
event = fields.Integer('Event', states={'readonly': True})
|
|
payroll = fields.Integer('Payroll', states={'readonly': True})
|
|
|
|
|
|
|