[IMP] Update the translation
[odoo/odoo.git] / addons / point_of_sale / pos.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import time
24 import netsvc
25 from osv import fields, osv
26 from mx import DateTime
27 from tools.translate import _
28 import tools
29
30
31 class pos_config_journal(osv.osv):
32     _name = 'pos.config.journal'
33     _description = "Point of Sale journal configuration."
34     _columns = {
35         'name': fields.char('Description', size=64),
36         'code': fields.char('Code', size=64),
37         'journal_id': fields.many2one('account.journal', "Journal")
38     }
39
40 pos_config_journal()
41
42
43 class pos_order(osv.osv):
44     _name = "pos.order"
45     _description = "Point of Sale"
46     _order = "date_order, create_date desc"
47     _order = "date_order desc"
48
49     def unlink(self, cr, uid, ids, context={}):
50         for rec in self.browse(cr, uid, ids, context=context):
51             if rec.state<>'draft':
52                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is already confirmed !'))
53         return super(pos_order, self).unlink(cr, uid, ids, context=context)
54
55     def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
56         if not part:
57             return {}
58         pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id 
59         return {'value':{'pricelist_id': pricelist}}
60
61     def _amount_total(self, cr, uid, ids, field_name, arg, context):
62         id_set = ",".join(map(str, ids))
63         cr.execute("""
64         SELECT
65             p.id,
66             COALESCE(SUM(
67                 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
68                 ) AS amount
69         FROM pos_order p
70             LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
71         WHERE p.id IN (""" + id_set  +""") GROUP BY p.id """)
72         res = dict(cr.fetchall())
73
74         for rec in self.browse(cr, uid, ids, context):
75             if rec.partner_id \
76                and rec.partner_id.property_account_position \
77                and rec.partner_id.property_account_position.tax_ids:
78                 res[rec.id] = res[rec.id] - rec.amount_tax
79         return res
80
81     def _amount_tax(self, cr, uid, ids, field_name, arg, context):
82         res = {}
83         tax_obj = self.pool.get('account.tax')
84         for order in self.browse(cr, uid, ids):
85             val = 0.0
86             for line in order.lines:
87                 val = reduce(lambda x, y: x+round(y['amount'], 2),
88                         tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
89                             line.price_unit * \
90                             (1-(line.discount or 0.0)/100.0), line.qty),
91                             val)
92
93             res[order.id] = val
94         return res
95
96     def _total_payment(self, cr, uid, ids, field_name, arg, context):
97         res = {}
98         for order in self.browse(cr, uid, ids):
99             val = 0.0
100             for payment in order.payments:
101                 val += payment.amount
102             res[order.id] = val
103         return res
104
105     def _total_return(self, cr, uid, ids, field_name, arg, context):
106         res = {}
107         for order in self.browse(cr, uid, ids):
108             val = 0.0
109             for payment in order.payments:
110                 val += (payment.amount < 0 and payment.amount or 0)
111             res[order.id] = val
112         return res
113
114     def payment_get(self, cr, uid, ids, context=None):
115         cr.execute("select id from pos_payment where order_id in (%s)" % \
116                     ','.join([str(i) for i in ids]))
117         return [i[0] for i in cr.fetchall()]
118
119     def _sale_journal_get(self, cr, uid, context):
120         journal_obj = self.pool.get('account.journal')
121         res = journal_obj.search(cr, uid,
122             [('type', '=', 'sale')], limit=1)
123         if res:
124             return res[0]
125         else:
126             return False
127
128     def _receivable_get(self, cr, uid, context=None):
129         prop_obj = self.pool.get('ir.property')
130         res = prop_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
131         return res
132
133     def copy(self, cr, uid, id, default=None, context={}):
134         if not default:
135             default = {}
136         default.update({
137             'state': 'draft',
138             'payments': [],
139             'partner_id': False,
140             'invoice_id': False,
141             'account_move': False,
142             'last_out_picking': False,
143             'nb_print': 0,
144             'pickings': []
145         })
146         return super(pos_order, self).copy(cr, uid, id, default, context)
147
148     _columns = {
149         'name': fields.char('Order Description', size=64, required=True,
150             states={'draft': [('readonly', False)]}, readonly=True),
151         'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
152             states={'draft': [('readonly', False)]}, readonly=True),
153         'date_order': fields.date('Date Ordered', readonly=True),
154         'date_validity': fields.date('Validity Date', required=True),
155         'user_id': fields.many2one('res.users', 'Salesman',
156             readonly=True),
157         'amount_tax': fields.function(_amount_tax, method=True, string='Taxes'),
158         'amount_total': fields.function(_amount_total, method=True,
159             string='Total'),
160         'amount_paid': fields.function(_total_payment, 'Paid',
161             states={'draft': [('readonly', False)]}, readonly=True,
162             method=True),
163         'amount_return': fields.function(_total_return, 'Returned',
164                                         method=True),
165         'lines': fields.one2many('pos.order.line', 'order_id',
166             'Order Lines', states={'draft': [('readonly', False)]},
167             readonly=True),
168         'payments': fields.one2many('pos.payment', 'order_id',
169             'Order Payments', states={'draft': [('readonly', False)]},
170             readonly=True),
171         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
172             required=True, states={'draft': [('readonly', False)]},
173             readonly=True),
174         'partner_id': fields.many2one(
175             'res.partner', 'Partner', change_default=True,
176             states={'draft': [('readonly', False)], 'paid': [('readonly', False)]},
177             readonly=True),
178         'state': fields.selection([('cancel', 'Cancel'), ('draft', 'Draft'),
179             ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced')], 'State',
180             readonly=True, ),
181         'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
182         'account_move': fields.many2one('account.move', 'Account Entry',
183             readonly=True),
184         'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking',
185             readonly=True),
186         'last_out_picking': fields.many2one('stock.picking',
187                                             'Last output picking',
188                                             readonly=True),
189         'note': fields.text('Notes'),
190         'nb_print': fields.integer('Number of print', readonly=True),
191         'sale_journal': fields.many2one('account.journal', 'Journal',
192             required=True, states={'draft': [('readonly', False)]},
193             readonly=True, ),
194         'account_receivable': fields.many2one('account.account',
195             'Default Receivable', required=True, states={'draft': [('readonly', False)]},
196             readonly=True, ),
197         'invoice_wanted': fields.boolean('Create invoice')
198         }
199
200     def _journal_default(self, cr, uid, context={}):
201         journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
202         if journal_list:
203             return journal_list[0]
204         else:
205             return False
206
207     _defaults = {
208         'user_id': lambda self, cr, uid, context: uid,
209         'state': lambda *a: 'draft',
210         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence')\
211             .get(cr, uid, 'pos.order'),
212         'date_order': lambda *a: time.strftime('%Y-%m-%d'),
213         'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
214         'nb_print': lambda *a: 0,
215         'sale_journal': _sale_journal_get,
216         'account_receivable': _receivable_get,
217         'invoice_wanted': lambda *a: False
218     }
219
220     def test_order_lines(self, cr, uid, order, context={}):
221         if not order.lines:
222             raise osv.except_osv("Error", "No order lines defined for this sale.")
223
224         wf_service = netsvc.LocalService("workflow")
225         wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
226         return True
227
228     def dummy_button(self, cr, uid, order, context={}):
229         return True
230
231     def test_paid(self, cr, uid, ids, context=None):
232         for order in self.browse(cr, uid, ids, context):
233             if order.lines and not order.amount_total:
234                 return True
235             if (not order.lines) or (not order.payments) or \
236                 (order.amount_paid != order.amount_total):
237                 return False
238         return True
239
240     def _get_qty_differences(self, orders, old_picking):
241         """check if the customer changed the product quantity"""
242         order_dict = {}
243         for order in orders:
244             for line in order.lines:
245                 order_dict[line.product_id.id] = line
246
247         # check the quantity differences:
248         diff_dict = {}
249         for line in old_picking.move_lines:
250             order_line = order_dict.get(line.product_id.id)
251             if not order_line:
252                 deleted = True
253                 qty_to_delete_from_original_picking = line.product_qty
254                 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
255             elif line.product_qty != order_line.qty:
256                 deleted = False
257                 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
258                 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
259
260         return diff_dict
261
262     def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
263         """if the customer changes the product quantity, split the picking in two"""
264         # create a copy of the original picking and adjust the product qty:
265         picking_model = self.pool.get('stock.picking')
266         defaults = {
267             'note': "Partial picking from customer", # add a note to tell why we create a new picking
268             'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
269         }
270
271         new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
272         new_picking = picking_model.browse(cr, uid, new_picking_id, context)
273
274         for line in new_picking.move_lines:
275             p_id = line.product_id.id
276             if p_id in diff_dict:
277                 diff = diff_dict[p_id]
278                 deleted = diff[0]
279                 qty_to_del = diff[1]
280                 if deleted: # product has been deleted (customer didn't took it):
281                     # delete this product from old picking:
282                     for old_line in old_picking.move_lines:
283                         if old_line.product_id.id == p_id:
284                             old_line.write(cr, uid, [old_line.id], {'state': 'draft'}) # cannot delete if not draft
285                             old_line.unlink(cr, uid, [old_line.id], context)
286                 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
287                     # subtract qty from old picking:
288                     for old_line in old_picking.move_lines:
289                         if old_line.product_id.id == p_id:
290                             old_line.write(cr, uid, [old_line.id], {'product_qty': old_line.product_qty - qty_to_del})
291                     # add qty to new picking:
292                     line.write(cr, uid, [line.id], {'product_qty': qty_to_del})
293                 else: # product hasn't changed (customer took it without any change):
294                     # delete this product from new picking:
295                     line.unlink(cr, uid, [line.id], context)
296             else:
297                 # delete it in the new picking:
298                 line.unlink(cr, uid, [line.id], context)
299
300     def create_picking(self, cr, uid, ids, context={}):
301         """Create a picking for each order and validate it."""
302         picking_obj = self.pool.get('stock.picking')
303
304         orders = self.browse(cr, uid, ids, context)
305         for order in orders:
306             if not order.last_out_picking:
307                 new = True
308                 picking_id = picking_obj.create(cr, uid, {
309                     'origin': order.name,
310                     'type': 'out',
311                     'state': 'draft',
312                     'move_type': 'direct',
313                     'note': 'POS notes ' + (order.note or ""),
314                     'invoice_state': 'none',
315                     'auto_picking': True,
316                     'pos_order': order.id,
317                     })
318                 self.write(cr, uid, [order.id], {'last_out_picking': picking_id})
319             else:
320                 picking_id = order.last_out_picking.id
321                 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
322                 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
323                 new = False
324
325                 # split the picking (if product quantity has changed):
326                 diff_dict = self._get_qty_differences(orders, picking)
327                 if diff_dict:
328                     self._split_picking(cr, uid, ids, context, picking, diff_dict)
329
330             if new:
331                 for line in order.lines:
332                     prop_ids = self.pool.get("ir.property").search(cr, uid,
333                             [('name', '=', 'property_stock_customer')])
334                     val = self.pool.get("ir.property").browse(cr, uid,
335                             prop_ids[0]).value
336                     location_id = order.shop_id.warehouse_id.lot_stock_id.id
337                     stock_dest_id = int(val.split(',')[1])
338                     if line.qty < 0:
339                         (location_id, stock_dest_id)= (stock_dest_id, location_id)
340
341                     self.pool.get('stock.move').create(cr, uid, {
342                         'name': 'Stock move (POS %d)' % (order.id, ),
343                         'product_uom': line.product_id.uom_id.id,
344                         'product_uos': line.product_id.uom_id.id,
345                         'picking_id': picking_id,
346                         'product_id': line.product_id.id,
347                         'product_uos_qty': abs(line.qty),
348                         'product_qty': abs(line.qty),
349                         'tracking_id': False,
350                         'state': 'waiting',
351                         'location_id': location_id,
352                         'location_dest_id': stock_dest_id,
353                     })
354
355             wf_service = netsvc.LocalService("workflow")
356             wf_service.trg_validate(uid, 'stock.picking',
357                     picking_id, 'button_confirm', cr)
358             self.pool.get('stock.picking').force_assign(cr,
359                     uid, [picking_id], context)
360
361         return True
362
363     def set_to_draft(self, cr, uid, ids, *args):
364         if not len(ids):
365             return False
366
367         self.write(cr, uid, ids, {'state': 'draft'})
368
369         wf_service = netsvc.LocalService("workflow")
370         for i in ids:
371             wf_service.trg_create(uid, 'pos.order', i, cr)
372         return True
373
374     def cancel_order(self, cr, uid, ids, context=None):
375         """Cancel each picking with an inverted one."""
376
377         picking_obj = self.pool.get('stock.picking')
378         stock_move_obj = self.pool.get('stock.move')
379         payment_obj = self.pool.get('pos.payment')
380         picking_ids = picking_obj.search(cr, uid, [('pos_order', 'in', ids), ('state', '=', 'done')])
381         clone_list = []
382
383         # Copy all the picking and blank the last_out_picking
384         for order in self.browse(cr, uid, ids, context=context):
385             if not order.last_out_picking:
386                 continue
387
388             clone_id = picking_obj.copy(
389                 cr, uid, order.last_out_picking.id, {'type': 'in'})
390             # Confirm the picking
391             wf_service = netsvc.LocalService("workflow")
392             wf_service.trg_validate(uid, 'stock.picking',
393                 clone_id, 'button_confirm', cr)
394             clone_list.append(clone_id)
395             # Remove the ref to last picking and delete the payments
396             self.write(cr, uid, ids, {'last_out_picking': False})
397             payment_obj.unlink(cr, uid, [i.id for i in order.payments],
398                 context=context)
399
400             # Switch all the moves
401             move_ids = stock_move_obj.search(
402                 cr, uid, [('picking_id', '=', clone_id)])
403             for move in stock_move_obj.browse(cr, uid, move_ids, context=context):
404                 stock_move_obj.write(
405                     cr, uid, move.id, {'location_id': move.location_dest_id.id,
406                                     'location_dest_id': move.location_id.id})
407
408         self.pool.get('stock.picking').force_assign(cr,
409             uid, clone_list, context)
410
411         return True
412
413     def add_payment(self, cr, uid, order_id, data, context=None):
414         """Create a new payment for the order"""
415
416         order = self.browse(cr, uid, order_id, context)
417         if order.invoice_wanted and not order.partner_id:
418             raise osv.except_osv("Error", "Cannot create invoice without a partner.")
419
420         args = {
421             'order_id': order_id,
422             'journal_id': data['journal'],
423             'amount': data['amount'],
424             'payment_id': data['payment_id'],
425             }
426
427         if 'payment_date' in data.keys():
428             args['payment_date'] = data['payment_date']
429         if 'payment_name' in data.keys():
430             args['payment_name'] = data['payment_name']
431         if 'payment_nb' in data.keys():
432             args['payment_nb'] = data['payment_nb']
433
434         payment_id = self.pool.get('pos.payment').create(cr, uid, args )
435
436         wf_service = netsvc.LocalService("workflow")
437         wf_service.trg_validate(uid, 'pos.order', order_id, 'payment', cr)
438         wf_service.trg_write(uid, 'pos.order', order_id, cr)
439         return payment_id
440
441     def add_product(self, cr, uid, order_id, product_id, qty, context=None):
442         """Create a new order line the order"""
443         line_obj = self.pool.get('pos.order.line')
444         values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
445
446         pricelist = values['pricelist_id'] and values['pricelist_id'][0]
447         product = values['partner_id'] and values['partner_id'][0]
448
449         price = line_obj.price_by_product(cr, uid, [],
450                 pricelist, product_id, qty, product)
451
452         order_line_id = line_obj.create(cr, uid, {
453             'order_id': order_id,
454             'product_id': product_id,
455             'qty': qty,
456             'price_unit': price,
457             })
458         wf_service = netsvc.LocalService("workflow")
459         wf_service.trg_write(uid, 'pos.order', order_id, cr)
460
461         return order_line_id
462
463     def refund(self, cr, uid, ids, context={}):
464         clone_list = []
465         line_obj = self.pool.get('pos.order.line')
466
467         for order in self.browse(cr, uid, ids):
468             clone_id = self.copy(cr, uid, order.id, {
469                 'name': order.name + ' REFUND',
470                 'date_order': time.strftime('%Y-%m-%d'),
471                 'state': 'draft',
472                 'note': 'REFUND\n'+ (order.note or ''),
473                 'invoice_id': False,
474                 'nb_print': 0,
475                 'payments': False,
476                 })
477             clone_list.append(clone_id)
478
479
480         for clone in self.browse(cr, uid, clone_list):
481             for order_line in clone.lines:
482                 line_obj.write(cr, uid, [order_line.id], {
483                     'qty': -order_line.qty
484                     })
485         return clone_list
486
487     def action_invoice(self, cr, uid, ids, context={}):
488         inv_ref = self.pool.get('account.invoice')
489         inv_line_ref = self.pool.get('account.invoice.line')
490         inv_ids = []
491
492         for order in self.browse(cr, uid, ids, context):
493             if order.invoice_id:
494                 inv_ids.append(order.invoice_id.id)
495                 continue
496
497             if not order.partner_id:
498                 raise osv.except_osv('Error', 'Please provide a partner for the sale.')
499
500             inv = {
501                 'name': 'Invoice from POS: '+order.name,
502                 'origin': order.name,
503                 'type': 'out_invoice',
504                 'reference': order.name,
505                 'partner_id': order.partner_id.id,
506                 'comment': order.note or '',
507                 'price_type': 'tax_included'
508             }
509             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
510             inv_id = inv_ref.create(cr, uid, inv, context)
511
512             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
513             inv_ids.append(inv_id)
514
515             for line in order.lines:
516                 inv_line = {
517                     'invoice_id': inv_id,
518                     'product_id': line.product_id.id,
519                     'quantity': line.qty,
520                 }
521                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
522                     line.product_id.id,
523                     line.product_id.uom_id.id,
524                     line.qty, partner_id = order.partner_id.id)['value'])
525                 inv_line['price_unit'] = line.price_unit
526                 inv_line['discount'] = line.discount
527
528                 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
529                     and [(6, 0, inv_line['invoice_line_tax_id'])] or []
530                 inv_line_ref.create(cr, uid, inv_line, context)
531
532         for i in inv_ids:
533             wf_service = netsvc.LocalService("workflow")
534             wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
535         return inv_ids
536
537     def create_account_move(self, cr, uid, ids, context=None):
538         account_move_obj = self.pool.get('account.move')
539         account_move_line_obj = self.pool.get('account.move.line')
540         account_period_obj = self.pool.get('account.period')
541         account_tax_obj = self.pool.get('account.tax')
542         period = account_period_obj.find(cr, uid, context=context)[0]
543
544         for order in self.browse(cr, uid, ids, context=context):
545
546             to_reconcile = []
547             group_tax = {}
548
549             if order.amount_total > 0:
550                 order_account = order.sale_journal.default_credit_account_id.id
551             else:
552                 order_account = order.sale_journal.default_debit_account_id.id
553
554             # Create an entry for the sale
555             move_id = account_move_obj.create(cr, uid, {
556                 'journal_id': order.sale_journal.id,
557                 'period_id': period,
558                 }, context=context)
559
560             # Create an move for each order line
561             for line in order.lines:
562
563                 tax_amount = 0
564                 taxes = [t for t in line.product_id.taxes_id]
565                 computed_taxes = account_tax_obj.compute_inv(
566                     cr, uid, taxes, line.price_unit, line.qty)
567
568                 for tax in computed_taxes:
569                     tax_amount += round(tax['amount'], 2)
570                     group_key = (tax['tax_code_id'],
571                                 tax['base_code_id'],
572                                 tax['account_collected_id'])
573
574                     if group_key in group_tax:
575                         group_tax[group_key] += round(tax['amount'], 2)
576                     else:
577                         group_tax[group_key] = round(tax['amount'], 2)
578
579                 amount = line.price_subtotal - tax_amount
580
581                 # Search for the income account
582                 if  line.product_id.property_account_income.id:
583                     income_account = line.\
584                                     product_id.property_account_income.id
585                 elif line.product_id.categ_id.\
586                         property_account_income_categ.id:
587                     income_account = line.product_id.categ_id.\
588                                     property_account_income_categ.id
589                 else:
590                     raise osv.except_osv('Error !', 'There is no income '\
591                         'account defined for this product: "%s" (id:%d)'\
592                         % (line.product_id.name, line.product_id.id, ))
593
594
595                 # Empty the tax list as long as there is no tax code:
596                 tax_code_id = False
597                 tax_amount = 0
598                 while computed_taxes:
599                     tax = computed_taxes.pop(0)
600                     if amount > 0:
601                         tax_code_id = tax['base_code_id']
602                         tax_amount = line.price_subtotal * tax['base_sign']
603                     else:
604                         tax_code_id = tax['ref_base_code_id']
605                         tax_amount = line.price_subtotal * tax['ref_base_sign']
606                     # If there is one we stop
607                     if tax_code_id:
608                         break
609
610                 # Create a move for the line
611                 account_move_line_obj.create(cr, uid, {
612                     'name': order.name,
613                     'date': order.date_order,
614                     'ref': order.name,
615                     'move_id': move_id,
616                     'account_id': income_account,
617                     'credit': ((amount>0) and amount) or 0.0,
618                     'debit': ((amount<0) and -amount) or 0.0,
619                     'journal_id': order.sale_journal.id,
620                     'period_id': period,
621                     'tax_code_id': tax_code_id,
622                     'tax_amount': tax_amount,
623                 }, context=context)
624
625                 # For each remaining tax with a code, whe create a move line
626                 for tax in computed_taxes:
627                     if amount > 0:
628                         tax_code_id = tax['base_code_id']
629                         tax_amount = line.price_subtotal * tax['base_sign']
630                     else:
631                         tax_code_id = tax['ref_base_code_id']
632                         tax_amount = line.price_subtotal * tax['ref_base_sign']
633                     if not tax_code_id:
634                         continue
635
636                     account_move_line_obj.create(cr, uid, {
637                         'name': order.name,
638                         'date': order.date_order,
639                         'ref': order.name,
640                         'move_id': move_id,
641                         'account_id': income_account,
642                         'credit': 0.0,
643                         'debit': 0.0,
644                         'journal_id': order.sale_journal.id,
645                         'period_id': period,
646                         'tax_code_id': tax_code_id,
647                         'tax_amount': tax_amount,
648                     }, context=context)
649
650
651             # Create a move for each tax group
652             (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
653             for key, amount in group_tax.items():
654                 account_move_line_obj.create(cr, uid, {
655                     'name': order.name,
656                     'date': order.date_order,
657                     'ref': order.name,
658                     'move_id': move_id,
659                     'account_id': key[account_pos],
660                     'credit': ((amount>0) and amount) or 0.0,
661                     'debit': ((amount<0) and -amount) or 0.0,
662                     'journal_id': order.sale_journal.id,
663                     'period_id': period,
664                     'tax_code_id': key[tax_code_pos],
665                     'tax_amount': amount,
666                 }, context=context)
667
668             # counterpart
669             to_reconcile.append(account_move_line_obj.create(cr, uid, {
670                 'name': order.name,
671                 'date': order.date_order,
672                 'ref': order.name,
673                 'move_id': move_id,
674                 'account_id': order_account,
675                 'credit': ((order.amount_total<0) and -order.amount_total)\
676                     or 0.0,
677                 'debit': ((order.amount_total>0) and order.amount_total)\
678                     or 0.0,
679                 'journal_id': order.sale_journal.id,
680                 'period_id': period,
681             }, context=context))
682
683
684             # search the account receivable for the payments:
685             account_receivable = order.sale_journal.default_credit_account_id.id
686             if not account_receivable:
687                 raise  osv.except_osv('Error !',
688                     'There is no receivable account defined for this journal:'\
689                     ' "%s" (id:%d)' % (order.sale_journal.name, order.sale_journal.id, ))
690
691             for payment in order.payments:
692
693                 if payment.amount > 0:
694                     payment_account = \
695                         payment.journal_id.default_debit_account_id.id
696                 else:
697                     payment_account = \
698                         payment.journal_id.default_credit_account_id.id
699
700                 if payment.amount > 0:
701                     order_account = \
702                         order.sale_journal.default_credit_account_id.id
703                 else:
704                     order_account = \
705                         order.sale_journal.default_debit_account_id.id
706
707                 # Create one entry for the payment
708                 payment_move_id = account_move_obj.create(cr, uid, {
709                     'journal_id': payment.journal_id.id,
710                     'period_id': period,
711                 }, context=context)
712                 account_move_line_obj.create(cr, uid, {
713                     'name': order.name,
714                     'date': order.date_order,
715                     'ref': order.name,
716                     'move_id': payment_move_id,
717                     'account_id': payment_account,
718                     'credit': ((payment.amount<0) and -payment.amount) or 0.0,
719                     'debit': ((payment.amount>0) and payment.amount) or 0.0,
720                     'journal_id': payment.journal_id.id,
721                     'period_id': period,
722                 }, context=context)
723                 to_reconcile.append(account_move_line_obj.create(cr, uid, {
724                     'name': order.name,
725                     'date': order.date_order,
726                     'ref': order.name,
727                     'move_id': payment_move_id,
728                     'account_id': order_account,
729                     'credit': ((payment.amount>0) and payment.amount) or 0.0,
730                     'debit': ((payment.amount<0) and -payment.amount) or 0.0,
731                     'journal_id': payment.journal_id.id,
732                     'period_id': period,
733                 }, context=context))
734
735             account_move_obj.button_validate(cr, uid, [move_id, payment_move_id], context=context)
736             account_move_line_obj.reconcile(cr, uid, to_reconcile, type='manual', context=context)
737         return True
738
739     def action_paid(self, cr, uid, ids, context=None):
740         self.create_picking(cr, uid, ids, context={})
741         self.write(cr, uid, ids, {'state': 'paid'})
742         return True
743
744     def action_cancel(self, cr, uid, ids, context=None):
745         self.cancel_order(cr, uid, ids, context={})
746         self.write(cr, uid, ids, {'state': 'cancel'})
747         return True
748
749     def action_done(self, cr, uid, ids, context=None):
750         self.create_account_move(cr, uid, ids, context={})
751         self.write(cr, uid, ids, {'state': 'done'})
752         return True
753
754 pos_order()
755
756
757 class pos_order_line(osv.osv):
758     _name = "pos.order.line"
759     _description = "Lines of Point of Sale"
760
761     def _amount_line(self, cr, uid, ids, field_name, arg, context):
762         res = {}
763         for line in self.browse(cr, uid, ids):
764             res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
765         return res
766
767     def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
768         if not product_id:
769             return 0.0
770         if not pricelist:
771             raise osv.except_osv('No Pricelist !',
772                 'You have to select a pricelist in the sale form !\n'
773                 'Please set one before choosing a product.')
774
775         price = self.pool.get('product.pricelist').price_get(cr, uid,
776             [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
777         if price is False:
778             raise osv.except_osv('No valid pricelist line found !',
779                 "Couldn't find a pricelist line matching this product"
780                 " and quantity.\nYou have to change either the product,"
781                 " the quantity or the pricelist.")
782         return price
783
784     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
785         price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
786
787         return {'value': {'price_unit': price}}
788
789     _columns = {
790         'name': fields.char('Line Description', size=512),
791         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
792         'price_unit': fields.float('Unit Price', required=True),
793         'qty': fields.float('Quantity'),
794         'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal'),
795         'discount': fields.float('Discount (%)', digits=(16, 2)),
796         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
797         'create_date': fields.datetime('Creation date', readonly=True),
798         }
799
800     _defaults = {
801         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
802         'qty': lambda *a: 1,
803         'discount': lambda *a: 0.0,
804         }
805
806     def create(self, cr, user, vals, context={}):
807         if vals.get('product_id'):
808             return super(pos_order_line, self).create(cr, user, vals, context)
809         return False
810
811     def write(self, cr, user, ids, values, context={}):
812         if 'product_id' in values and not values['product_id']:
813             return False
814         return super(pos_order_line, self).write(cr, user, ids, values, context)
815
816     def _scan_product(self, cr, uid, ean, qty, order):
817         # search pricelist_id
818         pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
819         if not pricelist_id:
820             return False
821
822         new_line = True
823
824         product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
825         if not product_id:
826            return False
827
828         # search price product
829         product = self.pool.get('product.product').read(cr, uid, product_id)
830         product_name = product[0]['name']
831         price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
832
833         order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
834         if order_line_ids:
835             new_line = False
836             order_line_id = order_line_ids[0]
837             qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
838
839         if new_line:
840             vals = {'product_id': product_id[0],
841                     'price_unit': price,
842                     'qty': qty,
843                     'name': product_name,
844                     'order_id': order,
845                    }
846             line_id = self.create(cr, uid, vals)
847             if not line_id:
848                 raise wizard.except_wizard(_('Error'), _('Create line failed !'))
849         else:
850             vals = {
851                 'qty': qty,
852                 'price_unit': price
853             }
854             line_id = self.write(cr, uid, order_line_id, vals)
855             if not line_id:
856                 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
857             line_id = order_line_id
858
859         price_line = float(qty)*float(price)
860         return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
861
862 pos_order_line()
863
864
865 class pos_payment(osv.osv):
866     _name = 'pos.payment'
867     _description = 'Pos Payment'
868
869     def _journal_get(self, cr, uid, context={}):
870         obj = self.pool.get('account.journal')
871         ids = obj.search(cr, uid, [('type', '=', 'cash')])
872         res = obj.read(cr, uid, ids, ['id', 'name'], context)
873         res = [(r['id'], r['name']) for r in res]
874         return res
875
876     def _journal_default(self, cr, uid, context={}):
877         journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
878         if journal_list:
879             return journal_list[0]
880         else:
881             return False
882
883     _columns = {
884         'name': fields.char('Description', size=64),
885         'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
886         'journal_id': fields.many2one('account.journal', "Journal", required=True),
887         'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
888         'payment_nb': fields.char('Piece number', size=32),
889         'payment_name': fields.char('Payment name', size=32),
890         'payment_date': fields.date('Payment date', required=True),
891         'amount': fields.float('Amount', required=True),
892     }
893     _defaults = {
894         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
895         'journal_id': _journal_default,
896         'payment_date':  lambda *a: time.strftime('%Y-%m-%d'),
897     }
898
899     def create(self, cr, user, vals, context={}):
900         if vals.get('journal_id') and vals.get('amount'):
901             return super(pos_payment, self).create(cr, user, vals, context)
902         return False
903
904     def write(self, cr, user, ids, values, context={}):
905         if 'amount' in values and not values['amount']:
906             return False
907         if 'journal_id' in values and not values['journal_id']:
908             return False
909         return super(pos_payment, self).write(cr, user, ids, values, context)
910
911 pos_payment()
912
913
914 class report_transaction_pos(osv.osv):
915     _name = "report.transaction.pos"
916     _description = "transaction for the pos"
917     _auto = False
918     _columns = {
919         'date_create': fields.char('Date', size=16, readonly=True),
920         'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
921         'user_id': fields.many2one('res.users', 'User', readonly=True),
922         'no_trans': fields.float('Number of transaction', readonly=True),
923         'amount': fields.float('Amount', readonly=True),
924         'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
925     }
926
927     def init(self, cr):
928         tools.drop_view_if_exists(cr, 'report_transaction_pos')
929         cr.execute("""
930             create or replace view report_transaction_pos as (
931                 select
932                     min(pp.id) as id,
933                     count(pp.id) as no_trans,
934                     sum(amount) as amount,
935                     pp.journal_id,
936                     date_trunc('day',pp.create_date)::text as date_create,
937                     ps.user_id,
938                     ps.invoice_id
939                 from
940                     pos_payment pp, pos_order ps
941                 WHERE ps.id = pp.order_id
942                 group by
943                     pp.journal_id, date_trunc('day',pp.create_date), ps.user_id, ps.invoice_id
944             )
945             """)
946 report_transaction_pos()
947
948 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
949