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 _
31 class pos_config_journal(osv.osv):
32 _name = 'pos.config.journal'
33 _description = "Point of Sale journal configuration."
35 'name': fields.char('Description', size=64),
36 'code': fields.char('Code', size=64),
37 'journal_id': fields.many2one('account.journal', "Journal")
43 class pos_order(osv.osv):
45 _description = "Point of Sale"
46 _order = "date_order, create_date desc"
47 _order = "date_order desc"
49 def unlink(self, cr, uid, ids, context={}):
50 for rec in self.browse(cr, uid, ids, context=context):
51 if rec.state<>'draft':
52 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is already confirmed !'))
53 return super(pos_order, self).unlink(cr, uid, ids, context=context)
55 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
58 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
59 return {'value':{'pricelist_id': pricelist}}
61 def _amount_total(self, cr, uid, ids, field_name, arg, context):
62 id_set = ",".join(map(str, ids))
67 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
70 LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
71 WHERE p.id IN (""" + id_set +""") GROUP BY p.id """)
72 res = dict(cr.fetchall())
74 for rec in self.browse(cr, uid, ids, context):
76 and rec.partner_id.property_account_position \
77 and rec.partner_id.property_account_position.tax_ids:
78 res[rec.id] = res[rec.id] - rec.amount_tax
81 def _amount_tax(self, cr, uid, ids, field_name, arg, context):
83 tax_obj = self.pool.get('account.tax')
84 for order in self.browse(cr, uid, ids):
86 for line in order.lines:
87 val = reduce(lambda x, y: x+round(y['amount'], 2),
88 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
90 (1-(line.discount or 0.0)/100.0), line.qty),
96 def _total_payment(self, cr, uid, ids, field_name, arg, context):
98 for order in self.browse(cr, uid, ids):
100 for payment in order.payments:
101 val += payment.amount
105 def _total_return(self, cr, uid, ids, field_name, arg, context):
107 for order in self.browse(cr, uid, ids):
109 for payment in order.payments:
110 val += (payment.amount < 0 and payment.amount or 0)
114 def payment_get(self, cr, uid, ids, context=None):
115 cr.execute("select id from pos_payment where order_id in (%s)" % \
116 ','.join([str(i) for i in ids]))
117 return [i[0] for i in cr.fetchall()]
119 def _sale_journal_get(self, cr, uid, context):
120 journal_obj = self.pool.get('account.journal')
121 res = journal_obj.search(cr, uid,
122 [('type', '=', 'sale')], limit=1)
128 def _receivable_get(self, cr, uid, context=None):
129 prop_obj = self.pool.get('ir.property')
130 res = prop_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
133 def copy(self, cr, uid, id, default=None, context={}):
141 'account_move': False,
142 'last_out_picking': False,
146 return super(pos_order, self).copy(cr, uid, id, default, context)
149 'name': fields.char('Order Description', size=64, required=True,
150 states={'draft': [('readonly', False)]}, readonly=True),
151 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
152 states={'draft': [('readonly', False)]}, readonly=True),
153 'date_order': fields.date('Date Ordered', readonly=True),
154 'date_validity': fields.date('Validity Date', required=True),
155 'user_id': fields.many2one('res.users', 'Salesman',
157 'amount_tax': fields.function(_amount_tax, method=True, string='Taxes'),
158 'amount_total': fields.function(_amount_total, method=True,
160 'amount_paid': fields.function(_total_payment, 'Paid',
161 states={'draft': [('readonly', False)]}, readonly=True,
163 'amount_return': fields.function(_total_return, 'Returned',
165 'lines': fields.one2many('pos.order.line', 'order_id',
166 'Order Lines', states={'draft': [('readonly', False)]},
168 'payments': fields.one2many('pos.payment', 'order_id',
169 'Order Payments', states={'draft': [('readonly', False)]},
171 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
172 required=True, states={'draft': [('readonly', False)]},
174 'partner_id': fields.many2one(
175 'res.partner', 'Partner', change_default=True,
176 states={'draft': [('readonly', False)], 'paid': [('readonly', False)]},
178 'state': fields.selection([('cancel', 'Cancel'), ('draft', 'Draft'),
179 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced')], 'State',
181 'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
182 'account_move': fields.many2one('account.move', 'Account Entry',
184 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking',
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'),
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):
232 for order in self.browse(cr, uid, ids, context):
233 if order.lines and not order.amount_total:
235 if (not order.lines) or (not order.payments) or \
236 (order.amount_paid != order.amount_total):
240 def _get_qty_differences(self, orders, old_picking):
241 """check if the customer changed the product quantity"""
244 for line in order.lines:
245 order_dict[line.product_id.id] = line
247 # check the quantity differences:
249 for line in old_picking.move_lines:
250 order_line = order_dict.get(line.product_id.id)
253 qty_to_delete_from_original_picking = line.product_qty
254 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
255 elif line.product_qty != order_line.qty:
257 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
258 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
262 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
263 """if the customer changes the product quantity, split the picking in two"""
264 # create a copy of the original picking and adjust the product qty:
265 picking_model = self.pool.get('stock.picking')
267 'note': "Partial picking from customer", # add a note to tell why we create a new picking
268 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
271 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
272 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
274 for line in new_picking.move_lines:
275 p_id = line.product_id.id
276 if p_id in diff_dict:
277 diff = diff_dict[p_id]
280 if deleted: # product has been deleted (customer didn't took it):
281 # delete this product from old picking:
282 for old_line in old_picking.move_lines:
283 if old_line.product_id.id == p_id:
284 old_line.write(cr, uid, [old_line.id], {'state': 'draft'}) # cannot delete if not draft
285 old_line.unlink(cr, uid, [old_line.id], context)
286 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
287 # subtract qty from old picking:
288 for old_line in old_picking.move_lines:
289 if old_line.product_id.id == p_id:
290 old_line.write(cr, uid, [old_line.id], {'product_qty': old_line.product_qty - qty_to_del})
291 # add qty to new picking:
292 line.write(cr, uid, [line.id], {'product_qty': qty_to_del})
293 else: # product hasn't changed (customer took it without any change):
294 # delete this product from new picking:
295 line.unlink(cr, uid, [line.id], context)
297 # delete it in the new picking:
298 line.unlink(cr, uid, [line.id], context)
300 def create_picking(self, cr, uid, ids, context={}):
301 """Create a picking for each order and validate it."""
302 picking_obj = self.pool.get('stock.picking')
304 orders = self.browse(cr, uid, ids, context)
306 if not order.last_out_picking:
308 picking_id = picking_obj.create(cr, uid, {
309 'origin': order.name,
312 'move_type': 'direct',
313 'note': 'POS notes ' + (order.note or ""),
314 'invoice_state': 'none',
315 'auto_picking': True,
316 'pos_order': order.id,
318 self.write(cr, uid, [order.id], {'last_out_picking': picking_id})
320 picking_id = order.last_out_picking.id
321 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
322 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
325 # split the picking (if product quantity has changed):
326 diff_dict = self._get_qty_differences(orders, picking)
328 self._split_picking(cr, uid, ids, context, picking, diff_dict)
331 for line in order.lines:
332 prop_ids = self.pool.get("ir.property").search(cr, uid,
333 [('name', '=', 'property_stock_customer')])
334 val = self.pool.get("ir.property").browse(cr, uid,
336 location_id = order.shop_id.warehouse_id.lot_stock_id.id
337 stock_dest_id = int(val.split(',')[1])
339 (location_id, stock_dest_id)= (stock_dest_id, location_id)
341 self.pool.get('stock.move').create(cr, uid, {
342 'name': 'Stock move (POS %d)' % (order.id, ),
343 'product_uom': line.product_id.uom_id.id,
344 'product_uos': line.product_id.uom_id.id,
345 'picking_id': picking_id,
346 'product_id': line.product_id.id,
347 'product_uos_qty': abs(line.qty),
348 'product_qty': abs(line.qty),
349 'tracking_id': False,
351 'location_id': location_id,
352 'location_dest_id': stock_dest_id,
355 wf_service = netsvc.LocalService("workflow")
356 wf_service.trg_validate(uid, 'stock.picking',
357 picking_id, 'button_confirm', cr)
358 self.pool.get('stock.picking').force_assign(cr,
359 uid, [picking_id], context)
363 def set_to_draft(self, cr, uid, ids, *args):
367 self.write(cr, uid, ids, {'state': 'draft'})
369 wf_service = netsvc.LocalService("workflow")
371 wf_service.trg_create(uid, 'pos.order', i, cr)
374 def cancel_order(self, cr, uid, ids, context=None):
375 """Cancel each picking with an inverted one."""
377 picking_obj = self.pool.get('stock.picking')
378 stock_move_obj = self.pool.get('stock.move')
379 payment_obj = self.pool.get('pos.payment')
380 picking_ids = picking_obj.search(cr, uid, [('pos_order', 'in', ids), ('state', '=', 'done')])
383 # Copy all the picking and blank the last_out_picking
384 for order in self.browse(cr, uid, ids, context=context):
385 if not order.last_out_picking:
388 clone_id = picking_obj.copy(
389 cr, uid, order.last_out_picking.id, {'type': 'in'})
390 # Confirm the picking
391 wf_service = netsvc.LocalService("workflow")
392 wf_service.trg_validate(uid, 'stock.picking',
393 clone_id, 'button_confirm', cr)
394 clone_list.append(clone_id)
395 # Remove the ref to last picking and delete the payments
396 self.write(cr, uid, ids, {'last_out_picking': False})
397 payment_obj.unlink(cr, uid, [i.id for i in order.payments],
400 # Switch all the moves
401 move_ids = stock_move_obj.search(
402 cr, uid, [('picking_id', '=', clone_id)])
403 for move in stock_move_obj.browse(cr, uid, move_ids, context=context):
404 stock_move_obj.write(
405 cr, uid, move.id, {'location_id': move.location_dest_id.id,
406 'location_dest_id': move.location_id.id})
408 self.pool.get('stock.picking').force_assign(cr,
409 uid, clone_list, context)
413 def add_payment(self, cr, uid, order_id, data, context=None):
414 """Create a new payment for the order"""
416 order = self.browse(cr, uid, order_id, context)
417 if order.invoice_wanted and not order.partner_id:
418 raise osv.except_osv("Error", "Cannot create invoice without a partner.")
421 'order_id': order_id,
422 'journal_id': data['journal'],
423 'amount': data['amount'],
424 'payment_id': data['payment_id'],
427 if 'payment_date' in data.keys():
428 args['payment_date'] = data['payment_date']
429 if 'payment_name' in data.keys():
430 args['payment_name'] = data['payment_name']
431 if 'payment_nb' in data.keys():
432 args['payment_nb'] = data['payment_nb']
434 payment_id = self.pool.get('pos.payment').create(cr, uid, args )
436 wf_service = netsvc.LocalService("workflow")
437 wf_service.trg_validate(uid, 'pos.order', order_id, 'payment', cr)
438 wf_service.trg_write(uid, 'pos.order', order_id, cr)
441 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
442 """Create a new order line the order"""
443 line_obj = self.pool.get('pos.order.line')
444 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
446 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
447 product = values['partner_id'] and values['partner_id'][0]
449 price = line_obj.price_by_product(cr, uid, [],
450 pricelist, product_id, qty, product)
452 order_line_id = line_obj.create(cr, uid, {
453 'order_id': order_id,
454 'product_id': product_id,
458 wf_service = netsvc.LocalService("workflow")
459 wf_service.trg_write(uid, 'pos.order', order_id, cr)
463 def refund(self, cr, uid, ids, context={}):
465 line_obj = self.pool.get('pos.order.line')
467 for order in self.browse(cr, uid, ids):
468 clone_id = self.copy(cr, uid, order.id, {
469 'name': order.name + ' REFUND',
470 'date_order': time.strftime('%Y-%m-%d'),
472 'note': 'REFUND\n'+ (order.note or ''),
477 clone_list.append(clone_id)
480 for clone in self.browse(cr, uid, clone_list):
481 for order_line in clone.lines:
482 line_obj.write(cr, uid, [order_line.id], {
483 'qty': -order_line.qty
487 def action_invoice(self, cr, uid, ids, context={}):
488 inv_ref = self.pool.get('account.invoice')
489 inv_line_ref = self.pool.get('account.invoice.line')
492 for order in self.browse(cr, uid, ids, context):
494 inv_ids.append(order.invoice_id.id)
497 if not order.partner_id:
498 raise osv.except_osv('Error', 'Please provide a partner for the sale.')
501 'name': 'Invoice from POS: '+order.name,
502 'origin': order.name,
503 'type': 'out_invoice',
504 'reference': order.name,
505 'partner_id': order.partner_id.id,
506 'comment': order.note or '',
507 'price_type': 'tax_included'
509 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
510 inv_id = inv_ref.create(cr, uid, inv, context)
512 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
513 inv_ids.append(inv_id)
515 for line in order.lines:
517 'invoice_id': inv_id,
518 'product_id': line.product_id.id,
519 'quantity': line.qty,
521 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
523 line.product_id.uom_id.id,
524 line.qty, partner_id = order.partner_id.id)['value'])
525 inv_line['price_unit'] = line.price_unit
526 inv_line['discount'] = line.discount
528 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
529 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
530 inv_line_ref.create(cr, uid, inv_line, context)
533 wf_service = netsvc.LocalService("workflow")
534 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
537 def create_account_move(self, cr, uid, ids, context=None):
538 account_move_obj = self.pool.get('account.move')
539 account_move_line_obj = self.pool.get('account.move.line')
540 account_period_obj = self.pool.get('account.period')
541 account_tax_obj = self.pool.get('account.tax')
542 period = account_period_obj.find(cr, uid, context=context)[0]
544 for order in self.browse(cr, uid, ids, context=context):
549 if order.amount_total > 0:
550 order_account = order.sale_journal.default_credit_account_id.id
552 order_account = order.sale_journal.default_debit_account_id.id
554 # Create an entry for the sale
555 move_id = account_move_obj.create(cr, uid, {
556 'journal_id': order.sale_journal.id,
560 # Create an move for each order line
561 for line in order.lines:
564 taxes = [t for t in line.product_id.taxes_id]
565 computed_taxes = account_tax_obj.compute_inv(
566 cr, uid, taxes, line.price_unit, line.qty)
568 for tax in computed_taxes:
569 tax_amount += round(tax['amount'], 2)
570 group_key = (tax['tax_code_id'],
572 tax['account_collected_id'])
574 if group_key in group_tax:
575 group_tax[group_key] += round(tax['amount'], 2)
577 group_tax[group_key] = round(tax['amount'], 2)
579 amount = line.price_subtotal - tax_amount
581 # Search for the income account
582 if line.product_id.property_account_income.id:
583 income_account = line.\
584 product_id.property_account_income.id
585 elif line.product_id.categ_id.\
586 property_account_income_categ.id:
587 income_account = line.product_id.categ_id.\
588 property_account_income_categ.id
590 raise osv.except_osv('Error !', 'There is no income '\
591 'account defined for this product: "%s" (id:%d)'\
592 % (line.product_id.name, line.product_id.id, ))
595 # Empty the tax list as long as there is no tax code:
598 while computed_taxes:
599 tax = computed_taxes.pop(0)
601 tax_code_id = tax['base_code_id']
602 tax_amount = line.price_subtotal * tax['base_sign']
604 tax_code_id = tax['ref_base_code_id']
605 tax_amount = line.price_subtotal * tax['ref_base_sign']
606 # If there is one we stop
610 # Create a move for the line
611 account_move_line_obj.create(cr, uid, {
613 'date': order.date_order,
616 'account_id': income_account,
617 'credit': ((amount>0) and amount) or 0.0,
618 'debit': ((amount<0) and -amount) or 0.0,
619 'journal_id': order.sale_journal.id,
621 'tax_code_id': tax_code_id,
622 'tax_amount': tax_amount,
625 # For each remaining tax with a code, whe create a move line
626 for tax in computed_taxes:
628 tax_code_id = tax['base_code_id']
629 tax_amount = line.price_subtotal * tax['base_sign']
631 tax_code_id = tax['ref_base_code_id']
632 tax_amount = line.price_subtotal * tax['ref_base_sign']
636 account_move_line_obj.create(cr, uid, {
638 'date': order.date_order,
641 'account_id': income_account,
644 'journal_id': order.sale_journal.id,
646 'tax_code_id': tax_code_id,
647 'tax_amount': tax_amount,
651 # Create a move for each tax group
652 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
653 for key, amount in group_tax.items():
654 account_move_line_obj.create(cr, uid, {
656 'date': order.date_order,
659 'account_id': key[account_pos],
660 'credit': ((amount>0) and amount) or 0.0,
661 'debit': ((amount<0) and -amount) or 0.0,
662 'journal_id': order.sale_journal.id,
664 'tax_code_id': key[tax_code_pos],
665 'tax_amount': amount,
669 to_reconcile.append(account_move_line_obj.create(cr, uid, {
671 'date': order.date_order,
674 'account_id': order_account,
675 'credit': ((order.amount_total<0) and -order.amount_total)\
677 'debit': ((order.amount_total>0) and order.amount_total)\
679 'journal_id': order.sale_journal.id,
684 # search the account receivable for the payments:
685 account_receivable = order.sale_journal.default_credit_account_id.id
686 if not account_receivable:
687 raise osv.except_osv('Error !',
688 'There is no receivable account defined for this journal:'\
689 ' "%s" (id:%d)' % (order.sale_journal.name, order.sale_journal.id, ))
691 for payment in order.payments:
693 if payment.amount > 0:
695 payment.journal_id.default_debit_account_id.id
698 payment.journal_id.default_credit_account_id.id
700 if payment.amount > 0:
702 order.sale_journal.default_credit_account_id.id
705 order.sale_journal.default_debit_account_id.id
707 # Create one entry for the payment
708 payment_move_id = account_move_obj.create(cr, uid, {
709 'journal_id': payment.journal_id.id,
712 account_move_line_obj.create(cr, uid, {
714 'date': order.date_order,
716 'move_id': payment_move_id,
717 'account_id': payment_account,
718 'credit': ((payment.amount<0) and -payment.amount) or 0.0,
719 'debit': ((payment.amount>0) and payment.amount) or 0.0,
720 'journal_id': payment.journal_id.id,
723 to_reconcile.append(account_move_line_obj.create(cr, uid, {
725 'date': order.date_order,
727 'move_id': payment_move_id,
728 'account_id': order_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,
735 account_move_obj.button_validate(cr, uid, [move_id, payment_move_id], context=context)
736 account_move_line_obj.reconcile(cr, uid, to_reconcile, type='manual', context=context)
739 def action_paid(self, cr, uid, ids, context=None):
740 self.create_picking(cr, uid, ids, context={})
741 self.write(cr, uid, ids, {'state': 'paid'})
744 def action_cancel(self, cr, uid, ids, context=None):
745 self.cancel_order(cr, uid, ids, context={})
746 self.write(cr, uid, ids, {'state': 'cancel'})
749 def action_done(self, cr, uid, ids, context=None):
750 self.create_account_move(cr, uid, ids, context={})
751 self.write(cr, uid, ids, {'state': 'done'})
757 class pos_order_line(osv.osv):
758 _name = "pos.order.line"
759 _description = "Lines of Point of Sale"
761 def _amount_line(self, cr, uid, ids, field_name, arg, context):
763 for line in self.browse(cr, uid, ids):
764 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
767 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
771 raise osv.except_osv('No Pricelist !',
772 'You have to select a pricelist in the sale form !\n'
773 'Please set one before choosing a product.')
775 price = self.pool.get('product.pricelist').price_get(cr, uid,
776 [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
778 raise osv.except_osv('No valid pricelist line found !',
779 "Couldn't find a pricelist line matching this product"
780 " and quantity.\nYou have to change either the product,"
781 " the quantity or the pricelist.")
784 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
785 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
787 return {'value': {'price_unit': price}}
790 'name': fields.char('Line Description', size=512),
791 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
792 'price_unit': fields.float('Unit Price', required=True),
793 'qty': fields.float('Quantity'),
794 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal'),
795 'discount': fields.float('Discount (%)', digits=(16, 2)),
796 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
797 'create_date': fields.datetime('Creation Date', readonly=True),
801 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
803 'discount': lambda *a: 0.0,
806 def create(self, cr, user, vals, context={}):
807 if vals.get('product_id'):
808 return super(pos_order_line, self).create(cr, user, vals, context)
811 def write(self, cr, user, ids, values, context={}):
812 if 'product_id' in values and not values['product_id']:
814 return super(pos_order_line, self).write(cr, user, ids, values, context)
816 def _scan_product(self, cr, uid, ean, qty, order):
817 # search pricelist_id
818 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
824 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
828 # search price product
829 product = self.pool.get('product.product').read(cr, uid, product_id)
830 product_name = product[0]['name']
831 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
833 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
836 order_line_id = order_line_ids[0]
837 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
840 vals = {'product_id': product_id[0],
843 'name': product_name,
846 line_id = self.create(cr, uid, vals)
848 raise wizard.except_wizard(_('Error'), _('Create line failed !'))
854 line_id = self.write(cr, uid, order_line_id, vals)
856 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
857 line_id = order_line_id
859 price_line = float(qty)*float(price)
860 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
865 class pos_payment(osv.osv):
866 _name = 'pos.payment'
867 _description = 'Pos Payment'
869 def _journal_get(self, cr, uid, context={}):
870 obj = self.pool.get('account.journal')
871 ids = obj.search(cr, uid, [('type', '=', 'cash')])
872 res = obj.read(cr, uid, ids, ['id', 'name'], context)
873 res = [(r['id'], r['name']) for r in res]
876 def _journal_default(self, cr, uid, context={}):
877 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
879 return journal_list[0]
884 'name': fields.char('Description', size=64),
885 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
886 'journal_id': fields.many2one('account.journal', "Journal", required=True),
887 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
888 'payment_nb': fields.char('Piece Number', size=32),
889 'payment_name': fields.char('Payment Name', size=32),
890 'payment_date': fields.date('Payment Date', required=True),
891 'amount': fields.float('Amount', required=True),
894 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
895 'journal_id': _journal_default,
896 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
899 def create(self, cr, user, vals, context={}):
900 if vals.get('journal_id') and vals.get('amount'):
901 return super(pos_payment, self).create(cr, user, vals, context)
904 def write(self, cr, user, ids, values, context={}):
905 if 'amount' in values and not values['amount']:
907 if 'journal_id' in values and not values['journal_id']:
909 return super(pos_payment, self).write(cr, user, ids, values, context)
914 class report_transaction_pos(osv.osv):
915 _name = "report.transaction.pos"
916 _description = "transaction for the pos"
919 'date_create': fields.char('Date', size=16, readonly=True),
920 'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
921 'user_id': fields.many2one('res.users', 'User', readonly=True),
922 'no_trans': fields.float('Number of Transaction', readonly=True),
923 'amount': fields.float('Amount', readonly=True),
924 'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
928 tools.drop_view_if_exists(cr, 'report_transaction_pos')
930 create or replace view report_transaction_pos as (
933 count(pp.id) as no_trans,
934 sum(amount) as amount,
936 date_trunc('day',pp.create_date)::text as date_create,
940 pos_payment pp, pos_order ps
941 WHERE ps.id = pp.order_id
943 pp.journal_id, date_trunc('day',pp.create_date), ps.user_id, ps.invoice_id
946 report_transaction_pos()
948 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: