Browse Source

[IMP] project structure

robert 6 years ago
parent
commit
4790ead9d8

+ 14 - 0
controllers/helpers/__init__.py

@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+from account_journal import get_journals, get_currencies_from_journal
+from account_payment_term import get_payment_terms
+from http_response import make_gzip_response
+from product_template import get_products
+from res_bank_cheque_type import get_cheque_types
+from res_bank_payments_type import get_bank_payment_types
+from res_bank import get_banks
+from res_currency import check_base_currency
+from res_partner import get_suppliers
+from res_users import get_current_user
+from server_date import get_date
+from stock_picking_type import get_picking_types
+from stock_picking import get_pickings

+ 44 - 0
controllers/helpers/account_invoice.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def create_invoice(
+    supplier_id, 
+    cart_items, 
+    currency_id, 
+    payment_term_id=None, 
+    supplier_invoice_number=None
+):
+    partner = r.env['res.partner'].browse(supplier_id)
+    journal = r.env['account.journal'].search([('type', 'in', ['purchase']), ('company_id', '=', partner.company_id.id)])
+
+    return r.env['account.invoice'].create({
+        'name': '/',
+        'partner_id': partner.id,
+        'invoice_line': [[0, False, {
+            'name': line.get('name'),
+            'product_id': int(line.get('id')),
+            'quantity': float(line.get('quantity')),
+            'price_unit': float(line.get('price'))
+        }] for line in cart_items],
+        'account_id': partner.property_account_payable.id,
+        'journal_id': journal.id,
+        'currency_id': currency_id,
+        'payment_term': payment_term_id,
+        'supplier_invoice_number': supplier_invoice_number,
+        'type': 'in_invoice'
+    })
+
+
+def prepare_invoice(invoice_ids, currency_id, date_today):
+    assert len(invoice_ids) == 1
+
+    invoice = r.env['account.invoice'].browse(invoice_ids)
+    
+    date_due = parse(date_today) + rd(days=max(invoice.payment_term.line_ids.mapped(lambda x: x.days + x.days2)))
+
+    invoice.write({
+        'currency_id': currency_id,
+        'date_invoice': date_today,
+        'date_due': date_due.strftime(DATE_FORMAT),
+        'state': 'open'
+    })

+ 71 - 0
controllers/helpers/account_journal.py

@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_currencies_from_journal():
+    domain = [
+        ('type', 'in', ['bank', 'cash']), 
+        ('default_debit_account_id.currency_id', '=', False), 
+        ('active', '=', True)
+    ]
+
+    currencies = []
+
+    for j in r.env['account.journal'].search(domain):
+        c = j.currency or j.company_id.currency_id
+
+        currencies.append({
+            'id': c.id,
+            'name': c.display_name,
+            'base': c.base,
+            'symbol': c.symbol,
+            'position': c.position,
+            'rateSilent': c.rate_silent,
+            'decimalSeparator': c.decimal_separator,
+            'decimalPlaces': c.decimal_places,
+            'thousandsSeparator': c.thousands_separator
+        })
+    
+    return {c['id']:c for c in currencies}.values()
+
+def get_journals():
+    domain = [
+        ('type', 'in', ['bank', 'cash']), 
+        ('default_debit_account_id.currency_id', '=', False), 
+        ('active', '=', True)
+    ]
+
+    return [{
+        'id': j.id,
+        'name': j.name,
+        'displayName': j.display_name,
+        'code': j.code,
+        'cashControl': j.cash_control,
+        'type': j.type,
+        'currency': {
+            'id': j.currency.id,
+            'name': j.currency.name,
+            'displayName': j.currency.display_name
+        },
+        'defaultDebitAccount': {
+            'id': j.default_debit_account_id.id,
+            'name': j.default_debit_account_id.name,
+            'displayName': j.default_debit_account_id.display_name,
+            'code': j.default_debit_account_id.code,
+            'exchange_rate': j.default_credit_account_id.exchange_rate,
+            'foreignBalance': j.default_credit_account_id.foreign_balance,
+            'reconcile': j.default_credit_account_id.reconcile,
+            'debit': j.default_credit_account_id.debit,
+            'credit': j.default_credit_account_id.credit,
+            'currencyMode': j.default_credit_account_id.currency_mode,
+            'companyCurrency': {
+                'id': j.default_credit_account_id.company_currency_id.id,
+                'name': j.default_credit_account_id.company_currency_id.name,
+                'displayName': j.default_credit_account_id.company_currency_id.display_name,
+            },
+            'currency': {
+                'id': j.default_credit_account_id.currency_id.id,
+                'name': j.default_credit_account_id.currency_id.name,
+                'displayName': j.default_credit_account_id.currency_id.display_name
+            }
+        }
+    } for j in r.env['account.journal'].search(domain, order='id')]

+ 118 - 0
controllers/helpers/account_move.py

@@ -0,0 +1,118 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+
+def create_invoice_move_lines(invoice_ids, paid_amount, date_today):
+    assert len(invoice_ids) == 1
+    invoice = r.env['account.invoice'].browse(invoice_ids)
+    is_purchase = False
+
+    scoped_context = dict(r.context, lang=invoice.partner_id.lang)
+
+    invoice_move_lines = invoice._get_analytic_lines()
+    decimal_precision = r.env['decimal.precision'].precision_get('Account')
+
+    compute_taxes = r.env['account.invoice.tax'].compute(invoice.with_context(lang=invoice.partner_id.lang))
+    invoice.check_tax_lines(compute_taxes)
+    invoice._recompute_tax_amount()
+
+    invoice_move_lines += r.env['account.invoice.tax'].move_line_get(invoice.id)
+    total, total_currency, invoice_move_lines = invoice.with_context(scoped_context).compute_invoice_totals(invoice.company_id.currency_id, invoice.reference, invoice_move_lines)
+
+    if total < 0:
+        total = total * -1
+        is_purchase = True
+
+    paid_percentage = abs(paid_amount / round(total, decimal_precision))
+    distributed_percentage = -(paid_percentage / len(invoice.payment_term.line_ids))
+
+    payment_lines = []
+
+    for line in invoice.payment_term.line_ids:
+        date_due = (parse(date_today) + rd(days=line.days + line.days2)).strftime(DATE_FORMAT)
+
+        if paid_percentage and paid_percentage < 1.0:
+            payment_lines.append([date_today, paid_percentage])
+            paid_percentage = paid_amount = 0
+
+            if date_due == date_today and line.value_amount:
+                distributed_percentage = -((payment_lines[0][1] - line.value_amount)  / (len(invoice.payment_term.line_ids) - 1))
+                continue
+        
+        if line.value != 'balance':
+            payment_lines.append([date_due, line.value_amount + distributed_percentage])
+            continue
+
+        payment_lines.append([date_due, line.value_amount])
+
+        for payment_line in payment_lines:
+            current_price = round(total * payment_line[1], decimal_precision)
+
+            if current_price < 0.0:
+                continue
+
+            paid_amount = paid_amount + current_price
+            price = current_price if payment_line[1] else round(total - paid_amount, decimal_precision) or total
+
+            if is_purchase:
+                price = price * -1
+
+            invoice_move_lines.append({
+                'type': 'dest',
+                'name': '/',
+                'price': price,
+                'account_id': invoice.account_id.id,
+                'date_maturity': payment_line[0],
+                'amount_currency': invoice.company_id.currency_id.compute(payment_line[1], invoice.currency_id) if invoice.currency_id != invoice.company_id.currency_id else False,
+                'currency_id': invoice.currency_id != invoice.company_id.currency_id and invoice.currency_id.id,
+                'ref': invoice.type in ('in_invoice', 'in_refund') and invoice.reference or invoice.number 
+            })
+            
+        payment_lines = []
+
+    return invoice_move_lines
+
+
+def create_account_move(invoice_ids, invoice_move_lines):
+    assert len(invoice_ids) == 1
+
+    invoice = r.env['account.invoice'].browse(invoice_ids)
+    accounting_partner = r.env['res.partner']._find_accounting_partner(invoice.partner_id)
+
+    move_line_values = [(0, 0, invoice.line_get_convert(line, accounting_partner.id, invoice.date_invoice)) for line in invoice_move_lines]
+    move_line_values = invoice.group_lines(invoice_move_lines, move_line_values)
+    move_line_values = invoice.finalize_invoice_move_lines(move_line_values)
+
+    ctx = dict(r.context, lang=invoice.partner_id.lang, company_id=invoice.company_id.id)
+    period = invoice.period_id
+
+    if not period:
+        period = period.with_context(ctx).find(invoice.date_invoice)[:1]
+
+    if period:
+        for line in move_line_values:
+            line[2]['period_id'] = period.id
+
+    ctx['invoice'] = invoice
+    ctx_nolang = ctx.copy()
+    ctx_nolang.pop('lang', None)
+
+    account_move = r.env['account.move'].with_context(ctx_nolang).create({
+        'ref': invoice.reference or invoice.name,
+        'line_id': move_line_values,
+        'journal_id': invoice.journal_id.with_context(r.context, lang=invoice.partner_id.lang).id,
+        'date': invoice.date_invoice,
+        'narration': invoice.comment,
+        'company_id': invoice.company_id.id,
+        'period_id': period.id
+    })
+
+    invoice.with_context(ctx).write({
+        'move_id': account_move.id,
+        'period_id': account_move.period_id.id,
+        'move_name': account_move.name,
+    })
+
+    account_move.post()
+
+    return account_move

+ 22 - 0
controllers/helpers/account_payment_term.py

@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_payment_terms():
+    domain = [
+        ('active', '=', True)
+    ]
+
+    return [
+        {
+            'id': pt.id,
+            'name': pt.name,
+            'displayName': pt.display_name,
+            'lines': [{
+                'id': l.id,
+                'days': l.days,
+                'days2': l.days2,
+                'value': l.value,
+                'valueAmount': l.value_amount
+            } for l in pt.line_ids]
+        } for pt in r.env['account.payment.term'].search(domain)
+    ]

+ 39 - 0
controllers/helpers/http_response.py

@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+from werkzeug.wrappers import Response
+from werkzeug.datastructures import Headers
+from gzip import GzipFile
+
+import simplejson as json
+import gzip
+
+try:
+    from cStringIO import StringIO as IO
+except ImportError:
+    from StringIO import StringIO as IO
+
+GZIP_COMPRESSION_LEVEL = 9
+
+'''
+    Make JSON response
+'''
+def make_json_response(data=None, status=200):
+    return Response(json.dumps(data), status=status, content_type='application/json')
+
+'''
+    Make GZIP to JSON response
+'''
+def make_gzip_response(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')

+ 21 - 0
controllers/helpers/product_pricelist.py

@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_pricelist_id(currency_id):
+    domain = [
+        ('active', '=', True),
+        ('type', '=', 'sale')
+    ]
+
+    pricelist = r.env['product.pricelist'].search(domain)
+
+    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

+ 73 - 0
controllers/helpers/product_template.py

@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_products(type=None):
+    product_obj = r.env['product.template']
+    domain = [('standard_price', '>=', 0), ('active', '=', True)]
+
+    if type == 'purchase':
+        domain.append(('purchase_ok', '=', True))
+    else:
+        if product_obj.fields_get('hr_expense_ok'):
+            domain.append(('hr_expense_ok', '=', True))
+        else:
+            return []
+
+    return [
+        {
+            'id': p.id,
+            'name': p.name,
+            'displayName': p.display_name,
+            'ean13': p.ean13,
+            'imageMedium': p.image_medium,
+            'standardPrice': p.standard_price,
+            'variantCount': p.product_variant_count,
+            'quantity': 1,
+            'price': p.standard_price,
+            'minimumPrice': p.minimum_price,
+            'maximumPrice': p.maximum_price,
+            'variants': [{
+                'id': v.id,
+                'name': v.name,
+                'displayName': v.display_name,
+                'ean13': v.ean13,
+                'imageMedium': v.image_medium,
+                'standardPrice': v.standard_price,
+                'quantity': 1,
+                'price': v.standard_price,
+                'minimumPrice': p.minimum_price,
+                'maximumPrice': p.maximum_price
+            } for v in p.product_variant_ids if v.active]
+        } for p in product_obj.search(domain)
+    ]
+
+def create_product(self, values):
+    p = r.env['product.template'].create({
+        'name': values.get('name'),
+        'standard_price': float(values.get('price')),
+        'ean13': values.get('ean13')
+    })
+
+    return {
+        'id': p.id,
+        'name': p.name,
+        'displayName': p.display_name,
+        'ean13': p.ean13,
+        'imageMedium': p.image_medium,
+        'standardPrice': p.standard_price,
+        'variantCount': p.product_variant_count,
+        'price': p.list_price,
+        'minimumPrice': p.minimum_price,
+        'maximumPrice': p.maximum_price,
+        'variants': [{
+            'id': v.id,
+            'name': v.name,
+            'displayName': v.display_name,
+            'ean13': v.ean13,
+            'imageMedium': v.image_medium,
+            'standardPrice': p.standard_price,
+            'price': v.standard_price,
+            'minimumPrice': p.minimum_price,
+            'maximumPrice': p.maximum_price
+        } for v in p.product_variant_ids if v.active]
+    }

+ 55 - 0
controllers/helpers/purchase_order.py

@@ -0,0 +1,55 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def create_purchase_order(
+    supplier_id, 
+    cart_items, 
+    date_order, 
+    currency_id, 
+    pricelist_id, 
+    payment_term_id=None
+):
+
+    def get_product_obj(product_id):
+        return r.env['product.product'].browse(product_id)
+
+    lines = []
+
+    for item in cart_items:
+        product = get_product_obj(item.get('id'))
+
+        lines += [[0, False, {
+            'name': item.get('name'),
+            'date_planned': date_order,
+            'product_id': product.id,
+            'product_qty': float(item.get('quantity')),
+            'price_unit': float(item.get('price')),
+            'product_uom': product.uom_id.id
+        }]]
+
+    values = {
+        'name': '/',
+        'partner_id': supplier_id,
+        'order_line': lines,
+        'date_order': datetime.utcnow().strftime(DATETIME_FORMAT),
+        'currency_id': currency_id,
+        'pricelist_id': pricelist_id,
+        'payment_term_id': payment_term_id,
+        'location_id': self.get_stock_location_id(),
+        'invoice_method': 'order'
+    }
+
+    return request.env['purchase.order'].create(values)
+
+
+def confirm_purchase_order(purchase_order_id):
+    po = r.env['purchase.order'].browse(purchase_order_id)
+    po.action_purchase_confirm()
+
+    for picking in po.picking_ids:
+            picking.force_assign()
+            picking.action_done()
+
+    po.write({
+        'state': 'done'
+    })

+ 13 - 0
controllers/helpers/res_bank.py

@@ -0,0 +1,13 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_banks():
+    domain = [
+        ('active', '=', True)
+    ]
+    return [
+        {
+            'id': bank.id,
+            'name': bank.display_name
+        } for bank in r.env['res.bank'].search(domain)
+    ]

+ 12 - 0
controllers/helpers/res_bank_cheque_type.py

@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_cheque_types():
+    return [
+        {
+            'id': t.id,
+            'name': t.display_name,
+            'isBank': t.is_bank,
+            'isCash': t.is_cash
+        } for t in r.env['res.bank.cheque.type'].search([])
+    ]

+ 5 - 0
controllers/helpers/res_bank_payments_type.py

@@ -0,0 +1,5 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_bank_payment_types(journal_id=None):
+    return r.env['res.bank.payments.type'].get_bank_payments_type(journal_id)

+ 15 - 0
controllers/helpers/res_currency.py

@@ -0,0 +1,15 @@
+# -*- coding: utf-8-*-
+from openerp.http import request as r
+
+def check_base_currency():
+    base_currency = request.env['res.currency'].search([('base', '=', True)])
+
+    if not base_currency:
+        request.env.user.company_id.currency_id.write({
+            'base': True
+        })
+
+def get_currency_id(journal_id):
+    j = r.env['account.journal'].browse(journal_id)
+    return j.default_debit_account_id.currency_id.id or j.default_debit_account_id.company_currency_id.id
+    

+ 40 - 0
controllers/helpers/res_partner.py

@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_suppliers():
+    domain = [
+        ('supplier', '=', True),
+        ('active', '=', True)
+    ]
+
+    return [
+        {
+            'id': s.id,
+            'name': s.name,
+            'displayName': s.display_name,
+            'imageMedium': s.image_medium,
+            'ruc': s.ruc,
+            'phone': s.phone,
+            'mobile': s.mobile,
+            'email': s.email
+        } for s in r.env['res.partner'].search(domain)
+    ]
+
+def create_supplier(values):
+    s = r.env['res.partner'].create({
+        'name': values.get('name'),
+        'ruc': values.get('ruc'),
+        'phone': values.get('phone'),
+        'supplier': True,
+        'customer': False
+    })
+
+    return {
+        'id': s.id,
+        'name': s.name,
+        'displayName': s.display_name,
+        'imageMedium': s.image_medium,
+        'phone': s.phone,
+        'mobile': s.mobile,
+        'email': s.email
+    }

+ 22 - 0
controllers/helpers/res_users.py

@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_current_user():
+    user = r.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
+        }
+    }

+ 14 - 0
controllers/helpers/server_date.py

@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
+from pytz import timezone
+from datetime import datetime
+
+def get_timezone():
+    return timezone(r.context['tz'])
+
+def get_datetime():
+    return datetime.now(get_timezone()).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
+
+def get_date():
+    return datetime.now(get_timezone()).strftime(DEFAULT_SERVER_DATE_FORMAT)

+ 7 - 0
controllers/helpers/stock_location.py

@@ -0,0 +1,7 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_stock_location_id():
+    stock_location = request.env['stock.location'].search([('usage', '=', 'internal')])
+    
+    return stock_location.id

+ 44 - 0
controllers/helpers/stock_picking.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_pickings():
+    purchase_orders = r.env['purchase.order'].search([('from_pos', '=', True)])
+    purchase_orders = purchase_orders.mapped(lambda x: x.name)
+
+    domain = [
+        ('origin', 'in', purchase_orders),
+        ('state', '=', 'assigned')
+    ]
+
+    return [
+        {
+            'id': sp.id,
+            'name': sp.display_name,
+            'origin': sp.origin,
+            'packOperationExist': sp.pack_operation_exist,
+            'moveLines': [
+                {
+                    'id': m.id,
+                    'name': m.display_name,
+                    'availability': m.availability,
+                    'origin': m.origin,
+                    'quantity': m.product_qty,
+                    'product': {
+                        'id': m.product_id.id,
+                        'name': m.product_id.display_name,
+                        'image': m.product_id.image_medium
+                    }
+                }
+                for m in sp.move_lines
+            ],
+            'partner': {
+                'id': sp.partner_id.id,
+                'name': sp.partner_id.display_name,
+                'image': sp.partner_id.image_medium or None,
+                'ruc': sp.partner_id.ruc or None,
+                'phone': sp.partner_id.phone or None,
+                'mobile': sp.partner_id.mobile or None,
+                'email': sp.partner_id.email or None
+            }
+        } for sp in r.env['stock.picking'].search(domain)
+    ]

+ 16 - 0
controllers/helpers/stock_picking_type.py

@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+from openerp.http import request as r
+
+def get_picking_types():
+    domain = [
+        ('code', '=', 'incoming'),
+        ('active', '=', True)
+    ]
+
+    return [
+        {
+            'id': pt.id,
+            'name': pt.name,
+            'displayName': pt.display_name
+        } for pt in r.env['stock.picking.type'].search(domain)
+    ]

+ 258 - 791
controllers/main.py

@@ -1,287 +1,26 @@
 # -*- 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 pytz import timezone
-from gzip import GzipFile
-from StringIO import StringIO as IO
-import simplejson as json
-import gzip
+from openerp.http import request as r
+from helpers import (
+    get_date,
+    get_current_user,
+    get_currencies_from_journal,
+    get_journals,
+    get_suppliers,
+    get_products,
+    get_picking_types,
+    get_payment_terms,
+    get_banks,
+    get_bank_payment_types,
+    get_cheque_types,
+    get_pickings,
+    make_gzip_response
+)
 import logging
 
 LOGGER = logging.getLogger(__name__)
-DATE_FORMAT = '%Y-%m-%d'
-DATETIME_FORMAT = '%Y-%m-%d %H:%m:%S'
-GZIP_COMPRESSION_LEVEL = 9
 
 class Purchases(http.Controller):
-    
-    '''
-        Get timezone
-    '''
-    def get_timezone(self):
-        return timezone(request.context['tz'])
-
-    '''
-        Get server date to send
-    '''
-    def get_server_date(self):
-        return datetime.now(self.get_timezone()).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 currencies from journals
-    '''
-    def get_currencies_from_journal(self):
-        domain = [
-            ('type', 'in', ['bank', 'cash']), 
-            ('default_debit_account_id.currency_id', '=', False), 
-            ('active', '=', True)
-        ]
-
-        currencies = []
-
-        for j in request.env['account.journal'].search(domain):
-            c = j.currency or j.company_id.currency_id
-
-            currencies.append({
-                'id': c.id,
-                'name': c.display_name,
-                'base': c.base,
-                'symbol': c.symbol,
-                'position': c.position,
-                'rateSilent': c.rate_silent,
-                'decimalSeparator': c.decimal_separator,
-                'decimalPlaces': c.decimal_places,
-                'thousandsSeparator': c.thousands_separator
-            })
-        
-        return {c['id']:c for c in currencies}.values()
-
-    '''
-        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,
-            'ruc': supplier.ruc,
-            '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, type=None):
-        product_obj = request.env['product.template']
-        domain = [('standard_price', '>=', 0), ('active', '=', True)]
-
-        if type == 'purchase':
-            domain.append(('purchase_ok', '=', True))
-        else:
-            if product_obj.fields_get('hr_expense_ok'):
-                domain.append(('hr_expense_ok', '=', True))
-            else:
-                return []
-
-        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,
-            'minimumPrice': product.minimum_price,
-            'maximumPrice': product.maximum_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,
-                'minimumPrice': product.minimum_price,
-                'maximumPrice': product.maximum_price
-            } for variant in product.product_variant_ids if variant.active]
-        } for product in product_obj.search(domain)]
-        
-    '''
-        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)])]
-
-    '''
-        Get all banks
-    '''
-    def get_banks(self):
-        banks = [
-            {
-                'id': bank.id,
-                'name': bank.display_name
-            } for bank in request.env['res.bank'].search([('active', '=', True)])
-        ]
-
-        return banks
-
-    '''
-    '''
-    def get_cheque_types(self):
-        return [
-            {
-                'id': type.id,
-                'name': type.display_name,
-                'isBank': type.is_bank,
-                'isCash': type.is_cash
-            } for type in request.env['res.bank.cheque.type'].search([])
-        ]
-
-    '''
-        Get bank payment types
-    '''
-    def get_bank_payment_types(self, journal_id=None):
-        return request.env['res.bank.payments.type'].get_bank_payments_type(journal_id)
-
-    '''
-        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):
@@ -294,533 +33,261 @@ class Purchases(http.Controller):
     def init_purchase(self, **kw):
         self.make_info_log('Preparing data to {}'.format(kw.get('mode')))
 
-        return self.make_gzip_response({
-            'date': self.get_server_date(),
-            'user': self.get_user(),
-            'currencies': self.get_currencies_from_journal(),
-            'journals': self.get_journals(),
-            'suppliers': self.get_suppliers(),
-            'products': self.get_products(kw.get('mode')),
-            'pickingTypes': self.get_picking_types(),
-            'paymentTerms': self.get_payment_terms(),
-            'banks': self.get_banks(),
-            'bankPaymentTypes': self.get_bank_payment_types(),
-            'chequeTypes': self.get_cheque_types()
-        })
-
-    '''
-        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,
-            'standardPrice': product.standard_price,
-            'variantCount': product.product_variant_count,
-            'price': product.list_price,
-            'minimumPrice': product.minimum_price,
-            'maximumPrice': product.maximum_price,
-            'variants': [{
-                'id': variant.id,
-                'name': variant.name,
-                'displayName': variant.display_name,
-                'ean13': variant.ean13,
-                'imageMedium': variant.image_medium,
-                'standardPrice': product.standard_price,
-                'price': variant.standard_price,
-                'minimumPrice': product.minimum_price,
-                'maximumPrice': product.maximum_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
-
-    '''
-        Get default location
-    '''
-    def get_stock_location_id(self):
-        stock_location = request.env['stock.location'].search([('usage', '=', 'internal')])
-
-        return stock_location.id
-
-    '''
-        Create purchase order from cart and return id
-    '''
-    def create_purchase_order(
-        self, 
-        supplier_id, 
-        cart_items, 
-        date_order, 
-        currency_id, 
-        pricelist_id, 
-        payment_term_id=None
-    ):
-
-        def get_product_obj(product_id):
-            return request.env['product.product'].browse(product_id)
-
-        lines = []
-
-        for item in cart_items:
-            product = get_product_obj(item.get('id'))
-
-            lines += [[0, False, {
-                'name': item.get('name'),
-                'date_planned': date_order,
-                'product_id': product.id,
-                'product_qty': float(item.get('quantity')),
-                'price_unit': float(item.get('price')),
-                'product_uom': product.uom_id.id
-            }]]
-
-        values = {
-            'name': '/',
-            'partner_id': supplier_id,
-            'order_line': lines,
-            'date_order': datetime.utcnow().strftime(DATETIME_FORMAT),
-            'currency_id': currency_id,
-            'pricelist_id': pricelist_id,
-            'payment_term_id': payment_term_id,
-            'location_id': self.get_stock_location_id(),
-            'invoice_method': 'order'
+        mode = kw.get('mode', 'unknown')
+        data = None
+
+        if mode == 'purchase' or mode == 'expense':
+            data = {
+            'date': get_date(),
+            'user': get_current_user(),
+            'currencies': get_currencies_from_journal(),
+            'journals': get_journals(),
+            'suppliers': get_suppliers(),
+            'products': get_products(kw.get('mode')),
+            'pickingTypes': get_picking_types(),
+            'paymentTerms': get_payment_terms(),
+            'banks': get_banks(),
+            'bankPaymentTypes': get_bank_payment_types(),
+            'chequeTypes': get_cheque_types()
         }
 
-        return request.env['purchase.order'].create(values)
-
-    '''
-        Confirm purchase order
-    '''
-    def confirm_purchase_order(self, purchase_order_id):
-        purchase_order = request.env['purchase.order'].browse(purchase_order_id)
-        purchase_order.action_purchase_confirm()
-
-        for picking in purchase_order.picking_ids:
-                picking.force_assign()
-                picking.action_done()
-
-        purchase_order.write({
-            'state': 'done'
-        })
-
-    '''
-        Create invoice
-    '''
-    def create_invoice(
-        self, 
-        supplier_id, 
-        cart_items, 
-        currency_id, 
-        payment_term_id=None, 
-        supplier_invoice_number=None
-    ):
-        partner = request.env['res.partner'].browse(supplier_id)
-        journal = request.env['account.journal'].search([('type', 'in', ['purchase']), ('company_id', '=', partner.company_id.id)])
-
-        return request.env['account.invoice'].create({
-            'name': '/',
-            'partner_id': partner.id,
-            'invoice_line': [[0, False, {
-                'name': line.get('name'),
-                'product_id': int(line.get('id')),
-                'quantity': float(line.get('quantity')),
-                'price_unit': float(line.get('price'))
-            }] for line in cart_items],
-            'account_id': partner.property_account_payable.id,
-            'journal_id': journal.id,
-            'currency_id': currency_id,
-            'payment_term': payment_term_id,
-            'supplier_invoice_number': supplier_invoice_number,
-            'type': 'in_invoice'
-        })
-
-    '''
-        Validate invoice
-    '''
-    def prepare_invoice(self, invoice_ids, currency_id, date_today):
-        assert len(invoice_ids) == 1
+        if mode == 'product_picking':
+            data = {
+                'date': get_date(),
+                'user': get_current_user(),
+                'currencies': get_currencies_from_journal(),
+                'suppliers': get_suppliers(),
+                'products': get_products()
+            }
 
-        invoice = request.env['account.invoice'].browse(invoice_ids)
+        if mode == 'payment':
+            data = {
+                'currencies': get_currencies_from_journal(),
+                'suppliers': get_suppliers(),
+                'journals': get_journals(),
+                'paymentTerms': get_payment_terms(),
+                'banks': get_banks(),
+                'bankPaymentTypes': get_bank_payment_types(),
+                'chequeTypes': get_cheque_types()
+            }
         
-        date_due = parse(date_today) + rd(days=max(invoice.payment_term.line_ids.mapped(lambda x: x.days + x.days2)))
-
-        invoice.write({
-            'currency_id': currency_id,
-            'date_invoice': date_today,
-            'date_due': date_due.strftime(DATE_FORMAT),
-            'state': 'open'
-        })
-
-    '''
-        Create move lines
-    '''
-    def create_invoice_move_lines(self, invoice_ids, paid_amount, date_today):
-        assert len(invoice_ids) == 1
-        invoice = request.env['account.invoice'].browse(invoice_ids)
-        is_purchase = False
-
-        scoped_context = dict(request.context, lang=invoice.partner_id.lang)
-
-        invoice_move_lines = invoice._get_analytic_lines()
-        decimal_precision = request.env['decimal.precision'].precision_get('Account')
-
-        compute_taxes = request.env['account.invoice.tax'].compute(invoice.with_context(lang=invoice.partner_id.lang))
-        invoice.check_tax_lines(compute_taxes)
-        invoice._recompute_tax_amount()
-
-        invoice_move_lines += request.env['account.invoice.tax'].move_line_get(invoice.id)
-        total, total_currency, invoice_move_lines = invoice.with_context(scoped_context).compute_invoice_totals(invoice.company_id.currency_id, invoice.reference, invoice_move_lines)
-
-        if total < 0:
-            total = total * -1
-            is_purchase = True
-
-        paid_percentage = abs(paid_amount / round(total, decimal_precision))
-        distributed_percentage = -(paid_percentage / len(invoice.payment_term.line_ids))
-
-        payment_lines = []
-
-        for line in invoice.payment_term.line_ids:
-            date_due = (parse(date_today) + rd(days=line.days + line.days2)).strftime(DATE_FORMAT)
-
-            if paid_percentage and paid_percentage < 1.0:
-                payment_lines.append([date_today, paid_percentage])
-                paid_percentage = paid_amount = 0
-
-                if date_due == date_today and line.value_amount:
-                    distributed_percentage = -((payment_lines[0][1] - line.value_amount)  / (len(invoice.payment_term.line_ids) - 1))
-                    continue
-            
-            if line.value != 'balance':
-                payment_lines.append([date_due, line.value_amount + distributed_percentage])
-                continue
-
-            payment_lines.append([date_due, line.value_amount])
-
-            for payment_line in payment_lines:
-                current_price = round(total * payment_line[1], decimal_precision)
-
-                if current_price < 0.0:
-                    continue
-
-                paid_amount = paid_amount + current_price
-                price = current_price if payment_line[1] else round(total - paid_amount, decimal_precision) or total
-
-                if is_purchase:
-                    price = price * -1
-
-                invoice_move_lines.append({
-                    'type': 'dest',
-                    'name': '/',
-                    'price': price,
-                    'account_id': invoice.account_id.id,
-                    'date_maturity': payment_line[0],
-                    'amount_currency': invoice.company_id.currency_id.compute(payment_line[1], invoice.currency_id) if invoice.currency_id != invoice.company_id.currency_id else False,
-                    'currency_id': invoice.currency_id != invoice.company_id.currency_id and invoice.currency_id.id,
-                    'ref': invoice.type in ('in_invoice', 'in_refund') and invoice.reference or invoice.number 
-                })
-                
-            payment_lines = []
-
-        return invoice_move_lines
-
-    '''
-        Create account move
-    '''
-    def create_account_move(self, invoice_ids, invoice_move_lines):
-        assert len(invoice_ids) == 1
-
-        invoice = request.env['account.invoice'].browse(invoice_ids)
-        accounting_partner = request.env['res.partner']._find_accounting_partner(invoice.partner_id)
-
-        move_line_values = [(0, 0, invoice.line_get_convert(line, accounting_partner.id, invoice.date_invoice)) for line in invoice_move_lines]
-        move_line_values = invoice.group_lines(invoice_move_lines, move_line_values)
-        move_line_values = invoice.finalize_invoice_move_lines(move_line_values)
-
-        ctx = dict(request.context, lang=invoice.partner_id.lang, company_id=invoice.company_id.id)
-        period = invoice.period_id
-
-        if not period:
-            period = period.with_context(ctx).find(invoice.date_invoice)[:1]
-
-        if period:
-            for line in move_line_values:
-                line[2]['period_id'] = period.id
-
-        ctx['invoice'] = invoice
-        ctx_nolang = ctx.copy()
-        ctx_nolang.pop('lang', None)
- 
-        account_move = request.env['account.move'].with_context(ctx_nolang).create({
-            'ref': invoice.reference or invoice.name,
-            'line_id': move_line_values,
-            'journal_id': invoice.journal_id.with_context(request.context, lang=invoice.partner_id.lang).id,
-            'date': invoice.date_invoice,
-            'narration': invoice.comment,
-            'company_id': invoice.company_id.id,
-            'period_id': period.id
-        })
-
-        invoice.with_context(ctx).write({
-            'move_id': account_move.id,
-            'period_id': account_move.period_id.id,
-            'move_name': account_move.name,
-        })
-
-        account_move.post()
-
-        return account_move
-
-    '''
-        Number to invoice
-    '''
-    def validate_invoice(self, invoice_ids, type=None):
-        assert len(invoice_ids) == 1
-
-        invoice = request.env['account.invoice'].browse(invoice_ids)
-
-        invoice.action_number()
-        invoice.invoice_validate()
-
-        if type != 'purchase':
-            name = 'GASTO' + invoice.name[invoice.name.index('/'):]
-            invoice.write({
-                'number': name,
-                'internal_number': name
-            })
-
-    '''
-        Create voucher
-    '''
-    def create_account_voucher(self, account_move_id, journal_id, currency_id, paid_amount):
-        account_move = request.env['account.move'].browse(account_move_id)
-        account_journal = request.env['account.journal'].browse(journal_id)
-
-        account_voucher = request.env['account.voucher'].create({
-            'reference': account_move.name,
-            'type': 'payment',
-            'journal_id': account_journal.id,
-            'company_id': account_move.company_id.id,
-            'pre_line': True,
-            'amount': paid_amount,
-            'period_id': account_move.period_id.id,
-            'date': account_move.date,
-            'partner_id': account_move.partner_id.id,
-            'account_id': account_journal.default_debit_account_id.id,
-            'currency_id': currency_id,
-            'line_dr_ids': [[0, False, {
-                'date_due': l.date_maturity,
-                'account_id': l.account_id.id,
-                'date_original': l.invoice.date_invoice,
-                'move_line_id': l.id,
-                'amount_original': abs(l.credit or l.debit or 0.0),
-                'amount_unreconciled': abs(l.amount_residual),
-                'amount': abs(l.credit) if account_move.date == l.date_maturity else 0.0,
-                'reconcile': account_move.date == l.date_maturity,
-                'currency_id': currency_id
-            }] for l in account_move.line_id]
-        })
-
-        account_voucher.action_move_line_create()
-
-        return account_voucher
-
-    '''
-        Close a invoice
-    '''
-    def close_invoice(self, invoice_ids):
-        assert len(invoice_ids) == 1
-
-        invoice = request.env['account.invoice'].browse(invoice_ids)
-
-        if invoice.residual == 0:
-            invoice.write({
-                'state': 'paid'
-            })
-
-    '''
-        Create account bank statement
-    '''
-    def create_bank_statement(self, account_voucher_id, account_bank_statement_lines, date_today):
-        account_voucher = request.env['account.voucher'].browse(account_voucher_id)
-        account_bank_statement = request.env['account.bank.statement'].search([('journal_id', '=', account_voucher.journal_id.id), ('date', '=', date_today)])
-
-        account_bank_statement_values = {
-            'date': date_today,
-            'user_id': request.env.user.id,
-            'journal_id': account_voucher.journal_id.id,
-            'period_id': account_voucher.period_id.id,
-            'line_ids': account_bank_statement_lines,
-            'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft'
-        }
-
-        if account_bank_statement:
-            size = len(account_bank_statement)
-
-            if size == 1:
-                account_bank_statement.write(account_bank_statement_values)
-            else:
-                account_bank_statement[size - 1].write(account_bank_statement_values)
-        else:
-            account_bank_statement.create(account_bank_statement_values)
-
-        return account_bank_statement
-
-
-    '''
-        Create account bank statement lines
-    '''
-    def create_bank_statement_lines(self, account_voucher_id, reference=None):
-        account_voucher = request.env['account.voucher'].browse(account_voucher_id)
+        if mode == 'product_taking':
+            data = {
+                'stockPickings': get_pickings()
+            }
 
-        amount = account_voucher.amount
+        return make_gzip_response(data)
+
+    # '''
+    #     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')
+
+
+
+    # '''
+    #     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')
+
+
+
+    # '''
+    #     Number to invoice
+    # '''
+    # def validate_invoice(self, invoice_ids, type=None):
+    #     assert len(invoice_ids) == 1
+
+    #     invoice = request.env['account.invoice'].browse(invoice_ids)
+
+    #     invoice.action_number()
+    #     invoice.invoice_validate()
+
+    #     if type != 'purchase':
+    #         name = 'GASTO' + invoice.name[invoice.name.index('/'):]
+    #         invoice.write({
+    #             'number': name,
+    #             'internal_number': name
+    #         })
+
+    # '''
+    #     Create voucher
+    # '''
+    # def create_account_voucher(self, account_move_id, journal_id, currency_id, paid_amount):
+    #     account_move = request.env['account.move'].browse(account_move_id)
+    #     account_journal = request.env['account.journal'].browse(journal_id)
+
+    #     account_voucher = request.env['account.voucher'].create({
+    #         'reference': account_move.name,
+    #         'type': 'payment',
+    #         'journal_id': account_journal.id,
+    #         'company_id': account_move.company_id.id,
+    #         'pre_line': True,
+    #         'amount': paid_amount,
+    #         'period_id': account_move.period_id.id,
+    #         'date': account_move.date,
+    #         'partner_id': account_move.partner_id.id,
+    #         'account_id': account_journal.default_debit_account_id.id,
+    #         'currency_id': currency_id,
+    #         'line_dr_ids': [[0, False, {
+    #             'date_due': l.date_maturity,
+    #             'account_id': l.account_id.id,
+    #             'date_original': l.invoice.date_invoice,
+    #             'move_line_id': l.id,
+    #             'amount_original': abs(l.credit or l.debit or 0.0),
+    #             'amount_unreconciled': abs(l.amount_residual),
+    #             'amount': abs(l.credit) if account_move.date == l.date_maturity else 0.0,
+    #             'reconcile': account_move.date == l.date_maturity,
+    #             'currency_id': currency_id
+    #         }] for l in account_move.line_id]
+    #     })
+
+    #     account_voucher.action_move_line_create()
+
+    #     return account_voucher
+
+    # '''
+    #     Close a invoice
+    # '''
+    # def close_invoice(self, invoice_ids):
+    #     assert len(invoice_ids) == 1
+
+    #     invoice = request.env['account.invoice'].browse(invoice_ids)
+
+    #     if invoice.residual == 0:
+    #         invoice.write({
+    #             'state': 'paid'
+    #         })
+
+    # '''
+    #     Create account bank statement
+    # '''
+    # def create_bank_statement(self, account_voucher_id, account_bank_statement_lines, date_today):
+    #     account_voucher = request.env['account.voucher'].browse(account_voucher_id)
+    #     account_bank_statement = request.env['account.bank.statement'].search([('journal_id', '=', account_voucher.journal_id.id), ('date', '=', date_today)])
+
+    #     account_bank_statement_values = {
+    #         'date': date_today,
+    #         'user_id': request.env.user.id,
+    #         'journal_id': account_voucher.journal_id.id,
+    #         'period_id': account_voucher.period_id.id,
+    #         'line_ids': account_bank_statement_lines,
+    #         'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft'
+    #     }
+
+    #     if account_bank_statement:
+    #         size = len(account_bank_statement)
+
+    #         if size == 1:
+    #             account_bank_statement.write(account_bank_statement_values)
+    #         else:
+    #             account_bank_statement[size - 1].write(account_bank_statement_values)
+    #     else:
+    #         account_bank_statement.create(account_bank_statement_values)
+
+    #     return account_bank_statement
+
+
+    # '''
+    #     Create account bank statement lines
+    # '''
+    # def create_bank_statement_lines(self, account_voucher_id, reference=None):
+    #     account_voucher = request.env['account.voucher'].browse(account_voucher_id)
+
+    #     amount = account_voucher.amount
         
-        if account_voucher.type == 'payment':
-            amount = amount * -1
-
-        return [[0, False, {
-            'name': account_voucher.reference,
-            'amount': amount,
-            'partner_id': account_voucher.partner_id.id,
-            'voucher_id': account_voucher.id,
-            'journal_id': account_voucher.journal_id.id,
-            'account_id': account_voucher.account_id.id,
-            'journal_entry_id': account_voucher.move_id.id,
-            'currency_id': account_voucher.currency_id.id,
-            'ref': 'POS/' + (reference or '')
-        }]]
-
-    '''
-        Purchase processing resource route
-    ''' 
-    @http.route('/eiru_purchases/process', type='json', auth='user', methods=['POST'], cors='*')
-    def process_purchase(self, **kw):
-        mode = kw.get('mode')
-        self.make_info_log('Processing {}'.format(mode))
-
-        # Get date
-        date_now = datetime.now(self.get_timezone()).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('Product pricelist checked')
-
-        invoice = None
-
-        if mode == 'purchase':
-            # Create purchase order 
-            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('Purchase order created')
-
-            # Confirm purchase 
-            self.confirm_purchase_order(purchase_order.id)
-            self.make_info_log('Purchase order confirmed')
+    #     if account_voucher.type == 'payment':
+    #         amount = amount * -1
+
+    #     return [[0, False, {
+    #         'name': account_voucher.reference,
+    #         'amount': amount,
+    #         'partner_id': account_voucher.partner_id.id,
+    #         'voucher_id': account_voucher.id,
+    #         'journal_id': account_voucher.journal_id.id,
+    #         'account_id': account_voucher.account_id.id,
+    #         'journal_entry_id': account_voucher.move_id.id,
+    #         'currency_id': account_voucher.currency_id.id,
+    #         'ref': 'POS/' + (reference or '')
+    #     }]]
+
+    # '''
+    #     Purchase processing resource route
+    # ''' 
+    # @http.route('/eiru_purchases/process', type='json', auth='user', methods=['POST'], cors='*')
+    # def process_purchase(self, **kw):
+    #     mode = kw.get('mode')
+    #     self.make_info_log('Processing {}'.format(mode))
+
+    #     # Get date
+    #     date_now = datetime.now(self.get_timezone()).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('Product pricelist checked')
+
+    #     invoice = None
+
+    #     if mode == 'purchase':
+    #         # Create purchase order 
+    #         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('Purchase order created')
+
+    #         # Confirm purchase 
+    #         self.confirm_purchase_order(purchase_order.id)
+    #         self.make_info_log('Purchase order confirmed')
             
-            invoice = purchase_order.invoice_ids
-            invoice.write({
-                'supplier_invoice_number': kw.get('supplierInvoiceNumber', None)
-            })
-        else:
-            invoice = self.create_invoice(kw.get('supplierId'), kw.get('items'), currency_id, kw.get('paymentTermId'), kw.get('supplierInvoiceNumber', None))
-            self.make_info_log('Invoice created')
-
-        invoice_ids = invoice.mapped(lambda x: x.id) 
+    #         invoice = purchase_order.invoice_ids
+    #         invoice.write({
+    #             'supplier_invoice_number': kw.get('supplierInvoiceNumber', None)
+    #         })
+    #     else:
+    #         invoice = self.create_invoice(kw.get('supplierId'), kw.get('items'), currency_id, kw.get('paymentTermId'), kw.get('supplierInvoiceNumber', None))
+    #         self.make_info_log('Invoice created')
+
+    #     invoice_ids = invoice.mapped(lambda x: x.id) 
         
-        # Validate invoice
-        self.prepare_invoice(invoice_ids, currency_id, date_now)
-        self.make_info_log('Invoice prepared')
+    #     # Validate invoice
+    #     self.prepare_invoice(invoice_ids, currency_id, date_now)
+    #     self.make_info_log('Invoice prepared')
 
-        # Create invoice move lines
-        invoice_move_lines = self.create_invoice_move_lines(invoice_ids, float(kw.get('payment')), date_now)
-        self.make_info_log('Invoice move lines created')
+    #     # Create invoice move lines
+    #     invoice_move_lines = self.create_invoice_move_lines(invoice_ids, float(kw.get('payment')), date_now)
+    #     self.make_info_log('Invoice move lines created')
 
-        # Create account move
-        account_move = self.create_account_move(invoice_ids, invoice_move_lines)
-        self.make_info_log('Account move created')
+    #     # Create account move
+    #     account_move = self.create_account_move(invoice_ids, invoice_move_lines)
+    #     self.make_info_log('Account move created')
 
-        # Validate invoice
-        self.validate_invoice(invoice_ids, mode)
-        self.make_info_log('Invoice validated')
+    #     # Validate invoice
+    #     self.validate_invoice(invoice_ids, mode)
+    #     self.make_info_log('Invoice validated')
 
-        # Create account voucher
-        account_voucher = self.create_account_voucher(account_move.id, kw.get('journalId'), currency_id, float(kw.get('payment')))
-        self.make_info_log('Account voucher created')
+    #     # Create account voucher
+    #     account_voucher = self.create_account_voucher(account_move.id, kw.get('journalId'), currency_id, float(kw.get('payment')))
+    #     self.make_info_log('Account voucher created')
 
-        # Close invoice
-        self.close_invoice(invoice_ids)
-        self.make_info_log('Attempt close invoice')
+    #     # Close invoice
+    #     self.close_invoice(invoice_ids)
+    #     self.make_info_log('Attempt close invoice')
 
-        # Create account bank statement lines
-        account_bank_statement_lines = self.create_bank_statement_lines(account_voucher.id)
-        self.make_info_log('Bank statement lines created')
+    #     # Create account bank statement lines
+    #     account_bank_statement_lines = self.create_bank_statement_lines(account_voucher.id)
+    #     self.make_info_log('Bank statement lines created')
 
-        # Create account bank statement
-        self.create_bank_statement(account_voucher.id, account_bank_statement_lines, date_now)
-        self.make_info_log('Bank statement created')
+    #     # Create account bank statement
+    #     self.create_bank_statement(account_voucher.id, account_bank_statement_lines, date_now)
+    #     self.make_info_log('Bank statement created')
 
-        return {
-            'status': 'ok'
-        }
+    #     return {
+    #         'status': 'ok'
+    #     }

+ 4 - 2
models/purchase_order.py

@@ -1,9 +1,11 @@
 # -*- coding: utf-8 -*-
-from openerp import api, models
+from openerp import api, models, fields
 
 class PurchaseOrder(models.Model):
     _inherit = 'purchase.order'
 
+    from_pop = fields.Boolean(string='Created from POP', default=False)
+
     '''
     '''
     def action_purchase_confirm(self, cr, uid, ids, context=None):
@@ -26,4 +28,4 @@ class PurchaseOrder(models.Model):
             purchase.action_purchase_confirm()
             for picking in purchase.picking_ids:
                 picking.force_assign()
-                picking.action_done()
+                picking.action_done()