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