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