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