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