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