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