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