123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346 |
- # -*- coding: utf-8 -*-
- from openerp import http
- from openerp.http import request
- from werkzeug.wrappers import Response
- from werkzeug.datastructures import Headers
- from datetime import datetime
- from dateutil.relativedelta import relativedelta as rd
- from dateutil.parser import parse
- from gzip import GzipFile
- from StringIO import StringIO as IO
- import simplejson as json
- import gzip
- import logging
- LOGGER = logging.getLogger(__name__)
- DATE_FORMAT = '%Y-%m-%d'
- GZIP_COMPRESSION_LEVEL = 9
- class Purchases(http.Controller):
- '''
- Get server date to send
- '''
- def get_server_date(self):
- return datetime.now().strftime(DATE_FORMAT)
- '''
- Get current user information
- '''
- def get_user(self):
- user = request.env.user
- return {
- 'id': user.id,
- 'name': user.name,
- 'displayName': user.display_name,
- 'currency': {
- 'id': user.company_id.currency_id.id,
- 'name': user.company_id.currency_id.name,
- 'displayName': user.company_id.currency_id.display_name,
- 'symbol': user.company_id.currency_id.symbol
- },
- 'company': {
- 'id': user.company_id.id,
- 'name': user.company_id.name,
- 'displayName': user.company_id.display_name
- }
- }
- '''
- Get currencies
- '''
- def get_currencies(self):
- return [{
- 'id': currency.id,
- 'name': currency.name,
- 'displayName': currency.display_name,
- 'base': currency.base,
- 'accuracy': currency.accuracy,
- 'rateSilent': currency.rate_silent,
- 'rounding': currency.rounding,
- 'symbol': currency.symbol,
- 'position': currency.position,
- 'decimalSeparator': currency.decimal_separator,
- 'decimalPlaces': currency.decimal_places,
- 'thousandsSeparator': currency.thousands_separator
- } for currency in request.env['res.currency'].search([('active', '=', True)])]
- '''
- Get all active journals
- '''
- def get_journals(self):
- return [{
- 'id': journal.id,
- 'name': journal.name,
- 'displayName': journal.display_name,
- 'code': journal.code,
- 'cashControl': journal.cash_control,
- 'type': journal.type,
- 'currency': {
- 'id': journal.currency.id,
- 'name': journal.currency.name,
- 'displayName': journal.currency.display_name
- },
- 'defaultDebitAccount': {
- 'id': journal.default_debit_account_id.id,
- 'name': journal.default_debit_account_id.name,
- 'displayName': journal.default_debit_account_id.display_name,
- 'code': journal.default_debit_account_id.code,
- 'exchange_rate': journal.default_credit_account_id.exchange_rate,
- 'foreignBalance': journal.default_credit_account_id.foreign_balance,
- 'reconcile': journal.default_credit_account_id.reconcile,
- 'debit': journal.default_credit_account_id.debit,
- 'credit': journal.default_credit_account_id.credit,
- 'currencyMode': journal.default_credit_account_id.currency_mode,
- 'companyCurrency': {
- 'id': journal.default_credit_account_id.company_currency_id.id,
- 'name': journal.default_credit_account_id.company_currency_id.name,
- 'displayName': journal.default_credit_account_id.company_currency_id.display_name,
- },
- 'currency': {
- 'id': journal.default_credit_account_id.currency_id.id,
- 'name': journal.default_credit_account_id.currency_id.name,
- 'displayName': journal.default_credit_account_id.currency_id.display_name
- }
- }
- } for journal in request.env['account.journal'].search([('type', 'in', ['bank', 'cash']), ('default_debit_account_id.currency_id', '=', False), ('active', '=', True)], order='id')]
- '''
- Get all active suppliers
- '''
- def get_suppliers(self):
- return [{
- 'id': supplier.id,
- 'name': supplier.name,
- 'displayName': supplier.display_name,
- 'imageMedium': supplier.image_medium,
- 'phone': supplier.phone,
- 'mobile': supplier.mobile,
- 'email': supplier.email
- } for supplier in request.env['res.partner'].search([('supplier', '=', True), ('active', '=', True)])]
- '''
- Get all purchasable and active products
- '''
- def get_products(self):
- return [{
- 'id': product.id,
- 'name': product.name,
- 'displayName': product.display_name,
- 'ean13': product.ean13,
- 'imageMedium': product.image_medium,
- 'standardPrice': product.standard_price,
- 'variantCount': product.product_variant_count,
- 'quantity': 1,
- 'price': product.standard_price,
- 'variants': [{
- 'id': variant.id,
- 'name': variant.name,
- 'displayName': variant.display_name,
- 'ean13': variant.ean13,
- 'imageMedium': variant.image_medium,
- 'standardPrice': variant.standard_price,
- 'quantity': 1,
- 'price': variant.standard_price
- } for variant in product.product_variant_ids if variant.active]
- } for product in request.env['product.template'].search([('purchase_ok', '=', True), ('standard_price', '>', 0), ('active', '=', True)])]
-
- '''
- Get all incoming and active picking types
- '''
- def get_picking_types(self):
- return [{
- 'id': picking_type.id,
- 'name': picking_type.name,
- 'displayName': picking_type.display_name
- } for picking_type in request.env['stock.picking.type'].search([('code', '=', 'incoming'), ('active', '=', True)])]
-
- '''
- Get all active payment terms
- '''
- def get_payment_terms(self):
- return [{
- 'id': payment_term.id,
- 'name': payment_term.name,
- 'displayName': payment_term.display_name,
- 'lines': [{
- 'id': line.id,
- 'days': line.days,
- 'days2': line.days2,
- 'value': line.value,
- 'valueAmount': line.value_amount
- } for line in payment_term.line_ids]
- } for payment_term in request.env['account.payment.term'].search([('active', '=', True)])]
- '''
- Make JSON response to send
- '''
- def make_response(self, data=None, status=200):
- return Response(json.dumps(data), status=status, content_type='application/json')
- '''
- Make GZIP to JSON response
- '''
- def make_gzip_response(self, data=None, status=200):
- gzip_buffer = IO()
- with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file:
- gzip_file.write(json.dumps(data))
-
- contents = gzip_buffer.getvalue()
- gzip_buffer.close()
- headers = Headers()
- headers.add('Content-Encoding', 'gzip')
- headers.add('Vary', 'Accept-Encoding')
- headers.add('Content-Length', len(contents))
- return Response(contents, status=status, headers=headers, content_type='application/json')
- '''
- '''
- def make_info_log(self, log):
- LOGGER.info('[INFO]' + log)
- '''
- New purchase resource route
- '''
- @http.route('/eiru_purchases/init', auth='user', methods=['GET'], cors='*')
- def init_purchase(self, **kw):
- self.make_info_log('Sending JSON response')
- return self.make_response({
- 'date': self.get_server_date(),
- 'user': self.get_user(),
- 'currencies': self.get_currencies(),
- 'journals': self.get_journals(),
- 'suppliers': self.get_suppliers(),
- 'products': self.get_products(),
- 'pickingTypes': self.get_picking_types(),
- 'paymentTerms': self.get_payment_terms()
- })
- '''
- Create supplier and return data
- '''
- @http.route('/eiru_purchases/create_supplier', type='json', auth='user', methods=['POST'], cors='*')
- def create_supplier(self, **kw):
- self.make_info_log('Creating supplier')
- supplier = request.env['res.partner'].create({
- 'name': kw.get('name'),
- 'ruc': kw.get('ruc'),
- 'phone': kw.get('phone'),
- 'supplier': True,
- 'customer': False
- })
- return {
- 'id': supplier.id,
- 'name': supplier.name,
- 'displayName': supplier.display_name,
- 'imageMedium': supplier.image_medium,
- 'phone': supplier.phone,
- 'mobile': supplier.mobile,
- 'email': supplier.email
- }
- '''
- Create product and return data
- '''
- @http.route('/eiru_purchases/create_product', type='json', auth='user', methods=['POST'], cors='*')
- def create_product(self, **kw):
- self.make_info_log('Creating product')
- product = request.env['product.template'].create({
- 'name': kw.get('name'),
- 'standard_price': float(kw.get('price')),
- 'ean13': kw.get('ean13')
- })
- return {
- 'id': product.id,
- 'name': product.name,
- 'displayName': product.display_name,
- 'ean13': product.ean13,
- 'imageMedium': product.image_medium,
- 'listPrice': product.list_price,
- 'variantCount': product.product_variant_count,
- 'variants': [{
- 'id': variant.id,
- 'name': variant.name,
- 'displayName': variant.display_name,
- 'ean13': variant.ean13,
- 'imageMedium': variant.image_medium,
- 'standardPrice': variant.standard_price
- } for variant in product.product_variant_ids if variant.active]
- }
- '''
- Get currency id based on journal
- '''
- def get_currency_id(self, journal_id):
- journal = request.env['account.journal'].browse(journal_id)
- return journal.default_debit_account_id.currency_id.id or journal.default_debit_account_id.company_currency_id.id
- '''
- Check currency in pricelist and return it
- '''
- def get_pricelist_id(self, currency_id):
- pricelist = request.env['product.pricelist'].search([('active', '=', True), ('type', '=', 'sale')])
- if not True in pricelist.mapped(lambda p: p.currency_id.id == currency_id):
- pricelist = pricelist[0].copy()
- pricelist.write({
- 'currency_id': currency_id
- })
- else:
- pricelist = pricelist.filtered(lambda p: p.currency_id.id == currency_id)
-
- return pricelist.id
- '''
- Create purchase order from cart and return id
- '''
- def create_purchase_order(self, supplier_id, cart_items, date_aprove, currency_id, pricelist_id, payment_term_id=None):
- return request.env['purchase.order'].create({
- 'partner_id': supplier_id,
- 'order_line': [[0, False, {
- 'product_id': int(line.get('id')),
- 'product_uom_qty': float(line.get('quantity')),
- 'price_unit': float(line.get('price'))
- }] for line in cart_items],
- 'date_aprove': date_aprove,
- 'currency_id': currency_id,
- 'pricelist_id': pricelist_id,
- 'payment_term_id': payment_term_id,
- 'state': 'draft'
- })
- '''
- Purchase processing resource route
- '''
- @http.route('/eiru_purchases/process', type='json', auth='user', methods=['POST'], cors='*')
- def process_purchase(self, **kw):
- self.make_info_log('Processing purchase...')
- # Get date
- date_now = datetime.now().strftime(DATE_FORMAT)
- self.make_info_log('Getting date')
- # Get currency
- currency_id = self.get_currency_id(kw.get('journalId'))
- self.make_info_log('Getting currency')
- # Get pricelist
- pricelist_id = self.get_pricelist_id(currency_id)
- self.make_info_log('Getting product pricelist')
- purchase_order = self.create_purchase_order(kw.get('supplierId'), kw.get('items'), date_now, currency_id, pricelist_id, kw.get('paymentTermId'))
- self.make_info_log('Created purchase order')
- return {
- 'status': 'ok'
- }
|