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"
49 _order = "date_order desc, name desc"
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)
57 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
60 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
61 return {'value': {'pricelist_id': pricelist}}
63 def _amount_total(self, cr, uid, ids, field_name, arg, context):
64 id_set = ",".join(map(str, ids))
69 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
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())
76 for rec in self.browse(cr, uid, ids, context):
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
83 def _amount_tax(self, cr, uid, ids, field_name, arg, context):
85 tax_obj = self.pool.get('account.tax')
86 for order in self.browse(cr, uid, ids):
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,
92 (1-(line.discount or 0.0)/100.0), line.qty),
98 def _total_payment(self, cr, uid, ids, field_name, arg, context):
100 for order in self.browse(cr, uid, ids):
102 for payment in order.payments:
103 val += payment.amount
107 def _total_return(self, cr, uid, ids, field_name, arg, context):
109 for order in self.browse(cr, uid, ids):
111 for payment in order.payments:
112 val += (payment.amount < 0 and payment.amount or 0)
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()]
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)
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)
135 def copy(self, cr, uid, id, default=None, context={}):
141 #'partner_id': False,
143 'account_move': False,
144 'last_out_picking': False,
148 return super(pos_order, self).copy(cr, uid, id, default, context)
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,
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)]},
170 'payments': fields.one2many('pos.payment', 'order_id',
171 'Order Payments', states={'draft': [('readonly', False)]},
173 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
174 required=True, states={'draft': [('readonly', False)]},
176 'partner_id': fields.many2one(
177 'res.partner', 'Partner', change_default=True,
178 states={'draft': [('readonly', False)], 'paid': [('readonly', False)]},
180 'state': fields.selection([('cancel', 'Cancel'), ('draft', 'Draft'),
181 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced')], 'State',
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',
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)]},
194 'account_receivable': fields.many2one('account.account',
195 'Default Receivable', required=True, states={'draft': [('readonly', False)]},
197 'invoice_wanted': fields.boolean('Create Invoice')
200 def _journal_default(self, cr, uid, context={}):
201 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
203 return journal_list[0]
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
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(str(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')
307 orders = self.browse(cr, uid, ids, context)
309 if not order.last_out_picking:
311 picking_id = picking_obj.create(cr, uid, {
312 'origin': order.name,
315 'move_type': 'direct',
316 'note': 'POS notes ' + (order.note or ""),
317 'invoice_state': 'none',
318 'auto_picking': True,
319 'pos_order': order.id,
321 self.write(cr, uid, [order.id], {'last_out_picking': picking_id})
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]
328 # split the picking (if product quantity has changed):
329 diff_dict = self._get_qty_differences(orders, picking)
331 self._split_picking(cr, uid, ids, context, picking, diff_dict)
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,
339 location_id = order.shop_id.warehouse_id.lot_stock_id.id
340 stock_dest_id = int(val.split(',')[1])
342 (location_id, stock_dest_id)= (stock_dest_id, location_id)
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,
354 'location_id': location_id,
355 'location_dest_id': stock_dest_id,
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)
366 def set_to_draft(self, cr, uid, ids, *args):
370 self.write(cr, uid, ids, {'state': 'draft'})
372 wf_service = netsvc.LocalService("workflow")
374 wf_service.trg_create(uid, 'pos.order', i, cr)
377 def cancel_order(self, cr, uid, ids, context=None):
378 """Cancel each picking with an inverted one."""
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')])
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:
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],
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})
411 self.pool.get('stock.picking').force_assign(cr,
412 uid, clone_list, context)
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.'))
423 'order_id': order_id,
424 'journal_id': data['journal'],
425 'amount': data['amount'],
426 'payment_id': data['payment_id'],
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']
436 payment_id = self.pool.get('pos.payment').create(cr, uid, args )
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)
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'])
448 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
449 product = values['partner_id'] and values['partner_id'][0]
451 price = line_obj.price_by_product(cr, uid, [],
452 pricelist, product_id, qty, product)
454 order_line_id = line_obj.create(cr, uid, {
455 'order_id': order_id,
456 'product_id': product_id,
460 wf_service = netsvc.LocalService("workflow")
461 wf_service.trg_write(uid, 'pos.order', order_id, cr)
465 def refund(self, cr, uid, ids, context={}):
467 line_obj = self.pool.get('pos.order.line')
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'),
474 'note': 'REFUND\n'+ (order.note or ''),
479 clone_list.append(clone_id)
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,
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')
493 for order in self.browse(cr, uid, ids, context):
495 inv_ids.append(order.invoice_id.id)
498 if not order.partner_id:
499 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
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'
510 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
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).'))
515 inv_id = inv_ref.create(cr, uid, inv, context)
517 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
518 inv_ids.append(inv_id)
520 for line in order.lines:
522 'invoice_id': inv_id,
523 'product_id': line.product_id.id,
524 'quantity': line.qty,
526 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
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
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)
538 wf_service = netsvc.LocalService("workflow")
539 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
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]
549 for order in self.browse(cr, uid, ids, context=context):
554 if order.amount_total > 0:
555 order_account = order.sale_journal.default_credit_account_id.id
557 order_account = order.sale_journal.default_debit_account_id.id
559 # Create an entry for the sale
560 move_id = account_move_obj.create(cr, uid, {
561 'journal_id': order.sale_journal.id,
565 # Create an move for each order line
566 for line in order.lines:
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)
573 for tax in computed_taxes:
574 tax_amount += round(tax['amount'], 2)
575 group_key = (tax['tax_code_id'],
577 tax['account_collected_id'])
579 if group_key in group_tax:
580 group_tax[group_key] += round(tax['amount'], 2)
582 group_tax[group_key] = round(tax['amount'], 2)
584 amount = line.price_subtotal - tax_amount
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
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, ))
600 # Empty the tax list as long as there is no tax code:
603 while computed_taxes:
604 tax = computed_taxes.pop(0)
606 tax_code_id = tax['base_code_id']
607 tax_amount = line.price_subtotal * tax['base_sign']
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
615 # Create a move for the line
616 account_move_line_obj.create(cr, uid, {
618 'date': order.date_order,
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,
626 'tax_code_id': tax_code_id,
627 'tax_amount': tax_amount,
630 # For each remaining tax with a code, whe create a move line
631 for tax in computed_taxes:
633 tax_code_id = tax['base_code_id']
634 tax_amount = line.price_subtotal * tax['base_sign']
636 tax_code_id = tax['ref_base_code_id']
637 tax_amount = line.price_subtotal * tax['ref_base_sign']
641 account_move_line_obj.create(cr, uid, {
643 'date': order.date_order,
646 'account_id': income_account,
649 'journal_id': order.sale_journal.id,
651 'tax_code_id': tax_code_id,
652 'tax_amount': tax_amount,
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, {
661 'date': order.date_order,
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,
669 'tax_code_id': key[tax_code_pos],
670 'tax_amount': amount,
674 to_reconcile.append(account_move_line_obj.create(cr, uid, {
676 'date': order.date_order,
679 'account_id': order_account,
680 'credit': ((order.amount_total<0) and -order.amount_total)\
682 'debit': ((order.amount_total>0) and order.amount_total)\
684 'journal_id': order.sale_journal.id,
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, ))
696 for payment in order.payments:
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'))
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'))
706 if payment.amount > 0:
707 payment_account = payment.journal_id.default_debit_account_id.id
709 payment_account = payment.journal_id.default_credit_account_id.id
711 if payment.amount > 0:
713 order.sale_journal.default_credit_account_id.id
716 order.sale_journal.default_debit_account_id.id
718 # Create one entry for the payment
719 payment_move_id = account_move_obj.create(cr, uid, {
720 'journal_id': payment.journal_id.id,
723 account_move_line_obj.create(cr, uid, {
725 'date': order.date_order,
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,
734 to_reconcile.append(account_move_line_obj.create(cr, uid, {
736 'date': order.date_order,
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,
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)
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'})
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'})
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'})
768 class pos_order_line(osv.osv):
769 _name = "pos.order.line"
770 _description = "Lines of Point of Sale"
772 def _amount_line(self, cr, uid, ids, field_name, arg, context):
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)
778 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
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.'))
786 price = self.pool.get('product.pricelist').price_get(cr, uid,
787 [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
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."))
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)
798 return {'value': {'price_unit': price}}
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),
812 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
814 'discount': lambda *a: 0.0,
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)
822 def write(self, cr, user, ids, values, context={}):
823 if 'product_id' in values and not values['product_id']:
825 return super(pos_order_line, self).write(cr, user, ids, values, context)
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'] )
835 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
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)
844 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
847 order_line_id = order_line_ids[0]
848 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
851 vals = {'product_id': product_id[0],
854 'name': product_name,
857 line_id = self.create(cr, uid, vals)
859 raise except_wizard(_('Error'), _('Create line failed !'))
865 line_id = self.write(cr, uid, order_line_id, vals)
867 raise except_wizard(_('Error'), _('Modify line failed !'))
868 line_id = order_line_id
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 }
876 class pos_payment(osv.osv):
877 _name = 'pos.payment'
878 _description = 'Pos Payment'
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]
887 def _journal_default(self, cr, uid, context={}):
888 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
890 return journal_list[0]
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),
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'),
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)
915 def write(self, cr, user, ids, values, context={}):
916 if 'amount' in values and not values['amount']:
918 if 'journal_id' in values and not values['journal_id']:
920 return super(pos_payment, self).write(cr, user, ids, values, context)
925 class report_transaction_pos(osv.osv):
926 _name = "report.transaction.pos"
927 _description = "transaction for the pos"
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),
939 tools.drop_view_if_exists(cr, 'report_transaction_pos')
941 create or replace view report_transaction_pos as (
944 count(pp.id) as no_trans,
945 sum(amount) as amount,
947 to_char(pp.create_date, 'YYYY-MM-DD') as date_create,
951 pos_payment pp, pos_order ps
952 WHERE ps.id = pp.order_id
954 pp.journal_id, date_create, ps.user_id, ps.invoice_id
957 report_transaction_pos()
959 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: