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 prop_ids = self.pool.get("ir.property").search(cr, uid,
343 [('name', '=', 'property_stock_customer')])
344 val = self.pool.get("ir.property").browse(cr, uid,
346 location_id = order.shop_id.warehouse_id.lot_stock_id.id
347 stock_dest_id = int(val.split(',')[1])
349 (location_id, stock_dest_id)= (stock_dest_id, location_id)
351 self.pool.get('stock.move').create(cr, uid, {
352 'name': 'Stock move (POS %d)' % (order.id, ),
353 'product_uom': line.product_id.uom_id.id,
354 'product_uos': line.product_id.uom_id.id,
355 'picking_id': picking_id,
356 'product_id': line.product_id.id,
357 'product_uos_qty': abs(line.qty),
358 'product_qty': abs(line.qty),
359 'tracking_id': False,
361 'location_id': location_id,
362 'location_dest_id': stock_dest_id,
365 wf_service = netsvc.LocalService("workflow")
366 wf_service.trg_validate(uid, 'stock.picking',
367 picking_id, 'button_confirm', cr)
368 self.pool.get('stock.picking').force_assign(cr,
369 uid, [picking_id], context)
373 def set_to_draft(self, cr, uid, ids, *args):
377 self.write(cr, uid, ids, {'state': 'draft'})
379 wf_service = netsvc.LocalService("workflow")
381 wf_service.trg_create(uid, 'pos.order', i, cr)
384 def cancel_order(self, cr, uid, ids, context=None):
385 """Cancel each picking with an inverted one."""
387 picking_obj = self.pool.get('stock.picking')
388 stock_move_obj = self.pool.get('stock.move')
389 payment_obj = self.pool.get('pos.payment')
390 picking_ids = picking_obj.search(cr, uid, [('pos_order', 'in', ids), ('state', '=', 'done')])
393 # Copy all the picking and blank the last_out_picking
394 for order in self.browse(cr, uid, ids, context=context):
395 if not order.last_out_picking:
398 clone_id = picking_obj.copy(
399 cr, uid, order.last_out_picking.id, {'type': 'in'})
400 # Confirm the picking
401 wf_service = netsvc.LocalService("workflow")
402 wf_service.trg_validate(uid, 'stock.picking',
403 clone_id, 'button_confirm', cr)
404 clone_list.append(clone_id)
405 # Remove the ref to last picking and delete the payments
406 self.write(cr, uid, ids, {'last_out_picking': False})
407 payment_obj.unlink(cr, uid, [i.id for i in order.payments],
410 # Switch all the moves
411 move_ids = stock_move_obj.search(
412 cr, uid, [('picking_id', '=', clone_id)])
413 for move in stock_move_obj.browse(cr, uid, move_ids, context=context):
414 stock_move_obj.write(
415 cr, uid, move.id, {'location_id': move.location_dest_id.id,
416 'location_dest_id': move.location_id.id})
418 self.pool.get('stock.picking').force_assign(cr,
419 uid, clone_list, context)
423 def add_payment(self, cr, uid, order_id, data, context=None):
424 """Create a new payment for the order"""
425 order = self.browse(cr, uid, order_id, context)
426 if order.invoice_wanted and not order.partner_id:
427 raise osv.except_osv(_('Error'), _('Cannot create invoice without a partner.'))
430 'order_id': order_id,
431 'journal_id': data['journal'],
432 'amount': data['amount'],
433 'payment_id': data['payment_id'],
436 if 'payment_date' in data.keys():
437 args['payment_date'] = data['payment_date']
438 if 'payment_name' in data.keys():
439 args['payment_name'] = data['payment_name']
440 if 'payment_nb' in data.keys():
441 args['payment_nb'] = data['payment_nb']
443 payment_id = self.pool.get('pos.payment').create(cr, uid, args )
445 wf_service = netsvc.LocalService("workflow")
446 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
447 wf_service.trg_write(uid, 'pos.order', order_id, cr)
450 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
451 """Create a new order line the order"""
452 line_obj = self.pool.get('pos.order.line')
453 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
455 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
456 product = values['partner_id'] and values['partner_id'][0]
458 price = line_obj.price_by_product(cr, uid, [],
459 pricelist, product_id, qty, product)
461 order_line_id = line_obj.create(cr, uid, {
462 'order_id': order_id,
463 'product_id': product_id,
467 wf_service = netsvc.LocalService("workflow")
468 wf_service.trg_write(uid, 'pos.order', order_id, cr)
472 def refund(self, cr, uid, ids, context={}):
474 line_obj = self.pool.get('pos.order.line')
476 for order in self.browse(cr, uid, ids):
477 clone_id = self.copy(cr, uid, order.id, {
478 'name': order.name + ' REFUND',
479 'date_order': time.strftime('%Y-%m-%d'),
481 'note': 'REFUND\n'+ (order.note or ''),
486 clone_list.append(clone_id)
487 self.write(cr, uid, clone_id, {
488 'partner_id': order.partner_id.id,
491 for clone in self.browse(cr, uid, clone_list):
492 for order_line in clone.lines:
493 line_obj.write(cr, uid, [order_line.id], {
494 'qty': -order_line.qty,
498 def action_invoice(self, cr, uid, ids, context={}):
499 inv_ref = self.pool.get('account.invoice')
500 inv_line_ref = self.pool.get('account.invoice.line')
503 for order in self.browse(cr, uid, ids, context):
505 inv_ids.append(order.invoice_id.id)
508 if not order.partner_id:
509 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
512 'name': 'Invoice from POS: '+order.name,
513 'origin': order.name,
514 'type': 'out_invoice',
515 'reference': order.name,
516 'partner_id': order.partner_id.id,
517 'comment': order.note or '',
518 'price_type': 'tax_included'
520 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
522 if not self.pool.get('res.partner').browse(cr, uid, inv['partner_id']).address:
523 raise osv.except_osv(_('Error'), _('Unable to create invoice (partner has no address).'))
525 inv_id = inv_ref.create(cr, uid, inv, context)
527 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
528 inv_ids.append(inv_id)
530 for line in order.lines:
532 'invoice_id': inv_id,
533 'product_id': line.product_id.id,
534 'quantity': line.qty,
536 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
538 line.product_id.uom_id.id,
539 line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
540 inv_line['price_unit'] = line.price_unit
541 inv_line['discount'] = line.discount
543 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
544 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
545 inv_line_ref.create(cr, uid, inv_line, context)
548 wf_service = netsvc.LocalService("workflow")
549 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
552 def create_account_move(self, cr, uid, ids, context=None):
555 account_move_obj = self.pool.get('account.move')
556 account_move_line_obj = self.pool.get('account.move.line')
557 account_period_obj = self.pool.get('account.period')
558 account_tax_obj = self.pool.get('account.tax')
559 period = account_period_obj.find(cr, uid, context=context)[0]
561 for order in self.browse(cr, uid, ids, context=context):
566 if order.amount_total > 0:
567 order_account = order.sale_journal.default_credit_account_id.id
569 order_account = order.sale_journal.default_debit_account_id.id
571 # Create an entry for the sale
572 move_id = account_move_obj.create(cr, uid, {
573 'journal_id': order.sale_journal.id,
577 # Create an move for each order line
578 for line in order.lines:
581 taxes = [t for t in line.product_id.taxes_id]
582 computed_taxes = account_tax_obj.compute_inv(
583 cr, uid, taxes, line.price_unit, line.qty)
585 for tax in computed_taxes:
586 tax_amount += round(tax['amount'], 2)
587 group_key = (tax['tax_code_id'],
589 tax['account_collected_id'])
591 if group_key in group_tax:
592 group_tax[group_key] += round(tax['amount'], 2)
594 group_tax[group_key] = round(tax['amount'], 2)
596 amount = line.price_subtotal - tax_amount
598 # Search for the income account
599 if line.product_id.property_account_income.id:
600 income_account = line.\
601 product_id.property_account_income.id
602 elif line.product_id.categ_id.\
603 property_account_income_categ.id:
604 income_account = line.product_id.categ_id.\
605 property_account_income_categ.id
607 raise osv.except_osv(_('Error !'), _('There is no income '\
608 'account defined for this product: "%s" (id:%d)') \
609 % (line.product_id.name, line.product_id.id, ))
612 # Empty the tax list as long as there is no tax code:
615 while computed_taxes:
616 tax = computed_taxes.pop(0)
618 tax_code_id = tax['base_code_id']
619 tax_amount = line.price_subtotal * tax['base_sign']
621 tax_code_id = tax['ref_base_code_id']
622 tax_amount = line.price_subtotal * tax['ref_base_sign']
623 # If there is one we stop
627 # Create a move for the line
628 account_move_line_obj.create(cr, uid, {
630 'date': order.date_order,
633 'account_id': income_account,
634 'credit': ((amount>0) and amount) or 0.0,
635 'debit': ((amount<0) and -amount) or 0.0,
636 'journal_id': order.sale_journal.id,
638 'tax_code_id': tax_code_id,
639 'tax_amount': tax_amount,
640 'partner_id' : order.partner_id and order.partner_id.id or False,
643 # For each remaining tax with a code, whe create a move line
644 for tax in computed_taxes:
646 tax_code_id = tax['base_code_id']
647 tax_amount = line.price_subtotal * tax['base_sign']
649 tax_code_id = tax['ref_base_code_id']
650 tax_amount = line.price_subtotal * tax['ref_base_sign']
654 account_move_line_obj.create(cr, uid, {
656 'date': order.date_order,
659 'account_id': income_account,
662 'journal_id': order.sale_journal.id,
664 'tax_code_id': tax_code_id,
665 'tax_amount': tax_amount,
666 'partner_id' : order.partner_id and order.partner_id.id or False,
670 # Create a move for each tax group
671 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
672 for key, amount in group_tax.items():
673 account_move_line_obj.create(cr, uid, {
675 'date': order.date_order,
678 'account_id': key[account_pos],
679 'credit': ((amount>0) and amount) or 0.0,
680 'debit': ((amount<0) and -amount) or 0.0,
681 'journal_id': order.sale_journal.id,
683 'tax_code_id': key[tax_code_pos],
684 'tax_amount': amount,
685 'partner_id' : order.partner_id and order.partner_id.id or False,
689 to_reconcile.append(account_move_line_obj.create(cr, uid, {
691 'date': order.date_order,
694 'account_id': order_account,
695 'credit': ((order.amount_total<0) and -order.amount_total)\
697 'debit': ((order.amount_total>0) and order.amount_total)\
699 'journal_id': order.sale_journal.id,
701 'partner_id' : order.partner_id and order.partner_id.id or False,
705 # search the account receivable for the payments:
706 account_receivable = order.sale_journal.default_credit_account_id.id
707 if not account_receivable:
708 raise osv.except_osv(_('Error !'),
709 _('There is no receivable account defined for this journal:'\
710 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
712 for payment in order.payments:
713 if not payment.journal_id.default_debit_account_id:
714 raise osv.except_osv(_('No Default Debit Account !'),
715 _('You have to define a Default Debit Account for your Financial Journals!\n'))
717 if not payment.journal_id.default_credit_account_id:
718 raise osv.except_osv(_('No Default Credit Account !'),
719 _('You have to define a Default Credit Account for your Financial Journals!\n'))
721 if payment.amount > 0:
722 payment_account = payment.journal_id.default_debit_account_id.id
724 payment_account = payment.journal_id.default_credit_account_id.id
726 if payment.amount > 0:
728 order.sale_journal.default_credit_account_id.id
731 order.sale_journal.default_debit_account_id.id
733 # Create one entry for the payment
734 payment_move_id = account_move_obj.create(cr, uid, {
735 'journal_id': payment.journal_id.id,
738 account_move_line_obj.create(cr, uid, {
740 'date': order.date_order,
742 'move_id': payment_move_id,
743 'account_id': payment_account,
744 'credit': ((payment.amount<0) and -payment.amount) or 0.0,
745 'debit': ((payment.amount>0) and payment.amount) or 0.0,
746 'journal_id': payment.journal_id.id,
748 'partner_id' : order.partner_id and order.partner_id.id or False,
750 to_reconcile.append(account_move_line_obj.create(cr, uid, {
752 'date': order.date_order,
754 'move_id': payment_move_id,
755 'account_id': order_account,
756 'credit': ((payment.amount>0) and payment.amount) or 0.0,
757 'debit': ((payment.amount<0) and -payment.amount) or 0.0,
758 'journal_id': payment.journal_id.id,
760 'partner_id' : order.partner_id and order.partner_id.id or False,
763 account_move_obj.button_validate(cr, uid, [move_id, payment_move_id], context=context)
764 account_move_line_obj.reconcile(cr, uid, to_reconcile, type='manual', context=context)
767 def action_paid(self, cr, uid, ids, context=None):
770 self.create_picking(cr, uid, ids, context=context)
771 self.write(cr, uid, ids, {'state': 'paid'})
774 def action_cancel(self, cr, uid, ids, context=None):
777 self.cancel_order(cr, uid, ids, context=context)
778 self.write(cr, uid, ids, {'state': 'cancel'})
781 def action_done(self, cr, uid, ids, context=None):
784 self.create_account_move(cr, uid, ids, context=context)
785 self.write(cr, uid, ids, {'state': 'done'})
791 class pos_order_line(osv.osv):
792 _name = "pos.order.line"
793 _description = "Lines of Point of Sale"
795 def _amount_line(self, cr, uid, ids, field_name, arg, context):
797 for line in self.browse(cr, uid, ids):
798 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
801 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
805 raise osv.except_osv(_('No Pricelist !'),
806 _('You have to select a pricelist in the sale form !\n' \
807 'Please set one before choosing a product.'))
809 price = self.pool.get('product.pricelist').price_get(cr, uid,
810 [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
812 raise osv.except_osv(_('No valid pricelist line found !'),
813 _("Couldn't find a pricelist line matching this product" \
814 " and quantity.\nYou have to change either the product," \
815 " the quantity or the pricelist."))
818 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
819 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
821 return {'value': {'price_unit': price}}
824 'name': fields.char('Line Description', size=512),
825 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
826 'price_unit': fields.float('Unit Price', required=True),
827 'qty': fields.float('Quantity'),
828 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal'),
829 'discount': fields.float('Discount (%)', digits=(16, 2)),
830 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
831 'create_date': fields.datetime('Creation Date', readonly=True),
835 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
837 'discount': lambda *a: 0.0,
840 def create(self, cr, user, vals, context={}):
841 if vals.get('product_id'):
842 return super(pos_order_line, self).create(cr, user, vals, context)
845 def write(self, cr, user, ids, values, context={}):
846 if 'product_id' in values and not values['product_id']:
848 return super(pos_order_line, self).write(cr, user, ids, values, context)
850 def _scan_product(self, cr, uid, ean, qty, order):
851 # search pricelist_id
852 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
858 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
862 # search price product
863 product = self.pool.get('product.product').read(cr, uid, product_id)
864 product_name = product[0]['name']
865 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
867 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
870 order_line_id = order_line_ids[0]
871 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
874 vals = {'product_id': product_id[0],
877 'name': product_name,
880 line_id = self.create(cr, uid, vals)
882 raise except_wizard(_('Error'), _('Create line failed !'))
888 line_id = self.write(cr, uid, order_line_id, vals)
890 raise except_wizard(_('Error'), _('Modify line failed !'))
891 line_id = order_line_id
893 price_line = float(qty)*float(price)
894 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
896 def unlink(self, cr, uid, ids, context={}):
897 """Allows to delete pos order lines in draft,cancel state"""
898 for rec in self.browse(cr, uid, ids, context=context):
899 if rec.order_id.state not in ['draft','cancel']:
900 raise osv.except_osv(_('Invalid action !'), _('Cannot delete an order line which is %s !')%(rec.order_id.state,))
901 return super(pos_order_line, self).unlink(cr, uid, ids, context=context)
906 class pos_payment(osv.osv):
907 _name = 'pos.payment'
908 _description = 'Pos Payment'
910 def _journal_get(self, cr, uid, context={}):
911 obj = self.pool.get('account.journal')
912 ids = obj.search(cr, uid, [('type', '=', 'cash')])
913 res = obj.read(cr, uid, ids, ['id', 'name'], context)
914 res = [(r['id'], r['name']) for r in res]
917 def _journal_default(self, cr, uid, context={}):
918 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
920 return journal_list[0]
925 'name': fields.char('Description', size=64),
926 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
927 'journal_id': fields.many2one('account.journal', "Journal", required=True),
928 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
929 'payment_nb': fields.char('Piece Number', size=32),
930 'payment_name': fields.char('Payment Name', size=32),
931 'payment_date': fields.date('Payment Date', required=True),
932 'amount': fields.float('Amount', required=True),
935 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
936 'journal_id': _journal_default,
937 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
940 def create(self, cr, user, vals, context={}):
941 if vals.get('journal_id') and vals.get('amount'):
942 return super(pos_payment, self).create(cr, user, vals, context)
945 def write(self, cr, user, ids, values, context={}):
946 if 'amount' in values and not values['amount']:
948 if 'journal_id' in values and not values['journal_id']:
950 return super(pos_payment, self).write(cr, user, ids, values, context)
955 class report_transaction_pos(osv.osv):
956 _name = "report.transaction.pos"
957 _description = "transaction for the pos"
960 'date_create': fields.char('Date', size=16, readonly=True),
961 'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
962 'user_id': fields.many2one('res.users', 'User', readonly=True),
963 'no_trans': fields.float('Number of Transaction', readonly=True),
964 'amount': fields.float('Amount', readonly=True),
965 'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
969 tools.drop_view_if_exists(cr, 'report_transaction_pos')
971 create or replace view report_transaction_pos as (
974 count(pp.id) as no_trans,
975 sum(amount) as amount,
977 to_char(pp.create_date, 'YYYY-MM-DD') as date_create,
981 pos_payment pp, pos_order ps
982 WHERE ps.id = pp.order_id
984 pp.journal_id, date_create, ps.user_id, ps.invoice_id
987 report_transaction_pos()
989 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: