1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
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.
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.
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/>.
21 ##############################################################################
25 from osv import fields, osv
26 from mx import DateTime
27 from tools.translate import _
29 from wizard import except_wizard
30 from decimal import Decimal
33 class pos_config_journal(osv.osv):
34 _name = 'pos.config.journal'
35 _description = "Point of Sale journal configuration."
37 'name': fields.char('Description', size=64),
38 'code': fields.char('Code', size=64),
39 'journal_id': fields.many2one('account.journal', "Journal")
45 class pos_order(osv.osv):
47 _description = "Point of Sale"
48 _order = "date_order, create_date desc"
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)
56 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
59 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
60 return {'value': {'pricelist_id': pricelist}}
62 def _amount_total(self, cr, uid, ids, field_name, arg, context):
63 id_set = ",".join(map(str, ids))
68 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
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())
75 for rec in self.browse(cr, uid, ids, context):
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
82 def _amount_tax(self, cr, uid, ids, field_name, arg, context):
84 tax_obj = self.pool.get('account.tax')
85 for order in self.browse(cr, uid, ids):
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,
91 (1-(line.discount or 0.0)/100.0), line.qty),
97 def _total_payment(self, cr, uid, ids, field_name, arg, context):
99 for order in self.browse(cr, uid, ids):
101 for payment in order.payments:
102 val += payment.amount
106 def _total_return(self, cr, uid, ids, field_name, arg, context):
108 for order in self.browse(cr, uid, ids):
110 for payment in order.payments:
111 val += (payment.amount < 0 and payment.amount or 0)
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()]
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)
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)
134 def copy(self, cr, uid, id, default=None, context={}):
142 'account_move': False,
143 'last_out_picking': False,
147 return super(pos_order, self).copy(cr, uid, id, default, context)
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,
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)]},
169 'payments': fields.one2many('pos.payment', 'order_id',
170 'Order Payments', states={'draft': [('readonly', False)]},
172 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
173 required=True, states={'draft': [('readonly', False)]},
175 'partner_id': fields.many2one(
176 'res.partner', 'Partner', change_default=True,
177 states={'draft': [('readonly', False)], 'paid': [('readonly', False)]},
179 'state': fields.selection([('cancel', 'Cancel'), ('draft', 'Draft'),
180 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced')], 'State',
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',
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)]},
193 'account_receivable': fields.many2one('account.account',
194 'Default Receivable', required=True, states={'draft': [('readonly', False)]},
196 'invoice_wanted': fields.boolean('Create Invoice')
199 def _journal_default(self, cr, uid, context={}):
200 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
202 return journal_list[0]
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
220 def test_order_lines(self, cr, uid, order, context={}):
222 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
224 wf_service = netsvc.LocalService("workflow")
225 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
228 def dummy_button(self, cr, uid, order, context={}):
231 def test_paid(self, cr, uid, ids, context=None):
233 return Decimal("%f" % (val, ))
235 for order in self.browse(cr, uid, ids, context):
236 if order.lines and not order.amount_total:
238 if (not order.lines) or (not order.payments) or \
239 (deci(order.amount_paid) != deci(order.amount_total)):
243 def _get_qty_differences(self, orders, old_picking):
244 """check if the customer changed the product quantity"""
247 for line in order.lines:
248 order_dict[line.product_id.id] = line
250 # check the quantity differences:
252 for line in old_picking.move_lines:
253 order_line = order_dict.get(line.product_id.id)
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:
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)
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')
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
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)
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]
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)
300 # delete it in the new picking:
301 line.unlink(context=context)
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')
308 orders = self.browse(cr, uid, ids, context)
310 if not order.last_out_picking:
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,
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
325 self.write(cr, uid, [order.id], {'last_out_picking': picking_id})
327 picking_id = order.last_out_picking.id
328 picking_obj.write(cr, uid, [picking_id], {
329 'auto_picking': True,
330 'invoice_state': '2binvoiced',
332 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
335 # split the picking (if product quantity has changed):
336 diff_dict = self._get_qty_differences(orders, picking)
338 self._split_picking(cr, uid, ids, context, picking, diff_dict)
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,
347 location_id = order.shop_id.warehouse_id.lot_stock_id.id
348 stock_dest_id = int(val.split(',')[1])
350 (location_id, stock_dest_id)= (stock_dest_id, location_id)
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,
362 'location_id': location_id,
363 'location_dest_id': stock_dest_id,
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)
374 def set_to_draft(self, cr, uid, ids, *args):
378 self.write(cr, uid, ids, {'state': 'draft'})
380 wf_service = netsvc.LocalService("workflow")
382 wf_service.trg_create(uid, 'pos.order', i, cr)
385 def cancel_order(self, cr, uid, ids, context=None):
386 """Cancel each picking with an inverted one."""
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')])
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:
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],
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})
419 self.pool.get('stock.picking').force_assign(cr,
420 uid, clone_list, context)
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.'))
431 'order_id': order_id,
432 'journal_id': data['journal'],
433 'amount': data['amount'],
434 'payment_id': data['payment_id'],
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']
444 payment_id = self.pool.get('pos.payment').create(cr, uid, args )
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)
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'])
456 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
457 product = values['partner_id'] and values['partner_id'][0]
459 price = line_obj.price_by_product(cr, uid, [],
460 pricelist, product_id, qty, product)
462 order_line_id = line_obj.create(cr, uid, {
463 'order_id': order_id,
464 'product_id': product_id,
468 wf_service = netsvc.LocalService("workflow")
469 wf_service.trg_write(uid, 'pos.order', order_id, cr)
473 def refund(self, cr, uid, ids, context={}):
475 line_obj = self.pool.get('pos.order.line')
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'),
482 'note': 'REFUND\n'+ (order.note or ''),
487 clone_list.append(clone_id)
488 self.write(cr, uid, clone_id, {
489 'partner_id': order.partner_id.id,
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,
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')
504 for order in self.browse(cr, uid, ids, context):
506 inv_ids.append(order.invoice_id.id)
509 if not order.partner_id:
510 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
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'
521 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
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).'))
526 inv_id = inv_ref.create(cr, uid, inv, context)
528 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
529 inv_ids.append(inv_id)
531 for line in order.lines:
533 'invoice_id': inv_id,
534 'product_id': line.product_id.id,
535 'quantity': line.qty,
537 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
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
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)
549 wf_service = netsvc.LocalService("workflow")
550 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
553 def create_account_move(self, cr, uid, ids, context=None):
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]
562 for order in self.browse(cr, uid, ids, context=context):
567 if order.amount_total > 0:
568 order_account = order.sale_journal.default_credit_account_id.id
570 order_account = order.sale_journal.default_debit_account_id.id
572 # Create an entry for the sale
573 move_id = account_move_obj.create(cr, uid, {
574 'journal_id': order.sale_journal.id,
578 # Create an move for each order line
579 for line in order.lines:
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)
586 for tax in computed_taxes:
587 tax_amount += round(tax['amount'], 2)
588 group_key = (tax['tax_code_id'],
590 tax['account_collected_id'])
592 if group_key in group_tax:
593 group_tax[group_key] += round(tax['amount'], 2)
595 group_tax[group_key] = round(tax['amount'], 2)
597 amount = line.price_subtotal - tax_amount
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
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, ))
613 # Empty the tax list as long as there is no tax code:
616 while computed_taxes:
617 tax = computed_taxes.pop(0)
619 tax_code_id = tax['base_code_id']
620 tax_amount = line.price_subtotal * tax['base_sign']
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
628 # Create a move for the line
629 account_move_line_obj.create(cr, uid, {
631 'date': order.date_order,
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,
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,
644 # For each remaining tax with a code, whe create a move line
645 for tax in computed_taxes:
647 tax_code_id = tax['base_code_id']
648 tax_amount = line.price_subtotal * tax['base_sign']
650 tax_code_id = tax['ref_base_code_id']
651 tax_amount = line.price_subtotal * tax['ref_base_sign']
655 account_move_line_obj.create(cr, uid, {
657 'date': order.date_order,
660 'account_id': income_account,
663 'journal_id': order.sale_journal.id,
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,
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, {
676 'date': order.date_order,
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,
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,
690 to_reconcile.append(account_move_line_obj.create(cr, uid, {
692 'date': order.date_order,
695 'account_id': order_account,
696 'credit': ((order.amount_total<0) and -order.amount_total)\
698 'debit': ((order.amount_total>0) and order.amount_total)\
700 'journal_id': order.sale_journal.id,
702 'partner_id' : order.partner_id and order.partner_id.id or False,
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, ))
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'))
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'))
722 if payment.amount > 0:
723 payment_account = payment.journal_id.default_debit_account_id.id
725 payment_account = payment.journal_id.default_credit_account_id.id
727 if payment.amount > 0:
729 order.sale_journal.default_credit_account_id.id
732 order.sale_journal.default_debit_account_id.id
734 # Create one entry for the payment
735 payment_move_id = account_move_obj.create(cr, uid, {
736 'journal_id': payment.journal_id.id,
739 account_move_line_obj.create(cr, uid, {
741 'date': order.date_order,
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,
749 'partner_id' : order.partner_id and order.partner_id.id or False,
751 to_reconcile.append(account_move_line_obj.create(cr, uid, {
753 'date': order.date_order,
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,
761 'partner_id' : order.partner_id and order.partner_id.id or False,
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)
768 def action_paid(self, cr, uid, ids, context=None):
771 self.create_picking(cr, uid, ids, context=context)
772 self.write(cr, uid, ids, {'state': 'paid'})
775 def action_cancel(self, cr, uid, ids, context=None):
778 self.cancel_order(cr, uid, ids, context=context)
779 self.write(cr, uid, ids, {'state': 'cancel'})
782 def action_done(self, cr, uid, ids, context=None):
785 self.create_account_move(cr, uid, ids, context=context)
786 self.write(cr, uid, ids, {'state': 'done'})
792 class pos_order_line(osv.osv):
793 _name = "pos.order.line"
794 _description = "Lines of Point of Sale"
796 def _amount_line(self, cr, uid, ids, field_name, arg, context):
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)
802 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
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.'))
810 price = self.pool.get('product.pricelist').price_get(cr, uid,
811 [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
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."))
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)
822 return {'value': {'price_unit': price}}
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),
836 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
838 'discount': lambda *a: 0.0,
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)
846 def write(self, cr, user, ids, values, context={}):
847 if 'product_id' in values and not values['product_id']:
849 return super(pos_order_line, self).write(cr, user, ids, values, context)
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'] )
859 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
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)
868 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
871 order_line_id = order_line_ids[0]
872 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
875 vals = {'product_id': product_id[0],
878 'name': product_name,
881 line_id = self.create(cr, uid, vals)
883 raise except_wizard(_('Error'), _('Create line failed !'))
889 line_id = self.write(cr, uid, order_line_id, vals)
891 raise except_wizard(_('Error'), _('Modify line failed !'))
892 line_id = order_line_id
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 }
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)
907 class pos_payment(osv.osv):
908 _name = 'pos.payment'
909 _description = 'Pos Payment'
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]
918 def _journal_default(self, cr, uid, context={}):
919 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
921 return journal_list[0]
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),
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'),
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)
946 def write(self, cr, user, ids, values, context={}):
947 if 'amount' in values and not values['amount']:
949 if 'journal_id' in values and not values['journal_id']:
951 return super(pos_payment, self).write(cr, user, ids, values, context)
956 class report_transaction_pos(osv.osv):
957 _name = "report.transaction.pos"
958 _description = "transaction for the pos"
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),
970 tools.drop_view_if_exists(cr, 'report_transaction_pos')
972 create or replace view report_transaction_pos as (
975 count(pp.id) as no_trans,
976 sum(amount) as amount,
978 to_char(pp.create_date, 'YYYY-MM-DD') as date_create,
982 pos_payment pp, pos_order ps
983 WHERE ps.id = pp.order_id
985 pp.journal_id, date_create, ps.user_id, ps.invoice_id
988 report_transaction_pos()
990 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: