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