~eduardo-bayardo-bias/openobject-addons/addons_interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time
import netsvc
from osv import fields, osv
from mx import DateTime
from tools import config
from tools.translate import _
import time
from datetime import datetime, timedelta

class sale_order(osv.osv):
    _inherit = "sale.order"

    _columns = {
            'copy': fields.boolean('Copy'),
            'state': fields.selection([
            ('draft', 'Quotation'),
            ('pre_approve', 'Pre-Approve'),
            ('waiting_date', 'Waiting Schedule'),
            ('manual', 'Manual In Progress'),
            ('progress', 'In Progress'),
            ('shipping_except', 'Shipping Exception'),
            ('invoice_except', 'Invoice Exception'),
            ('done', 'Done'),
            ('cancel', 'Cancelled')
            ], 'Order State', readonly=True, help="Gives the state of the quotation or sales order. \nThe exception state is automatically set when a cancel operation occurs in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception). \nThe 'Waiting Schedule' state is set when the invoice is confirmed but waiting for the scheduler to run on the date 'Ordered Date'.", select=True),
        'element': fields.char('Elemento a Colar', size=64, readonly=True, states={'draft': [('readonly', False)]}),
        }

    def copy(self, cr, uid, id, default=None, context=None):
        if not default:
            default = {}
        payment_term = False
        if id:
            partner_term = self.browse(cr, uid, id).partner_id.property_payment_term
            payment_term = partner_term and partner_term.id
        default.update({
            'date_order': (datetime.strptime(time.strftime('%Y-%m-%d'), '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d'),
            'payment_term': payment_term,
            'copy': True,
        })
        return super(sale_order, self).copy(cr, uid, id, default, context=context)

    def write(self, cr, uid, ids, vals, context=None):
        group_id = self.pool.get('sale.order.line').get_obj(cr, uid, 'res.groups', 'account_payment.group_account_payment')
        payment_group_users = [x.id for x in self.pool.get('res.groups').browse(cr, uid, group_id).users]
        so = self.browse(cr, uid, ids)[0]
        copy = so.copy
        if ('copy' in vals):
            copy = vals['copy']
        if ('payment_term' in vals) and not (uid in payment_group_users):
            raise osv.except_osv(_('Error !'), _('Solo los usuarios en el grupo Accounting / Payment pueden modificar el termino de pago.'))
        if not copy:
            if ('user_id' in vals):
                raise osv.except_osv(_('Error !'), _('El asesor comercial no se puede cambiar en el pedido de venta.'))
            if ('state' in vals):
                raise osv.except_osv(_('Error !'), _('Este pedido de venta es el acuerdo comercial y no puede cambiar de estado.'))
            if uid != so.user_id.id:
                raise osv.except_osv(_('Error !'), _('Este pedido de venta es el acuerdo comercial solo puede ser modificado por el vendedor asignado'))
        return super(sale_order, self).write(cr, uid, ids, vals, context=context)

    def get_saldo_credit_limit(self, cr, uid, ids, context=None):
        so = self.browse(cr, uid, ids[0], context)
        partner = so.partner_id        
        moveline_obj = self.pool.get('account.move.line')
        movelines = moveline_obj.search(cr, uid, [('partner_id', '=', partner.id),('account_id.type', 'in', ['receivable', 'payable']), ('state', '<>', 'draft'), ('reconcile_id', '=', False)])
        movelines = moveline_obj.browse(cr, uid, movelines)        
        debit, credit = 0.0, 0.0
        dias_vencimiento = True
        for line in movelines:
            credit += line.debit
            debit += line.credit
            if not (line.date_maturity <= time.strftime('%Y-%m-%d')):
                dias_vencimiento = False
        return (credit - debit), dias_vencimiento

    def get_partner_contado(self, cr, uid, ids, context):
        so = self.browse(cr, uid, ids[0], context)
        partner = so.partner_id
        contado = False
        payment_term = str(so.payment_term.name).lower()
        if payment_term.find('contado') >= 0:
            contado = True
        return contado


    def check_limit(self, cr, uid, ids, context={}):
        so = self.browse(cr, uid, ids[0], context)
        partner = so.partner_id
        if len([x for x in so.order_line if x.product_id.type=='product']) > 1:
            raise osv.except_osv(_("Error !"), _("Only sale orders with one line can be preaproved !"))
        if partner.over_credit:
            return True

        contado = self.get_partner_contado(cr, uid, ids, context)
        saldo, dias_vencimiento = self.get_saldo_credit_limit(cr, uid, ids, context)
        if contado:
            if (saldo + so.amount_total) <= 0:
                return True
            else:
                raise osv.except_osv(_("Credit Over Limits !"), _("No se puede confirmar la Venta! \n '(Total facturas con saldo pendiente - Total de pagos no aplicados + Total pedido a autorizar)' No es <= 0.0 \n  %s <= 0.0  !"%(saldo + so.amount_total) ))
        else:
            if not dias_vencimiento:
                raise osv.except_osv(_("Credit Over Limits !"), _("No se puede confirmar la Venta! \n 'Los dias del Vencimiento de La Factura no es <= Días de Plazo de Pago !"))

            if not ((saldo + so.amount_total) <= partner.credit_limit):
                raise osv.except_osv(_("Credit Over Limits !"), _("No se puede confirmar la Venta! \n ' (Total facturas con saldo pendiente - Total de pagos no aplicados + Total pedido a autorizar) NO es <= Limite de Credito \n %s <= %s !"%(saldo + so.amount_total, partner.credit_limit) ))

        return True

sale_order()

class sale_order_line(osv.osv):
    _inherit = "sale.order.line"

    def get_obj(self, cr, uid, model, external_id):
        # Return id from Model and External ID
        obj_id = False
        try:
            external_id = external_id.split('.')[1]
        except:
            osv.except_osv(_('Warning!'), _('Such External ID does not Exist!'))
        model_data_pool = self.pool.get('ir.model.data')
        ir_model_data_id = model_data_pool.search(cr, uid, [('model', '=', model), ('name', '=', external_id)])
        if ir_model_data_id:
            ir_model_data_obj = model_data_pool.browse(cr, uid, ir_model_data_id)[0]
            obj = self.pool.get(model).browse(cr, uid, ir_model_data_obj.res_id)
            obj_id = obj and obj.id
        else:
            osv.except_osv(_('Warning!'), _('Such External ID does not Exist!'))
        return obj_id

    def product_id_change(self, cr, uid, ids, pricelist, product, qty=0,
            uom=False, qty_uos=0, uos=False, name='', partner_id=False,
            lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
        group_id = self.get_obj(cr, uid, 'res.groups', 'base.group_sale_price_modificator')
        users = [x.id for x in self.pool.get('res.groups').browse(cr, uid, group_id).users]
        if not uid in users:
            return {}        
        res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty,
            uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,
            lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag)
        return res

sale_order_line()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: