1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
27 from osv import fields, osv
28 from tools.translate import _
29 from decimal import Decimal
30 import decimal_precision as dp
32 class pos_config_journal(osv.osv):
33 """ Point of Sale journal configuration"""
34 _name = 'pos.config.journal'
35 _description = "Journal Configuration"
38 'name': fields.char('Description', size=64),
39 'code': fields.char('Code', size=64),
40 'journal_id': fields.many2one('account.journal', "Journal")
46 class pos_company_discount(osv.osv):
47 """ Company Discount and Cashboxes """
48 _inherit = 'res.company'
51 'company_discount': fields.float('Max Discount(%)', digits_compute=dp.get_precision('Point Of Sale')),
52 'max_diff': fields.float('Max Difference for Cashboxes', digits_compute=dp.get_precision('Point Of Sale Discount')),
55 pos_company_discount()
57 class pos_order(osv.osv):
58 """ Point of sale gives business owners a convenient way of checking out customers
59 and of recording sales """
62 _description = "Point of Sale"
63 _order = "date_order, create_date desc"
65 def unlink(self, cr, uid, ids, context=None):
66 for rec in self.browse(cr, uid, ids, context=context):
67 for rec_statement in rec.statement_ids:
68 if (rec_statement.statement_id and rec_statement.statement_id.state == 'confirm') or rec.state == 'done':
69 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
70 return super(pos_order, self).unlink(cr, uid, ids, context=context)
72 def onchange_partner_pricelist(self, cr, uid, ids, part=False, context=None):
74 """ Changed price list on_change of partner_id"""
77 pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
78 return {'value': {'pricelist_id': pricelist}}
80 def _amount_total(self, cr, uid, ids, field_name, arg, context=None):
81 """ Calculates amount_tax of order line
82 @param field_names: Names of fields.
83 @return: Dictionary of values """
88 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
91 LEFT OUTER JOIN pos_order_line l ON (p.id = l.order_id)
92 WHERE p.id IN %s GROUP BY p.id """,(tuple(ids),))
93 res = dict(cr.fetchall())
94 for rec in self.browse(cr, uid, ids, context=context):
96 and rec.partner_id.property_account_position \
97 and rec.partner_id.property_account_position.tax_ids:
98 res[rec.id] = res[rec.id] - rec.amount_tax
100 res[rec.id] = res[rec.id] + rec.amount_tax
103 def _get_date_payment2(self, cr, uid, ids, context=None, *a):
104 # Todo need to check this function
105 """ Find payment Date
106 @param field_names: Names of fields.
107 @return: Dictionary of values """
110 for order in self.browse(cr, uid, ids, context=context):
111 cr.execute("SELECT date_payment FROM pos_order WHERE id = %s", (order.id,))
112 date_p = cr.fetchone()
113 date_p = date_p and date_p[0] or None
115 res[order.id] = date_p
117 cr.execute(" SELECT MAX(l.date) "
118 " FROM account_move_line l, account_move m, account_invoice i, account_move_reconcile r, pos_order o "
119 " WHERE i.move_id = m.id AND l.move_id = m.id AND l.reconcile_id = r.id AND o.id = %s AND o.invoice_id = i.id",
122 val = val and val[0] or None
127 def _get_date_payment(self, cr, uid, ids, context, *a):
128 """ Find Validation Date
129 @return: Dictionary of values """
132 for order in self.browse(cr, uid, ids):
133 cr.execute("SELECT date_validation FROM pos_order WHERE id = %s", (order.id,))
134 date_p = cr.fetchone()
135 date_p = date_p and date_p[0] or None
137 res[order.id] = date_p
139 discount_allowed = order.company_id.company_discount
140 for line in order.lines:
141 if line.discount > discount_allowed:
142 return {order.id: None }
143 if order.amount_paid == order.amount_total and not date_p:
144 cr.execute("SELECT MAX(date) FROM account_bank_statement_line WHERE pos_statement_id = %s", (order.id,))
146 val = val and val[0] or None
147 if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
148 for o in order.invoice_id.move_id.line_id:
150 if val < o.date_created:
156 def _amount_all(self, cr, uid, ids, name, args, context=None):
157 tax_obj = self.pool.get('account.tax')
158 cur_obj = self.pool.get('res.currency')
160 for order in self.browse(cr, uid, ids, context=context):
167 cur = order.pricelist_id.currency_id
168 for payment in order.statement_ids:
169 res[order.id]['amount_paid'] += payment.amount
170 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
171 for line in order.lines:
172 val1 += line.price_subtotal_incl
173 if order.price_type != 'tax_excluded':
174 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
175 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
177 (1-(line.discount or 0.0)/100.0), line.qty),
178 res[order.id]['amount_tax'])
179 elif line.qty != 0.0:
180 for c in tax_obj.compute_all(cr, uid, line.product_id.taxes_id, \
181 line.price_unit * (1-(line.discount or 0.0)/100.0), \
182 line.qty, line.product_id, line.order_id.partner_id)['taxes']:
183 val += c.get('amount', 0.0)
184 res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
185 res[order.id]['amount_total'] = res[order.id]['amount_tax'] + cur_obj.round(cr, uid, cur, val1)
188 def _sale_journal_get(self, cr, uid, context=None):
189 """ To get sale journal for this order
191 journal_obj = self.pool.get('account.journal')
192 res = journal_obj.search(cr, uid, [('type', '=', 'sale')], limit=1)
193 return res and res[0] or False
195 def _shop_get(self, cr, uid, context=None):
196 """ To get Shop for this order
198 res = self.pool.get('sale.shop').search(cr, uid, [])
199 return res and res[0] or False
201 def copy(self, cr, uid, id, default=None, context=None):
208 'account_move': False,
214 return super(pos_order, self).copy(cr, uid, id, default, context=context)
216 def _get_v( self, cr, uid, ids, *args):
217 """ Changed the Validation state of order
219 res_obj = self.pool.get('res.users')
220 company_disc = self.browse(cr, uid, ids)
224 comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
226 comp = company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
227 cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount <= %s", (ids[0], comp))
229 cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount > %s", (ids[0], comp))
231 cr.execute("SELECT journal_id FROM account_bank_statement_line WHERE pos_statement_id = %s ", (ids[0], ))
234 cr.execute("SELECT id FROM account_journal WHERE name = '%s' AND special_journal = 't'", (r[0], ))
236 is_special = res3 and res3[0] or None
238 list_jrnl.append(is_special)
239 for order in self.browse(cr, uid, ids):
240 if order.state in ('paid', 'done', 'invoiced') and res and not res2 and not len(list_jrnl):
241 r[order.id] = 'accepted'
245 'name': fields.char('Order Description', size=64, required=True,
246 states={'draft': [('readonly', False)]}, readonly=True),
247 'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
248 'num_sale': fields.char('Internal Note', size=64),
249 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
250 states={'draft': [('readonly', False)]}, readonly=True),
251 'date_order': fields.datetime('Date Ordered', readonly=True, select=True),
252 'date_validation': fields.function(_get_date_payment,
254 string='Validation Date',
255 type='date', select=True, store=True),
256 'date_payment': fields.function(_get_date_payment2, method=True,
257 string='Payment Date',
258 type='date', select=True, store=True),
259 'date_validity': fields.date('Validity Date', required=True),
260 'user_id': fields.many2one('res.users', 'Connected Salesman', help="Person who uses the the cash register. It could be a reliever, a student or an interim employee."),
261 'user_salesman_id': fields.many2one('res.users', 'Cashier', required=True, help="User who is logged into the system."),
262 'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
263 'amount_tax': fields.function(_amount_all, method=True, string='Taxes', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
264 'amount_total': fields.function(_amount_all, method=True, string='Total', multi='all'),
265 'amount_paid': fields.function(_amount_all, string='Paid', states={'draft': [('readonly', False)]}, readonly=True, method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
266 'amount_return': fields.function(_amount_all, 'Returned', method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
267 'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
268 'price_type': fields.selection([
269 ('tax_excluded','Tax excluded')],
270 'Price method', required=True),
271 'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
272 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
273 'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
274 'state': fields.selection([('draft', 'Quotation'),
275 ('payment', 'Payment'),
276 ('advance','Advance'),
279 ('invoiced', 'Invoiced'),
280 ('cancel', 'Cancel')],
281 'State', readonly=True),
282 'invoice_id': fields.many2one('account.invoice', 'Invoice'),
283 'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
284 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
285 'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
286 'first_name': fields.char('First Name', size=64),
287 'note': fields.text('Internal Notes'),
288 'nb_print': fields.integer('Number of Print', readonly=True),
289 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True),
290 'invoice_wanted': fields.boolean('Create Invoice'),
291 'note_2': fields.char('Customer Note', size=64),
292 'type_rec': fields.char('Type of Receipt', size=64),
293 'remboursed': fields.boolean('Remboursed'),
294 'contract_number': fields.char('Contract Number', size=512, select=1),
295 'journal_entry': fields.boolean('Journal Entry'),
298 def _select_pricelist(self, cr, uid, context=None):
299 """ To get default pricelist for the order
300 @param name: Names of fields.
301 @return: pricelist ID
303 res = self.pool.get('sale.shop').search(cr, uid, [], context=context)
305 shop = self.pool.get('sale.shop').browse(cr, uid, res[0], context=context)
306 return shop.pricelist_id and shop.pricelist_id.id or False
309 def _journal_default(self, cr, uid, context=None):
310 """ To get default pricelist for the order
311 @param name: Names of fields.
314 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
315 return journal_list and journal_list[0] or False
318 'user_salesman_id':lambda self, cr, uid, context: uid,
319 'user_id': lambda self, cr, uid, context: uid,
320 'sale_manager': lambda self, cr, uid, context: uid,
322 'price_type': 'tax_excluded',
323 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
324 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
325 'date_validity': lambda *a: (datetime.today() + relativedelta(months=+6)).strftime('%Y-%m-%d'),
327 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
328 'sale_journal': _sale_journal_get,
329 'invoice_wanted': False,
330 'shop_id': _shop_get,
331 'pricelist_id': _select_pricelist,
335 def test_order_lines(self, cr, uid, order, context=None):
336 """ Test order line is created or not for the order
337 @param name: Names of fields.
341 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
343 wf_service = netsvc.LocalService("workflow")
344 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
347 def dummy_button(self, cr, uid, order, context=None):
350 def test_paid(self, cr, uid, ids, context=None):
351 """ Test all amount is paid for this order
354 for order in self.browse(cr, uid, ids, context=context):
355 if order.lines and not order.amount_total:
357 if (not order.lines) or (not order.statement_ids) or \
358 Decimal(str(order.amount_total)) != Decimal(str(order.amount_paid)):
362 def _get_qty_differences(self, orders, old_picking):
363 """check if the customer changed the product quantity """
366 for line in order.lines:
367 order_dict[line.product_id.id] = line
369 # check the quantity differences:
371 for line in old_picking.move_lines:
372 order_line = order_dict.get(line.product_id.id)
375 qty_to_delete_from_original_picking = line.product_qty
376 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
377 elif line.product_qty != order_line.qty:
379 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
380 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
384 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
385 """if the customer changes the product quantity, split the picking in two"""
386 # create a copy of the original picking and adjust the product qty:
387 picking_model = self.pool.get('stock.picking')
389 'note': "Partial picking from customer", # add a note to tell why we create a new picking
390 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
393 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
394 new_picking = picking_model.browse(cr, uid, new_picking_id, context=context)
396 for line in new_picking.move_lines:
397 p_id = line.product_id.id
398 if p_id in diff_dict:
399 diff = diff_dict[p_id]
402 if deleted: # product has been deleted (customer didn't took it):
403 # delete this product from old picking:
404 for old_line in old_picking.move_lines:
405 if old_line.product_id.id == p_id:
406 old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
407 old_line.unlink(context=context)
408 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
409 # subtract qty from old picking:
410 for old_line in old_picking.move_lines:
411 if old_line.product_id.id == p_id:
412 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
413 # add qty to new picking:
414 line.write({'product_qty': qty_to_del}, context=context)
415 else: # product hasn't changed (customer took it without any change):
416 # delete this product from new picking:
417 line.unlink(context=context)
419 # delete it in the new picking:
420 line.unlink(context=context)
422 def create_picking(self, cr, uid, ids, context=None):
423 """Create a picking for each order and validate it."""
424 picking_obj = self.pool.get('stock.picking')
425 property_obj = self.pool.get("ir.property")
426 move_obj = self.pool.get('stock.move')
427 pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
428 orders = self.browse(cr, uid, ids, context=context)
430 if not order.picking_id:
432 picking_id = picking_obj.create(cr, uid, {
434 'origin': order.name,
437 'move_type': 'direct',
438 'note': 'POS notes ' + (order.note or ""),
439 'invoice_state': 'none',
440 'auto_picking': True,
441 'pos_order': order.id,
443 self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
445 picking_id = order.picking_id.id
446 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True}, context=context)
447 picking = picking_obj.browse(cr, uid, [picking_id], context=context)[0]
450 # split the picking (if product quantity has changed):
451 diff_dict = self._get_qty_differences(orders, picking)
453 self._split_picking(cr, uid, ids, context, picking, diff_dict)
456 for line in order.lines:
457 if line.product_id and line.product_id.type == 'service':
459 prop_ids = property_obj.search(cr, uid, [('name', '=', 'property_stock_customer')], context=context)
460 val = property_obj.browse(cr, uid, prop_ids[0], context=context).value_reference
461 cr.execute("SELECT s.id FROM stock_location s, stock_warehouse w WHERE w.lot_stock_id = s.id AND w.id = %s", (order.shop_id.warehouse_id.id, ))
463 location_id = res and res[0] or None
464 stock_dest_id = val.id
466 location_id, stock_dest_id = stock_dest_id, location_id
467 move_obj.create(cr, uid, {
468 'name': '(POS %d)' % (order.id, ),
469 'product_uom': line.product_id.uom_id.id,
470 'product_uos': line.product_id.uom_id.id,
471 'picking_id': picking_id,
472 'product_id': line.product_id.id,
473 'product_uos_qty': abs(line.qty),
474 'product_qty': abs(line.qty),
475 'tracking_id': False,
476 'pos_line_id': line.id,
478 'location_id': location_id,
479 'location_dest_id': stock_dest_id,
480 'prodlot_id': line.prodlot_id and line.prodlot_id.id or False
483 wf_service = netsvc.LocalService("workflow")
484 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
485 picking_obj.force_assign(cr, uid, [picking_id], context)
488 def set_to_draft(self, cr, uid, ids, *args):
489 """ Changes order state to draft
494 self.write(cr, uid, ids, {'state': 'draft'})
495 wf_service = netsvc.LocalService("workflow")
497 wf_service.trg_create(uid, 'pos.order', i, cr)
500 def button_invalidate(self, cr, uid, ids, *args):
501 """ Check the access for the sale order
504 res_obj = self.pool.get('res.company')
506 part_company = res_obj.browse(cr, uid, uid) and res_obj.browse(cr, uid, uid).parent_id and res_obj.browse(cr, uid, uid).parent_id.id or None
508 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
510 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
513 def cancel_order(self, cr, uid, ids, context=None):
514 """ Changes order state to cancel
517 self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
518 self.cancel_picking(cr, uid, ids, context=context)
521 def add_payment(self, cr, uid, order_id, data, context=None):
522 """Create a new payment for the order"""
523 statement_obj = self.pool.get('account.bank.statement')
524 statement_line_obj = self.pool.get('account.bank.statement.line')
525 prod_obj = self.pool.get('product.product')
526 property_obj = self.pool.get('ir.property')
527 curr_c = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
528 curr_company = curr_c.id
529 order = self.browse(cr, uid, order_id, context=context)
530 if not order.num_sale and data['num_sale']:
531 self.write(cr, uid, order_id, {'num_sale': data['num_sale']}, context=context)
534 'amount': data['amount'],
536 if 'payment_date' in data.keys():
537 args['date'] = data['payment_date']
538 if 'payment_name' in data.keys():
539 args['name'] = data['payment_name'] + ' ' + order.name
540 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
541 args['account_id'] = order.partner_id and order.partner_id.property_account_receivable \
542 and order.partner_id.property_account_receivable.id or account_def.id or curr_c.account_receivable.id
543 if data.get('is_acc', False):
544 args['is_acc'] = data['is_acc']
545 args['account_id'] = prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income \
546 and prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income.id
547 if not args['account_id']:
548 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')% \
549 (prod_obj.browse(cr, uid, data['product_id'], context=context).name))
550 args['partner_id'] = order.partner_id and order.partner_id.id or None
551 args['ref'] = order.contract_number or None
553 statement_id = statement_obj.search(cr,uid, [
554 ('journal_id', '=', data['journal']),
555 ('company_id', '=', curr_company),
556 ('user_id', '=', uid),
557 ('state', '=', 'open')], context=context)
558 if len(statement_id) == 0:
559 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
561 statement_id = statement_id[0]
562 args['statement_id'] = statement_id
563 args['pos_statement_id'] = order_id
564 args['journal_id'] = data['journal']
565 args['type'] = 'customer'
566 args['ref'] = order.name
567 statement_line_obj.create(cr, uid, args, context=context)
568 ids_new.append(statement_id)
570 wf_service = netsvc.LocalService("workflow")
571 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
572 wf_service.trg_write(uid, 'pos.order', order_id, cr)
576 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
578 """Create a new order line the order"""
580 line_obj = self.pool.get('pos.order.line')
581 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
583 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
584 product = values['partner_id'] and values['partner_id'][0]
586 price = line_obj.price_by_product(cr, uid, [],
587 pricelist, product_id, qty, product)
589 order_line_id = line_obj.create(cr, uid, {
590 'order_id': order_id,
591 'product_id': product_id,
595 return order_line_id, price
597 def refund(self, cr, uid, ids, context=None):
599 """Create a copy of order for refund order"""
602 line_obj = self.pool.get('pos.order.line')
604 for order in self.browse(cr, uid, ids, context=context):
605 clone_id = self.copy(cr, uid, order.id, {
606 'name': order.name + ' REFUND',
607 'date_order': time.strftime('%Y-%m-%d'),
609 'note': 'REFUND\n'+ (order.note or ''),
612 'statement_ids': False,
614 clone_list.append(clone_id)
617 for clone in self.browse(cr, uid, clone_list, context=context):
618 for order_line in clone.lines:
619 line_obj.write(cr, uid, [order_line.id], {
620 'qty': -order_line.qty
624 def action_invoice(self, cr, uid, ids, context=None):
626 """Create a invoice of order """
628 inv_ref = self.pool.get('account.invoice')
629 inv_line_ref = self.pool.get('account.invoice.line')
630 product_obj = self.pool.get('product.product')
633 for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
635 inv_ids.append(order.invoice_id.id)
638 if not order.partner_id:
639 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
641 acc = order.partner_id.property_account_receivable.id
643 'name': 'Invoice from POS: '+order.name,
644 'origin': order.name,
646 'journal_id': order.sale_journal.id or None,
647 'type': 'out_invoice',
648 'reference': order.name,
649 'partner_id': order.partner_id.id,
650 'comment': order.note or '',
651 'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
653 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
654 if not inv.get('account_id', None):
655 inv['account_id'] = acc
656 inv_id = inv_ref.create(cr, uid, inv, context=context)
658 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
659 inv_ids.append(inv_id)
660 for line in order.lines:
662 'invoice_id': inv_id,
663 'product_id': line.product_id.id,
664 'quantity': line.qty,
666 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
668 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
670 line.product_id.uom_id.id,
671 line.qty, partner_id = order.partner_id.id,
672 fposition_id=order.partner_id.property_account_position.id)['value'])
673 inv_line['price_unit'] = line.price_unit
674 inv_line['discount'] = line.discount
675 inv_line['name'] = inv_name
676 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
677 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
678 inv_line_ref.create(cr, uid, inv_line, context=context)
681 wf_service = netsvc.LocalService("workflow")
682 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
685 def create_account_move(self, cr, uid, ids, context=None):
686 """Create a account move line of order """
687 account_move_obj = self.pool.get('account.move')
688 account_move_line_obj = self.pool.get('account.move.line')
689 account_period_obj = self.pool.get('account.period')
690 account_tax_obj = self.pool.get('account.tax')
691 res_obj=self.pool.get('res.users')
692 property_obj=self.pool.get('ir.property')
693 period = account_period_obj.find(cr, uid, context=context)[0]
695 for order in self.browse(cr, uid, ids, context=context):
696 curr_c = res_obj.browse(cr, uid, uid).company_id
697 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
698 comp_id = comp_id and comp_id.id or False
701 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
703 order_account = order.partner_id and order.partner_id.property_account_receivable and order.partner_id.property_account_receivable.id or account_def or curr_c.account_receivable.id
705 # Create an entry for the sale
706 move_id = account_move_obj.create(cr, uid, {
707 'journal_id': order.sale_journal.id,
711 # Create an move for each order line
712 for line in order.lines:
714 taxes = [t for t in line.product_id.taxes_id]
715 if order.price_type == 'tax_excluded':
716 computed_taxes = account_tax_obj.compute_all(
717 cr, uid, taxes, line.price_unit, line.qty)['taxes']
719 computed_taxes = account_tax_obj.compute_inv(
720 cr, uid, taxes, line.price_unit, line.qty)
722 for tax in computed_taxes:
723 tax_amount += round(tax['amount'], 2)
724 group_key = (tax['tax_code_id'],
726 tax['account_collected_id'])
728 if group_key in group_tax:
729 group_tax[group_key] += round(tax['amount'], 2)
731 group_tax[group_key] = round(tax['amount'], 2)
732 if order.price_type != 'tax_excluded':
733 amount = line.price_subtotal - tax_amount
735 amount = line.price_subtotal
737 # Search for the income account
738 if line.product_id.property_account_income.id:
739 income_account = line.\
740 product_id.property_account_income.id
741 elif line.product_id.categ_id.\
742 property_account_income_categ.id:
743 income_account = line.product_id.categ_id.\
744 property_account_income_categ.id
746 raise osv.except_osv(_('Error !'), _('There is no income '\
747 'account defined for this product: "%s" (id:%d)') \
748 % (line.product_id.name, line.product_id.id, ))
750 # Empty the tax list as long as there is no tax code:
753 while computed_taxes:
754 tax = computed_taxes.pop(0)
756 tax_code_id = tax['base_code_id']
757 tax_amount = line.price_subtotal * tax['base_sign']
759 tax_code_id = tax['ref_base_code_id']
760 tax_amount = line.price_subtotal * tax['ref_base_sign']
761 # If there is one we stop
765 # Create a move for the line
766 account_move_line_obj.create(cr, uid, {
767 'name': "aa"+order.name,
768 'date': order.date_order[:10],
769 'ref': order.contract_number or order.name,
770 'quantity': line.qty,
771 'product_id': line.product_id.id,
773 'account_id': income_account,
774 'company_id': comp_id,
775 'credit': ((amount>0) and amount) or 0.0,
776 'debit': ((amount<0) and -amount) or 0.0,
777 'journal_id': order.sale_journal.id,
779 'tax_code_id': tax_code_id,
780 'tax_amount': tax_amount,
781 'partner_id': order.partner_id and order.partner_id.id or False
784 # For each remaining tax with a code, whe create a move line
785 for tax in computed_taxes:
787 tax_code_id = tax['base_code_id']
788 tax_amount = line.price_subtotal * tax['base_sign']
790 tax_code_id = tax['ref_base_code_id']
791 tax_amount = line.price_subtotal * tax['ref_base_sign']
795 account_move_line_obj.create(cr, uid, {
796 'name': "bb" + order.name,
797 'date': order.date_order[:10],
798 'ref': order.contract_number or order.name,
799 'product_id':line.product_id.id,
800 'quantity': line.qty,
802 'account_id': income_account,
803 'company_id': comp_id,
806 'journal_id': order.sale_journal.id,
808 'tax_code_id': tax_code_id,
809 'tax_amount': tax_amount,
813 # Create a move for each tax group
814 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
815 for key, amount in group_tax.items():
816 account_move_line_obj.create(cr, uid, {
817 'name': "cc" + order.name,
818 'date': order.date_order[:10],
819 'ref': order.contract_number or order.name,
821 'company_id': comp_id,
822 'quantity': line.qty,
823 'product_id': line.product_id.id,
824 'account_id': key[account_pos],
825 'credit': ((amount>0) and amount) or 0.0,
826 'debit': ((amount<0) and -amount) or 0.0,
827 'journal_id': order.sale_journal.id,
829 'tax_code_id': key[tax_code_pos],
830 'tax_amount': amount,
834 to_reconcile.append(account_move_line_obj.create(cr, uid, {
835 'name': "dd" + order.name,
836 'date': order.date_order[:10],
837 'ref': order.contract_number or order.name,
839 'company_id': comp_id,
840 'account_id': order_account,
841 'credit': ((order.amount_total < 0) and -order.amount_total)\
843 'debit': ((order.amount_total > 0) and order.amount_total)\
845 'journal_id': order.sale_journal.id,
847 'partner_id': order.partner_id and order.partner_id.id or False
851 # search the account receivable for the payments:
852 account_receivable = order.sale_journal.default_credit_account_id.id
853 if not account_receivable:
854 raise osv.except_osv(_('Error !'),
855 _('There is no receivable account defined for this journal:'\
856 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
857 for payment in order.statement_ids:
858 # Create one entry for the payment
861 account_move_obj.create(cr, uid, {
862 'journal_id': payment.statement_id.journal_id.id,
866 for stat_l in order.statement_ids:
867 if stat_l.is_acc and len(stat_l.move_ids):
868 for st in stat_l.move_ids:
871 account_move_line_obj.copy(cr, uid, s.id, {
873 'statement_id': False,
876 account_move_line_obj.copy(cr, uid, s.id, {
877 'statement_id': False,
878 'account_id': order_account
881 self.write(cr, uid, order.id, {'state':'done'}, context=context)
884 def cancel_picking(self, cr, uid, ids, context=None):
885 stock_picking_obj = self.pool.get('stock.picking')
886 for order in self.browse(cr, uid, ids, context=context):
887 for picking in order.pickings:
888 stock_picking_obj.unlink(cr, uid, [picking.id], context=context)
892 def action_payment(self, cr, uid, ids, context=None):
893 vals = {'state': 'payment'}
894 sequence_obj = self.pool.get('ir.sequence')
895 for pos in self.browse(cr, uid, ids, context=context):
896 create_contract_nb = False
897 for line in pos.lines:
898 if line.product_id.product_type == 'MD':
899 create_contract_nb = True
901 if create_contract_nb:
902 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
903 vals['contract_number'] = '%s-%s' % (pos.user_salesman_id.login, seq)
904 self.write(cr, uid, ids, vals, context=context)
906 def action_paid(self, cr, uid, ids, context=None):
909 if context.get('flag', False):
910 self.create_picking(cr, uid, ids, context=None)
911 self.write(cr, uid, ids, {'state': 'paid'}, context=context)
913 context['flag'] = True
916 def action_cancel(self, cr, uid, ids, context=None):
917 self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
920 def action_done(self, cr, uid, ids, context=None):
921 for order in self.browse(cr, uid, ids, context=context):
922 if not order.journal_entry:
923 self.create_account_move(cr, uid, ids, context=None)
926 def compute_state(self, cr, uid, id):
927 cr.execute("SELECT act.id, act.name FROM wkf_activity act "
928 "INNER JOIN wkf_workitem item ON act.id = item.act_id "
929 "INNER JOIN wkf_instance inst ON item.inst_id = inst.id "
930 "INNER JOIN wkf ON inst.wkf_id = wkf.id "
931 "WHERE wkf.osv = 'pos.order' AND inst.res_id = %s "
932 "ORDER BY act.name", (id, ))
933 return [name for id, name in cr.fetchall()]
937 class account_bank_statement(osv.osv):
938 _inherit = 'account.bank.statement'
940 'user_id': fields.many2one('res.users', ondelete='cascade', string='User', readonly=True),
943 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
945 account_bank_statement()
947 class account_bank_statement_line(osv.osv):
948 _inherit = 'account.bank.statement.line'
949 def _get_statement_journal(self, cr, uid, ids, context, *a):
951 for line in self.browse(cr, uid, ids):
952 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
955 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
956 'am_out': fields.boolean("To count"),
957 'is_acc': fields.boolean("Is accompte"),
958 'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
960 account_bank_statement_line()
962 class pos_order_line(osv.osv):
963 _name = "pos.order.line"
964 _description = "Lines of Point of Sale"
966 def _get_amount(self, cr, uid, ids, field_name, arg, context=None):
968 for line in self.browse(cr, uid, ids, context=context):
969 price = self.price_by_product(cr, uid, ids, line.order_id.pricelist_id.id, line.product_id.id, line.qty, line.order_id.partner_id.id)
973 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context=None):
974 res = dict.fromkeys(ids, 0.0)
975 account_tax_obj = self.pool.get('account.tax')
976 self.price_by_product_multi(cr, uid, ids)
977 for line in self.browse(cr, uid, ids, context=context):
979 taxes = [t for t in line.product_id.taxes_id]
982 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
983 for tax in computed_taxes:
984 tax_amount += tax['amount']
985 if line.discount != 0.0:
986 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
988 res[line.id] = line.price_unit*line.qty
989 res[line.id] = res[line.id] + tax_amount
992 def _amount_line(self, cr, uid, ids, field_name, arg, context=None):
994 self.price_by_product_multi(cr, uid, ids)
995 for line in self.browse(cr, uid, ids, context=context):
996 if line.discount!=0.0:
997 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
999 res[line.id] = line.price_unit * line.qty
1002 def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
1003 res = dict([(i, {}) for i in ids])
1004 account_tax_obj = self.pool.get('account.tax')
1006 self.price_by_product_multi(cr, uid, ids)
1007 for line in self.browse(cr, uid, ids, context=context):
1008 for f in field_names:
1009 if f == 'price_subtotal':
1010 if line.discount != 0.0:
1011 res[line.id][f] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1013 res[line.id][f] = line.price_unit * line.qty
1014 elif f == 'price_subtotal_incl':
1015 taxes = [t for t in line.product_id.taxes_id]
1017 res[line.id][f] = 0.0
1019 price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
1020 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, price, line.qty)
1021 cur = line.order_id.pricelist_id.currency_id
1022 res[line.id][f] = self.pool.get('res.currency').round(cr, uid, cur, computed_taxes['total'])
1025 def price_by_product_multi(self, cr, uid, ids, context=None):
1028 res = {}.fromkeys(ids, 0.0)
1029 lines = self.browse(cr, uid, ids, context=context)
1031 pricelist_ids = [line.order_id.pricelist_id.id for line in lines]
1032 products_by_qty_by_partner = [(line.product_id.id, line.qty, line.order_id.partner_id.id) for line in lines]
1034 price_get_multi_res = self.pool.get('product.pricelist').price_get_multi(cr, uid, pricelist_ids, products_by_qty_by_partner, context=context)
1037 pricelist = line.order_id.pricelist_id.id
1038 product_id = line.product_id
1044 raise osv.except_osv(_('No Pricelist !'),
1045 _('You have to select a pricelist in the sale form !\n' \
1046 'Please set one before choosing a product.'))
1048 #old_price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product_id.id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1049 #print "prod_id: %s, pricelist: %s, price: %s" % (product_id.id, pricelist, price)
1050 price = price_get_multi_res[line.product_id.id][pricelist]
1051 #print "prod_id: %s, pricelist: %s, price2: %s" % (product_id.id, pricelist, price2)
1053 #if old_price != price:
1054 # raise Exception('old_price != price')
1056 unit_price = price or product_id.list_price
1057 res[line.id] = unit_price
1058 if unit_price is False:
1059 raise osv.except_osv(_('No valid pricelist line found !'),
1060 _("Couldn't find a pricelist line matching this product" \
1061 " and quantity.\nYou have to change either the product," \
1062 " the quantity or the pricelist."))
1065 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1069 raise osv.except_osv(_('No Pricelist !'),
1070 _('You have to select a pricelist in the sale form !\n' \
1071 'Please set one before choosing a product.'))
1072 p_obj = self.pool.get('product.product').browse(cr, uid, [product_id])[0]
1073 uom_id = p_obj.uom_po_id.id
1074 price = self.pool.get('product.pricelist').price_get(cr, uid,
1075 [pricelist], product_id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1076 unit_price=price or p_obj.list_price
1077 if unit_price is False:
1078 raise osv.except_osv(_('No valid pricelist line found !'),
1079 _("Couldn't find a pricelist line matching this product" \
1080 " and quantity.\nYou have to change either the product," \
1081 " the quantity or the pricelist."))
1084 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1085 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1086 self.write(cr, uid, ids, {'price_unit':price})
1087 pos_stot = (price * qty)
1088 return {'value': {'price_unit': price, 'price_subtotal_incl': pos_stot}}
1090 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist, qty,partner_id, product_id, *a):
1091 prod_obj = self.pool.get('product.product')
1092 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1095 prod_id = prod_obj.browse(cr, uid, product_id).disc_controle
1097 if (disc != 0.0 or prod_id) and price_f > 0:
1098 disc = 100 - (price/price_f*100)
1099 return {'value': {'discount': disc, 'price_unit': price_f}}
1102 def onchange_ded(self, cr, uid, ids, val_ded, price_u, *a):
1103 res_obj = self.pool.get('res.users')
1104 comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
1106 if val_ded and price_u:
1107 val=100.0 * val_ded / price_u
1109 return {'value': {'discount': val, 'notice': '' }}
1110 return {'value': {'discount': val}}
1112 def onchange_discount(self, cr, uid, ids, discount, price, *a):
1113 pos_order = self.pool.get('pos.order.line')
1114 res_obj = self.pool.get('res.users')
1115 company_disc = pos_order.browse(cr,uid,ids)
1117 if not company_disc:
1118 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1120 comp= company_disc[0] and company_disc[0].order_id.company_id and company_disc[0].order_id.company_id.company_discount or 0.0
1122 if discount > comp :
1123 return {'value': {'notice': '', 'price_ded': price * discount * 0.01 or 0.0 }}
1125 return {'value': {'notice': 'Minimum Discount', 'price_ded': price * discount * 0.01 or 0.0 }}
1127 return {'value': {'notice': 'No Discount', 'price_ded': price * discount * 0.01 or 0.0}}
1129 def onchange_qty(self, cr, uid, ids, discount, qty, price, context=None):
1130 subtotal = qty * price
1132 subtotal = subtotal - (subtotal * discount / 100)
1133 return {'value': {'price_subtotal_incl': subtotal}}
1136 'name': fields.char('Line Description', size=512),
1137 'company_id': fields.many2one('res.company', 'Company', required=True),
1138 'notice': fields.char('Discount Notice', size=128, required=True),
1139 'serial_number': fields.char('Serial Number', size=128),
1140 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1141 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1142 'price_ded': fields.float('Discount(Amount)', digits_compute=dp.get_precision('Point Of Sale')),
1143 'qty': fields.float('Quantity'),
1144 'qty_rfd': fields.float('Refunded Quantity'),
1145 'price_subtotal': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal w/o Tax'),
1146 'price_subtotal_incl': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal'),
1147 'discount': fields.float('Discount (%)', digits=(16, 2)),
1148 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1149 'create_date': fields.datetime('Creation Date', readonly=True),
1150 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help="You can specify Production lot for stock move created when you validate the pos order"),
1154 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1155 'qty': lambda *a: 1,
1156 'discount': lambda *a: 0.0,
1157 'price_ded': lambda *a: 0.0,
1158 'notice': lambda *a: 'No Discount',
1159 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1162 def create(self, cr, user, vals, context=None):
1163 if vals.get('product_id'):
1164 return super(pos_order_line, self).create(cr, user, vals, context=context)
1167 def write(self, cr, user, ids, values, context=None):
1168 if 'product_id' in values and not values['product_id']:
1170 return super(pos_order_line, self).write(cr, user, ids, values, context=context)
1172 def _scan_product(self, cr, uid, ean, qty, order):
1173 # search pricelist_id
1174 product_obj = self.pool.get('product.product')
1175 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1176 if not pricelist_id:
1181 product_id = product_obj.search(cr, uid, [('ean13','=', ean)])
1185 # search price product
1186 product = product_obj.read(cr, uid, product_id)
1187 product_name = product[0]['name']
1188 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1190 order_line_ids = self.search(cr, uid, [('name', '=', product_name), ('order_id', '=' ,order)])
1193 order_line_id = order_line_ids[0]
1194 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1197 vals = {'product_id': product_id[0],
1198 'price_unit': price,
1200 'name': product_name,
1203 line_id = self.create(cr, uid, vals)
1205 raise osv.except_osv(_('Error'), _('Create line failed !'))
1211 line_id = self.write(cr, uid, order_line_id, vals)
1213 raise osv.except_osv(_('Error'), _('Modify line failed !'))
1214 line_id = order_line_id
1216 price_line = float(qty) * float(price)
1218 'name': product_name,
1219 'product_id': product_id[0],
1221 'price_line': price_line ,
1227 class product_product(osv.osv):
1228 _inherit = 'product.product'
1230 'income_pdt': fields.boolean('Product for Input'),
1231 'expense_pdt': fields.boolean('Product for expenses'),
1232 'am_out': fields.boolean('Control for Output Operations'),
1233 'disc_controle': fields.boolean('Discount Control'),
1236 'disc_controle': True,
1240 class stock_picking(osv.osv):
1241 _inherit = 'stock.picking'
1243 'pos_order': fields.many2one('pos.order', 'Pos order'),
1248 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: