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