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