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 _
30 class pos_config_journal(osv.osv):
31 _name = 'pos.config.journal'
32 _description = "Point of Sale journal configuration."
34 'name': fields.char('Description', size=64),
35 'code': fields.char('Code', size=64),
36 'journal_id': fields.many2one('account.journal', "Journal")
42 class pos_order(osv.osv):
44 _description = "Point of Sale"
45 _order = "date_order, create_date desc"
46 _order = "date_order desc"
48 def unlink(self, cr, uid, ids, context={}):
49 for rec in self.browse(cr, uid, ids, context=context):
50 if rec.state<>'draft':
51 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is already confirmed !'))
52 return super(pos_order, self).unlink(cr, uid, ids, context=context)
54 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
57 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
58 return {'value':{'pricelist_id': pricelist}}
60 def _amount_total(self, cr, uid, ids, field_name, arg, context):
61 id_set = ",".join(map(str, ids))
66 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
69 LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
70 WHERE p.id IN (""" + id_set +""") GROUP BY p.id """)
71 res = dict(cr.fetchall())
73 for rec in self.browse(cr, uid, ids, context):
75 and rec.partner_id.property_account_position \
76 and rec.partner_id.property_account_position.tax_ids:
77 res[rec.id] = res[rec.id] - rec.amount_tax
80 def _amount_tax(self, cr, uid, ids, field_name, arg, context):
82 tax_obj = self.pool.get('account.tax')
83 for order in self.browse(cr, uid, ids):
85 for line in order.lines:
86 val = reduce(lambda x, y: x+round(y['amount'], 2),
87 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
89 (1-(line.discount or 0.0)/100.0), line.qty),
95 def _total_payment(self, cr, uid, ids, field_name, arg, context):
97 for order in self.browse(cr, uid, ids):
99 for payment in order.payments:
100 val += payment.amount
104 def _total_return(self, cr, uid, ids, field_name, arg, context):
106 for order in self.browse(cr, uid, ids):
108 for payment in order.payments:
109 val += (payment.amount < 0 and payment.amount or 0)
113 def payment_get(self, cr, uid, ids, context=None):
114 cr.execute("select id from pos_payment where order_id in (%s)" % \
115 ','.join([str(i) for i in ids]))
116 return [i[0] for i in cr.fetchall()]
118 def _sale_journal_get(self, cr, uid, context):
119 journal_obj = self.pool.get('account.journal')
120 res = journal_obj.search(cr, uid,
121 [('type', '=', 'sale')], limit=1)
127 def _receivable_get(self, cr, uid, context=None):
128 prop_obj = self.pool.get('ir.property')
129 res = prop_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
132 def copy(self, cr, uid, id, default=None, context={}):
140 'account_move': False,
141 'last_out_picking': False,
145 return super(pos_order, self).copy(cr, uid, id, default, context)
148 'name': fields.char('Order Description', size=64, required=True,
149 states={'draft': [('readonly', False)]}, readonly=True),
150 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
151 states={'draft': [('readonly', False)]}, readonly=True),
152 'date_order': fields.date('Date Ordered', readonly=True),
153 'date_validity': fields.date('Validity Date', required=True),
154 'user_id': fields.many2one('res.users', 'Salesman',
156 'amount_tax': fields.function(_amount_tax, method=True, string='Taxes'),
157 'amount_total': fields.function(_amount_total, method=True,
159 'amount_paid': fields.function(_total_payment, 'Paid',
160 states={'draft': [('readonly', False)]}, readonly=True,
162 'amount_return': fields.function(_total_return, 'Returned',
164 'lines': fields.one2many('pos.order.line', 'order_id',
165 'Order Lines', states={'draft': [('readonly', False)]},
167 'payments': fields.one2many('pos.payment', 'order_id',
168 'Order Payments', states={'draft': [('readonly', False)]},
170 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist',
171 required=True, states={'draft': [('readonly', False)]},
173 'partner_id': fields.many2one(
174 'res.partner', 'Partner', change_default=True,
175 states={'draft': [('readonly', False)], 'paid': [('readonly', False)]},
177 'state': fields.selection([('cancel', 'Cancel'), ('draft', 'Draft'),
178 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced')], 'State',
180 'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
181 'account_move': fields.many2one('account.move', 'Account Entry',
183 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking',
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 'state': lambda *a: 'draft',
209 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence')\
210 .get(cr, uid, 'pos.order'),
211 'date_order': lambda *a: time.strftime('%Y-%m-%d'),
212 'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
213 'nb_print': lambda *a: 0,
214 'sale_journal': _sale_journal_get,
215 'account_receivable': _receivable_get,
216 'invoice_wanted': lambda *a: False
219 def test_order_lines(self, cr, uid, order, context={}):
221 raise osv.except_osv("Error", "No order lines defined for this sale.")
223 wf_service = netsvc.LocalService("workflow")
224 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
227 def dummy_button(self, cr, uid, order, context={}):
230 def test_paid(self, cr, uid, ids, context=None):
231 for order in self.browse(cr, uid, ids, context):
232 if order.lines and not order.amount_total:
234 if (not order.lines) or (not order.payments) or \
235 (order.amount_paid != order.amount_total):
239 def _get_qty_differences(self, orders, old_picking):
240 """check if the customer changed the product quantity"""
243 for line in order.lines:
244 order_dict[line.product_id.id] = line
246 # check the quantity differences:
248 for line in old_picking.move_lines:
249 order_line = order_dict.get(line.product_id.id)
252 qty_to_delete_from_original_picking = line.product_qty
253 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
254 elif line.product_qty != order_line.qty:
256 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
257 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
261 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
262 """if the customer changes the product quantity, split the picking in two"""
263 # create a copy of the original picking and adjust the product qty:
264 picking_model = self.pool.get('stock.picking')
266 'note': "Partial picking from customer", # add a note to tell why we create a new picking
267 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
270 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
271 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
273 for line in new_picking.move_lines:
274 p_id = line.product_id.id
275 if p_id in diff_dict:
276 diff = diff_dict[p_id]
279 if deleted: # product has been deleted (customer didn't took it):
280 # delete this product from old picking:
281 for old_line in old_picking.move_lines:
282 if old_line.product_id.id == p_id:
283 old_line.write(cr, uid, [old_line.id], {'state': 'draft'}) # cannot delete if not draft
284 old_line.unlink(cr, uid, [old_line.id], context)
285 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
286 # subtract qty from old picking:
287 for old_line in old_picking.move_lines:
288 if old_line.product_id.id == p_id:
289 old_line.write(cr, uid, [old_line.id], {'product_qty': old_line.product_qty - qty_to_del})
290 # add qty to new picking:
291 line.write(cr, uid, [line.id], {'product_qty': qty_to_del})
292 else: # product hasn't changed (customer took it without any change):
293 # delete this product from new picking:
294 line.unlink(cr, uid, [line.id], context)
296 # delete it in the new picking:
297 line.unlink(cr, uid, [line.id], context)
299 def create_picking(self, cr, uid, ids, context={}):
300 """Create a picking for each order and validate it."""
301 picking_obj = self.pool.get('stock.picking')
303 orders = self.browse(cr, uid, ids, context)
305 if not order.last_out_picking:
307 picking_id = picking_obj.create(cr, uid, {
308 'origin': order.name,
311 'move_type': 'direct',
312 'note': 'POS notes ' + (order.note or ""),
313 'invoice_state': 'none',
314 'auto_picking': True,
315 'pos_order': order.id,
317 self.write(cr, uid, [order.id], {'last_out_picking': picking_id})
319 picking_id = order.last_out_picking.id
320 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
321 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
324 # split the picking (if product quantity has changed):
325 diff_dict = self._get_qty_differences(orders, picking)
327 self._split_picking(cr, uid, ids, context, picking, diff_dict)
330 for line in order.lines:
331 prop_ids = self.pool.get("ir.property").search(cr, uid,
332 [('name', '=', 'property_stock_customer')])
333 val = self.pool.get("ir.property").browse(cr, uid,
335 location_id = order.shop_id.warehouse_id.lot_stock_id.id
336 stock_dest_id = int(val.split(',')[1])
338 (location_id, stock_dest_id)= (stock_dest_id, location_id)
340 self.pool.get('stock.move').create(cr, uid, {
341 'name': 'Stock move (POS %d)' % (order.id, ),
342 'product_uom': line.product_id.uom_id.id,
343 'product_uos': line.product_id.uom_id.id,
344 'picking_id': picking_id,
345 'product_id': line.product_id.id,
346 'product_uos_qty': abs(line.qty),
347 'product_qty': abs(line.qty),
348 'tracking_id': False,
350 'location_id': location_id,
351 'location_dest_id': stock_dest_id,
354 wf_service = netsvc.LocalService("workflow")
355 wf_service.trg_validate(uid, 'stock.picking',
356 picking_id, 'button_confirm', cr)
357 self.pool.get('stock.picking').force_assign(cr,
358 uid, [picking_id], context)
362 def set_to_draft(self, cr, uid, ids, *args):
366 self.write(cr, uid, ids, {'state': 'draft'})
368 wf_service = netsvc.LocalService("workflow")
370 wf_service.trg_create(uid, 'pos.order', i, cr)
373 def cancel_order(self, cr, uid, ids, context=None):
374 """Cancel each picking with an inverted one."""
376 picking_obj = self.pool.get('stock.picking')
377 stock_move_obj = self.pool.get('stock.move')
378 payment_obj = self.pool.get('pos.payment')
379 picking_ids = picking_obj.search(cr, uid, [('pos_order', 'in', ids), ('state', '=', 'done')])
382 # Copy all the picking and blank the last_out_picking
383 for order in self.browse(cr, uid, ids, context=context):
384 if not order.last_out_picking:
387 clone_id = picking_obj.copy(
388 cr, uid, order.last_out_picking.id, {'type': 'in'})
389 # Confirm the picking
390 wf_service = netsvc.LocalService("workflow")
391 wf_service.trg_validate(uid, 'stock.picking',
392 clone_id, 'button_confirm', cr)
393 clone_list.append(clone_id)
394 # Remove the ref to last picking and delete the payments
395 self.write(cr, uid, ids, {'last_out_picking': False})
396 payment_obj.unlink(cr, uid, [i.id for i in order.payments],
399 # Switch all the moves
400 move_ids = stock_move_obj.search(
401 cr, uid, [('picking_id', '=', clone_id)])
402 for move in stock_move_obj.browse(cr, uid, move_ids, context=context):
403 stock_move_obj.write(
404 cr, uid, move.id, {'location_id': move.location_dest_id.id,
405 'location_dest_id': move.location_id.id})
407 self.pool.get('stock.picking').force_assign(cr,
408 uid, clone_list, context)
412 def add_payment(self, cr, uid, order_id, data, context=None):
413 """Create a new payment for the order"""
415 order = self.browse(cr, uid, order_id, context)
416 if order.invoice_wanted and not order.partner_id:
417 raise osv.except_osv("Error", "Cannot create invoice without a partner.")
420 'order_id': order_id,
421 'journal_id': data['journal'],
422 'amount': data['amount'],
423 'payment_id': data['payment_id'],
426 if 'payment_date' in data.keys():
427 args['payment_date'] = data['payment_date']
428 if 'payment_name' in data.keys():
429 args['payment_name'] = data['payment_name']
430 if 'payment_nb' in data.keys():
431 args['payment_nb'] = data['payment_nb']
433 payment_id = self.pool.get('pos.payment').create(cr, uid, args )
435 wf_service = netsvc.LocalService("workflow")
436 wf_service.trg_validate(uid, 'pos.order', order_id, 'payment', cr)
437 wf_service.trg_write(uid, 'pos.order', order_id, cr)
440 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
441 """Create a new order line the order"""
442 line_obj = self.pool.get('pos.order.line')
443 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
445 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
446 product = values['partner_id'] and values['partner_id'][0]
448 price = line_obj.price_by_product(cr, uid, [],
449 pricelist, product_id, qty, product)
451 order_line_id = line_obj.create(cr, uid, {
452 'order_id': order_id,
453 'product_id': product_id,
457 wf_service = netsvc.LocalService("workflow")
458 wf_service.trg_write(uid, 'pos.order', order_id, cr)
462 def refund(self, cr, uid, ids, context={}):
464 line_obj = self.pool.get('pos.order.line')
466 for order in self.browse(cr, uid, ids):
467 clone_id = self.copy(cr, uid, order.id, {
468 'name': order.name + ' REFUND',
469 'date_order': time.strftime('%Y-%m-%d'),
471 'note': 'REFUND\n'+ (order.note or ''),
476 clone_list.append(clone_id)
479 for clone in self.browse(cr, uid, clone_list):
480 for order_line in clone.lines:
481 line_obj.write(cr, uid, [order_line.id], {
482 'qty': -order_line.qty
486 def action_invoice(self, cr, uid, ids, context={}):
487 inv_ref = self.pool.get('account.invoice')
488 inv_line_ref = self.pool.get('account.invoice.line')
491 for order in self.browse(cr, uid, ids, context):
493 inv_ids.append(order.invoice_id.id)
496 if not order.partner_id:
497 raise osv.except_osv('Error', 'Please provide a partner for the sale.')
500 'name': 'Invoice from POS: '+order.name,
501 'origin': order.name,
502 'type': 'out_invoice',
503 'reference': order.name,
504 'partner_id': order.partner_id.id,
505 'comment': order.note or '',
506 'price_type': 'tax_included'
508 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
509 inv_id = inv_ref.create(cr, uid, inv, context)
511 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
512 inv_ids.append(inv_id)
514 for line in order.lines:
516 'invoice_id': inv_id,
517 'product_id': line.product_id.id,
518 'quantity': line.qty,
520 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
522 line.product_id.uom_id.id,
523 line.qty, partner_id = order.partner_id.id)['value'])
524 inv_line['price_unit'] = line.price_unit
525 inv_line['discount'] = line.discount
527 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
528 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
529 inv_line_ref.create(cr, uid, inv_line, context)
532 wf_service = netsvc.LocalService("workflow")
533 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
536 def create_account_move(self, cr, uid, ids, context=None):
537 account_move_obj = self.pool.get('account.move')
538 account_move_line_obj = self.pool.get('account.move.line')
539 account_period_obj = self.pool.get('account.period')
540 account_tax_obj = self.pool.get('account.tax')
541 period = account_period_obj.find(cr, uid, context=context)[0]
543 for order in self.browse(cr, uid, ids, context=context):
548 if order.amount_total > 0:
549 order_account = order.sale_journal.default_credit_account_id.id
551 order_account = order.sale_journal.default_debit_account_id.id
553 # Create an entry for the sale
554 move_id = account_move_obj.create(cr, uid, {
555 'journal_id': order.sale_journal.id,
559 # Create an move for each order line
560 for line in order.lines:
563 taxes = [t for t in line.product_id.taxes_id]
564 computed_taxes = account_tax_obj.compute_inv(
565 cr, uid, taxes, line.price_unit, line.qty)
567 for tax in computed_taxes:
568 tax_amount += round(tax['amount'], 2)
569 group_key = (tax['tax_code_id'],
571 tax['account_collected_id'])
573 if group_key in group_tax:
574 group_tax[group_key] += round(tax['amount'], 2)
576 group_tax[group_key] = round(tax['amount'], 2)
578 amount = line.price_subtotal - tax_amount
580 # Search for the income account
581 if line.product_id.property_account_income.id:
582 income_account = line.\
583 product_id.property_account_income.id
584 elif line.product_id.categ_id.\
585 property_account_income_categ.id:
586 income_account = line.product_id.categ_id.\
587 property_account_income_categ.id
589 raise osv.except_osv('Error !', 'There is no income '\
590 'account defined for this product: "%s" (id:%d)'\
591 % (line.product_id.name, line.product_id.id, ))
594 # Empty the tax list as long as there is no tax code:
597 while computed_taxes:
598 tax = computed_taxes.pop(0)
600 tax_code_id = tax['base_code_id']
601 tax_amount = line.price_subtotal * tax['base_sign']
603 tax_code_id = tax['ref_base_code_id']
604 tax_amount = line.price_subtotal * tax['ref_base_sign']
605 # If there is one we stop
609 # Create a move for the line
610 account_move_line_obj.create(cr, uid, {
612 'date': order.date_order,
615 'account_id': income_account,
616 'credit': ((amount>0) and amount) or 0.0,
617 'debit': ((amount<0) and -amount) or 0.0,
618 'journal_id': order.sale_journal.id,
620 'tax_code_id': tax_code_id,
621 'tax_amount': tax_amount,
624 # For each remaining tax with a code, whe create a move line
625 for tax in computed_taxes:
627 tax_code_id = tax['base_code_id']
628 tax_amount = line.price_subtotal * tax['base_sign']
630 tax_code_id = tax['ref_base_code_id']
631 tax_amount = line.price_subtotal * tax['ref_base_sign']
635 account_move_line_obj.create(cr, uid, {
637 'date': order.date_order,
640 'account_id': income_account,
643 'journal_id': order.sale_journal.id,
645 'tax_code_id': tax_code_id,
646 'tax_amount': tax_amount,
650 # Create a move for each tax group
651 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
652 for key, amount in group_tax.items():
653 account_move_line_obj.create(cr, uid, {
655 'date': order.date_order,
658 'account_id': key[account_pos],
659 'credit': ((amount>0) and amount) or 0.0,
660 'debit': ((amount<0) and -amount) or 0.0,
661 'journal_id': order.sale_journal.id,
663 'tax_code_id': key[tax_code_pos],
664 'tax_amount': amount,
668 to_reconcile.append(account_move_line_obj.create(cr, uid, {
670 'date': order.date_order,
673 'account_id': order_account,
674 'credit': ((order.amount_total<0) and -order.amount_total)\
676 'debit': ((order.amount_total>0) and order.amount_total)\
678 'journal_id': order.sale_journal.id,
683 # search the account receivable for the payments:
684 account_receivable = order.sale_journal.default_credit_account_id.id
685 if not account_receivable:
686 raise osv.except_osv('Error !',
687 'There is no receivable account defined for this journal:'\
688 ' "%s" (id:%d)' % (order.sale_journal.name, order.sale_journal.id, ))
690 for payment in order.payments:
692 if payment.amount > 0:
694 payment.journal_id.default_debit_account_id.id
697 payment.journal_id.default_credit_account_id.id
699 if payment.amount > 0:
701 order.sale_journal.default_credit_account_id.id
704 order.sale_journal.default_debit_account_id.id
706 # Create one entry for the payment
707 payment_move_id = account_move_obj.create(cr, uid, {
708 'journal_id': payment.journal_id.id,
711 account_move_line_obj.create(cr, uid, {
713 'date': order.date_order,
715 'move_id': payment_move_id,
716 'account_id': payment_account,
717 'credit': ((payment.amount<0) and -payment.amount) or 0.0,
718 'debit': ((payment.amount>0) and payment.amount) or 0.0,
719 'journal_id': payment.journal_id.id,
722 to_reconcile.append(account_move_line_obj.create(cr, uid, {
724 'date': order.date_order,
726 'move_id': payment_move_id,
727 'account_id': order_account,
728 'credit': ((payment.amount>0) and payment.amount) or 0.0,
729 'debit': ((payment.amount<0) and -payment.amount) or 0.0,
730 'journal_id': payment.journal_id.id,
734 account_move_obj.button_validate(cr, uid, [move_id, payment_move_id], context=context)
735 account_move_line_obj.reconcile(cr, uid, to_reconcile, type='manual', context=context)
738 def action_paid(self, cr, uid, ids, context=None):
739 self.create_picking(cr, uid, ids, context={})
740 self.write(cr, uid, ids, {'state': 'paid'})
743 def action_cancel(self, cr, uid, ids, context=None):
744 self.cancel_order(cr, uid, ids, context={})
745 self.write(cr, uid, ids, {'state': 'cancel'})
748 def action_done(self, cr, uid, ids, context=None):
749 self.create_account_move(cr, uid, ids, context={})
750 self.write(cr, uid, ids, {'state': 'done'})
756 class pos_order_line(osv.osv):
757 _name = "pos.order.line"
758 _description = "Lines of Point of Sale"
760 def _amount_line(self, cr, uid, ids, field_name, arg, context):
762 for line in self.browse(cr, uid, ids):
763 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
766 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
770 raise osv.except_osv('No Pricelist !',
771 'You have to select a pricelist in the sale form !\n'
772 'Please set one before choosing a product.')
774 price = self.pool.get('product.pricelist').price_get(cr, uid,
775 [pricelist], product_id, qty or 1.0, partner_id)[pricelist]
777 raise osv.except_osv('No valid pricelist line found !',
778 "Couldn't find a pricelist line matching this product"
779 " and quantity.\nYou have to change either the product,"
780 " the quantity or the pricelist.")
783 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
784 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
786 return {'value': {'price_unit': price}}
789 'name': fields.char('Line Description', size=512),
790 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
791 'price_unit': fields.float('Unit Price', required=True),
792 'qty': fields.float('Quantity'),
793 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal'),
794 'discount': fields.float('Discount (%)', digits=(16, 2)),
795 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
796 'create_date': fields.datetime('Creation date', readonly=True),
800 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
802 'discount': lambda *a: 0.0,
805 def create(self, cr, user, vals, context={}):
806 if vals.get('product_id'):
807 return super(pos_order_line, self).create(cr, user, vals, context)
810 def write(self, cr, user, ids, values, context={}):
811 if 'product_id' in values and not values['product_id']:
813 return super(pos_order_line, self).write(cr, user, ids, values, context)
815 def _scan_product(self, cr, uid, ean, qty, order):
816 # search pricelist_id
817 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
823 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
827 # search price product
828 product = self.pool.get('product.product').read(cr, uid, product_id)
829 product_name = product[0]['name']
830 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
832 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
835 order_line_id = order_line_ids[0]
836 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
839 vals = {'product_id': product_id[0],
842 'name': product_name,
845 line_id = self.create(cr, uid, vals)
847 raise wizard.except_wizard(_('Error'), _('Create line failed !'))
853 line_id = self.write(cr, uid, order_line_id, vals)
855 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
856 line_id = order_line_id
858 price_line = float(qty)*float(price)
859 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
864 class pos_payment(osv.osv):
865 _name = 'pos.payment'
866 _description = 'Pos Payment'
868 def _journal_get(self, cr, uid, context={}):
869 obj = self.pool.get('account.journal')
870 ids = obj.search(cr, uid, [('type', '=', 'cash')])
871 res = obj.read(cr, uid, ids, ['id', 'name'], context)
872 res = [(r['id'], r['name']) for r in res]
875 def _journal_default(self, cr, uid, context={}):
876 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
878 return journal_list[0]
883 'name': fields.char('Description', size=64),
884 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
885 'journal_id': fields.many2one('account.journal', "Journal", required=True),
886 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
887 'payment_nb': fields.char('Piece number', size=32),
888 'payment_name': fields.char('Payment name', size=32),
889 'payment_date': fields.date('Payment date', required=True),
890 'amount': fields.float('Amount', required=True),
893 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
894 'journal_id': _journal_default,
895 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
898 def create(self, cr, user, vals, context={}):
899 if vals.get('journal_id') and vals.get('amount'):
900 return super(pos_payment, self).create(cr, user, vals, context)
903 def write(self, cr, user, ids, values, context={}):
904 if 'amount' in values and not values['amount']:
906 if 'journal_id' in values and not values['journal_id']:
908 return super(pos_payment, self).write(cr, user, ids, values, context)
913 class report_transaction_pos(osv.osv):
914 _name = "report.transaction.pos"
915 _description = "transaction for the pos"
918 'date_create': fields.date('Date', readonly=True),
919 'journal_id': fields.many2one('account.journal', 'Journal', readonly=True),
920 'user_id': fields.many2one('res.users', 'User', readonly=True),
921 'no_trans': fields.float('Number of transaction', readonly=True),
922 'amount': fields.float('Amount', readonly=True),
923 'invoice_id': fields.many2one('account.invoice', 'Invoice', readonly=True),
928 create or replace view report_transaction_pos as (
931 count(pp.id) as no_trans,
932 sum(amount) as amount,
934 date_trunc('day',pp.create_date)::date as date_create,
938 pos_payment pp, pos_order ps
939 WHERE ps.id = pp.order_id
941 pp.journal_id, date_trunc('day',pp.create_date), ps.user_id, ps.invoice_id
944 report_transaction_pos()
946 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: