[FIX]: fix a problem Point of sale create outgoing shipments incl. service items
[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                     if line.product_id.type != 'service':
343                         prop_ids = self.pool.get("ir.property").search(cr, uid,
344                                 [('name', '=', 'property_stock_customer')])
345                         val = self.pool.get("ir.property").browse(cr, uid,
346                                 prop_ids[0]).value
347                         location_id = order.shop_id.warehouse_id.lot_stock_id.id
348                         stock_dest_id = int(val.split(',')[1])
349                         if line.qty < 0:
350                             (location_id, stock_dest_id)= (stock_dest_id, location_id)
351
352                         self.pool.get('stock.move').create(cr, uid, {
353                             'name': 'Stock move (POS %d)' % (order.id, ),
354                             'product_uom': line.product_id.uom_id.id,
355                             'product_uos': line.product_id.uom_id.id,
356                             'picking_id': picking_id,
357                             'product_id': line.product_id.id,
358                             'product_uos_qty': abs(line.qty),
359                             'product_qty': abs(line.qty),
360                             'tracking_id': False,
361                             'state': 'waiting',
362                             'location_id': location_id,
363                             'location_dest_id': stock_dest_id,
364                         })
365
366             wf_service = netsvc.LocalService("workflow")
367             wf_service.trg_validate(uid, 'stock.picking',
368                     picking_id, 'button_confirm', cr)
369             self.pool.get('stock.picking').force_assign(cr,
370                     uid, [picking_id], context)
371
372         return True
373
374     def set_to_draft(self, cr, uid, ids, *args):
375         if not len(ids):
376             return False
377
378         self.write(cr, uid, ids, {'state': 'draft'})
379
380         wf_service = netsvc.LocalService("workflow")
381         for i in ids:
382             wf_service.trg_create(uid, 'pos.order', i, cr)
383         return True
384
385     def cancel_order(self, cr, uid, ids, context=None):
386         """Cancel each picking with an inverted one."""
387
388         picking_obj = self.pool.get('stock.picking')
389         stock_move_obj = self.pool.get('stock.move')
390         payment_obj = self.pool.get('pos.payment')
391         picking_ids = picking_obj.search(cr, uid, [('pos_order', 'in', ids), ('state', '=', 'done')])
392         clone_list = []
393
394         # Copy all the picking and blank the last_out_picking
395         for order in self.browse(cr, uid, ids, context=context):
396             if not order.last_out_picking:
397                 continue
398
399             clone_id = picking_obj.copy(
400                 cr, uid, order.last_out_picking.id, {'type': 'in'})
401             # Confirm the picking
402             wf_service = netsvc.LocalService("workflow")
403             wf_service.trg_validate(uid, 'stock.picking',
404                 clone_id, 'button_confirm', cr)
405             clone_list.append(clone_id)
406             # Remove the ref to last picking and delete the payments
407             self.write(cr, uid, ids, {'last_out_picking': False})
408             payment_obj.unlink(cr, uid, [i.id for i in order.payments],
409                 context=context)
410
411             # Switch all the moves
412             move_ids = stock_move_obj.search(
413                 cr, uid, [('picking_id', '=', clone_id)])
414             for move in stock_move_obj.browse(cr, uid, move_ids, context=context):
415                 stock_move_obj.write(
416                     cr, uid, move.id, {'location_id': move.location_dest_id.id,
417                                     'location_dest_id': move.location_id.id})
418
419         self.pool.get('stock.picking').force_assign(cr,
420             uid, clone_list, context)
421
422         return True
423
424     def add_payment(self, cr, uid, order_id, data, context=None):
425         """Create a new payment for the order"""
426         order = self.browse(cr, uid, order_id, context)
427         if order.invoice_wanted and not order.partner_id:
428             raise osv.except_osv(_('Error'), _('Cannot create invoice without a partner.'))
429
430         args = {
431             'order_id': order_id,
432             'journal_id': data['journal'],
433             'amount': data['amount'],
434             'payment_id': data['payment_id'],
435             }
436
437         if 'payment_date' in data.keys():
438             args['payment_date'] = data['payment_date']
439         if 'payment_name' in data.keys():
440             args['payment_name'] = data['payment_name']
441         if 'payment_nb' in data.keys():
442             args['payment_nb'] = data['payment_nb']
443
444         payment_id = self.pool.get('pos.payment').create(cr, uid, args )
445
446         wf_service = netsvc.LocalService("workflow")
447         wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
448         wf_service.trg_write(uid, 'pos.order', order_id, cr)
449         return payment_id
450
451     def add_product(self, cr, uid, order_id, product_id, qty, context=None):
452         """Create a new order line the order"""
453         line_obj = self.pool.get('pos.order.line')
454         values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
455
456         pricelist = values['pricelist_id'] and values['pricelist_id'][0]
457         product = values['partner_id'] and values['partner_id'][0]
458
459         price = line_obj.price_by_product(cr, uid, [],
460                 pricelist, product_id, qty, product)
461
462         order_line_id = line_obj.create(cr, uid, {
463             'order_id': order_id,
464             'product_id': product_id,
465             'qty': qty,
466             'price_unit': price,
467             })
468         wf_service = netsvc.LocalService("workflow")
469         wf_service.trg_write(uid, 'pos.order', order_id, cr)
470
471         return order_line_id
472
473     def refund(self, cr, uid, ids, context={}):
474         clone_list = []
475         line_obj = self.pool.get('pos.order.line')
476
477         for order in self.browse(cr, uid, ids):
478             clone_id = self.copy(cr, uid, order.id, {
479                 'name': order.name + ' REFUND',
480                 'date_order': time.strftime('%Y-%m-%d'),
481                 'state': 'draft',
482                 'note': 'REFUND\n'+ (order.note or ''),
483                 'invoice_id': False,
484                 'nb_print': 0,
485                 'payments': False,
486                 })
487             clone_list.append(clone_id)
488             self.write(cr, uid, clone_id, {
489                 'partner_id': order.partner_id.id,
490             })
491
492         for clone in self.browse(cr, uid, clone_list):
493             for order_line in clone.lines:
494                 line_obj.write(cr, uid, [order_line.id], {
495                     'qty': -order_line.qty,
496                     })
497         return clone_list
498
499     def action_invoice(self, cr, uid, ids, context={}):
500         inv_ref = self.pool.get('account.invoice')
501         inv_line_ref = self.pool.get('account.invoice.line')
502         inv_ids = []
503
504         for order in self.browse(cr, uid, ids, context):
505             if order.invoice_id:
506                 inv_ids.append(order.invoice_id.id)
507                 continue
508
509             if not order.partner_id:
510                 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
511
512             inv = {
513                 'name': 'Invoice from POS: '+order.name,
514                 'origin': order.name,
515                 'type': 'out_invoice',
516                 'reference': order.name,
517                 'partner_id': order.partner_id.id,
518                 'comment': order.note or '',
519                 'price_type': 'tax_included'
520             }
521             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
522
523             if not self.pool.get('res.partner').browse(cr, uid, inv['partner_id']).address:
524                 raise osv.except_osv(_('Error'), _('Unable to create invoice (partner has no address).'))
525
526             inv_id = inv_ref.create(cr, uid, inv, context)
527
528             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
529             inv_ids.append(inv_id)
530
531             for line in order.lines:
532                 inv_line = {
533                     'invoice_id': inv_id,
534                     'product_id': line.product_id.id,
535                     'quantity': line.qty,
536                 }
537                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
538                     line.product_id.id,
539                     line.product_id.uom_id.id,
540                     line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
541                 inv_line['price_unit'] = line.price_unit
542                 inv_line['discount'] = line.discount
543
544                 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
545                     and [(6, 0, inv_line['invoice_line_tax_id'])] or []
546                 inv_line_ref.create(cr, uid, inv_line, context)
547
548         for i in inv_ids:
549             wf_service = netsvc.LocalService("workflow")
550             wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
551         return inv_ids
552
553     def create_account_move(self, cr, uid, ids, context=None):
554         if context is None:
555             context = {}
556         account_move_obj = self.pool.get('account.move')
557         account_move_line_obj = self.pool.get('account.move.line')
558         account_period_obj = self.pool.get('account.period')
559         account_tax_obj = self.pool.get('account.tax')
560         period = account_period_obj.find(cr, uid, context=context)[0]
561
562         for order in self.browse(cr, uid, ids, context=context):
563
564             to_reconcile = []
565             group_tax = {}
566
567             if order.amount_total > 0:
568                 order_account = order.sale_journal.default_credit_account_id.id
569             else:
570                 order_account = order.sale_journal.default_debit_account_id.id
571
572             # Create an entry for the sale
573             move_id = account_move_obj.create(cr, uid, {
574                 'journal_id': order.sale_journal.id,
575                 'period_id': period,
576                 }, context=context)
577
578             # Create an move for each order line
579             for line in order.lines:
580
581                 tax_amount = 0
582                 taxes = [t for t in line.product_id.taxes_id]
583                 computed_taxes = account_tax_obj.compute_inv(
584                     cr, uid, taxes, line.price_unit, line.qty)
585
586                 for tax in computed_taxes:
587                     tax_amount += round(tax['amount'], 2)
588                     group_key = (tax['tax_code_id'],
589                                 tax['base_code_id'],
590                                 tax['account_collected_id'])
591
592                     if group_key in group_tax:
593                         group_tax[group_key] += round(tax['amount'], 2)
594                     else:
595                         group_tax[group_key] = round(tax['amount'], 2)
596
597                 amount = line.price_subtotal - tax_amount
598
599                 # Search for the income account
600                 if  line.product_id.property_account_income.id:
601                     income_account = line.\
602                                     product_id.property_account_income.id
603                 elif line.product_id.categ_id.\
604                         property_account_income_categ.id:
605                     income_account = line.product_id.categ_id.\
606                                     property_account_income_categ.id
607                 else:
608                     raise osv.except_osv(_('Error !'), _('There is no income '\
609                         'account defined for this product: "%s" (id:%d)') \
610                         % (line.product_id.name, line.product_id.id, ))
611
612
613                 # Empty the tax list as long as there is no tax code:
614                 tax_code_id = False
615                 tax_amount = 0
616                 while computed_taxes:
617                     tax = computed_taxes.pop(0)
618                     if amount > 0:
619                         tax_code_id = tax['base_code_id']
620                         tax_amount = line.price_subtotal * tax['base_sign']
621                     else:
622                         tax_code_id = tax['ref_base_code_id']
623                         tax_amount = line.price_subtotal * tax['ref_base_sign']
624                     # If there is one we stop
625                     if tax_code_id:
626                         break
627
628                 # Create a move for the line
629                 account_move_line_obj.create(cr, uid, {
630                     'name': order.name,
631                     'date': order.date_order,
632                     'ref': order.name,
633                     'move_id': move_id,
634                     'account_id': income_account,
635                     'credit': ((amount>0) and amount) or 0.0,
636                     'debit': ((amount<0) and -amount) or 0.0,
637                     'journal_id': order.sale_journal.id,
638                     'period_id': period,
639                     'tax_code_id': tax_code_id,
640                     'tax_amount': tax_amount,
641                     'partner_id' : order.partner_id and order.partner_id.id or False,
642                 }, context=context)
643
644                 # For each remaining tax with a code, whe create a move line
645                 for tax in computed_taxes:
646                     if amount > 0:
647                         tax_code_id = tax['base_code_id']
648                         tax_amount = line.price_subtotal * tax['base_sign']
649                     else:
650                         tax_code_id = tax['ref_base_code_id']
651                         tax_amount = line.price_subtotal * tax['ref_base_sign']
652                     if not tax_code_id:
653                         continue
654
655                     account_move_line_obj.create(cr, uid, {
656                         'name': order.name,
657                         'date': order.date_order,
658                         'ref': order.name,
659                         'move_id': move_id,
660                         'account_id': income_account,
661                         'credit': 0.0,
662                         'debit': 0.0,
663                         'journal_id': order.sale_journal.id,
664                         'period_id': period,
665                         'tax_code_id': tax_code_id,
666                         'tax_amount': tax_amount,
667                         'partner_id' : order.partner_id and order.partner_id.id or False,
668                     }, context=context)
669
670
671             # Create a move for each tax group
672             (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
673             for key, amount in group_tax.items():
674                 account_move_line_obj.create(cr, uid, {
675                     'name': order.name,
676                     'date': order.date_order,
677                     'ref': order.name,
678                     'move_id': move_id,
679                     'account_id': key[account_pos],
680                     'credit': ((amount>0) and amount) or 0.0,
681                     'debit': ((amount<0) and -amount) or 0.0,
682                     'journal_id': order.sale_journal.id,
683                     'period_id': period,
684                     'tax_code_id': key[tax_code_pos],
685                     'tax_amount': amount,
686                     'partner_id' : order.partner_id and order.partner_id.id or False,
687                 }, context=context)
688
689             # counterpart
690             to_reconcile.append(account_move_line_obj.create(cr, uid, {
691                 'name': order.name,
692                 'date': order.date_order,
693                 'ref': order.name,
694                 'move_id': move_id,
695                 'account_id': order_account,
696                 'credit': ((order.amount_total<0) and -order.amount_total)\
697                     or 0.0,
698                 'debit': ((order.amount_total>0) and order.amount_total)\
699                     or 0.0,
700                 'journal_id': order.sale_journal.id,
701                 'period_id': period,
702                 'partner_id' : order.partner_id and order.partner_id.id or False,
703             }, context=context))
704
705
706             # search the account receivable for the payments:
707             account_receivable = order.sale_journal.default_credit_account_id.id
708             if not account_receivable:
709                 raise  osv.except_osv(_('Error !'),
710                     _('There is no receivable account defined for this journal:'\
711                     ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
712
713             for payment in order.payments:
714                 if not payment.journal_id.default_debit_account_id:
715                     raise osv.except_osv(_('No Default Debit Account !'),
716                         _('You have to define a Default Debit Account for your Financial Journals!\n'))
717
718                 if not payment.journal_id.default_credit_account_id:
719                     raise osv.except_osv(_('No Default Credit Account !'),
720                         _('You have to define a Default Credit Account for your Financial Journals!\n'))
721
722                 if payment.amount > 0:
723                     payment_account = payment.journal_id.default_debit_account_id.id
724                 else:
725                     payment_account = payment.journal_id.default_credit_account_id.id
726
727                 if payment.amount > 0:
728                     order_account = \
729                         order.sale_journal.default_credit_account_id.id
730                 else:
731                     order_account = \
732                         order.sale_journal.default_debit_account_id.id
733
734                 # Create one entry for the payment
735                 payment_move_id = account_move_obj.create(cr, uid, {
736                     'journal_id': payment.journal_id.id,
737                     'period_id': period,
738                 }, context=context)
739                 account_move_line_obj.create(cr, uid, {
740                     'name': order.name,
741                     'date': order.date_order,
742                     'ref': order.name,
743                     'move_id': payment_move_id,
744                     'account_id': payment_account,
745                     'credit': ((payment.amount<0) and -payment.amount) or 0.0,
746                     'debit': ((payment.amount>0) and payment.amount) or 0.0,
747                     'journal_id': payment.journal_id.id,
748                     'period_id': period,
749                     'partner_id' : order.partner_id and order.partner_id.id or False,
750                 }, context=context)
751                 to_reconcile.append(account_move_line_obj.create(cr, uid, {
752                     'name': order.name,
753                     'date': order.date_order,
754                     'ref': order.name,
755                     'move_id': payment_move_id,
756                     'account_id': order_account,
757                     'credit': ((payment.amount>0) and payment.amount) or 0.0,
758                     'debit': ((payment.amount<0) and -payment.amount) or 0.0,
759                     'journal_id': payment.journal_id.id,
760                     'period_id': period,
761                     'partner_id' : order.partner_id and order.partner_id.id or False,
762                 }, context=context))
763
764             account_move_obj.button_validate(cr, uid, [move_id, payment_move_id], context=context)
765             account_move_line_obj.reconcile(cr, uid, to_reconcile, type='manual', context=context)
766         return True
767
768     def action_paid(self, cr, uid, ids, context=None):
769         if context is None:
770             context = {}
771         self.create_picking(cr, uid, ids, context=context)
772         self.write(cr, uid, ids, {'state': 'paid'})
773         return True
774
775     def action_cancel(self, cr, uid, ids, context=None):
776         if context is None:
777             context = {}
778         self.cancel_order(cr, uid, ids, context=context)
779         self.write(cr, uid, ids, {'state': 'cancel'})
780         return True
781
782     def action_done(self, cr, uid, ids, context=None):
783         if context is None:
784             context = {}
785         self.create_account_move(cr, uid, ids, context=context)
786         self.write(cr, uid, ids, {'state': 'done'})
787         return True
788
789 pos_order()
790
791
792 class pos_order_line(osv.osv):
793     _name = "pos.order.line"
794     _description = "Lines of Point of Sale"
795
796     def _amount_line(self, cr, uid, ids, field_name, arg, context):
797         res = {}
798         for line in self.browse(cr, uid, ids):
799             res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
800         return res
801
802     def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
803         if not product_id:
804             return 0.0
805         if not pricelist:
806             raise osv.except_osv(_('No Pricelist !'),
807                 _('You have to select a pricelist in the sale form !\n' \
808                 'Please set one before choosing a product.'))
809
810         price = self.pool.get('product.pricelist').price_get(cr, uid,
811             [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
812         if price is False:
813             raise osv.except_osv(_('No valid pricelist line found !'),
814                 _("Couldn't find a pricelist line matching this product" \
815                 " and quantity.\nYou have to change either the product," \
816                 " the quantity or the pricelist."))
817         return price
818
819     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
820         price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
821
822         return {'value': {'price_unit': price}}
823
824     _columns = {
825         'name': fields.char('Line Description', size=512),
826         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
827         'price_unit': fields.float('Unit Price', required=True),
828         'qty': fields.float('Quantity'),
829         'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal'),
830         'discount': fields.float('Discount (%)', digits=(16, 2)),
831         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
832         'create_date': fields.datetime('Creation Date', readonly=True),
833         }
834
835     _defaults = {
836         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
837         'qty': lambda *a: 1,
838         'discount': lambda *a: 0.0,
839         }
840
841     def create(self, cr, user, vals, context={}):
842         if vals.get('product_id'):
843             return super(pos_order_line, self).create(cr, user, vals, context)
844         return False
845
846     def write(self, cr, user, ids, values, context={}):
847         if 'product_id' in values and not values['product_id']:
848             return False
849         return super(pos_order_line, self).write(cr, user, ids, values, context)
850
851     def _scan_product(self, cr, uid, ean, qty, order):
852         # search pricelist_id
853         pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
854         if not pricelist_id:
855             return False
856
857         new_line = True
858
859         product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
860         if not product_id:
861             return False
862
863         # search price product
864         product = self.pool.get('product.product').read(cr, uid, product_id)
865         product_name = product[0]['name']
866         price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
867
868         order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
869         if order_line_ids:
870             new_line = False
871             order_line_id = order_line_ids[0]
872             qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
873
874         if new_line:
875             vals = {'product_id': product_id[0],
876                     'price_unit': price,
877                     'qty': qty,
878                     'name': product_name,
879                     'order_id': order,
880                    }
881             line_id = self.create(cr, uid, vals)
882             if not line_id:
883                 raise except_wizard(_('Error'), _('Create line failed !'))
884         else:
885             vals = {
886                 'qty': qty,
887                 'price_unit': price
888             }
889             line_id = self.write(cr, uid, order_line_id, vals)
890             if not line_id:
891                 raise except_wizard(_('Error'), _('Modify line failed !'))
892             line_id = order_line_id
893
894         price_line = float(qty)*float(price)
895         return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
896     
897     def unlink(self, cr, uid, ids, context={}):
898         """Allows to delete pos order lines in draft,cancel state"""
899         for rec in self.browse(cr, uid, ids, context=context):
900             if rec.order_id.state not in ['draft','cancel']:
901                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete an order line which is %s !')%(rec.order_id.state,))
902         return super(pos_order_line, self).unlink(cr, uid, ids, context=context)
903     
904 pos_order_line()
905
906
907 class pos_payment(osv.osv):
908     _name = 'pos.payment'
909     _description = 'Pos Payment'
910
911     def _journal_get(self, cr, uid, context={}):
912         obj = self.pool.get('account.journal')
913         ids = obj.search(cr, uid, [('type', '=', 'cash')])
914         res = obj.read(cr, uid, ids, ['id', 'name'], context)
915         res = [(r['id'], r['name']) for r in res]
916         return res
917
918     def _journal_default(self, cr, uid, context={}):
919         journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
920         if journal_list:
921             return journal_list[0]
922         else:
923             return False
924
925     _columns = {
926         'name': fields.char('Description', size=64),
927         'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
928         'journal_id': fields.many2one('account.journal', "Journal", required=True),
929         'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
930         'payment_nb': fields.char('Piece Number', size=32),
931         'payment_name': fields.char('Payment Name', size=32),
932         'payment_date': fields.date('Payment Date', required=True),
933         'amount': fields.float('Amount', required=True),
934     }
935     _defaults = {
936         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
937         'journal_id': _journal_default,
938         'payment_date':  lambda *a: time.strftime('%Y-%m-%d'),
939     }
940
941     def create(self, cr, user, vals, context={}):
942         if vals.get('journal_id') and vals.get('amount'):
943             return super(pos_payment, self).create(cr, user, vals, context)
944         return False
945
946     def write(self, cr, user, ids, values, context={}):
947         if 'amount' in values and not values['amount']:
948             return False
949         if 'journal_id' in values and not values['journal_id']:
950             return False
951         return super(pos_payment, self).write(cr, user, ids, values, context)
952
953 pos_payment()
954
955
956 class report_transaction_pos(osv.osv):
957     _name = "report.transaction.pos"
958     _description = "transaction for the pos"
959     _auto = False
960     _columns = {
961         'date_create': fields.char('Date', size=16, readonly=True),
962         'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
963         'user_id': fields.many2one('res.users', 'User', readonly=True),
964         'no_trans': fields.float('Number of Transaction', readonly=True),
965         'amount': fields.float('Amount', readonly=True),
966         'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
967     }
968
969     def init(self, cr):
970         tools.drop_view_if_exists(cr, 'report_transaction_pos')
971         cr.execute("""
972             create or replace view report_transaction_pos as (
973                 select
974                     min(pp.id) as id,
975                     count(pp.id) as no_trans,
976                     sum(amount) as amount,
977                     pp.journal_id,
978                     to_char(pp.create_date, 'YYYY-MM-DD') as date_create,
979                     ps.user_id,
980                     ps.invoice_id
981                 from
982                     pos_payment pp, pos_order ps
983                 WHERE ps.id = pp.order_id
984                 group by
985                     pp.journal_id, date_create, ps.user_id, ps.invoice_id
986             )
987             """)
988 report_transaction_pos()
989
990 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
991