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