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