Compare commits

...

6 Commits

Author SHA1 Message Date
wilsongomez a69e1dccd4 minor fix 2022-06-16 18:21:10 -05:00
wilsongomez e0ea77eade minor fix 2022-06-16 18:09:20 -05:00
wilsongomez dfce52f5ae minor fix 2022-06-16 17:35:16 -05:00
wilsongomez 3334d38edb minor fix 2022-06-16 17:25:12 -05:00
wilsongomez 2384a57675 minor fix 2022-06-16 17:22:35 -05:00
wilsongomez 9f01fc6de6 minor fix 2022-06-16 17:21:23 -05:00
5 changed files with 15 additions and 1691 deletions

View File

@ -1,833 +0,0 @@
# Project for test Flask Tryton and React friendship ;)
import os
import json
import configparser
from decimal import Decimal
from datetime import date, datetime
# from dateutil import tz
from pytz import timezone
from functools import wraps
from flask import Flask, jsonify, request, abort
from flask_tryton import Tryton
from flask_cors import CORS
DELTA_FORECAST = 15
app = Flask(__name__)
CORS(app)
USER = 1
manager = {}
HOME_DIR = os.getenv('HOME')
default_dir = os.path.join(HOME_DIR, '.flask')
config_file = os.path.join(default_dir, 'escool.ini')
config = configparser.ConfigParser()
config.read(config_file)
databases = list(eval(config.get('General', 'databases')))
trytond_config = config.get('General', 'trytond_config')
host_ = config.get('General', 'host')
API_KEY = config.get('Auth', 'api_key')
for db in databases:
app.config['TRYTON_DATABASE'] = db
app.config['TRYTON_CONFIG'] = trytond_config
# app.config['TRYTON_USER'] = 1
# app.config['CORS_HEADERS'] = 'Content-Type'
manager[db] = Tryton(app)
def send_data(data):
res = jsonify(data)
res.headers.add('Access-Control-Allow-Origin', '*')
res.headers.add('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS')
res.headers.add('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token')
return res
def get_model(database, model_name):
tryton = manager[database]
@tryton.transaction()
def _get(model_name):
model = tryton.pool.get(model_name)
return model
return _get(model_name)
# The actual decorator function
def require_appkey(view_function):
@wraps(view_function)
# the new, post-decoration function. Note *args and **kwargs here.
def decorated_function(*args, **kwargs):
if request.headers.get('Authorization') and request.headers.get('Authorization') == API_KEY:
return view_function(*args, **kwargs)
else:
abort(401)
return decorated_function
@app.route('/home')
def home():
return "Welcome to Presik Technologies"
@app.route('/login')
def login():
res = {
'msg': 'User name not found!',
'user_id': None,
'name': None,
}
database = request.args.get('database', None)
username = request.args.get('user', None)
# passwd = request.args.get('passwd', None)
tryton = manager[database]
@tryton.transaction()
def search_user(username):
User = tryton.pool.get('res.user')
users = User.search_read([
('login', '=', username),
('active', '=', True),
], fields_names=['id', 'name', 'company', 'company.party.name'])
return users
# FIXME: Add check password ('password', '=', passwd),
users = search_user(username)
if users:
user = users[0]
res['msg'] = 'ok'
res['name'] = user['name']
res['user_id'] = user['id']
res['company_id'] = user['company.']['id']
res['company_name'] = user['company.']['party.name']
return send_data(res)
def search(tryton, model, domain):
@tryton.transaction()
def _search():
Model = tryton.pool.get(model)
records = Model.search(domain)
return records
return _search()
@app.route("/<db>/countries/", methods=['GET', 'OPTIONS'])
# @cross_origin()
def get_countries(db):
tryton = manager[db]
@tryton.transaction()
def _get_countries():
Country = tryton.pool.get('party.country_code')
countries = Country.search_read([],
fields_names=['id', 'name']
)
return countries
countries = _get_countries()
return send_data(countries)
@app.route("/<db>/departments/", methods=['GET'])
@require_appkey
def get_departments(db):
tryton = manager[db]
@tryton.transaction()
def _get_departments():
Department = tryton.pool.get('party.department_code')
departments = Department.search_read([],
fields_names=['id', 'name']
)
return departments
departments = _get_departments()
return send_data(departments)
@app.route("/<db>/cities/<departmentId>", methods=['GET'])
@require_appkey
def get_cities(db, departmentId):
tryton = manager[db]
@tryton.transaction()
def _get_cities():
City = tryton.pool.get('party.city_code')
cities = City.search_read([
('department', '=', int(departmentId))
], fields_names=['id', 'name', 'department'])
return cities
cities = _get_cities()
return send_data(cities)
@app.route("/<db>/parties/", methods=['GET'])
@require_appkey
def get_parties(db):
tryton = manager[db]
@tryton.transaction()
def _get_parties():
Party = tryton.pool.get('party.party')
lines = Party.search_read(
[],
fields_names=['id', 'name', 'id_number', 'email']
)
return lines
lines = _get_parties()
return send_data(lines)
@app.route("/<db>/payment_term/", methods=['GET'])
@require_appkey
def get_payment_term(db):
tryton = manager[db]
@tryton.transaction()
def _get_payment_term():
Payment = tryton.pool.get('account.invoice.payment_term')
lines = Payment.search_read([],
fields_names=['id', 'name']
)
return lines
lines = _get_payment_term()
return send_data(lines)
@app.route("/<db>/party/<idNumber>", methods=['GET'])
@require_appkey
def get_party(db, idNumber):
tryton = manager[db]
@tryton.transaction()
def _get_party():
Party = tryton.pool.get('party.party')
party = None
parties = Party.search_read([
('id_number', '=', idNumber),
], fields_names=['id', 'name', 'id_number', 'email']
)
if parties:
party = parties[0]
return party
p = _get_party()
return send_data(p)
@app.route("/<db>/products_by_shop/<shopId>")
@require_appkey
def get_products_by_shop(db, shopId):
tryton = manager[db]
@tryton.transaction()
def _get_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
Category = tryton.pool.get('product.category')
# ListPrice = tryton.pool.get('product.list_price')
shops = Shop.search([
('id', '=', shopId)
])
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search_read([
('account_category', 'in', categories_ids),
('categories', '!=', None),
('active', '=', True),
], fields_names=['id', 'template', 'template.name', 'code', 'template.categories', 'template.sale_price_w_tax'],
order=[('code', 'ASC')]
)
# prices = ListPrice.search_read([
# ('template', 'in', [v['template'] for v in values])
# ], fields_names=['id', 'template', 'list_price']
# )
# prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
template = val.get('template.', None)
if template and not template.get('sale_price_w_tax'):
continue
categories = Category.search_read([
('id', 'in', val['template.']['categories']),
], fields_names=['id', 'name', 'parent'])
products.append({
'id': val['id'],
'name': val['template.']['name'],
'code': val['code'],
'category': categories,
'sale_price': float(val['template.']['sale_price_w_tax']),
'images': '',
# 'sale_price': float(prices2product[val['template']]),
})
return send_data(products)
return _get_products()
@app.route("/<db>/categorized_products/<shopId>")
@require_appkey
def get_categorized_products(db, shopId):
tryton = manager[db]
@tryton.transaction()
def _get_categorized_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
ListPrice = tryton.pool.get('product.list_price')
Category = tryton.pool.get('product.category')
shops = Shop.search([
('id', '=', shopId)
])
target_categories = {}
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search([
('account_category', 'in', categories_ids),
('categories', '!=', None),
('active', '=', True),
], order=[('code', 'ASC')])
# fields_names=[
# 'id', 'template.name', 'code', 'template.categories',
# 'template.sale_price_w_tax', 'template', 'attributes'
# ],
prices = ListPrice.search_read([
('template', 'in', [v.template.id for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
product = {
'id': val.id,
'name': val.template.name,
'code': val.code,
'sale_price': float(round(prices2product[val.template.id], 2)),
'sale_price_w_tax': float(round(val.template.sale_price_w_tax, 2)),
'attributes': val.attributes,
}
# product['sale_price_w_tax'] = product['sale_price']
cat = val.template.categories[0]
if cat not in target_categories.keys():
c = Category(cat)
target_categories[cat] = {
'id': c.id,
'images': [i.image for i in c.images],
'name': c.name,
'parent': c.parent.id if c.parent else None,
'products': [product]
}
else:
target_categories[cat]['products'].append(product)
res = list(target_categories.values())
return send_data(res)
return _get_categorized_products()
@app.route("/<db>/products_shop_category/<shopId>/<categoryId>")
@require_appkey
def get_products_shop_category(db, shopId, categoryId):
tryton = manager[db]
@tryton.transaction()
def _get_products():
Product = tryton.pool.get('product.product')
ProductCategory = tryton.pool.get('product.template-product.category')
ListPrice = tryton.pool.get('product.list_price')
Shop = tryton.pool.get('sale.shop')
shops = Shop.search([
('id', '=', shopId)
])
templates_cat = ProductCategory.search_read([
('category', '=', int(categoryId))
], fields_names=['template'])
templates_cat = [t['template'] for t in templates_cat]
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search([
('account_category', 'in', categories_ids),
('active', '=', True),
('template', 'in', templates_cat),
],
order=[('code', 'ASC')]
)
prices = ListPrice.search_read([
('template', 'in', [v.template.id for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
products.append({
'id': val.id,
'name': val.template.name,
'code': val.code,
'sale_price': float(prices2product[val.template.id]),
'sale_price_w_tax': float(val.template.sale_price_w_tax),
'categories': [c.id for c in val.template.categories],
})
return send_data(products)
return _get_products()
@app.route("/<db>/products_elastic/<shopId>/<query>", methods=['GET'])
@require_appkey
def get_products_elastic(db, shopId, query):
tryton = manager[db]
@tryton.transaction()
def _get_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
ListPrice = tryton.pool.get('product.list_price')
shops = Shop.search([
('id', '=', shopId)
])
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search_read([
('account_category', 'in', categories_ids),
('active', '=', True),
('categories', '!=', None),
('template.name', 'ilike', '%' + query + '%'),
('template.salable', '=', True),
], fields_names=[
'id', 'template.name', 'code', 'template.categories',
'template.sale_price_w_tax', 'template'
],
order=[('code', 'ASC')]
)
prices = ListPrice.search_read([
('template', 'in', [v['template.']['id'] for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
products.append({
'id': val['id'],
'name': val['template.']['name'],
'code': val['code'],
'sale_price': float(prices2product[val['template.']['id']]),
'sale_price_w_tax': float(val['template.']['sale_price_w_tax']),
'categories': val['template.']['categories'],
})
return products
products = _get_products()
return send_data(products)
@app.route("/<db>/categories/", methods=['GET'])
@require_appkey
def get_categories(db):
tryton = manager[db]
@tryton.transaction()
def _get_categories():
Category = tryton.pool.get('product.category')
categories = Category.search([
('accounting', '=', False),
('parent', '=', )
])
values = []
for cat in categories:
values.append({
'id': cat.id,
'name': cat.name,
'parent': cat.parent.id if cat.parent else None,
'images': [img.image for img in cat.images]
})
return values
categories = _get_categories()
return send_data(categories)
@app.route("/<db>/shops/", methods=['GET'])
@require_appkey
def get_shops(db):
tryton = manager[db]
@tryton.transaction()
def _get_shops():
Shop = tryton.pool.get('sale.shop')
shops = Shop.search_read(
[],
fields_names=[
'id', 'name',
'freight_product',
'freight_product.template.name',
'freight_product.template.sale_price_w_tax',
])
shops_ = []
for shop in shops:
freight_price = 0
if shop['id'] == 4:
freight_price = 10000
new_shop = {
'id': shop['id'],
'name': shop['name'],
'product_freight_id': shop['freight_product.']['id'],
'product_freight_name': 'FLETE',
'product_freight_price': freight_price,
}
shops_.append(new_shop)
return shops_
shops = _get_shops()
return send_data(shops)
@app.route("/<db>/add_party/", methods=['POST'])
@require_appkey
def add_party(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8") )
regime_tax = ''
if data['type_document'] == '31':
regime_tax = 'regimen_comun'
msg = 'User created succesfully'
values = {
'name': data['name'].upper(),
'id_number': data['id_number'],
'type_document': data['type_document'],
'regime_tax': regime_tax,
'addresses': [('create', [{
'street': data['address'],
'country_code': data['country'],
'department_code': data['department'],
'city_code': data['city'],
}]
)],
'contact_mechanisms': [('create', [{
'type': 'mobile',
'value': data['phone'],
}, {
'type': 'email',
'value': data['email'],
}]
)],
}
@tryton.transaction()
def _create(_values):
Party = tryton.pool.get('party.party')
PartyAccount = tryton.pool.get('party.party.account')
Configuration = tryton.pool.get('account.configuration.default_account')
config = Configuration(1)
party, = Party.create([_values])
if config.default_account_receivable:
PartyAccount.create([{
'company': 1,
'party': party.id,
'account_payable': None,
'account_receivable': config.default_account_receivable.id,
}])
# PartyAccount.create([{
# 'company': 1,
# 'party': party.id,
# 'account_payable': config.default_account_payable.id,
# 'account_receivable': config.default_account_receivable.id,
# }])
return party
try:
_create(values)
except:
msg = 'Error in user creation!'
return send_data(msg)
@app.route("/<db>/update_party/", methods=['POST'])
@require_appkey
def update_party(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
regime_tax = ''
if data['type_document'] == '31':
regime_tax = 'regimen_comun'
values = {
'name': data['name'],
'id_number': data['id_number'],
'type_document': data['type_document'],
'regime_tax': regime_tax,
}
addresses = {
'street': data['address'],
'country_code': data['country'],
'department_code': data['department'],
'city_code': data['city']
}
@tryton.transaction()
def _update_party():
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Party.write([party], values)
return party
@tryton.transaction()
def _update_address():
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Address = tryton.pool.get('party.address')
Address.write(list(party.addresses), addresses)
@tryton.transaction()
def _update_contact(type_, val):
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Contact = tryton.pool.get('party.contact_mechanism')
contacts = Contact.search([
('party', '=', party.id,),
('type', '=', type_,),
])
Contact.write(contacts, {
'type': type_,
'value': val,
})
try:
_update_party()
if data['address']:
_update_address()
if data['phone']:
_update_contact('mobile', data['phone'])
if data['email']:
_update_contact('email', data['email'])
msg = 'User updated succesfully!, you can check it with /party/ route'
except:
msg = 'Error in user update!'
return send_data(msg)
@app.route("/<db>/add_sale/", methods=['POST'])
@require_appkey
def add_sale(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
print(data)
@tryton.transaction()
def _get_user():
User = tryton.pool.get('res.user')
user, = User.search([
('login', '=', 'ecommerce')
])
return user.id
user_id = _get_user()
ctx = {'company': 1}
@tryton.transaction(context=ctx, user=user_id)
def _get_lines():
lines = []
# Template = tryton.pool.get('product.template')
Product = tryton.pool.get('product.product')
for l in data['lines']:
product = Product(l['product'])
template = product.template
taxes = [tax.id for tax in template.account_category.customer_taxes_used]
lines.append({
'product': l['product'],
'description': template.name,
'unit_price': Decimal(l['list_price']),
'unit': template.default_uom.id,
'quantity': l['quantity'],
'taxes': [('add', taxes)]
})
return lines
@tryton.transaction(user=user_id)
def _create(lines):
Party = tryton.pool.get('party.party')
Sale = tryton.pool.get('sale.sale')
Shop = tryton.pool.get('sale.shop')
PartyAccount = tryton.pool.get('party.party.account')
Statement = tryton.pool.get('account.statement')
StatementLine = tryton.pool.get('account.statement.line')
shipment_party = data['party']
party = Party(data['party'])
shipment_address_id = party.addresses[0].id
shop = Shop(data['shop'])
sale_date = datetime.now(timezone(shop.company.timezone)).date()
vals = {
'company': shop.company.id,
'state': 'draft',
'party': data['party'],
'sale_date': sale_date,
'currency': shop.company.currency.id,
'shop': data['shop'],
'payment_term': data['payment_term'],
'shipment_party': shipment_party,
'shipment_address': shipment_address_id,
'invoice_address': shipment_address_id,
'warehouse': shop.warehouse.id,
'shipment_method': 'order',
'invoice_method': 'order',
'shipment_state': 'none',
'invoice_state': 'none',
'invoice_type': 'P',
'lines': [('create', lines)],
'description': 'WEB SALE',
'reference': shop.name,
'self_pick_up': False
}
sale, = Sale.create([vals])
Sale.quote([sale])
# Sale.confirm([sale])
statements = Statement.search([
('journal.name', '=', 'pagos_web'),
('sale_device.shop', '=', int(data['shop'])),
('state', '=', 'draft'),
])
statement = None
if statements:
statement = statements[0]
# Sale.process([sale])
party_accs = PartyAccount.search([
('party', '=', party.id),
('account_receivable', '!=', None),
])
party_acc = party_accs[0]
if statement and data.get('paid_amount') and data.get('voucher'):
StatementLine.create([{
'sale': sale.id,
'date': sale_date,
'statement': statement.id,
'amount': data['paid_amount'],
'party': sale.party.id,
'account': party_acc.account_receivable.id,
'description': data.get('voucher'),
}])
return sale
res = {
'msg': 'Error in sale creation!',
'status': 'error',
'order': ''
}
try:
lines = _get_lines()
sale = _create(lines)
if sale and sale.number:
res['msg'] = 'Sale created succesfully'
res['status'] = 'success'
res['order'] = sale.number
except Exception as e:
print(e)
res['msg'] = e
print(res)
return send_data(res)
@app.route("/<db>/product_freight/", methods=['GET'])
@require_appkey
def get_product_freight(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
@tryton.transaction()
def _get_user():
User = tryton.pool.get('res.user')
user, = User.search([
('login', '=', 'ecommerce')
])
return user.id
user_id = _get_user()
@tryton.transaction(user=user_id)
def _get_product_freight():
Product = tryton.pool.get('product.product')
product = None
products = Product.search_read(
[('code', '=', 'FLETE')],
fields_names=['id', 'template.name', 'template.sale_price_w_tax']
)
if products:
product_ = products[0]
product = {
'name': product_['template.']['name'],
'id': product_['id'],
'sale_price_w_tax': float(product_['template.']['sale_price_w_tax']),
}
return product
product = _get_product_freight()
return send_data(product)
@app.route("/<db>/categories_tree/<shopId>", methods=['GET'])
@require_appkey
def get_categories_tree(db, shopId):
tryton = manager[db]
@tryton.transaction()
def _get_categories():
Shop = tryton.pool.get('sale.shop')
def _get_childs(cat):
value = {
'id': cat.id,
'name': cat.name,
'parent': cat.parent.id if cat.parent else None,
'images': [img.image for img in cat.images]
}
if cat.childs:
value['childs'] = [_get_childs(c) for c in cat.childs]
return value
shop = Shop(shopId)
categories = [c for c in shop.product_categories if c.accounting == False]
categoryTree = []
if categories:
categoryTree = _get_childs(categories[0])
return categoryTree
categories = _get_categories()
return send_data(categories)
if __name__ == "__main__":
app.run(host=host_)

View File

@ -1,844 +0,0 @@
# Project for test Flask Tryton and React friendship ;)
import os
import json
import configparser
from decimal import Decimal
from datetime import date, datetime
# from dateutil import tz
from pytz import timezone
from functools import wraps
from flask import Flask, jsonify, request, abort
from flask_tryton import Tryton
from flask_cors import CORS
DELTA_FORECAST = 15
app = Flask(__name__)
CORS(app)
# FOREST
USER = 1
# ESCOOL
#USER = 83
manager = {}
HOME_DIR = os.getenv('HOME')
default_dir = os.path.join(HOME_DIR, '.flask')
config_file = os.path.join(default_dir, 'env_flask.ini')
config = configparser.ConfigParser()
config.read(config_file)
databases = list(eval(config.get('General', 'databases')))
trytond_config = config.get('General', 'trytond_config')
host_ = config.get('General', 'host')
API_KEY = config.get('Auth', 'api_key')
for db in databases:
app.config['TRYTON_DATABASE'] = db
app.config['TRYTON_CONFIG'] = trytond_config
# app.config['TRYTON_USER'] = 1
# app.config['CORS_HEADERS'] = 'Content-Type'
manager[db] = Tryton(app)
def send_data(data):
res = jsonify(data)
res.headers.add('Access-Control-Allow-Origin', '*')
res.headers.add('Access-Control-Allow-Methods', 'POST, GET, PUT, OPTIONS')
res.headers.add('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token')
return res
def get_model(database, model_name):
tryton = manager[database]
@tryton.transaction()
def _get(model_name):
model = tryton.pool.get(model_name)
return model
return _get(model_name)
# The actual decorator function
def require_appkey(view_function):
@wraps(view_function)
# the new, post-decoration function. Note *args and **kwargs here.
def decorated_function(*args, **kwargs):
if request.headers.get('Authorization') and request.headers.get('Authorization') == API_KEY:
return view_function(*args, **kwargs)
else:
abort(401)
return decorated_function
@app.route('/home')
def home():
return "Welcome to Presik Technologies"
@app.route('/login')
def login():
res = {
'msg': 'User name not found!',
'user_id': None,
'name': None,
}
database = request.args.get('database', None)
username = request.args.get('user', None)
# passwd = request.args.get('passwd', None)
tryton = manager[database]
@tryton.transaction()
def search_user(username):
User = tryton.pool.get('res.user')
users = User.search_read([
('login', '=', username),
('active', '=', True),
], fields_names=['id', 'name', 'company', 'company.party.name'])
return users
# FIXME: Add check password ('password', '=', passwd),
users = search_user(username)
if users:
user = users[0]
res['msg'] = 'ok'
res['name'] = user['name']
res['user_id'] = user['id']
res['company_id'] = user['company.']['id']
res['company_name'] = user['company.']['party.name']
return send_data(res)
def search(tryton, model, domain):
@tryton.transaction()
def _search():
Model = tryton.pool.get(model)
records = Model.search(domain)
return records
return _search()
@app.route("/<db>/countries/", methods=['GET', 'OPTIONS'])
# @cross_origin()
def get_countries(db):
tryton = manager[db]
@tryton.transaction()
def _get_countries():
Country = tryton.pool.get('party.country_code')
countries = Country.search_read([],
fields_names=['id', 'name']
)
return countries
countries = _get_countries()
return send_data(countries)
@app.route("/<db>/departments/", methods=['GET'])
@require_appkey
def get_departments(db):
tryton = manager[db]
@tryton.transaction()
def _get_departments():
Department = tryton.pool.get('party.department_code')
departments = Department.search_read([],
fields_names=['id', 'name']
)
return departments
departments = _get_departments()
return send_data(departments)
@app.route("/<db>/cities/<departmentId>", methods=['GET'])
@require_appkey
def get_cities(db, departmentId):
tryton = manager[db]
@tryton.transaction()
def _get_cities():
City = tryton.pool.get('party.city_code')
cities = City.search_read([
('department', '=', int(departmentId))
], fields_names=['id', 'name', 'department'])
return cities
cities = _get_cities()
return send_data(cities)
@app.route("/<db>/parties/", methods=['GET'])
@require_appkey
def get_parties(db):
tryton = manager[db]
@tryton.transaction()
def _get_parties():
Party = tryton.pool.get('party.party')
lines = Party.search_read(
[],
fields_names=['id', 'name', 'id_number', 'email']
)
return lines
lines = _get_parties()
return send_data(lines)
@app.route("/<db>/payment_term/", methods=['GET'])
@require_appkey
def get_payment_term(db):
tryton = manager[db]
@tryton.transaction()
def _get_payment_term():
Payment = tryton.pool.get('account.invoice.payment_term')
lines = Payment.search_read([],
fields_names=['id', 'name']
)
return lines
lines = _get_payment_term()
return send_data(lines)
@app.route("/<db>/party/<idNumber>", methods=['GET'])
@require_appkey
def get_party(db, idNumber):
tryton = manager[db]
@tryton.transaction()
def _get_party():
Party = tryton.pool.get('party.party')
party = None
parties = Party.search_read([
('id_number', '=', idNumber),
], fields_names=['id', 'name', 'id_number', 'email']
)
if parties:
party = parties[0]
return party
p = _get_party()
return send_data(p)
@app.route("/<db>/products_by_shop/<shopId>")
@require_appkey
def get_products_by_shop(db, shopId):
tryton = manager[db]
context = {'company': 1, 'user': 1}
@tryton.transaction(context=context)
def _get_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
Category = tryton.pool.get('product.category')
# ListPrice = tryton.pool.get('product.list_price')
shops = Shop.search([
('id', '=', shopId)
])
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search_read([
('account_category', 'in', categories_ids),
('categories', '!=', None),
('active', '=', True),
], fields_names=[
'id', 'template', 'template.name', 'code',
'template.categories', 'template.sale_price_w_tax',
'template.list_price'],
order=[('code', 'ASC')]
)
# prices = ListPrice.search_read([
# ('template', 'in', [v['template'] for v in values])
# ], fields_names=['id', 'template', 'list_price']
# )
# prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
template = val.get('template.', None)
if template and not template.get('list_price'):
continue
categories = Category.search_read([
('id', 'in', val['template.']['categories']),
], fields_names=['id', 'name', 'parent'])
products.append({
'id': val['id'],
'name': val['template.']['name'],
'code': val['code'],
'category': categories,
'sale_price': float(val['template.']['list_price']),
'images': '',
# 'sale_price': float(prices2product[val['template']]),
})
return send_data(products)
return _get_products()
@app.route("/<db>/categorized_products/<shopId>")
@require_appkey
def get_categorized_products(db, shopId):
tryton = manager[db]
context = {'company': 1, 'user': 1}
@tryton.transaction(context=context)
def _get_categorized_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
ListPrice = tryton.pool.get('product.list_price')
Category = tryton.pool.get('product.category')
shops = Shop.search([
('id', '=', shopId)
])
target_categories = {}
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search([
('account_category', 'in', categories_ids),
('categories', '!=', None),
('active', '=', True),
], order=[('code', 'ASC')])
# fields_names=[
# 'id', 'template.name', 'code', 'template.categories',
# 'template.sale_price_w_tax', 'template', 'attributes'
# ],
prices = ListPrice.search_read([
('template', 'in', [v.template.id for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
product = {
'id': val.id,
'name': val.template.name,
'code': val.code,
'sale_price': float(round(prices2product[val.template.id], 2)),
'sale_price_w_tax': float(round(val.template.list_price, 2)),
'attributes': val.attributes,
}
# product['sale_price_w_tax'] = product['sale_price']
cat = val.template.categories[0]
if cat not in target_categories.keys():
c = Category(cat)
target_categories[cat] = {
'id': c.id,
'images': [i.image for i in c.images],
'name': c.name,
'parent': c.parent.id if c.parent else None,
'products': [product]
}
else:
target_categories[cat]['products'].append(product)
res = list(target_categories.values())
return send_data(res)
return _get_categorized_products()
@app.route("/<db>/products_shop_category/<shopId>/<categoryId>")
@require_appkey
def get_products_shop_category(db, shopId, categoryId):
tryton = manager[db]
context = {'company': 1, 'user': 1}
@tryton.transaction(context=context)
def _get_products():
Product = tryton.pool.get('product.product')
ProductCategory = tryton.pool.get('product.template-product.category')
ListPrice = tryton.pool.get('product.list_price')
Shop = tryton.pool.get('sale.shop')
shops = Shop.search([
('id', '=', shopId)
])
templates_cat = ProductCategory.search_read([
('category', '=', int(categoryId))
], fields_names=['template'])
templates_cat = [t['template'] for t in templates_cat]
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search([
('account_category', 'in', categories_ids),
('active', '=', True),
('template', 'in', templates_cat),
],
order=[('code', 'ASC')]
)
prices = ListPrice.search_read([
('template', 'in', [v.template.id for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
products.append({
'id': val.id,
'name': val.template.name,
'code': val.code,
'sale_price': float(prices2product[val.template.id]),
'sale_price_w_tax': float(val.template.list_price),
'categories': [c.id for c in val.template.categories],
})
return send_data(products)
return _get_products()
@app.route("/<db>/products_elastic/<shopId>/<query>", methods=['GET'])
@require_appkey
def get_products_elastic(db, shopId, query):
tryton = manager[db]
@tryton.transaction()
def _get_products():
Product = tryton.pool.get('product.product')
Shop = tryton.pool.get('sale.shop')
ListPrice = tryton.pool.get('product.list_price')
shops = Shop.search([
('id', '=', shopId)
])
products = []
if shops:
shop = shops[0]
categories_ids = [pc.id for pc in shop.product_categories]
values = Product.search_read([
('account_category', 'in', categories_ids),
('active', '=', True),
('categories', '!=', None),
('template.name', 'ilike', '%' + query + '%'),
('template.salable', '=', True),
], fields_names=[
'id', 'template.name', 'code', 'template.categories',
'template.sale_price_w_tax', 'template',
'template.list_price'
],
order=[('code', 'ASC')]
)
prices = ListPrice.search_read([
('template', 'in', [v['template.']['id'] for v in values])
], fields_names=['id', 'template', 'list_price']
)
prices2product = {p['template']: p['list_price'] for p in prices}
for val in values:
products.append({
'id': val['id'],
'name': val['template.']['name'],
'code': val['code'],
'sale_price': float(prices2product[val['template.']['id']]),
'sale_price_w_tax': float(val['template.']['list_price']),
'categories': val['template.']['categories'],
})
return products
products = _get_products()
return send_data(products)
@app.route("/<db>/categories/", methods=['GET'])
@require_appkey
def get_categories(db):
tryton = manager[db]
@tryton.transaction()
def _get_categories():
Category = tryton.pool.get('product.category')
categories = Category.search([
('accounting', '=', False),
('parent', '=', )
])
values = []
for cat in categories:
values.append({
'id': cat.id,
'name': cat.name,
'parent': cat.parent.id if cat.parent else None,
'images': [img.image for img in cat.images]
})
return values
categories = _get_categories()
return send_data(categories)
@app.route("/<db>/shops/", methods=['GET'])
@require_appkey
def get_shops(db):
tryton = manager[db]
@tryton.transaction()
def _get_shops():
Shop = tryton.pool.get('sale.shop')
shops = Shop.search_read(
[],
fields_names=[
'id', 'name',
'freight_product',
'freight_product.template.name',
'freight_product.template.sale_price_w_tax',
])
shops_ = []
for shop in shops:
freight_price = 0
if shop['id'] == 4:
freight_price = 10000
new_shop = {
'id': shop['id'],
'name': shop['name'],
'product_freight_id': shop['freight_product.']['id'],
'product_freight_name': 'FLETE',
'product_freight_price': freight_price,
}
shops_.append(new_shop)
return shops_
shops = _get_shops()
return send_data(shops)
@app.route("/<db>/add_party/", methods=['POST'])
@require_appkey
def add_party(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8") )
regime_tax = ''
if data['type_document'] == '31':
regime_tax = 'regimen_comun'
msg = 'User created succesfully'
values = {
'name': data['name'].upper(),
'id_number': data['id_number'],
'type_document': data['type_document'],
'regime_tax': regime_tax,
'addresses': [('create', [{
'street': data['address'],
'country_code': data['country'],
'department_code': data['department'],
'city_code': data['city'],
}]
)],
'contact_mechanisms': [('create', [{
'type': 'mobile',
'value': data['phone'],
}, {
'type': 'email',
'value': data['email'],
}]
)],
}
@tryton.transaction()
def _create(_values):
Party = tryton.pool.get('party.party')
PartyAccount = tryton.pool.get('party.party.account')
Configuration = tryton.pool.get('account.configuration.default_account')
config = Configuration(1)
party, = Party.create([_values])
if config.default_account_receivable:
PartyAccount.create([{
'company': 1,
'party': party.id,
'account_payable': None,
'account_receivable': config.default_account_receivable.id,
}])
# PartyAccount.create([{
# 'company': 1,
# 'party': party.id,
# 'account_payable': config.default_account_payable.id,
# 'account_receivable': config.default_account_receivable.id,
# }])
return party
try:
_create(values)
except:
msg = 'Error in user creation!'
return send_data(msg)
@app.route("/<db>/update_party/", methods=['POST'])
@require_appkey
def update_party(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
regime_tax = ''
if data['type_document'] == '31':
regime_tax = 'regimen_comun'
values = {
'name': data['name'],
'id_number': data['id_number'],
'type_document': data['type_document'],
'regime_tax': regime_tax,
}
addresses = {
'street': data['address'],
'country_code': data['country'],
'department_code': data['department'],
'city_code': data['city']
}
@tryton.transaction()
def _update_party():
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Party.write([party], values)
return party
@tryton.transaction()
def _update_address():
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Address = tryton.pool.get('party.address')
Address.write(list(party.addresses), addresses)
@tryton.transaction()
def _update_contact(type_, val):
Party = tryton.pool.get('party.party')
party = Party(data['id'])
Contact = tryton.pool.get('party.contact_mechanism')
contacts = Contact.search([
('party', '=', party.id,),
('type', '=', type_,),
])
Contact.write(contacts, {
'type': type_,
'value': val,
})
try:
_update_party()
if data['address']:
_update_address()
if data['phone']:
_update_contact('mobile', data['phone'])
if data['email']:
_update_contact('email', data['email'])
msg = 'User updated succesfully!, you can check it with /party/ route'
except:
msg = 'Error in user update!'
return send_data(msg)
@app.route("/<db>/add_sale/", methods=['POST'])
@require_appkey
def add_sale(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
print(data)
@tryton.transaction()
def _get_user():
User = tryton.pool.get('res.user')
user, = User.search([
('login', '=', 'ecommerce')
])
return user.id
user_id = _get_user()
ctx = {'company': 1}
@tryton.transaction(context=ctx, user=user_id)
def _get_lines():
lines = []
# Template = tryton.pool.get('product.template')
Product = tryton.pool.get('product.product')
for l in data['lines']:
product = Product(l['product'])
template = product.template
# taxes = [tax.id for tax in template.account_category.customer_taxes_used]
lines.append({
'product': l['product'],
'description': template.name,
'unit_price': Decimal(l['list_price']),
'unit': template.default_uom.id,
'quantity': l['quantity'],
# 'taxes': [('add', taxes)]
})
return lines
@tryton.transaction(user=user_id)
def _create(lines):
Party = tryton.pool.get('party.party')
Sale = tryton.pool.get('sale.sale')
Shop = tryton.pool.get('sale.shop')
PartyAccount = tryton.pool.get('party.party.account')
Statement = tryton.pool.get('account.statement')
StatementLine = tryton.pool.get('account.statement.line')
shipment_party = data['party']
party = Party(data['party'])
shipment_address_id = party.addresses[0].id
shop = Shop(data['shop'])
sale_date = datetime.now(timezone(shop.company.timezone)).date()
vals = {
'company': shop.company.id,
'state': 'draft',
'party': data['party'],
'sale_date': sale_date,
'currency': shop.company.currency.id,
'shop': data['shop'],
'payment_term': data['payment_term'],
'shipment_party': shipment_party,
'shipment_address': shipment_address_id,
'invoice_address': shipment_address_id,
'warehouse': shop.warehouse.id,
'shipment_method': 'order',
'invoice_method': 'order',
'shipment_state': 'none',
'invoice_state': 'none',
'invoice_type': 'P',
'lines': [('create', lines)],
'description': 'WEB SALE',
'reference': shop.name,
'self_pick_up': False
}
sale, = Sale.create([vals])
Sale.quote([sale])
# Sale.confirm([sale])
statements = Statement.search([
('journal.name', '=', 'pagos_web'),
('sale_device.shop', '=', int(data['shop'])),
('state', '=', 'draft'),
])
statement = None
if statements:
statement = statements[0]
# Sale.process([sale])
party_accs = PartyAccount.search([
('party', '=', party.id),
('account_receivable', '!=', None),
])
party_acc = party_accs[0]
if statement and data.get('paid_amount') and data.get('voucher'):
StatementLine.create([{
'sale': sale.id,
'date': sale_date,
'statement': statement.id,
'amount': data['paid_amount'],
'party': sale.party.id,
'account': party_acc.account_receivable.id,
'description': data.get('voucher'),
}])
return sale
res = {
'msg': 'Error in sale creation!',
'status': 'error',
'order': ''
}
try:
lines = _get_lines()
sale = _create(lines)
if sale and sale.number:
res['msg'] = 'Sale created succesfully'
res['status'] = 'success'
res['order'] = sale.number
except Exception as e:
print(e)
res['msg'] = e
print(res)
return send_data(res)
@app.route("/<db>/product_freight/", methods=['GET'])
@require_appkey
def get_product_freight(db):
tryton = manager[db]
data = json.loads(request.data.decode("utf-8"))
@tryton.transaction()
def _get_user():
User = tryton.pool.get('res.user')
user, = User.search([
('login', '=', 'ecommerce')
])
return user.id
user_id = _get_user()
@tryton.transaction(user=user_id)
def _get_product_freight():
Product = tryton.pool.get('product.product')
product = None
products = Product.search_read(
[('code', '=', 'FLETE')],
fields_names=['id', 'template.name', 'template.sale_price_w_tax']
)
if products:
product_ = products[0]
product = {
'name': product_['template.']['name'],
'id': product_['id'],
'sale_price_w_tax': float(product_['template.']['sale_price_w_tax']),
}
return product
product = _get_product_freight()
return send_data(product)
@app.route("/<db>/categories_tree/<shopId>", methods=['GET'])
@require_appkey
def get_categories_tree(db, shopId):
tryton = manager[db]
@tryton.transaction()
def _get_categories():
Shop = tryton.pool.get('sale.shop')
def _get_childs(cat):
value = {
'id': cat.id,
'name': cat.name,
'parent': cat.parent.id if cat.parent else None,
'images': [img.image for img in cat.images]
}
if cat.childs:
value['childs'] = [_get_childs(c) for c in cat.childs]
return value
shop = Shop(shopId)
categories = [c for c in shop.product_categories if c.accounting == False]
categoryTree = []
if categories:
categoryTree = _get_childs(categories[0])
return categoryTree
categories = _get_categories()
return send_data(categories)
if __name__ == "__main__":
app.run(host=host_)

View File

@ -26,7 +26,7 @@ host_ = config.get('General', 'host')
API_KEY = config.get('Auth', 'api_key')
API_KEY_VO = config.get('Auth', 'api_key_vo')
context = {'company': 1, 'user': 1}
# The actual decorator function
def require_appkey(view_function):
@wraps(view_function)
@ -186,7 +186,7 @@ def create_app(dbname):
@require_appkey
def get_products_by_shop(shopId):
@tryton.transaction()
@tryton.transaction(context=context)
def _method():
Product = _pool.get('product.product')
Shop = _pool.get('sale.shop')
@ -223,6 +223,7 @@ def create_app(dbname):
'sale_price': float(val['template.']['list_price']) if val['template.'].get('list_price') else 0,
'images': '',
})
print('template', template)
return products
return send(exec_(_method))
@ -241,7 +242,7 @@ def create_app(dbname):
}
return context
context = _set_ctx()
context.update(_set_ctx())
@tryton.transaction(context=context)
def _method():
@ -312,7 +313,7 @@ def create_app(dbname):
}
return context
context = _set_ctx()
context.update(_set_ctx())
@tryton.transaction(context=context)
def _method():
@ -348,7 +349,7 @@ def create_app(dbname):
'code': val.code,
'quantity': val.quantity,
'sale_price': float(prices2product[val.template.id]),
'sale_price_w_tax': float(val.template.sale_price_w_tax),
'sale_price_w_tax': float(prices2product[val.template.id]),
'categories': [c.id for c in val.template.categories],
})
return products
@ -391,7 +392,7 @@ def create_app(dbname):
'name': val['template.']['name'],
'code': val['code'],
'sale_price': float(prices2product[val['template.']['id']]),
'sale_price_w_tax': float(val['template.']['sale_price_w_tax']),
'sale_price_w_tax': float(prices2product[val['template.']['id']]),
'categories': val['template.']['categories'],
})
return products
@ -763,7 +764,7 @@ def create_app(dbname):
Product = _pool.get('product.product')
fields_names = [
'id', 'code', 'name', 'template.categories',
'template.sale_price_w_tax', 'template.name']
'template.sale_price_w_tax', 'template.name', 'template.list_price']
products = Product.search_read(
['id', '=', id_product],
fields_names=fields_names
@ -774,7 +775,7 @@ def create_app(dbname):
'id': product['id'],
'name': product['template.']['name'],
'code': product['code'],
'sale_price': float(product['template.']['sale_price_w_tax']),
'sale_price': float(product['template.']['list_price']),
'categories': product['template.']['categories.'],
'images': ''
}

View File

@ -24,7 +24,7 @@ config.read(config_file)
trytond_config = get_config('trytond_config')
host_ = config.get('General', 'host')
API_KEY = config.get('Auth', 'api_key')
context = {'company': 1, 'user': 1}
# The actual decorator function
def require_appkey(view_function):
@ -182,7 +182,7 @@ def create_app(dbname):
@require_appkey
def get_products_by_shop(shopId):
@tryton.transaction()
@tryton.transaction(context=context)
def _method():
Product = _pool.get('product.product')
Shop = _pool.get('sale.shop')
@ -237,7 +237,7 @@ def create_app(dbname):
}
return context
context = _set_ctx()
context.update(_set_ctx())
@tryton.transaction(context=context)
def _method():
@ -308,7 +308,7 @@ def create_app(dbname):
}
return context
context = _set_ctx()
context.update(_set_ctx())
@tryton.transaction(context=context)
def _method():
@ -355,7 +355,7 @@ def create_app(dbname):
@require_appkey
def get_products_elastic(shopId, query):
@tryton.transaction()
@tryton.transaction(context=context)
def _method():
Product = _pool.get('product.product')
Shop = _pool.get('sale.shop')

View File

@ -11,7 +11,7 @@ if os.path.exists(certificate_):
else:
print('Mode: Http')
# bind = '0.0.0.0:5010'
bind = '0.0.0.0:5010'
proc_name = 'api-escool'
worker_connections = 1000
workers = 2