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