[REF] point_of_sale: Code cleaning
[odoo/odoo.git] / addons / point_of_sale / pos.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
55 class pos_order(osv.osv):
56     """ Point of sale gives business owners a convenient way of checking out customers
57         and of recording sales """
58
59     _name = "pos.order"
60     _description = "Point of Sale"
61     _order = "date_order, create_date desc"
62
63     def unlink(self, cr, uid, ids, context=None):
64         for rec in self.browse(cr, uid, ids, context=context):
65             for rec_statement in rec.statement_ids:
66                 if (rec_statement.statement_id and rec_statement.statement_id.state == 'confirm') or rec.state == 'done':
67                     raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
68         return super(pos_order, self).unlink(cr, uid, ids, context=context)
69
70     def onchange_partner_pricelist(self, cr, uid, ids, part, context=None):
71         """ Changed price list on_change of partner_id"""
72         if not part:
73             return {}
74         pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
75         return {'value': {'pricelist_id': pricelist}}
76
77     def _amount_total(self, cr, uid, ids, field_name, arg, context=None):
78         """ Calculates amount_tax of order line
79         @param field_names: Names of fields.
80         @return: Dictionary of values """
81         cr.execute("""
82             SELECT
83                 p.id,
84                 COALESCE(SUM(
85                     l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
86                     ) AS amount
87             FROM pos_order p
88             LEFT OUTER JOIN pos_order_line l ON (p.id = l.order_id)
89             WHERE p.id IN %s GROUP BY p.id """,(tuple(ids),))
90         res = dict(cr.fetchall())
91         for rec in self.browse(cr, uid, ids, context=context):
92             if rec.partner_id \
93                and rec.partner_id.property_account_position \
94                and rec.partner_id.property_account_position.tax_ids:
95                 res[rec.id] = res[rec.id] - rec.amount_tax
96             else :
97                 res[rec.id] = res[rec.id] + rec.amount_tax
98         return res
99
100     def _get_date_payment2(self, cr, uid, ids, context, *a):
101         # Todo need to check this function
102         """ Find payment Date
103         @param field_names: Names of fields.
104         @return: Dictionary of values """
105         res = {}
106         val = None
107         for order in self.browse(cr, uid, ids):
108             cr.execute("SELECT date_payment FROM pos_order WHERE id = %s", (order.id,))
109             date_p=cr.fetchone()
110             date_p=date_p and date_p[0] or None
111             if date_p:
112                 res[order.id]=date_p
113                 return res
114             cr.execute(" SELECT MAX(l.date) "
115                         " FROM account_move_line l, account_move m, account_invoice i, account_move_reconcile r, pos_order o "
116                         " 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",
117                         (order.id,))
118             val = cr.fetchone()
119             val = val and val[0] or None
120             if val:
121                 res[order.id] = val
122         return res
123
124     def _get_date_payment(self, cr, uid, ids, context, *a):
125         """ Find  Validation Date
126         @return: Dictionary of values """
127         res = {}
128         val = None
129         for order in self.browse(cr, uid, ids):
130             cr.execute("SELECT date_validation FROM pos_order WHERE id = %s", (order.id,))
131             date_p = cr.fetchone()
132             date_p = date_p and date_p[0] or None
133             if date_p:
134                 res[order.id] = date_p
135                 return res
136             discount_allowed = order.company_id.company_discount
137             for line in order.lines:
138                 if line.discount > discount_allowed:
139                     return {order.id: None }
140             if order.amount_paid == order.amount_total and not date_p:
141                 cr.execute("SELECT MAX(date) FROM account_bank_statement_line WHERE pos_statement_id = %s", (order.id,))
142                 val = cr.fetchone()
143                 val = val and val[0] or None
144             if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
145                 for o in order.invoice_id.move_id.line_id:
146                     if o.balance == 0:
147                         if val < o.date_created:
148                             val = o.date_created
149             if val:
150                 res[order.id] = val
151         return res
152
153     def _amount_all(self, cr, uid, ids, name, args, context=None):
154         tax_obj = self.pool.get('account.tax')
155         cur_obj = self.pool.get('res.currency')
156         res = {}
157         for order in self.browse(cr, uid, ids, context=context):
158             res[order.id] = {
159                 'amount_paid': 0.0,
160                 'amount_return':0.0,
161                 'amount_tax':0.0,
162             }
163             val = 0.0
164             cur = order.pricelist_id.currency_id
165             for payment in order.statement_ids:
166                 res[order.id]['amount_paid'] +=  payment.amount
167                 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
168             for line in order.lines:
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         return res
180
181     def _sale_journal_get(self, cr, uid, context=None):
182         """ To get  sale journal for this order"
183         @return: journal  """
184         journal_obj = self.pool.get('account.journal')
185         res = journal_obj.search(cr, uid, [('type', '=', 'sale')], limit=1)
186         return res and res[0] or False
187
188     def _shop_get(self, cr, uid, context=None):
189         """ To get  Shop  for this order"
190         @return: Shop id  """
191         res = self.pool.get('sale.shop').search(cr, uid, [])
192         return res and res[0] or False
193
194     def copy(self, cr, uid, id, default=None, context=None):
195         if not default:
196             default = {}
197         default.update({
198             'state': 'draft',
199             'partner_id': False,
200             'invoice_id': False,
201             'account_move': False,
202             'picking_id': False,
203             'statement_ids': [],
204             'nb_print': 0,
205             'pickings': []
206         })
207         return super(pos_order, self).copy(cr, uid, id, default, context=context)
208
209     def _get_v( self, cr, uid, ids, *a):
210         """ Changed the Validation state of order
211         @return: State  """
212         res_obj = self.pool.get('res.users')
213         company_disc = self.browse(cr, uid, ids)
214         list_jrnl = []
215         r = {}
216         if not company_disc:
217             comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
218         else:
219             comp = company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
220         cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount <= %s", (ids[0], comp))
221         res = cr.fetchone()
222         cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount > %s", (ids[0], comp))
223         res2 = cr.fetchone()
224         cr.execute("SELECT journal_id FROM account_bank_statement_line WHERE pos_statement_id = %s ", (ids[0], ))
225         res3 = cr.fetchall()
226         for r in res3:
227             cr.execute("SELECT id FROM account_journal WHERE name = '%s' AND special_journal = 't'", (r[0], ))
228             res3 = cr.fetchone()
229             is_special = res3 and res3[0] or None
230             if is_special:
231                 list_jrnl.append(is_special)
232         for order in self.browse(cr, uid, ids):
233             if order.state in ('paid', 'done', 'invoiced') and res and not res2 and not len(list_jrnl):
234                 r[order.id] = 'accepted'
235         return r
236
237     _columns = {
238         'name': fields.char('Order Description', size=64, required=True,
239             states={'draft': [('readonly', False)]}, readonly=True),
240         'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
241         'num_sale': fields.char('Internal Note', size=64),
242         'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
243             states={'draft': [('readonly', False)]}, readonly=True),
244         'date_order': fields.datetime('Date Ordered', readonly=True),
245         'date_validation': fields.function(_get_date_payment, method=True, string='Validation Date', type='date', store=True),
246         'date_payment': fields.function(_get_date_payment2, method=True, string='Payment Date', type='date', store=True),
247         'date_validity': fields.date('Validity Date', required=True),
248         'user_id': fields.many2one('res.users', 'Connected Salesman', help="Person who uses the the register. It could be a reliever, a student or an interim employee."),
249         'user_salesman_id': fields.many2one('res.users', 'Cashier', required=True, help="User who is logged into the system."),
250         'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
251         'amount_tax': fields.function(_amount_all, method=True, string='Taxes', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
252         'amount_total': fields.function(_amount_total, method=True, string='Total'),
253         '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'),
254         'amount_return': fields.function(_amount_all, 'Returned', method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
255         'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
256         'price_type': fields.selection([
257                                 ('tax_excluded','Tax excluded')],
258                                  'Price method', required=True),
259         'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
260         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
261         'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
262         'state': fields.selection([('draft', 'Quotation'),
263                                    ('payment', 'Payment'),
264                                    ('advance','Advance'),
265                                    ('paid', 'Paid'),
266                                    ('done', 'Done'),
267                                    ('invoiced', 'Invoiced'),
268                                    ('cancel', 'Cancel')],
269                                   'State', readonly=True),
270         'invoice_id': fields.many2one('account.invoice', 'Invoice'),
271         'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
272         'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
273         'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
274         'first_name': fields.char('First Name', size=64),
275         'note': fields.text('Internal Notes'),
276         'nb_print': fields.integer('Number of Print', readonly=True),
277         'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True),
278         'invoice_wanted': fields.boolean('Create Invoice'),
279         'note_2': fields.char('Customer Note', size=64),
280         'type_rec': fields.char('Type of Receipt', size=64),
281         'remboursed': fields.boolean('Remboursed'),
282         'contract_number': fields.char('Contract Number', size=512, select=1),
283         'journal_entry': fields.boolean('Journal Entry'),
284     }
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': 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
473         return True
474
475     def set_to_draft(self, cr, uid, ids, *args):
476         """ Changes order state to draft
477         @return: True
478         """
479         if not len(ids):
480             return False
481         self.write(cr, uid, ids, {'state': 'draft'}, context=context)
482         wf_service = netsvc.LocalService("workflow")
483         for i in ids:
484             wf_service.trg_create(uid, 'pos.order', i, cr)
485         return True
486
487     def button_invalidate(self, cr, uid, ids, *args):
488         """ Check the access for the sale order
489         @return: True
490         """
491         res_obj = self.pool.get('res.company')
492         try:
493             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
494         except Exception:
495             raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
496         if part_company:
497             raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
498         return True
499
500     def cancel_order(self, cr, uid, ids, context=None):
501         """ Changes order state to cancel
502         @return: True
503         """
504         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
505         self.cancel_picking(cr, uid, ids, context=context)
506         return True
507
508     def add_payment(self, cr, uid, order_id, data, context=None):
509         """Create a new payment for the order"""
510         statement_obj= self.pool.get('account.bank.statement')
511         statement_line_obj = self.pool.get('account.bank.statement.line')
512         prod_obj = self.pool.get('product.product')
513         property_obj = self.pool.get('ir.property')
514         curr_c = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
515         curr_company = curr_c.id
516         order = self.browse(cr, uid, order_id, context=context)
517         if not order.num_sale and data['num_sale']:
518             self.write(cr, uid, order_id, {'num_sale': data['num_sale']}, context=context)
519         ids_new = []
520         args = {
521             'amount': data['amount'],
522         }
523         if 'payment_date' in data.keys():
524             args['date'] = data['payment_date']
525         if 'payment_name' in data.keys():
526             args['name'] = data['payment_name'] + ' ' + order.name
527         account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
528         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
529         if data.get('is_acc', False):
530             args['is_acc'] = data['is_acc']
531             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
532             if not args['account_id']:
533                 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')%(prod_obj.browse(cr, uid, data['product_id'], context=context).name))
534         args['partner_id'] = order.partner_id and order.partner_id.id or None
535         args['ref'] = order.contract_number or None
536
537         statement_id = statement_obj.search(cr,uid, [
538                                                      ('journal_id', '=', data['journal']),
539                                                      ('company_id', '=', curr_company),
540                                                      ('user_id', '=', uid),
541                                                      ('state', '=', 'open')], context=context)
542         if len(statement_id) == 0:
543             raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
544         if statement_id:
545             statement_id = statement_id[0]
546         args['statement_id'] = statement_id
547         args['pos_statement_id'] = order_id
548         args['journal_id'] = data['journal']
549         statement_line_obj.create(cr, uid, args, context=context)
550         ids_new.append(statement_id)
551
552         wf_service = netsvc.LocalService("workflow")
553         wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
554         wf_service.trg_write(uid, 'pos.order', order_id, cr)
555
556         return statement_id
557
558     def add_product(self, cr, uid, order_id, product_id, qty, context=None):
559         """Create a new order line the order"""
560         line_obj = self.pool.get('pos.order.line')
561         values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
562
563         pricelist = values['pricelist_id'] and values['pricelist_id'][0]
564         product = values['partner_id'] and values['partner_id'][0]
565
566         price = line_obj.price_by_product(cr, uid, [],
567                 pricelist, product_id, qty, product)
568
569         order_line_id = line_obj.create(cr, uid, {
570             'order_id': order_id,
571             'product_id': product_id,
572             'qty': qty,
573             'price_unit': price,
574         }, context=context)
575         wf_service = netsvc.LocalService("workflow")
576         wf_service.trg_write(uid, 'pos.order', order_id, cr)
577         return order_line_id, price
578
579     def refund(self, cr, uid, ids, context=None):
580         """Create a copy of order  for refund order"""
581         clone_list = []
582         line_obj = self.pool.get('pos.order.line')
583
584         for order in self.browse(cr, uid, ids, context=context):
585             clone_id = self.copy(cr, uid, order.id, {
586                 'name': order.name + ' REFUND',
587                 'date_order': time.strftime('%Y-%m-%d'),
588                 'state': 'draft',
589                 'note': 'REFUND\n'+ (order.note or ''),
590                 'invoice_id': False,
591                 'nb_print': 0,
592                 'statement_ids': False,
593                 }, context=context)
594             clone_list.append(clone_id)
595
596
597         for clone in self.browse(cr, uid, clone_list, context=context):
598             for order_line in clone.lines:
599                 line_obj.write(cr, uid, [order_line.id], {
600                     'qty': -order_line.qty
601                     }, context=context)
602         return clone_list
603
604     def action_invoice(self, cr, uid, ids, context=None):
605         """Create a invoice of order  """
606         inv_ref = self.pool.get('account.invoice')
607         inv_line_ref = self.pool.get('account.invoice.line')
608         product_obj = self.pool.get('product.product')
609         inv_ids = []
610
611         for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
612             if order.invoice_id:
613                 inv_ids.append(order.invoice_id.id)
614                 continue
615
616             if not order.partner_id:
617                 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
618
619             acc = order.partner_id.property_account_receivable.id
620             inv = {
621                 'name': 'Invoice from POS: '+order.name,
622                 'origin': order.name,
623                 'account_id': acc,
624                 'journal_id': order.sale_journal.id or None,
625                 'type': 'out_invoice',
626                 'reference': order.name,
627                 'partner_id': order.partner_id.id,
628                 'comment': order.note or '',
629             }
630             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
631             if not inv.get('account_id', None):
632                 inv['account_id'] = acc
633             inv_id = inv_ref.create(cr, uid, inv, context=context)
634
635             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
636             inv_ids.append(inv_id)
637             for line in order.lines:
638                 inv_line = {
639                     'invoice_id': inv_id,
640                     'product_id': line.product_id.id,
641                     'quantity': line.qty,
642                 }
643                 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
644
645                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
646                                                                line.product_id.id,
647                                                                line.product_id.uom_id.id,
648                                                                line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
649                 inv_line['price_unit'] = line.price_unit
650                 inv_line['discount'] = line.discount
651                 inv_line['account_id'] = acc
652                 inv_line['name'] = inv_name
653                 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
654                     and [(6, 0, inv_line['invoice_line_tax_id'])] or []
655                 inv_line_ref.create(cr, uid, inv_line, context=context)
656
657         for i in inv_ids:
658             wf_service = netsvc.LocalService("workflow")
659             wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
660         return inv_ids
661
662     def create_account_move(self, cr, uid, ids, context=None):
663         """Create a account move line of order  """
664         account_move_obj = self.pool.get('account.move')
665         account_move_line_obj = self.pool.get('account.move.line')
666         account_period_obj = self.pool.get('account.period')
667         account_tax_obj = self.pool.get('account.tax')
668         res_obj=self.pool.get('res.users')
669         property_obj=self.pool.get('ir.property')
670         period = account_period_obj.find(cr, uid, context=context)[0]
671
672         for order in self.browse(cr, uid, ids, context=context):
673             curr_c = res_obj.browse(cr, uid, uid).company_id
674             comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
675             comp_id = comp_id and comp_id.id or False
676             to_reconcile = []
677             group_tax = {}
678             account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
679
680             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
681
682             # Create an entry for the sale
683             move_id = account_move_obj.create(cr, uid, {
684                 'journal_id': order.sale_journal.id,
685                 'period_id': period,
686                 }, context=context)
687
688             # Create an move for each order line
689             for line in order.lines:
690                 tax_amount = 0
691                 taxes = [t for t in line.product_id.taxes_id]
692                 if order.price_type == 'tax_excluded':
693                     computed_taxes = account_tax_obj.compute_all(
694                         cr, uid, taxes, line.price_unit, line.qty)['taxes']
695                 else:
696                     computed_taxes = account_tax_obj.compute_inv(
697                         cr, uid, taxes, line.price_unit, line.qty)
698
699                 for tax in computed_taxes:
700                     tax_amount += round(tax['amount'], 2)
701                     group_key = (tax['tax_code_id'],
702                                 tax['base_code_id'],
703                                 tax['account_collected_id'])
704
705                     if group_key in group_tax:
706                         group_tax[group_key] += round(tax['amount'], 2)
707                     else:
708                         group_tax[group_key] = round(tax['amount'], 2)
709                 if order.price_type != 'tax_excluded':
710                     amount = line.price_subtotal - tax_amount
711                 else:
712                     amount = line.price_subtotal
713
714                 # Search for the income account
715                 if  line.product_id.property_account_income.id:
716                     income_account = line.\
717                                     product_id.property_account_income.id
718                 elif line.product_id.categ_id.\
719                         property_account_income_categ.id:
720                     income_account = line.product_id.categ_id.\
721                                     property_account_income_categ.id
722                 else:
723                     raise osv.except_osv(_('Error !'), _('There is no income '\
724                         'account defined for this product: "%s" (id:%d)') \
725                         % (line.product_id.name, line.product_id.id, ))
726
727                 # Empty the tax list as long as there is no tax code:
728                 tax_code_id = False
729                 tax_amount = 0
730                 while computed_taxes:
731                     tax = computed_taxes.pop(0)
732                     if amount > 0:
733                         tax_code_id = tax['base_code_id']
734                         tax_amount = line.price_subtotal * tax['base_sign']
735                     else:
736                         tax_code_id = tax['ref_base_code_id']
737                         tax_amount = line.price_subtotal * tax['ref_base_sign']
738                     # If there is one we stop
739                     if tax_code_id:
740                         break
741
742                 # Create a move for the line
743                 account_move_line_obj.create(cr, uid, {
744                     'name': "aa"+order.name,
745                     'date': order.date_order[:10],
746                     'ref': order.contract_number or order.name,
747                     'quantity': line.qty,
748                     'product_id': line.product_id.id,
749                     'move_id': move_id,
750                     'account_id': income_account,
751                     'company_id': comp_id,
752                     'credit': ((amount>0) and amount) or 0.0,
753                     'debit': ((amount<0) and -amount) or 0.0,
754                     'journal_id': order.sale_journal.id,
755                     'period_id': period,
756                     'tax_code_id': tax_code_id,
757                     'tax_amount': tax_amount,
758                 }, context=context)
759
760                 # For each remaining tax with a code, whe create a move line
761                 for tax in computed_taxes:
762                     if amount > 0:
763                         tax_code_id = tax['base_code_id']
764                         tax_amount = line.price_subtotal * tax['base_sign']
765                     else:
766                         tax_code_id = tax['ref_base_code_id']
767                         tax_amount = line.price_subtotal * tax['ref_base_sign']
768                     if not tax_code_id:
769                         continue
770
771                     account_move_line_obj.create(cr, uid, {
772                         'name': "bb" + order.name,
773                         'date': order.date_order[:10],
774                         'ref': order.contract_number or order.name,
775                         'product_id':line.product_id.id,
776                         'quantity': line.qty,
777                         'move_id': move_id,
778                         'account_id': income_account,
779                         'company_id': comp_id,
780                         'credit': 0.0,
781                         'debit': 0.0,
782                         'journal_id': order.sale_journal.id,
783                         'period_id': period,
784                         'tax_code_id': tax_code_id,
785                         'tax_amount': tax_amount,
786                     }, context=context)
787
788
789             # Create a move for each tax group
790             (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
791             for key, amount in group_tax.items():
792                 account_move_line_obj.create(cr, uid, {
793                     'name': "cc" + order.name,
794                     'date': order.date_order[:10],
795                     'ref': order.contract_number or order.name,
796                     'move_id': move_id,
797                     'company_id': comp_id,
798                     'quantity': line.qty,
799                     'product_id': line.product_id.id,
800                     'account_id': key[account_pos],
801                     'credit': ((amount>0) and amount) or 0.0,
802                     'debit': ((amount<0) and -amount) or 0.0,
803                     'journal_id': order.sale_journal.id,
804                     'period_id': period,
805                     'tax_code_id': key[tax_code_pos],
806                     'tax_amount': amount,
807                 }, context=context)
808
809             # counterpart
810             to_reconcile.append(account_move_line_obj.create(cr, uid, {
811                 'name': "dd" + order.name,
812                 'date': order.date_order[:10],
813                 'ref': order.contract_number or order.name,
814                 'move_id': move_id,
815                 'company_id': comp_id,
816                 'account_id': order_account,
817                 'credit': ((order.amount_total < 0) and -order.amount_total)\
818                     or 0.0,
819                 'debit': ((order.amount_total > 0) and order.amount_total)\
820                     or 0.0,
821                 'journal_id': order.sale_journal.id,
822                 'period_id': period,
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 not context:
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):
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):
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                     tax_amount = 0.0
991                     taxes = [t for t in line.product_id.taxes_id]
992                     if line.qty == 0.0:
993                         res[line.id][f] = 0.0
994                         continue
995                     computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
996                     for tax in computed_taxes:
997                         tax_amount += tax['amount']
998                     if line.discount!=0.0:
999                         res[line.id][f] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1000                     else:
1001                         res[line.id][f] = line.price_unit * line.qty
1002                     res[line.id][f] += tax_amount
1003         return res
1004
1005     def price_by_product_multi(self, cr, uid, ids, context=None):
1006         if context is None:
1007             context = {}
1008         res = {}.fromkeys(ids, 0.0)
1009         lines = self.browse(cr, uid, ids, context=context)
1010
1011         pricelist_ids = [line.order_id.pricelist_id.id for line in lines]
1012         products_by_qty_by_partner = [(line.product_id.id, line.qty, line.order_id.partner_id.id) for line in lines]
1013
1014         price_get_multi_res = self.pool.get('product.pricelist').price_get_multi(cr, uid, pricelist_ids, products_by_qty_by_partner, context=context)
1015
1016         for line in lines:
1017             pricelist = line.order_id.pricelist_id.id
1018             product_id = line.product_id
1019
1020             if not product_id:
1021                 res[line.id] = 0.0
1022                 continue
1023             if not pricelist:
1024                 raise osv.except_osv(_('No Pricelist !'),
1025                     _('You have to select a pricelist in the sale form !\n' \
1026                     'Please set one before choosing a product.'))
1027
1028             #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]
1029             #print "prod_id: %s, pricelist: %s, price: %s" % (product_id.id, pricelist, price)
1030             price = price_get_multi_res[line.product_id.id][pricelist]
1031             #print "prod_id: %s, pricelist: %s, price2: %s" % (product_id.id, pricelist, price2)
1032
1033             #if old_price != price:
1034             #    raise Exception('old_price != price')
1035
1036             unit_price = price or product_id.list_price
1037             res[line.id] = unit_price
1038             if unit_price is False:
1039                 raise osv.except_osv(_('No valid pricelist line found !'),
1040                     _("Couldn't find a pricelist line matching this product" \
1041                     " and quantity.\nYou have to change either the product," \
1042                     " the quantity or the pricelist."))
1043         return res
1044
1045     def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1046         if not product_id:
1047             return 0.0
1048         if not pricelist:
1049             raise osv.except_osv(_('No Pricelist !'),
1050                 _('You have to select a pricelist in the sale form !\n' \
1051                 'Please set one before choosing a product.'))
1052         p_obj = self.pool.get('product.product').browse(cr, uid, [product_id])[0]
1053         uom_id = p_obj.uom_po_id.id
1054         price = self.pool.get('product.pricelist').price_get(cr, uid,
1055             [pricelist], product_id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1056         unit_price=price or p_obj.list_price
1057         if unit_price is False:
1058             raise osv.except_osv(_('No valid pricelist line found !'),
1059                 _("Couldn't find a pricelist line matching this product" \
1060                 " and quantity.\nYou have to change either the product," \
1061                 " the quantity or the pricelist."))
1062         return unit_price
1063
1064     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1065         price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1066         self.write(cr, uid, ids, {'price_unit':price})
1067         pos_stot = (price * qty)
1068         return {'value': {'price_unit': price, 'price_subtotal_incl': pos_stot}}
1069
1070     def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist, qty,partner_id, product_id, *a):
1071         prod_obj = self.pool.get('product.product')
1072         price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1073         prod_id = ''
1074         if product_id:
1075             prod_id = prod_obj.browse(cr, uid, product_id).disc_controle
1076         disc = 0.0
1077         if (disc != 0.0 or prod_id) and price_f > 0:
1078             disc = 100 - (price/price_f*100)
1079             return {'value': {'discount': disc, 'price_unit': price_f}}
1080         return {}
1081
1082     def onchange_dis(self, cr, uid, ids,  qty, price_subtotal_incl, discount, *a):
1083         price_sub = price_subtotal_incl
1084         sub_total_discount = price_sub - (price_subtotal_incl*(discount*0.01))
1085         return {'value': {'price_subtotal_incl': sub_total_discount}}
1086
1087     def onchange_ded(self, cr, uid, ids, val_ded, price_u, *a):
1088         res_obj = self.pool.get('res.users')
1089         comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
1090         val = 0.0
1091         if val_ded and price_u:
1092             val=100.0 * val_ded / price_u
1093         if val > comp:
1094             return {'value': {'discount': val, 'notice': '' }}
1095         return {'value': {'discount': val}}
1096
1097     def onchange_discount(self, cr, uid, ids, discount, price, *a):
1098         pos_order = self.pool.get('pos.order.line')
1099         res_obj = self.pool.get('res.users')
1100         company_disc = pos_order.browse(cr,uid,ids)
1101         if discount:
1102             if not company_disc:
1103                 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1104             else:
1105                 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
1106
1107             if discount > comp :
1108                 return {'value': {'notice': '', 'price_ded': price * discount * 0.01 or 0.0  }}
1109             else:
1110                 return {'value': {'notice': 'Minimum Discount', 'price_ded': price * discount * 0.01 or 0.0  }}
1111         else :
1112             return {'value': {'notice': 'No Discount', 'price_ded': price * discount * 0.01 or 0.0}}
1113
1114     def onchange_qty(self, cr, uid, ids, discount, qty, price, context=None):
1115         subtotal = qty * price
1116         if discount:
1117             subtotal = subtotal - (subtotal * discount / 100)
1118         return {'value': {'price_subtotal_incl': subtotal}}
1119
1120     _columns = {
1121         'name': fields.char('Line Description', size=512),
1122         'company_id': fields.many2one('res.company', 'Company', required=True),
1123         'notice': fields.char('Discount Notice', size=128, required=True),
1124         'serial_number': fields.char('Serial Number', size=128),
1125         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1126         'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1127         'price_ded': fields.float('Discount(Amount)', digits_compute=dp.get_precision('Point Of Sale')),
1128         'qty': fields.float('Quantity'),
1129         'qty_rfd': fields.float('Refunded Quantity'),
1130         'price_subtotal': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal w/o Tax'),
1131         'price_subtotal_incl': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal'),
1132         'discount': fields.float('Discount (%)', digits=(16, 2)),
1133         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1134         'create_date': fields.datetime('Creation Date', readonly=True),
1135     }
1136
1137     _defaults = {
1138         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1139         'qty': lambda *a: 1,
1140         'discount': lambda *a: 0.0,
1141         'price_ded': lambda *a: 0.0,
1142         'notice': lambda *a: 'No Discount',
1143         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1144         }
1145
1146     def create(self, cr, user, vals, context=None):
1147         if vals.get('product_id'):
1148             return super(pos_order_line, self).create(cr, user, vals, context=context)
1149         return False
1150
1151     def write(self, cr, user, ids, values, context=None):
1152         if 'product_id' in values and not values['product_id']:
1153             return False
1154         return super(pos_order_line, self).write(cr, user, ids, values, context=context)
1155
1156     def _scan_product(self, cr, uid, ean, qty, order):
1157         # search pricelist_id
1158         product_obj = self.pool.get('product.product')
1159         pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1160         if not pricelist_id:
1161             return False
1162
1163         new_line = True
1164
1165         product_id = product_obj.search(cr, uid, [('ean13','=', ean)])
1166         if not product_id:
1167            return False
1168
1169         # search price product
1170         product = product_obj.read(cr, uid, product_id)
1171         product_name = product[0]['name']
1172         price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1173
1174         order_line_ids = self.search(cr, uid, [('name', '=', product_name), ('order_id', '=' ,order)])
1175         if order_line_ids:
1176             new_line = False
1177             order_line_id = order_line_ids[0]
1178             qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1179
1180         if new_line:
1181             vals = {'product_id': product_id[0],
1182                     'price_unit': price,
1183                     'qty': qty,
1184                     'name': product_name,
1185                     'order_id': order,
1186             }
1187             line_id = self.create(cr, uid, vals)
1188             if not line_id:
1189                 raise osv.except_osv(_('Error'), _('Create line failed !'))
1190         else:
1191             vals = {
1192                 'qty': qty,
1193                 'price_unit': price
1194             }
1195             line_id = self.write(cr, uid, order_line_id, vals)
1196             if not line_id:
1197                 raise osv.except_osv(_('Error'), _('Modify line failed !'))
1198             line_id = order_line_id
1199
1200         price_line = float(qty) * float(price)
1201         return {
1202             'name': product_name,
1203             'product_id': product_id[0],
1204             'price': price,
1205             'price_line': price_line ,
1206             'qty': qty
1207         }
1208
1209 pos_order_line()
1210
1211 class product_product(osv.osv):
1212     _inherit = 'product.product'
1213     _columns = {
1214         'income_pdt': fields.boolean('Product for Input'),
1215         'expense_pdt': fields.boolean('Product for expenses'),
1216         'am_out': fields.boolean('Control for Output Operations'),
1217         'disc_controle': fields.boolean('Discount Control'),
1218     }
1219     _defaults = {
1220         'disc_controle': True,
1221     }
1222 product_product()
1223
1224 class stock_picking(osv.osv):
1225     _inherit = 'stock.picking'
1226     _columns = {
1227         'pos_order': fields.many2one('pos.order', 'Pos order'),
1228     }
1229 stock_picking()
1230
1231 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: