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