[FIX] in POS, rename all 'Product for expenses' into 'Product for Output'
[odoo/odoo.git] / addons / point_of_sale / point_of_sale.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
25
26 import netsvc
27 from osv import fields, osv
28 from tools.translate import _
29 from decimal import Decimal
30 import decimal_precision as dp
31
32 class pos_config_journal(osv.osv):
33     """ Point of Sale journal configuration"""
34     _name = 'pos.config.journal'
35     _description = "Journal Configuration"
36
37     _columns = {
38         'name': fields.char('Description', size=64),
39         'code': fields.char('Code', size=64),
40         'journal_id': fields.many2one('account.journal', "Journal")
41     }
42
43 pos_config_journal()
44
45
46 class pos_company_discount(osv.osv):
47     """ Company Discount and Cashboxes """
48     _inherit = 'res.company'
49
50     _columns = {
51         'company_discount': fields.float('Max Discount(%)', digits_compute=dp.get_precision('Point Of Sale')),
52         'max_diff': fields.float('Max Difference for Cashboxes', digits_compute=dp.get_precision('Point Of Sale Discount')),
53     }
54
55 pos_company_discount()
56
57 class pos_order(osv.osv):
58     """ Point of sale gives business owners a convenient way of checking out customers
59         and of recording sales """
60
61     _name = "pos.order"
62     _description = "Point of Sale"
63     _order = "date_order, create_date desc"
64
65     def unlink(self, cr, uid, ids, context=None):
66         for rec in self.browse(cr, uid, ids, context=context):
67             for rec_statement in rec.statement_ids:
68                 if (rec_statement.statement_id and rec_statement.statement_id.state == 'confirm') or rec.state == 'done':
69                     raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
70         return super(pos_order, self).unlink(cr, uid, ids, context=context)
71
72     def onchange_partner_pricelist(self, cr, uid, ids, part=False, context=None):
73
74         """ Changed price list on_change of partner_id"""
75         if not part:
76             return {'value': {}}
77         pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
78         return {'value': {'pricelist_id': pricelist}}
79
80     def _amount_total(self, cr, uid, ids, field_name, arg, context=None):
81         """ Calculates amount_tax of order line
82         @param field_names: Names of fields.
83         @return: Dictionary of values """
84         cr.execute("""
85             SELECT
86                 p.id,
87                 COALESCE(SUM(
88                     l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
89                     ) AS amount
90             FROM pos_order p
91             LEFT OUTER JOIN pos_order_line l ON (p.id = l.order_id)
92             WHERE p.id IN %s GROUP BY p.id """,(tuple(ids),))
93         res = dict(cr.fetchall())
94         for rec in self.browse(cr, uid, ids, context=context):
95             if rec.partner_id \
96                and rec.partner_id.property_account_position \
97                and rec.partner_id.property_account_position.tax_ids:
98                 res[rec.id] = res[rec.id] - rec.amount_tax
99             else :
100                 res[rec.id] = res[rec.id] + rec.amount_tax
101         return res
102
103     def _get_date_payment2(self, cr, uid, ids, context=None, *a):
104         # Todo need to check this function
105         """ Find payment Date
106         @param field_names: Names of fields.
107         @return: Dictionary of values """
108         res = {}
109         val = None
110         for order in self.browse(cr, uid, ids, context=context):
111             cr.execute("SELECT date_payment FROM pos_order WHERE id = %s", (order.id,))
112             date_p = cr.fetchone()
113             date_p = date_p and date_p[0] or None
114             if date_p:
115                 res[order.id] = date_p
116                 return res
117             cr.execute(" SELECT MAX(l.date) "
118                         " FROM account_move_line l, account_move m, account_invoice i, account_move_reconcile r, pos_order o "
119                         " WHERE i.move_id = m.id AND l.move_id = m.id AND l.reconcile_id = r.id AND o.id = %s AND o.invoice_id = i.id",
120                         (order.id,))
121             val = cr.fetchone()
122             val = val and val[0] or None
123             if val:
124                 res[order.id] = val
125         return res
126
127     def _get_date_payment(self, cr, uid, ids, context, *a):
128         """ Find  Validation Date
129         @return: Dictionary of values """
130         res = {}
131         val = None
132         for order in self.browse(cr, uid, ids):
133             cr.execute("SELECT date_validation FROM pos_order WHERE id = %s", (order.id,))
134             date_p = cr.fetchone()
135             date_p = date_p and date_p[0] or None
136             if date_p:
137                 res[order.id] = date_p
138                 return res
139             discount_allowed = order.company_id.company_discount
140             for line in order.lines:
141                 if line.discount > discount_allowed:
142                     return {order.id: None }
143             if order.amount_paid == order.amount_total and not date_p:
144                 cr.execute("SELECT MAX(date) FROM account_bank_statement_line WHERE pos_statement_id = %s", (order.id,))
145                 val = cr.fetchone()
146                 val = val and val[0] or None
147             if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
148                 for o in order.invoice_id.move_id.line_id:
149                     if o.balance == 0:
150                         if val < o.date_created:
151                             val = o.date_created
152             if val:
153                 res[order.id] = val
154         return res
155
156     def _amount_all(self, cr, uid, ids, name, args, context=None):
157         tax_obj = self.pool.get('account.tax')
158         cur_obj = self.pool.get('res.currency')
159         res = {}
160         for order in self.browse(cr, uid, ids, context=context):
161             res[order.id] = {
162                 'amount_paid': 0.0,
163                 'amount_return':0.0,
164                 'amount_tax':0.0,
165             }
166             val = val1 = 0.0
167             cur = order.pricelist_id.currency_id
168             for payment in order.statement_ids:
169                 res[order.id]['amount_paid'] +=  payment.amount
170                 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
171             for line in order.lines:
172                 val1 += line.price_subtotal_incl
173                 if order.price_type != 'tax_excluded':
174                     res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
175                         tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
176                             line.price_unit * \
177                             (1-(line.discount or 0.0)/100.0), line.qty),
178                             res[order.id]['amount_tax'])
179                 elif line.qty != 0.0:
180                     for c in tax_obj.compute_all(cr, uid, line.product_id.taxes_id, \
181                                                  line.price_unit * (1-(line.discount or 0.0)/100.0), \
182                                                  line.qty,  line.product_id, line.order_id.partner_id)['taxes']:
183                         val += c.get('amount', 0.0)
184             res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
185             res[order.id]['amount_total'] = res[order.id]['amount_tax'] + cur_obj.round(cr, uid, cur, val1)
186         return res
187
188     def _sale_journal_get(self, cr, uid, context=None):
189         """ To get  sale journal for this order
190         @return: journal  """
191         journal_obj = self.pool.get('account.journal')
192         res = journal_obj.search(cr, uid, [('type', '=', 'sale')], limit=1)
193         return res and res[0] or False
194
195     def _shop_get(self, cr, uid, context=None):
196         """ To get  Shop  for this order
197         @return: Shop id  """
198         res = self.pool.get('sale.shop').search(cr, uid, [])
199         return res and res[0] or False
200
201     def copy(self, cr, uid, id, default=None, context=None):
202         if not default:
203             default = {}
204         default.update({
205             'state': 'draft',
206             'partner_id': False,
207             'invoice_id': False,
208             'account_move': False,
209             'picking_id': False,
210             'statement_ids': [],
211             'nb_print': 0,
212             'pickings': []
213         })
214         return super(pos_order, self).copy(cr, uid, id, default, context=context)
215
216     def _get_v( self, cr, uid, ids, *args):
217         """ Changed the Validation state of order
218         @return: State  """
219         res_obj = self.pool.get('res.users')
220         company_disc = self.browse(cr, uid, ids)
221         list_jrnl = []
222         r = {}
223         if not company_disc:
224             comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
225         else:
226             comp = company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
227         cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount <= %s", (ids[0], comp))
228         res = cr.fetchone()
229         cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount > %s", (ids[0], comp))
230         res2 = cr.fetchone()
231         cr.execute("SELECT journal_id FROM account_bank_statement_line WHERE pos_statement_id = %s ", (ids[0], ))
232         res3 = cr.fetchall()
233         for r in res3:
234             cr.execute("SELECT id FROM account_journal WHERE name = '%s' AND special_journal = 't'", (r[0], ))
235             res3 = cr.fetchone()
236             is_special = res3 and res3[0] or None
237             if is_special:
238                 list_jrnl.append(is_special)
239         for order in self.browse(cr, uid, ids):
240             if order.state in ('paid', 'done', 'invoiced') and res and not res2 and not len(list_jrnl):
241                 r[order.id] = 'accepted'
242         return r
243
244     _columns = {
245         'name': fields.char('Order Description', size=64, required=True,
246             states={'draft': [('readonly', False)]}, readonly=True),
247         'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
248         'num_sale': fields.char('Internal Note', size=64),
249         'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
250             states={'draft': [('readonly', False)]}, readonly=True),
251         'date_order': fields.datetime('Date Ordered', readonly=True, select=True),
252         'date_validation': fields.function(_get_date_payment,
253                                            method=True,
254                                            string='Validation Date',
255                                            type='date', select=True, store=True),
256         'date_payment': fields.function(_get_date_payment2, method=True,
257                                         string='Payment Date',
258                                         type='date', select=True, store=True),
259         'date_validity': fields.date('Validity Date', required=True),
260         'user_id': fields.many2one('res.users', 'Connected Salesman', help="Person who uses the the cash register. It could be a reliever, a student or an interim employee."),
261         'user_salesman_id': fields.many2one('res.users', 'Cashier', required=True, help="User who is logged into the system."),
262         'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
263         'amount_tax': fields.function(_amount_all, method=True, string='Taxes', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
264         'amount_total': fields.function(_amount_all, method=True, string='Total', multi='all'),
265         'amount_paid': fields.function(_amount_all, string='Paid', states={'draft': [('readonly', False)]}, readonly=True, method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
266         'amount_return': fields.function(_amount_all, 'Returned', method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
267         'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
268         'price_type': fields.selection([
269                                 ('tax_excluded','Tax excluded')],
270                                  'Price Method', required=True),
271         'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
272         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
273         'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
274         'state': fields.selection([('draft', 'Quotation'),
275                                    ('payment', 'Payment'),
276                                    ('advance','Advance'),
277                                    ('paid', 'Paid'),
278                                    ('done', 'Done'),
279                                    ('invoiced', 'Invoiced'),
280                                    ('cancel', 'Cancel')],
281                                   'State', readonly=True),
282         'invoice_id': fields.many2one('account.invoice', 'Invoice'),
283         'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
284         'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
285         'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
286         'first_name': fields.char('First Name', size=64),
287         'note': fields.text('Internal Notes'),
288         'nb_print': fields.integer('Number of Print', readonly=True),
289         'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True),
290         'invoice_wanted': fields.boolean('Create Invoice'),
291         'note_2': fields.char('Customer Note', size=64),
292         'type_rec': fields.char('Type of Receipt', size=64),
293         'remboursed': fields.boolean('Remboursed'),
294         'contract_number': fields.char('Contract Number', size=512, select=1),
295         'journal_entry': fields.boolean('Journal Entry'),
296     }
297
298     def _select_pricelist(self, cr, uid, context=None):
299         """ To get default pricelist for the order
300         @param name: Names of fields.
301         @return: pricelist ID
302         """
303         res = self.pool.get('sale.shop').search(cr, uid, [], context=context)
304         if res:
305             shop = self.pool.get('sale.shop').browse(cr, uid, res[0], context=context)
306             return shop.pricelist_id and shop.pricelist_id.id or False
307         return False
308
309     def _journal_default(self, cr, uid, context=None):
310         """ To get default pricelist for the order
311         @param name: Names of fields.
312         @return: journal ID
313         """
314         journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
315         return journal_list and journal_list[0] or False
316
317     _defaults = {
318         'user_salesman_id':lambda self, cr, uid, context: uid,
319         'user_id': lambda self, cr, uid, context: uid,
320         'sale_manager': lambda self, cr, uid, context: uid,
321         'state': 'draft',
322         'price_type': 'tax_excluded',
323         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
324         'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
325         'date_validity': lambda *a: (datetime.today() + relativedelta(months=+6)).strftime('%Y-%m-%d'),
326         'nb_print': 0,
327         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
328         'sale_journal': _sale_journal_get,
329         'invoice_wanted': False,
330         'shop_id': _shop_get,
331         'pricelist_id': _select_pricelist,
332     }
333
334
335     def test_order_lines(self, cr, uid, order, context=None):
336         """ Test order line is created or not for the order
337         @param name: Names of fields.
338         @return: True
339         """
340         if not order.lines:
341             raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
342
343         wf_service = netsvc.LocalService("workflow")
344         wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
345         return True
346
347     def dummy_button(self, cr, uid, order, context=None):
348         return True
349
350     def test_paid(self, cr, uid, ids, context=None):
351         """ Test all amount is paid for this order
352         @return: True
353         """
354         for order in self.browse(cr, uid, ids, context=context):
355             if order.lines and not order.amount_total:
356                 return True
357             if (not order.lines) or (not order.statement_ids) or \
358                 Decimal(str(order.amount_total)) != Decimal(str(order.amount_paid)):
359                 return False
360         return True
361
362     def _get_qty_differences(self, orders, old_picking):
363         """check if the customer changed the product quantity """
364         order_dict = {}
365         for order in orders:
366             for line in order.lines:
367                 order_dict[line.product_id.id] = line
368
369         # check the quantity differences:
370         diff_dict = {}
371         for line in old_picking.move_lines:
372             order_line = order_dict.get(line.product_id.id)
373             if not order_line:
374                 deleted = True
375                 qty_to_delete_from_original_picking = line.product_qty
376                 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
377             elif line.product_qty != order_line.qty:
378                 deleted = False
379                 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
380                 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
381
382         return diff_dict
383
384     def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
385         """if the customer changes the product quantity, split the picking in two"""
386         # create a copy of the original picking and adjust the product qty:
387         picking_model = self.pool.get('stock.picking')
388         defaults = {
389             'note': "Partial picking from customer", # add a note to tell why we create a new picking
390             'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
391         }
392
393         new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
394         new_picking = picking_model.browse(cr, uid, new_picking_id, context=context)
395
396         for line in new_picking.move_lines:
397             p_id = line.product_id.id
398             if p_id in diff_dict:
399                 diff = diff_dict[p_id]
400                 deleted = diff[0]
401                 qty_to_del = diff[1]
402                 if deleted: # product has been deleted (customer didn't took it):
403                     # delete this product from old picking:
404                     for old_line in old_picking.move_lines:
405                         if old_line.product_id.id == p_id:
406                             old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
407                             old_line.unlink(context=context)
408                 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
409                     # subtract qty from old picking:
410                     for old_line in old_picking.move_lines:
411                         if old_line.product_id.id == p_id:
412                             old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
413                     # add qty to new picking:
414                     line.write({'product_qty': qty_to_del}, context=context)
415                 else: # product hasn't changed (customer took it without any change):
416                     # delete this product from new picking:
417                     line.unlink(context=context)
418             else:
419                 # delete it in the new picking:
420                 line.unlink(context=context)
421
422     def create_picking(self, cr, uid, ids, context=None):
423         """Create a picking for each order and validate it."""
424         picking_obj = self.pool.get('stock.picking')
425         property_obj = self.pool.get("ir.property")
426         move_obj = self.pool.get('stock.move')
427         pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
428         orders = self.browse(cr, uid, ids, context=context)
429         partner_obj = self.pool.get('res.partner')
430         for order in orders:
431             addr = order.partner_id and partner_obj.address_get(cr, uid, [order.partner_id.id], ['delivery']) or {}
432             if not order.picking_id:
433                 new = True
434                 picking_id = picking_obj.create(cr, uid, {
435                     'name': pick_name,
436                     'origin': order.name,
437                     'address_id': addr.get('delivery',False),
438                     'type': 'out',
439                     'state': 'draft',
440                     'move_type': 'direct',
441                     'note': 'POS notes ' + (order.note or ""),
442                     'invoice_state': 'none',
443                     'auto_picking': True,
444                     'pos_order': order.id,
445                 }, context=context)
446                 self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
447             else:
448                 picking_id = order.picking_id.id
449                 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True}, context=context)
450                 picking = picking_obj.browse(cr, uid, [picking_id], context=context)[0]
451                 new = False
452
453                 # split the picking (if product quantity has changed):
454                 diff_dict = self._get_qty_differences(orders, picking)
455                 if diff_dict:
456                     self._split_picking(cr, uid, ids, context, picking, diff_dict)
457
458             if new:
459                 for line in order.lines:
460                     if line.product_id and line.product_id.type == 'service':
461                         continue
462                     prop_ids = property_obj.search(cr, uid, [('name', '=', 'property_stock_customer')], context=context)
463                     val = property_obj.browse(cr, uid, prop_ids[0], context=context).value_reference
464                     cr.execute("SELECT s.id FROM stock_location s, stock_warehouse w WHERE w.lot_stock_id = s.id AND w.id = %s", (order.shop_id.warehouse_id.id, ))
465                     res = cr.fetchone()
466                     location_id = res and res[0] or None
467                     stock_dest_id = val.id
468                     if line.qty < 0:
469                         location_id, stock_dest_id = stock_dest_id, location_id
470                     move_obj.create(cr, uid, {
471                             'name': '(POS %d)' % (order.id, ),
472                             'product_uom': line.product_id.uom_id.id,
473                             'product_uos': line.product_id.uom_id.id,
474                             'picking_id': picking_id,
475                             'product_id': line.product_id.id,
476                             'product_uos_qty': abs(line.qty),
477                             'product_qty': abs(line.qty),
478                             'tracking_id': False,
479                             'pos_line_id': line.id,
480                             'state': 'waiting',
481                             'location_id': location_id,
482                             'location_dest_id': stock_dest_id,
483                             'prodlot_id': line.prodlot_id and line.prodlot_id.id or False
484                         }, context=context)
485
486             wf_service = netsvc.LocalService("workflow")
487             wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
488             picking_obj.force_assign(cr, uid, [picking_id], context)
489         return True
490
491     def set_to_draft(self, cr, uid, ids, *args):
492         """ Changes order state to draft
493         @return: True
494         """
495         if not len(ids):
496             return False
497         self.write(cr, uid, ids, {'state': 'draft'})
498         wf_service = netsvc.LocalService("workflow")
499         for i in ids:
500             wf_service.trg_create(uid, 'pos.order', i, cr)
501         return True
502
503     def button_invalidate(self, cr, uid, ids, *args):
504         """ Check the access for the sale order
505         @return: True
506         """
507         res_obj = self.pool.get('res.company')
508         try:
509             part_company = res_obj.browse(cr, uid, uid) and res_obj.browse(cr, uid, uid).parent_id and res_obj.browse(cr, uid, uid).parent_id.id or None
510         except Exception:
511             raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
512         if part_company:
513             raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
514         return True
515
516     def cancel_order(self, cr, uid, ids, context=None):
517         """ Changes order state to cancel
518         @return: True
519         """
520         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
521         self.cancel_picking(cr, uid, ids, context=context)
522         return True
523
524     def add_payment(self, cr, uid, order_id, data, context=None):
525         """Create a new payment for the order"""
526         statement_obj = self.pool.get('account.bank.statement')
527         statement_line_obj = self.pool.get('account.bank.statement.line')
528         prod_obj = self.pool.get('product.product')
529         property_obj = self.pool.get('ir.property')
530         curr_c = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
531         curr_company = curr_c.id
532         order = self.browse(cr, uid, order_id, context=context)
533         if not order.num_sale and data['num_sale']:
534             self.write(cr, uid, order_id, {'num_sale': data['num_sale']}, context=context)
535         ids_new = []
536         args = {
537             'amount': data['amount'],
538         }
539         if 'payment_date' in data.keys():
540             args['date'] = data['payment_date']
541         if 'payment_name' in data.keys():
542             args['name'] = data['payment_name'] + ' ' + order.name
543         account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
544         args['account_id'] = order.partner_id and order.partner_id.property_account_receivable \
545                              and order.partner_id.property_account_receivable.id or account_def.id or curr_c.account_receivable.id
546         if data.get('is_acc', False):
547             args['is_acc'] = data['is_acc']
548             args['account_id'] = prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income \
549                                  and prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income.id
550             if not args['account_id']:
551                 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')% \
552                                      (prod_obj.browse(cr, uid, data['product_id'], context=context).name))
553         args['partner_id'] = order.partner_id and order.partner_id.id or None
554         args['ref'] = order.contract_number or None
555
556         statement_id = statement_obj.search(cr,uid, [
557                                                      ('journal_id', '=', data['journal']),
558                                                      ('company_id', '=', curr_company),
559                                                      ('user_id', '=', uid),
560                                                      ('state', '=', 'open')], context=context)
561         if len(statement_id) == 0:
562             raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
563         if statement_id:
564             statement_id = statement_id[0]
565         args['statement_id'] = statement_id
566         args['pos_statement_id'] = order_id
567         args['journal_id'] = data['journal']
568         args['type'] = 'customer'
569         args['ref'] = order.name
570         statement_line_obj.create(cr, uid, args, context=context)
571         ids_new.append(statement_id)
572
573         wf_service = netsvc.LocalService("workflow")
574         wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
575         wf_service.trg_write(uid, 'pos.order', order_id, cr)
576
577         return statement_id
578
579     def add_product(self, cr, uid, order_id, product_id, qty, context=None):
580
581         """Create a new order line the order"""
582
583         line_obj = self.pool.get('pos.order.line')
584         values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
585
586         pricelist = values['pricelist_id'] and values['pricelist_id'][0]
587         product = values['partner_id'] and values['partner_id'][0]
588
589         price = line_obj.price_by_product(cr, uid, [],
590                 pricelist, product_id, qty, product)
591
592         order_line_id = line_obj.create(cr, uid, {
593             'order_id': order_id,
594             'product_id': product_id,
595             'qty': qty,
596             'price_unit': price,
597         }, context=context)
598         return order_line_id, price
599
600     def refund(self, cr, uid, ids, context=None):
601
602         """Create a copy of order  for refund order"""
603
604         clone_list = []
605         line_obj = self.pool.get('pos.order.line')
606
607         for order in self.browse(cr, uid, ids, context=context):
608             clone_id = self.copy(cr, uid, order.id, {
609                 'name': order.name + ' REFUND',
610                 'date_order': time.strftime('%Y-%m-%d'),
611                 'state': 'draft',
612                 'note': 'REFUND\n'+ (order.note or ''),
613                 'invoice_id': False,
614                 'nb_print': 0,
615                 'statement_ids': False,
616                 }, context=context)
617             clone_list.append(clone_id)
618
619
620         for clone in self.browse(cr, uid, clone_list, context=context):
621             for order_line in clone.lines:
622                 line_obj.write(cr, uid, [order_line.id], {
623                     'qty': -order_line.qty
624                     }, context=context)
625         return clone_list
626
627     def action_invoice(self, cr, uid, ids, context=None):
628
629         """Create a invoice of order  """
630
631         inv_ref = self.pool.get('account.invoice')
632         inv_line_ref = self.pool.get('account.invoice.line')
633         product_obj = self.pool.get('product.product')
634         inv_ids = []
635
636         for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
637             if order.invoice_id:
638                 inv_ids.append(order.invoice_id.id)
639                 continue
640
641             if not order.partner_id:
642                 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
643
644             acc = order.partner_id.property_account_receivable.id
645             inv = {
646                 'name': 'Invoice from POS: '+order.name,
647                 'origin': order.name,
648                 'account_id': acc,
649                 'journal_id': order.sale_journal.id or None,
650                 'type': 'out_invoice',
651                 'reference': order.name,
652                 'partner_id': order.partner_id.id,
653                 'comment': order.note or '',
654                 'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
655             }
656             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
657             if not inv.get('account_id', None):
658                 inv['account_id'] = acc
659             inv_id = inv_ref.create(cr, uid, inv, context=context)
660
661             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
662             inv_ids.append(inv_id)
663             for line in order.lines:
664                 inv_line = {
665                     'invoice_id': inv_id,
666                     'product_id': line.product_id.id,
667                     'quantity': line.qty,
668                 }
669                 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
670
671                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
672                                                                line.product_id.id,
673                                                                line.product_id.uom_id.id,
674                                                                line.qty, partner_id = order.partner_id.id,
675                                                                fposition_id=order.partner_id.property_account_position.id)['value'])
676                 inv_line['price_unit'] = line.price_unit
677                 inv_line['discount'] = line.discount
678                 inv_line['name'] = inv_name
679                 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
680                     and [(6, 0, inv_line['invoice_line_tax_id'])] or []
681                 inv_line_ref.create(cr, uid, inv_line, context=context)
682
683         for i in inv_ids:
684             wf_service = netsvc.LocalService("workflow")
685             wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
686         return inv_ids
687
688     def create_account_move(self, cr, uid, ids, context=None):
689         """Create a account move line of order  """
690         account_move_obj = self.pool.get('account.move')
691         account_move_line_obj = self.pool.get('account.move.line')
692         account_period_obj = self.pool.get('account.period')
693         account_tax_obj = self.pool.get('account.tax')
694         res_obj=self.pool.get('res.users')
695         property_obj=self.pool.get('ir.property')
696         period = account_period_obj.find(cr, uid, context=context)[0]
697
698         for order in self.browse(cr, uid, ids, context=context):
699             curr_c = res_obj.browse(cr, uid, uid).company_id
700             comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
701             comp_id = comp_id and comp_id.id or False
702             to_reconcile = []
703             group_tax = {}
704             account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
705
706             order_account = order.partner_id and order.partner_id.property_account_receivable and order.partner_id.property_account_receivable.id or account_def or curr_c.account_receivable.id
707
708             # Create an entry for the sale
709             move_id = account_move_obj.create(cr, uid, {
710                 'journal_id': order.sale_journal.id,
711                 'period_id': period,
712                 }, context=context)
713
714             # Create an move for each order line
715             for line in order.lines:
716                 tax_amount = 0
717                 taxes = [t for t in line.product_id.taxes_id]
718                 if order.price_type == 'tax_excluded':
719                     computed_taxes = account_tax_obj.compute_all(
720                         cr, uid, taxes, line.price_unit, line.qty)['taxes']
721                 else:
722                     computed_taxes = account_tax_obj.compute_inv(
723                         cr, uid, taxes, line.price_unit, line.qty)
724
725                 for tax in computed_taxes:
726                     tax_amount += round(tax['amount'], 2)
727                     group_key = (tax['tax_code_id'],
728                                 tax['base_code_id'],
729                                 tax['account_collected_id'])
730
731                     if group_key in group_tax:
732                         group_tax[group_key] += round(tax['amount'], 2)
733                     else:
734                         group_tax[group_key] = round(tax['amount'], 2)
735                 if order.price_type != 'tax_excluded':
736                     amount = line.price_subtotal - tax_amount
737                 else:
738                     amount = line.price_subtotal
739
740                 # Search for the income account
741                 if  line.product_id.property_account_income.id:
742                     income_account = line.\
743                                     product_id.property_account_income.id
744                 elif line.product_id.categ_id.\
745                         property_account_income_categ.id:
746                     income_account = line.product_id.categ_id.\
747                                     property_account_income_categ.id
748                 else:
749                     raise osv.except_osv(_('Error !'), _('There is no income '\
750                         'account defined for this product: "%s" (id:%d)') \
751                         % (line.product_id.name, line.product_id.id, ))
752
753                 # Empty the tax list as long as there is no tax code:
754                 tax_code_id = False
755                 tax_amount = 0
756                 while computed_taxes:
757                     tax = computed_taxes.pop(0)
758                     if amount > 0:
759                         tax_code_id = tax['base_code_id']
760                         tax_amount = line.price_subtotal * tax['base_sign']
761                     else:
762                         tax_code_id = tax['ref_base_code_id']
763                         tax_amount = line.price_subtotal * tax['ref_base_sign']
764                     # If there is one we stop
765                     if tax_code_id:
766                         break
767
768                 # Create a move for the line
769                 account_move_line_obj.create(cr, uid, {
770                     'name': "aa"+order.name,
771                     'date': order.date_order[:10],
772                     'ref': order.contract_number or order.name,
773                     'quantity': line.qty,
774                     'product_id': line.product_id.id,
775                     'move_id': move_id,
776                     'account_id': income_account,
777                     'company_id': comp_id,
778                     'credit': ((amount>0) and amount) or 0.0,
779                     'debit': ((amount<0) and -amount) or 0.0,
780                     'journal_id': order.sale_journal.id,
781                     'period_id': period,
782                     'tax_code_id': tax_code_id,
783                     'tax_amount': tax_amount,
784                     'partner_id': order.partner_id and order.partner_id.id or False
785                 }, context=context)
786
787                 # For each remaining tax with a code, whe create a move line
788                 for tax in computed_taxes:
789                     if amount > 0:
790                         tax_code_id = tax['base_code_id']
791                         tax_amount = line.price_subtotal * tax['base_sign']
792                     else:
793                         tax_code_id = tax['ref_base_code_id']
794                         tax_amount = line.price_subtotal * tax['ref_base_sign']
795                     if not tax_code_id:
796                         continue
797
798                     account_move_line_obj.create(cr, uid, {
799                         'name': "bb" + order.name,
800                         'date': order.date_order[:10],
801                         'ref': order.contract_number or order.name,
802                         'product_id':line.product_id.id,
803                         'quantity': line.qty,
804                         'move_id': move_id,
805                         'account_id': income_account,
806                         'company_id': comp_id,
807                         'credit': 0.0,
808                         'debit': 0.0,
809                         'journal_id': order.sale_journal.id,
810                         'period_id': period,
811                         'tax_code_id': tax_code_id,
812                         'tax_amount': tax_amount,
813                     }, context=context)
814
815
816             # Create a move for each tax group
817             (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
818             for key, amount in group_tax.items():
819                 account_move_line_obj.create(cr, uid, {
820                     'name': "cc" + order.name,
821                     'date': order.date_order[:10],
822                     'ref': order.contract_number or order.name,
823                     'move_id': move_id,
824                     'company_id': comp_id,
825                     'quantity': line.qty,
826                     'product_id': line.product_id.id,
827                     'account_id': key[account_pos],
828                     'credit': ((amount>0) and amount) or 0.0,
829                     'debit': ((amount<0) and -amount) or 0.0,
830                     'journal_id': order.sale_journal.id,
831                     'period_id': period,
832                     'tax_code_id': key[tax_code_pos],
833                     'tax_amount': amount,
834                 }, context=context)
835
836             # counterpart
837             to_reconcile.append(account_move_line_obj.create(cr, uid, {
838                 'name': "dd" + order.name,
839                 'date': order.date_order[:10],
840                 'ref': order.contract_number or order.name,
841                 'move_id': move_id,
842                 'company_id': comp_id,
843                 'account_id': order_account,
844                 'credit': ((order.amount_total < 0) and -order.amount_total)\
845                     or 0.0,
846                 'debit': ((order.amount_total > 0) and order.amount_total)\
847                     or 0.0,
848                 'journal_id': order.sale_journal.id,
849                 'period_id': period,
850                 'partner_id': order.partner_id and order.partner_id.id or False
851             }, context=context))
852
853
854             # search the account receivable for the payments:
855             account_receivable = order.sale_journal.default_credit_account_id.id
856             if not account_receivable:
857                 raise  osv.except_osv(_('Error !'),
858                     _('There is no receivable account defined for this journal:'\
859                     ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
860             for payment in order.statement_ids:
861                 # Create one entry for the payment
862                 if payment.is_acc:
863                     continue
864                 account_move_obj.create(cr, uid, {
865                     'journal_id': payment.statement_id.journal_id.id,
866                     'period_id': period,
867                 }, context=context)
868
869             for stat_l in order.statement_ids:
870                 if stat_l.is_acc and len(stat_l.move_ids):
871                     for st in stat_l.move_ids:
872                         for s in st.line_id:
873                             if s.credit:
874                                 account_move_line_obj.copy(cr, uid, s.id, {
875                                                         'debit': s.credit,
876                                                         'statement_id': False,
877                                                         'credit': s.debit
878                                                     })
879                                 account_move_line_obj.copy(cr, uid, s.id, {
880                                                         'statement_id': False,
881                                                         'account_id': order_account
882                                                      })
883
884             self.write(cr, uid, order.id, {'state':'done'}, context=context)
885         return True
886
887     def cancel_picking(self, cr, uid, ids, context=None):
888         stock_picking_obj = self.pool.get('stock.picking')
889         for order in self.browse(cr, uid, ids, context=context):
890             for picking in order.pickings:
891                 stock_picking_obj.unlink(cr, uid, [picking.id], context=context)
892         return True
893
894
895     def action_payment(self, cr, uid, ids, context=None):
896         vals = {'state': 'payment'}
897         sequence_obj = self.pool.get('ir.sequence')
898         for pos in self.browse(cr, uid, ids, context=context):
899             create_contract_nb = False
900             for line in pos.lines:
901                 if line.product_id.product_type == 'MD':
902                     create_contract_nb = True
903                     break
904             if create_contract_nb:
905                 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
906                 vals['contract_number'] = '%s-%s' % (pos.user_salesman_id.login, seq)
907         self.write(cr, uid, ids, vals, context=context)
908
909     def action_paid(self, cr, uid, ids, context=None):
910         if context is None:
911             context = {}
912         if context.get('flag', False):
913             self.create_picking(cr, uid, ids, context=None)
914             self.write(cr, uid, ids, {'state': 'paid'}, context=context)
915         else:
916             context['flag'] = True
917         return True
918
919     def action_cancel(self, cr, uid, ids, context=None):
920         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
921         return True
922
923     def action_done(self, cr, uid, ids, context=None):
924         for order in self.browse(cr, uid, ids, context=context):
925             if not order.journal_entry:
926                 self.create_account_move(cr, uid, ids, context=None)
927         return True
928
929     def compute_state(self, cr, uid, id):
930         cr.execute("SELECT act.id, act.name FROM wkf_activity act "
931                    "INNER JOIN wkf_workitem item ON act.id = item.act_id "
932                    "INNER JOIN wkf_instance inst ON item.inst_id = inst.id "
933                    "INNER JOIN wkf ON inst.wkf_id = wkf.id "
934                    "WHERE wkf.osv = 'pos.order' AND inst.res_id = %s "
935                    "ORDER BY act.name", (id, ))
936         return [name for id, name in cr.fetchall()]
937
938 pos_order()
939
940 class account_bank_statement(osv.osv):
941     _inherit = 'account.bank.statement'
942     _columns= {
943         'user_id': fields.many2one('res.users', ondelete='cascade', string='User', readonly=True),
944     }
945     _defaults = {
946         'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
947     }
948 account_bank_statement()
949
950 class account_bank_statement_line(osv.osv):
951     _inherit = 'account.bank.statement.line'
952     def _get_statement_journal(self, cr, uid, ids, context, *a):
953         res = {}
954         for line in self.browse(cr, uid, ids):
955             res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
956         return res
957     _columns= {
958         'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
959         'am_out': fields.boolean("To count"),
960         'is_acc': fields.boolean("Is accompte"),
961         'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
962     }
963 account_bank_statement_line()
964
965 class pos_order_line(osv.osv):
966     _name = "pos.order.line"
967     _description = "Lines of Point of Sale"
968
969     def _get_amount(self, cr, uid, ids, field_name, arg, context=None):
970         res = {}
971         for line in self.browse(cr, uid, ids, context=context):
972             price = self.price_by_product(cr, uid, ids, line.order_id.pricelist_id.id, line.product_id.id, line.qty, line.order_id.partner_id.id)
973             res[line.id] = price
974         return res
975
976     def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context=None):
977         res = dict.fromkeys(ids, 0.0)
978         account_tax_obj = self.pool.get('account.tax')
979         self.price_by_product_multi(cr, uid, ids)
980         for line in self.browse(cr, uid, ids, context=context):
981             tax_amount = 0.0
982             taxes = [t for t in line.product_id.taxes_id]
983             if line.qty == 0.0:
984                 continue
985             computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
986             for tax in computed_taxes:
987                 tax_amount += tax['amount']
988             if line.discount != 0.0:
989                 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
990             else:
991                 res[line.id] = line.price_unit*line.qty
992             res[line.id] = res[line.id] + tax_amount
993         return res
994
995     def _amount_line(self, cr, uid, ids, field_name, arg, context=None):
996         res = {}
997         self.price_by_product_multi(cr, uid, ids)
998         for line in self.browse(cr, uid, ids, context=context):
999             if line.discount!=0.0:
1000                 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1001             else:
1002                 res[line.id] = line.price_unit * line.qty
1003         return res
1004
1005     def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
1006         res = dict([(i, {}) for i in ids])
1007         account_tax_obj = self.pool.get('account.tax')
1008
1009         self.price_by_product_multi(cr, uid, ids)
1010         for line in self.browse(cr, uid, ids, context=context):
1011             for f in field_names:
1012                 if f == 'price_subtotal':
1013                     if line.discount != 0.0:
1014                         res[line.id][f] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1015                     else:
1016                         res[line.id][f] = line.price_unit * line.qty
1017                 elif f == 'price_subtotal_incl':
1018                     taxes = [t for t in line.product_id.taxes_id]
1019                     if line.qty == 0.0:
1020                         res[line.id][f] = 0.0
1021                         continue
1022                     price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
1023                     computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, price, line.qty)
1024                     cur = line.order_id.pricelist_id.currency_id
1025                     res[line.id][f] = self.pool.get('res.currency').round(cr, uid, cur, computed_taxes['total'])
1026         return res
1027
1028     def price_by_product_multi(self, cr, uid, ids, context=None):
1029         if context is None:
1030             context = {}
1031         res = {}.fromkeys(ids, 0.0)
1032         lines = self.browse(cr, uid, ids, context=context)
1033
1034         pricelist_ids = [line.order_id.pricelist_id.id for line in lines]
1035         products_by_qty_by_partner = [(line.product_id.id, line.qty, line.order_id.partner_id.id) for line in lines]
1036
1037         price_get_multi_res = self.pool.get('product.pricelist').price_get_multi(cr, uid, pricelist_ids, products_by_qty_by_partner, context=context)
1038
1039         for line in lines:
1040             pricelist = line.order_id.pricelist_id.id
1041             product_id = line.product_id
1042
1043             if not product_id:
1044                 res[line.id] = 0.0
1045                 continue
1046             if not pricelist:
1047                 raise osv.except_osv(_('No Pricelist !'),
1048                     _('You have to select a pricelist in the sale form !\n' \
1049                     'Please set one before choosing a product.'))
1050
1051             #old_price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product_id.id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1052             #print "prod_id: %s, pricelist: %s, price: %s" % (product_id.id, pricelist, price)
1053             price = price_get_multi_res[line.product_id.id][pricelist]
1054             #print "prod_id: %s, pricelist: %s, price2: %s" % (product_id.id, pricelist, price2)
1055
1056             #if old_price != price:
1057             #    raise Exception('old_price != price')
1058
1059             unit_price = price or product_id.list_price
1060             res[line.id] = unit_price
1061             if unit_price is False:
1062                 raise osv.except_osv(_('No valid pricelist line found !'),
1063                     _("Couldn't find a pricelist line matching this product" \
1064                     " and quantity.\nYou have to change either the product," \
1065                     " the quantity or the pricelist."))
1066         return res
1067
1068     def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1069         if not product_id:
1070             return 0.0
1071         if not pricelist:
1072             raise osv.except_osv(_('No Pricelist !'),
1073                 _('You have to select a pricelist in the sale form !\n' \
1074                 'Please set one before choosing a product.'))
1075         p_obj = self.pool.get('product.product').browse(cr, uid, [product_id])[0]
1076         uom_id = p_obj.uom_po_id.id
1077         price = self.pool.get('product.pricelist').price_get(cr, uid,
1078             [pricelist], product_id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1079         unit_price=price or p_obj.list_price
1080         if unit_price is False:
1081             raise osv.except_osv(_('No valid pricelist line found !'),
1082                 _("Couldn't find a pricelist line matching this product" \
1083                 " and quantity.\nYou have to change either the product," \
1084                 " the quantity or the pricelist."))
1085         return unit_price
1086
1087     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1088         price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1089         self.write(cr, uid, ids, {'price_unit':price})
1090         pos_stot = (price * qty)
1091         return {'value': {'price_unit': price, 'price_subtotal_incl': pos_stot}}
1092
1093     def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist, qty,partner_id, product_id, *a):
1094         prod_obj = self.pool.get('product.product')
1095         price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1096         prod_id = ''
1097         if product_id:
1098             prod_id = prod_obj.browse(cr, uid, product_id).disc_controle
1099         disc = 0.0
1100         if (disc != 0.0 or prod_id) and price_f > 0:
1101             disc = 100 - (price/price_f*100)
1102             return {'value': {'discount': disc, 'price_unit': price_f}}
1103         return {}
1104
1105     def onchange_ded(self, cr, uid, ids, val_ded, price_u, *a):
1106         res_obj = self.pool.get('res.users')
1107         comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
1108         val = 0.0
1109         if val_ded and price_u:
1110             val=100.0 * val_ded / price_u
1111         if val > comp:
1112             return {'value': {'discount': val, 'notice': '' }}
1113         return {'value': {'discount': val}}
1114
1115     def onchange_discount(self, cr, uid, ids, discount, price, *a):
1116         pos_order = self.pool.get('pos.order.line')
1117         res_obj = self.pool.get('res.users')
1118         company_disc = pos_order.browse(cr,uid,ids)
1119         if discount:
1120             if not company_disc:
1121                 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1122             else:
1123                 comp= company_disc[0] and company_disc[0].order_id.company_id and  company_disc[0].order_id.company_id.company_discount  or 0.0
1124
1125             if discount > comp :
1126                 return {'value': {'notice': '', 'price_ded': price * discount * 0.01 or 0.0  }}
1127             else:
1128                 return {'value': {'notice': 'Minimum Discount', 'price_ded': price * discount * 0.01 or 0.0  }}
1129         else :
1130             return {'value': {'notice': 'No Discount', 'price_ded': price * discount * 0.01 or 0.0}}
1131
1132     def onchange_qty(self, cr, uid, ids, discount, qty, price, context=None):
1133         subtotal = qty * price
1134         if discount:
1135             subtotal = subtotal - (subtotal * discount / 100)
1136         return {'value': {'price_subtotal_incl': subtotal}}
1137
1138     _columns = {
1139         'name': fields.char('Line Description', size=512),
1140         'company_id': fields.many2one('res.company', 'Company', required=True),
1141         'notice': fields.char('Discount Notice', size=128, required=True),
1142         'serial_number': fields.char('Serial Number', size=128),
1143         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1144         'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1145         'price_ded': fields.float('Discount(Amount)', digits_compute=dp.get_precision('Point Of Sale')),
1146         'qty': fields.float('Quantity'),
1147         'qty_rfd': fields.float('Refunded Quantity'),
1148         'price_subtotal': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal w/o Tax'),
1149         'price_subtotal_incl': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal'),
1150         'discount': fields.float('Discount (%)', digits=(16, 2)),
1151         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1152         'create_date': fields.datetime('Creation Date', readonly=True),
1153         'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="You can specify Production lot for stock move created when you validate the pos order"),
1154     }
1155
1156     _defaults = {
1157         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1158         'qty': lambda *a: 1,
1159         'discount': lambda *a: 0.0,
1160         'price_ded': lambda *a: 0.0,
1161         'notice': lambda *a: 'No Discount',
1162         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1163         }
1164
1165     def create(self, cr, user, vals, context=None):
1166         if vals.get('product_id'):
1167             return super(pos_order_line, self).create(cr, user, vals, context=context)
1168         return False
1169
1170     def write(self, cr, user, ids, values, context=None):
1171         if 'product_id' in values and not values['product_id']:
1172             return False
1173         return super(pos_order_line, self).write(cr, user, ids, values, context=context)
1174
1175     def _scan_product(self, cr, uid, ean, qty, order):
1176         # search pricelist_id
1177         product_obj = self.pool.get('product.product')
1178         pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1179         if not pricelist_id:
1180             return False
1181
1182         new_line = True
1183
1184         product_id = product_obj.search(cr, uid, [('ean13','=', ean)])
1185         if not product_id:
1186            return False
1187
1188         # search price product
1189         product = product_obj.read(cr, uid, product_id)
1190         product_name = product[0]['name']
1191         price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1192
1193         order_line_ids = self.search(cr, uid, [('name', '=', product_name), ('order_id', '=' ,order)])
1194         if order_line_ids:
1195             new_line = False
1196             order_line_id = order_line_ids[0]
1197             qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1198
1199         if new_line:
1200             vals = {'product_id': product_id[0],
1201                     'price_unit': price,
1202                     'qty': qty,
1203                     'name': product_name,
1204                     'order_id': order,
1205             }
1206             line_id = self.create(cr, uid, vals)
1207             if not line_id:
1208                 raise osv.except_osv(_('Error'), _('Create line failed !'))
1209         else:
1210             vals = {
1211                 'qty': qty,
1212                 'price_unit': price
1213             }
1214             line_id = self.write(cr, uid, order_line_id, vals)
1215             if not line_id:
1216                 raise osv.except_osv(_('Error'), _('Modify line failed !'))
1217             line_id = order_line_id
1218
1219         price_line = float(qty) * float(price)
1220         return {
1221             'name': product_name,
1222             'product_id': product_id[0],
1223             'price': price,
1224             'price_line': price_line ,
1225             'qty': qty
1226         }
1227
1228 pos_order_line()
1229
1230 class product_product(osv.osv):
1231     _inherit = 'product.product'
1232     _columns = {
1233         'income_pdt': fields.boolean('Product for Input'),
1234         'expense_pdt': fields.boolean('Product for Output'),
1235         'am_out': fields.boolean('Control for Output Operations'),
1236         'disc_controle': fields.boolean('Discount Control'),
1237     }
1238     _defaults = {
1239         'disc_controle': True,
1240     }
1241 product_product()
1242
1243 class stock_picking(osv.osv):
1244     _inherit = 'stock.picking'
1245     _columns = {
1246         'pos_order': fields.many2one('pos.order', 'Pos order'),
1247     }
1248
1249 stock_picking()
1250
1251 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: