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
118 cr.execute(" SELECT MAX(l.date) "
119 " FROM account_move_line l, account_move m, account_invoice i, account_move_reconcile r, pos_order o "
120 " 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",
123 cr.execute("SELECT MAX(l.date) from account_move_line l "
124 "left join account_bank_statement abs on (l.statement_id=abs.id)"
125 "left join account_bank_statement_line absl on (absl.statement_id=abs.id) "
126 "left join pos_order p on (p.id=absl.pos_statement_id) "
127 "left join account_account a on (a.id=absl.account_id) "
128 "where p.id=%s and l.reconcile_id is not NULL and a.reconcile=True", (order.id,))
130 val = val and val[0] or None
135 def _get_date_payment(self, cr, uid, ids, context, *a):
136 """ Find Validation Date
137 @return: Dictionary of values """
140 for order in self.browse(cr, uid, ids):
141 cr.execute("SELECT date_validation FROM pos_order WHERE id = %s", (order.id,))
142 date_p = cr.fetchone()
143 date_p = date_p and date_p[0] or None
145 res[order.id] = date_p
147 discount_allowed = order.company_id.company_discount
148 for line in order.lines:
149 if line.discount > discount_allowed:
150 return {order.id: None }
151 if order.amount_paid == order.amount_total and not date_p:
152 cr.execute("SELECT MAX(date) FROM account_bank_statement_line WHERE pos_statement_id = %s", (order.id,))
154 val = val and val[0] or None
155 if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
156 for o in order.invoice_id.move_id.line_id:
158 if val < o.date_created:
164 def _amount_all(self, cr, uid, ids, name, args, context=None):
165 tax_obj = self.pool.get('account.tax')
166 cur_obj = self.pool.get('res.currency')
168 for order in self.browse(cr, uid, ids, context=context):
175 cur = order.pricelist_id.currency_id
176 for payment in order.statement_ids:
177 res[order.id]['amount_paid'] += payment.amount
178 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
179 for line in order.lines:
180 val1 += line.price_subtotal_incl
181 if order.price_type != 'tax_excluded':
182 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
183 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
185 (1-(line.discount or 0.0)/100.0), line.qty),
186 res[order.id]['amount_tax'])
187 elif line.qty != 0.0:
188 for c in tax_obj.compute_all(cr, uid, line.product_id.taxes_id, \
189 line.price_unit * (1-(line.discount or 0.0)/100.0), \
190 line.qty, line.product_id, line.order_id.partner_id)['taxes']:
191 val += c.get('amount', 0.0)
192 res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
193 res[order.id]['amount_total'] = res[order.id]['amount_tax'] + cur_obj.round(cr, uid, cur, val1)
196 def _sale_journal_get(self, cr, uid, context=None):
197 """ To get sale journal for this order
199 journal_obj = self.pool.get('account.journal')
200 res = journal_obj.search(cr, uid, [('type', '=', 'sale')], limit=1)
201 return res and res[0] or False
203 def _shop_get(self, cr, uid, context=None):
204 """ To get Shop for this order
206 res = self.pool.get('sale.shop').search(cr, uid, [])
207 return res and res[0] or False
209 def copy(self, cr, uid, id, default=None, context=None):
216 'account_move': False,
222 return super(pos_order, self).copy(cr, uid, id, default, context=context)
224 def _get_v( self, cr, uid, ids, *args):
225 """ Changed the Validation state of order
227 res_obj = self.pool.get('res.users')
228 company_disc = self.browse(cr, uid, ids)
232 comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
234 comp = company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
235 cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount <= %s", (ids[0], comp))
237 cr.execute("SELECT discount FROM pos_order_line WHERE order_id = %s AND discount > %s", (ids[0], comp))
239 cr.execute("SELECT journal_id FROM account_bank_statement_line WHERE pos_statement_id = %s ", (ids[0], ))
242 cr.execute("SELECT id FROM account_journal WHERE name = '%s' AND special_journal = 't'", (r[0], ))
244 is_special = res3 and res3[0] or None
246 list_jrnl.append(is_special)
247 for order in self.browse(cr, uid, ids):
248 if order.state in ('paid', 'done', 'invoiced') and res and not res2 and not len(list_jrnl):
249 r[order.id] = 'accepted'
253 'name': fields.char('Order Description', size=64, required=True,
254 states={'draft': [('readonly', False)]}, readonly=True),
255 'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
256 'num_sale': fields.char('Internal Note', size=64),
257 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
258 states={'draft': [('readonly', False)]}, readonly=True),
259 'date_order': fields.datetime('Date Ordered', readonly=True, select=True),
260 'date_validation': fields.function(_get_date_payment,
262 string='Validation Date',
263 type='date', select=True, store=True),
264 'date_payment': fields.function(_get_date_payment2, method=True,
265 string='Payment Date',
266 type='date', select=True, store=True),
267 'date_validity': fields.date('Validity Date', required=True),
268 '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."),
269 'user_salesman_id': fields.many2one('res.users', 'Cashier', required=True, help="User who is logged into the system."),
270 'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
271 'amount_tax': fields.function(_amount_all, method=True, string='Taxes', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
272 'amount_total': fields.function(_amount_all, method=True, string='Total', multi='all'),
273 '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'),
274 'amount_return': fields.function(_amount_all, 'Returned', method=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
275 'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
276 'price_type': fields.selection([
277 ('tax_excluded','Tax excluded')],
278 'Price method', required=True),
279 'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
280 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
281 'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
282 'state': fields.selection([('draft', 'Quotation'),
283 ('payment', 'Payment'),
284 ('advance','Advance'),
287 ('invoiced', 'Invoiced'),
288 ('cancel', 'Cancel')],
289 'State', readonly=True),
290 'invoice_id': fields.many2one('account.invoice', 'Invoice'),
291 'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
292 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
293 'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
294 'first_name': fields.char('First Name', size=64),
295 'note': fields.text('Internal Notes'),
296 'nb_print': fields.integer('Number of Print', readonly=True),
297 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True),
298 'invoice_wanted': fields.boolean('Create Invoice'),
299 'note_2': fields.char('Customer Note', size=64),
300 'type_rec': fields.char('Type of Receipt', size=64),
301 'remboursed': fields.boolean('Remboursed'),
302 'contract_number': fields.char('Contract Number', size=512, select=1),
303 'journal_entry': fields.boolean('Journal Entry'),
306 def _select_pricelist(self, cr, uid, context=None):
307 """ To get default pricelist for the order
308 @param name: Names of fields.
309 @return: pricelist ID
311 res = self.pool.get('sale.shop').search(cr, uid, [], context=context)
313 shop = self.pool.get('sale.shop').browse(cr, uid, res[0], context=context)
314 return shop.pricelist_id and shop.pricelist_id.id or False
317 def _journal_default(self, cr, uid, context=None):
318 """ To get default pricelist for the order
319 @param name: Names of fields.
322 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
323 return journal_list and journal_list[0] or False
326 'user_salesman_id':lambda self, cr, uid, context: uid,
327 'user_id': lambda self, cr, uid, context: uid,
328 'sale_manager': lambda self, cr, uid, context: uid,
330 'price_type': 'tax_excluded',
331 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
332 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
333 'date_validity': lambda *a: (datetime.today() + relativedelta(months=+6)).strftime('%Y-%m-%d'),
335 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
336 'sale_journal': _sale_journal_get,
337 'invoice_wanted': False,
338 'shop_id': _shop_get,
339 'pricelist_id': _select_pricelist,
343 def test_order_lines(self, cr, uid, order, context=None):
344 """ Test order line is created or not for the order
345 @param name: Names of fields.
349 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
351 wf_service = netsvc.LocalService("workflow")
352 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
355 def dummy_button(self, cr, uid, order, context=None):
358 def test_paid(self, cr, uid, ids, context=None):
359 """ Test all amount is paid for this order
362 for order in self.browse(cr, uid, ids, context=context):
363 if order.lines and not order.amount_total:
365 if (not order.lines) or (not order.statement_ids) or \
366 Decimal(str(order.amount_total)) != Decimal(str(order.amount_paid)):
370 def _get_qty_differences(self, orders, old_picking):
371 """check if the customer changed the product quantity """
374 for line in order.lines:
375 order_dict[line.product_id.id] = line
377 # check the quantity differences:
379 for line in old_picking.move_lines:
380 order_line = order_dict.get(line.product_id.id)
383 qty_to_delete_from_original_picking = line.product_qty
384 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
385 elif line.product_qty != order_line.qty:
387 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
388 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
392 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
393 """if the customer changes the product quantity, split the picking in two"""
394 # create a copy of the original picking and adjust the product qty:
395 picking_model = self.pool.get('stock.picking')
397 'note': "Partial picking from customer", # add a note to tell why we create a new picking
398 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
401 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
402 new_picking = picking_model.browse(cr, uid, new_picking_id, context=context)
404 for line in new_picking.move_lines:
405 p_id = line.product_id.id
406 if p_id in diff_dict:
407 diff = diff_dict[p_id]
410 if deleted: # product has been deleted (customer didn't took it):
411 # delete this product from old picking:
412 for old_line in old_picking.move_lines:
413 if old_line.product_id.id == p_id:
414 old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
415 old_line.unlink(context=context)
416 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
417 # subtract qty from old picking:
418 for old_line in old_picking.move_lines:
419 if old_line.product_id.id == p_id:
420 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
421 # add qty to new picking:
422 line.write({'product_qty': qty_to_del}, context=context)
423 else: # product hasn't changed (customer took it without any change):
424 # delete this product from new picking:
425 line.unlink(context=context)
427 # delete it in the new picking:
428 line.unlink(context=context)
430 def create_picking(self, cr, uid, ids, context=None):
431 """Create a picking for each order and validate it."""
432 picking_obj = self.pool.get('stock.picking')
433 property_obj = self.pool.get("ir.property")
434 move_obj = self.pool.get('stock.move')
435 pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
436 orders = self.browse(cr, uid, ids, context=context)
438 if not order.picking_id:
440 picking_id = picking_obj.create(cr, uid, {
442 'origin': order.name,
445 'move_type': 'direct',
446 'note': 'POS notes ' + (order.note or ""),
447 'invoice_state': 'none',
448 'auto_picking': True,
449 'pos_order': order.id,
451 self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
453 picking_id = order.picking_id.id
454 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True}, context=context)
455 picking = picking_obj.browse(cr, uid, [picking_id], context=context)[0]
458 # split the picking (if product quantity has changed):
459 diff_dict = self._get_qty_differences(orders, picking)
461 self._split_picking(cr, uid, ids, context, picking, diff_dict)
464 for line in order.lines:
465 if line.product_id and line.product_id.type == 'service':
467 prop_ids = property_obj.search(cr, uid, [('name', '=', 'property_stock_customer')], context=context)
468 val = property_obj.browse(cr, uid, prop_ids[0], context=context).value_reference
469 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, ))
471 location_id = res and res[0] or None
472 stock_dest_id = val.id
474 location_id, stock_dest_id = stock_dest_id, location_id
475 move_obj.create(cr, uid, {
476 'name': '(POS %d)' % (order.id, ),
477 'product_uom': line.product_id.uom_id.id,
478 'product_uos': line.product_id.uom_id.id,
479 'picking_id': picking_id,
480 'product_id': line.product_id.id,
481 'product_uos_qty': abs(line.qty),
482 'product_qty': abs(line.qty),
483 'tracking_id': False,
484 'pos_line_id': line.id,
486 'location_id': location_id,
487 'location_dest_id': stock_dest_id,
488 'prodlot_id': line.prodlot_id and line.prodlot_id.id or False
491 wf_service = netsvc.LocalService("workflow")
492 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
493 picking_obj.force_assign(cr, uid, [picking_id], context)
496 def set_to_draft(self, cr, uid, ids, *args):
497 """ Changes order state to draft
502 self.write(cr, uid, ids, {'state': 'draft'})
503 wf_service = netsvc.LocalService("workflow")
505 wf_service.trg_create(uid, 'pos.order', i, cr)
508 def button_invalidate(self, cr, uid, ids, *args):
509 """ Check the access for the sale order
512 res_obj = self.pool.get('res.company')
514 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
516 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
518 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
521 def cancel_order(self, cr, uid, ids, context=None):
522 """ Changes order state to cancel
525 self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
526 self.cancel_picking(cr, uid, ids, context=context)
529 def add_payment(self, cr, uid, order_id, data, context=None):
530 """Create a new payment for the order"""
531 statement_obj = self.pool.get('account.bank.statement')
532 statement_line_obj = self.pool.get('account.bank.statement.line')
533 prod_obj = self.pool.get('product.product')
534 property_obj = self.pool.get('ir.property')
535 curr_c = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
536 curr_company = curr_c.id
537 order = self.browse(cr, uid, order_id, context=context)
538 if not order.num_sale and data['num_sale']:
539 self.write(cr, uid, order_id, {'num_sale': data['num_sale']}, context=context)
542 'amount': data['amount'],
544 if 'payment_date' in data.keys():
545 args['date'] = data['payment_date']
546 if 'payment_name' in data.keys():
547 args['name'] = data['payment_name'] + ' ' + order.name
548 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
549 args['account_id'] = order.partner_id and order.partner_id.property_account_receivable \
550 and order.partner_id.property_account_receivable.id or account_def.id or curr_c.account_receivable.id
551 if data.get('is_acc', False):
552 args['is_acc'] = data['is_acc']
553 args['account_id'] = prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income \
554 and prod_obj.browse(cr, uid, data['product_id'], context=context).property_account_income.id
555 if not args['account_id']:
556 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')% \
557 (prod_obj.browse(cr, uid, data['product_id'], context=context).name))
558 args['partner_id'] = order.partner_id and order.partner_id.id or None
559 args['ref'] = order.contract_number or None
561 statement_id = statement_obj.search(cr,uid, [
562 ('journal_id', '=', data['journal']),
563 ('company_id', '=', curr_company),
564 ('user_id', '=', uid),
565 ('state', '=', 'open')], context=context)
566 if len(statement_id) == 0:
567 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
569 statement_id = statement_id[0]
570 args['statement_id'] = statement_id
571 args['pos_statement_id'] = order_id
572 args['journal_id'] = data['journal']
573 args['type'] = 'customer'
574 args['ref'] = order.name
575 statement_line_obj.create(cr, uid, args, context=context)
576 ids_new.append(statement_id)
578 wf_service = netsvc.LocalService("workflow")
579 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
580 wf_service.trg_write(uid, 'pos.order', order_id, cr)
584 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
586 """Create a new order line the order"""
588 line_obj = self.pool.get('pos.order.line')
589 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
591 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
592 product = values['partner_id'] and values['partner_id'][0]
594 price = line_obj.price_by_product(cr, uid, [],
595 pricelist, product_id, qty, product)
597 order_line_id = line_obj.create(cr, uid, {
598 'order_id': order_id,
599 'product_id': product_id,
603 return order_line_id, price
605 def refund(self, cr, uid, ids, context=None):
607 """Create a copy of order for refund order"""
610 line_obj = self.pool.get('pos.order.line')
612 for order in self.browse(cr, uid, ids, context=context):
613 clone_id = self.copy(cr, uid, order.id, {
614 'name': order.name + ' REFUND',
615 'date_order': time.strftime('%Y-%m-%d'),
617 'note': 'REFUND\n'+ (order.note or ''),
620 'statement_ids': False,
622 clone_list.append(clone_id)
625 for clone in self.browse(cr, uid, clone_list, context=context):
626 for order_line in clone.lines:
627 line_obj.write(cr, uid, [order_line.id], {
628 'qty': -order_line.qty
632 def action_invoice(self, cr, uid, ids, context=None):
634 """Create a invoice of order """
636 inv_ref = self.pool.get('account.invoice')
637 inv_line_ref = self.pool.get('account.invoice.line')
638 product_obj = self.pool.get('product.product')
641 for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
643 inv_ids.append(order.invoice_id.id)
646 if not order.partner_id:
647 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
649 acc = order.partner_id.property_account_receivable.id
651 'name': 'Invoice from POS: '+order.name,
652 'origin': order.name,
654 'journal_id': order.sale_journal.id or None,
655 'type': 'out_invoice',
656 'reference': order.name,
657 'partner_id': order.partner_id.id,
658 'comment': order.note or '',
659 'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
661 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
662 if not inv.get('account_id', None):
663 inv['account_id'] = acc
664 inv_id = inv_ref.create(cr, uid, inv, context=context)
666 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
667 inv_ids.append(inv_id)
668 for line in order.lines:
670 'invoice_id': inv_id,
671 'product_id': line.product_id.id,
672 'quantity': line.qty,
674 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
676 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
678 line.product_id.uom_id.id,
679 line.qty, partner_id = order.partner_id.id,
680 fposition_id=order.partner_id.property_account_position.id)['value'])
681 inv_line['price_unit'] = line.price_unit
682 inv_line['discount'] = line.discount
683 inv_line['name'] = inv_name
684 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
685 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
686 inv_line_ref.create(cr, uid, inv_line, context=context)
689 wf_service = netsvc.LocalService("workflow")
690 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
693 def create_account_move(self, cr, uid, ids, context=None):
694 """Create a account move line of order """
695 account_move_obj = self.pool.get('account.move')
696 account_move_line_obj = self.pool.get('account.move.line')
697 account_period_obj = self.pool.get('account.period')
698 account_tax_obj = self.pool.get('account.tax')
699 res_obj=self.pool.get('res.users')
700 property_obj=self.pool.get('ir.property')
701 period = account_period_obj.find(cr, uid, context=context)[0]
703 for order in self.browse(cr, uid, ids, context=context):
704 curr_c = res_obj.browse(cr, uid, uid).company_id
705 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
706 comp_id = comp_id and comp_id.id or False
709 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
711 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
713 # Create an entry for the sale
714 move_id = account_move_obj.create(cr, uid, {
715 'journal_id': order.sale_journal.id,
719 # Create an move for each order line
720 for line in order.lines:
722 taxes = [t for t in line.product_id.taxes_id]
723 if order.price_type == 'tax_excluded':
724 computed_taxes = account_tax_obj.compute_all(
725 cr, uid, taxes, line.price_unit, line.qty)['taxes']
727 computed_taxes = account_tax_obj.compute_inv(
728 cr, uid, taxes, line.price_unit, line.qty)
730 for tax in computed_taxes:
731 tax_amount += round(tax['amount'], 2)
732 group_key = (tax['tax_code_id'],
734 tax['account_collected_id'])
736 if group_key in group_tax:
737 group_tax[group_key] += round(tax['amount'], 2)
739 group_tax[group_key] = round(tax['amount'], 2)
740 if order.price_type != 'tax_excluded':
741 amount = line.price_subtotal - tax_amount
743 amount = line.price_subtotal
745 # Search for the income account
746 if line.product_id.property_account_income.id:
747 income_account = line.\
748 product_id.property_account_income.id
749 elif line.product_id.categ_id.\
750 property_account_income_categ.id:
751 income_account = line.product_id.categ_id.\
752 property_account_income_categ.id
754 raise osv.except_osv(_('Error !'), _('There is no income '\
755 'account defined for this product: "%s" (id:%d)') \
756 % (line.product_id.name, line.product_id.id, ))
758 # Empty the tax list as long as there is no tax code:
761 while computed_taxes:
762 tax = computed_taxes.pop(0)
764 tax_code_id = tax['base_code_id']
765 tax_amount = line.price_subtotal * tax['base_sign']
767 tax_code_id = tax['ref_base_code_id']
768 tax_amount = line.price_subtotal * tax['ref_base_sign']
769 # If there is one we stop
773 # Create a move for the line
774 account_move_line_obj.create(cr, uid, {
775 'name': "aa"+order.name,
776 'date': order.date_order[:10],
777 'ref': order.contract_number or order.name,
778 'quantity': line.qty,
779 'product_id': line.product_id.id,
781 'account_id': income_account,
782 'company_id': comp_id,
783 'credit': ((amount>0) and amount) or 0.0,
784 'debit': ((amount<0) and -amount) or 0.0,
785 'journal_id': order.sale_journal.id,
787 'tax_code_id': tax_code_id,
788 'tax_amount': tax_amount,
789 'partner_id': order.partner_id and order.partner_id.id or False
792 # For each remaining tax with a code, whe create a move line
793 for tax in computed_taxes:
795 tax_code_id = tax['base_code_id']
796 tax_amount = line.price_subtotal * tax['base_sign']
798 tax_code_id = tax['ref_base_code_id']
799 tax_amount = line.price_subtotal * tax['ref_base_sign']
803 account_move_line_obj.create(cr, uid, {
804 'name': "bb" + order.name,
805 'date': order.date_order[:10],
806 'ref': order.contract_number or order.name,
807 'product_id':line.product_id.id,
808 'quantity': line.qty,
810 'account_id': income_account,
811 'company_id': comp_id,
814 'journal_id': order.sale_journal.id,
816 'tax_code_id': tax_code_id,
817 'tax_amount': tax_amount,
821 # Create a move for each tax group
822 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
823 for key, amount in group_tax.items():
824 account_move_line_obj.create(cr, uid, {
825 'name': "cc" + order.name,
826 'date': order.date_order[:10],
827 'ref': order.contract_number or order.name,
829 'company_id': comp_id,
830 'quantity': line.qty,
831 'product_id': line.product_id.id,
832 'account_id': key[account_pos],
833 'credit': ((amount>0) and amount) or 0.0,
834 'debit': ((amount<0) and -amount) or 0.0,
835 'journal_id': order.sale_journal.id,
837 'tax_code_id': key[tax_code_pos],
838 'tax_amount': amount,
842 to_reconcile.append(account_move_line_obj.create(cr, uid, {
843 'name': "dd" + order.name,
844 'date': order.date_order[:10],
845 'ref': order.contract_number or order.name,
847 'company_id': comp_id,
848 'account_id': order_account,
849 'credit': ((order.amount_total < 0) and -order.amount_total)\
851 'debit': ((order.amount_total > 0) and order.amount_total)\
853 'journal_id': order.sale_journal.id,
855 'partner_id': order.partner_id and order.partner_id.id or False
859 # search the account receivable for the payments:
860 account_receivable = order.sale_journal.default_credit_account_id.id
861 if not account_receivable:
862 raise osv.except_osv(_('Error !'),
863 _('There is no receivable account defined for this journal:'\
864 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
865 for payment in order.statement_ids:
866 # Create one entry for the payment
869 account_move_obj.create(cr, uid, {
870 'journal_id': payment.statement_id.journal_id.id,
874 for stat_l in order.statement_ids:
875 if stat_l.is_acc and len(stat_l.move_ids):
876 for st in stat_l.move_ids:
879 account_move_line_obj.copy(cr, uid, s.id, {
881 'statement_id': False,
884 account_move_line_obj.copy(cr, uid, s.id, {
885 'statement_id': False,
886 'account_id': order_account
889 self.write(cr, uid, order.id, {'state':'done'}, context=context)
892 def cancel_picking(self, cr, uid, ids, context=None):
893 stock_picking_obj = self.pool.get('stock.picking')
894 for order in self.browse(cr, uid, ids, context=context):
895 for picking in order.pickings:
896 stock_picking_obj.unlink(cr, uid, [picking.id], context=context)
900 def action_payment(self, cr, uid, ids, context=None):
901 vals = {'state': 'payment'}
902 sequence_obj = self.pool.get('ir.sequence')
903 for pos in self.browse(cr, uid, ids, context=context):
904 create_contract_nb = False
905 for line in pos.lines:
906 if line.product_id.product_type == 'MD':
907 create_contract_nb = True
909 if create_contract_nb:
910 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
911 vals['contract_number'] = '%s-%s' % (pos.user_salesman_id.login, seq)
912 self.write(cr, uid, ids, vals, context=context)
914 def action_paid(self, cr, uid, ids, context=None):
917 if context.get('flag', False):
918 self.create_picking(cr, uid, ids, context=None)
919 self.write(cr, uid, ids, {'state': 'paid'}, context=context)
921 context['flag'] = True
924 def action_cancel(self, cr, uid, ids, context=None):
925 self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
928 def action_done(self, cr, uid, ids, context=None):
929 for order in self.browse(cr, uid, ids, context=context):
930 if not order.journal_entry:
931 self.create_account_move(cr, uid, ids, context=None)
934 def compute_state(self, cr, uid, id):
935 cr.execute("SELECT act.id, act.name FROM wkf_activity act "
936 "INNER JOIN wkf_workitem item ON act.id = item.act_id "
937 "INNER JOIN wkf_instance inst ON item.inst_id = inst.id "
938 "INNER JOIN wkf ON inst.wkf_id = wkf.id "
939 "WHERE wkf.osv = 'pos.order' AND inst.res_id = %s "
940 "ORDER BY act.name", (id, ))
941 return [name for id, name in cr.fetchall()]
945 class account_bank_statement(osv.osv):
946 _inherit = 'account.bank.statement'
948 'user_id': fields.many2one('res.users', ondelete='cascade', string='User', readonly=True),
951 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
953 account_bank_statement()
955 class account_bank_statement_line(osv.osv):
956 _inherit = 'account.bank.statement.line'
957 def _get_statement_journal(self, cr, uid, ids, context, *a):
959 for line in self.browse(cr, uid, ids):
960 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
963 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
964 'am_out': fields.boolean("To count"),
965 'is_acc': fields.boolean("Is accompte"),
966 'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
968 account_bank_statement_line()
970 class pos_order_line(osv.osv):
971 _name = "pos.order.line"
972 _description = "Lines of Point of Sale"
974 def _get_amount(self, cr, uid, ids, field_name, arg, context=None):
976 for line in self.browse(cr, uid, ids, context=context):
977 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)
981 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context=None):
982 res = dict.fromkeys(ids, 0.0)
983 account_tax_obj = self.pool.get('account.tax')
984 self.price_by_product_multi(cr, uid, ids)
985 for line in self.browse(cr, uid, ids, context=context):
987 taxes = [t for t in line.product_id.taxes_id]
990 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
991 for tax in computed_taxes:
992 tax_amount += tax['amount']
993 if line.discount != 0.0:
994 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
996 res[line.id] = line.price_unit*line.qty
997 res[line.id] = res[line.id] + tax_amount
1000 def _amount_line(self, cr, uid, ids, field_name, arg, context=None):
1002 self.price_by_product_multi(cr, uid, ids)
1003 for line in self.browse(cr, uid, ids, context=context):
1004 if line.discount!=0.0:
1005 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1007 res[line.id] = line.price_unit * line.qty
1010 def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
1011 res = dict([(i, {}) for i in ids])
1012 account_tax_obj = self.pool.get('account.tax')
1014 self.price_by_product_multi(cr, uid, ids)
1015 for line in self.browse(cr, uid, ids, context=context):
1016 for f in field_names:
1017 if f == 'price_subtotal':
1018 if line.discount != 0.0:
1019 res[line.id][f] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1021 res[line.id][f] = line.price_unit * line.qty
1022 elif f == 'price_subtotal_incl':
1023 taxes = [t for t in line.product_id.taxes_id]
1025 res[line.id][f] = 0.0
1027 price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
1028 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, price, line.qty)
1029 cur = line.order_id.pricelist_id.currency_id
1030 res[line.id][f] = self.pool.get('res.currency').round(cr, uid, cur, computed_taxes['total'])
1033 def price_by_product_multi(self, cr, uid, ids, context=None):
1036 res = {}.fromkeys(ids, 0.0)
1037 lines = self.browse(cr, uid, ids, context=context)
1039 pricelist_ids = [line.order_id.pricelist_id.id for line in lines]
1040 products_by_qty_by_partner = [(line.product_id.id, line.qty, line.order_id.partner_id.id) for line in lines]
1042 price_get_multi_res = self.pool.get('product.pricelist').price_get_multi(cr, uid, pricelist_ids, products_by_qty_by_partner, context=context)
1045 pricelist = line.order_id.pricelist_id.id
1046 product_id = line.product_id
1052 raise osv.except_osv(_('No Pricelist !'),
1053 _('You have to select a pricelist in the sale form !\n' \
1054 'Please set one before choosing a product.'))
1056 #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]
1057 #print "prod_id: %s, pricelist: %s, price: %s" % (product_id.id, pricelist, price)
1058 price = price_get_multi_res[line.product_id.id][pricelist]
1059 #print "prod_id: %s, pricelist: %s, price2: %s" % (product_id.id, pricelist, price2)
1061 #if old_price != price:
1062 # raise Exception('old_price != price')
1064 unit_price = price or product_id.list_price
1065 res[line.id] = unit_price
1066 if unit_price is False:
1067 raise osv.except_osv(_('No valid pricelist line found !'),
1068 _("Couldn't find a pricelist line matching this product" \
1069 " and quantity.\nYou have to change either the product," \
1070 " the quantity or the pricelist."))
1073 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1077 raise osv.except_osv(_('No Pricelist !'),
1078 _('You have to select a pricelist in the sale form !\n' \
1079 'Please set one before choosing a product.'))
1080 p_obj = self.pool.get('product.product').browse(cr, uid, [product_id])[0]
1081 uom_id = p_obj.uom_po_id.id
1082 price = self.pool.get('product.pricelist').price_get(cr, uid,
1083 [pricelist], product_id, qty or 1.0, partner_id, {'uom': uom_id})[pricelist]
1084 unit_price=price or p_obj.list_price
1085 if unit_price is False:
1086 raise osv.except_osv(_('No valid pricelist line found !'),
1087 _("Couldn't find a pricelist line matching this product" \
1088 " and quantity.\nYou have to change either the product," \
1089 " the quantity or the pricelist."))
1092 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1093 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1094 self.write(cr, uid, ids, {'price_unit':price})
1095 pos_stot = (price * qty)
1096 return {'value': {'price_unit': price, 'price_subtotal_incl': pos_stot}}
1098 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist, qty,partner_id, product_id, *a):
1099 prod_obj = self.pool.get('product.product')
1100 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1103 prod_id = prod_obj.browse(cr, uid, product_id).disc_controle
1105 if (disc != 0.0 or prod_id) and price_f > 0:
1106 disc = 100 - (price/price_f*100)
1107 return {'value': {'discount': disc, 'price_unit': price_f}}
1110 def onchange_ded(self, cr, uid, ids, val_ded, price_u, *a):
1111 res_obj = self.pool.get('res.users')
1112 comp = res_obj.browse(cr, uid, uid).company_id.company_discount or 0.0
1114 if val_ded and price_u:
1115 val=100.0 * val_ded / price_u
1117 return {'value': {'discount': val, 'notice': '' }}
1118 return {'value': {'discount': val}}
1120 def onchange_discount(self, cr, uid, ids, discount, price, *a):
1121 pos_order = self.pool.get('pos.order.line')
1122 res_obj = self.pool.get('res.users')
1123 company_disc = pos_order.browse(cr,uid,ids)
1125 if not company_disc:
1126 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1128 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
1130 if discount > comp :
1131 return {'value': {'notice': '', 'price_ded': price * discount * 0.01 or 0.0 }}
1133 return {'value': {'notice': 'Minimum Discount', 'price_ded': price * discount * 0.01 or 0.0 }}
1135 return {'value': {'notice': 'No Discount', 'price_ded': price * discount * 0.01 or 0.0}}
1137 def onchange_qty(self, cr, uid, ids, discount, qty, price, context=None):
1138 subtotal = qty * price
1140 subtotal = subtotal - (subtotal * discount / 100)
1141 return {'value': {'price_subtotal_incl': subtotal}}
1144 'name': fields.char('Line Description', size=512),
1145 'company_id': fields.many2one('res.company', 'Company', required=True),
1146 'notice': fields.char('Discount Notice', size=128, required=True),
1147 'serial_number': fields.char('Serial Number', size=128),
1148 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1149 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1150 'price_ded': fields.float('Discount(Amount)', digits_compute=dp.get_precision('Point Of Sale')),
1151 'qty': fields.float('Quantity'),
1152 'qty_rfd': fields.float('Refunded Quantity'),
1153 'price_subtotal': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal w/o Tax'),
1154 'price_subtotal_incl': fields.function(_amount_line_all, method=True, multi='pos_order_line_amount', string='Subtotal'),
1155 'discount': fields.float('Discount (%)', digits=(16, 2)),
1156 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1157 'create_date': fields.datetime('Creation Date', readonly=True),
1158 '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"),
1162 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1163 'qty': lambda *a: 1,
1164 'discount': lambda *a: 0.0,
1165 'price_ded': lambda *a: 0.0,
1166 'notice': lambda *a: 'No Discount',
1167 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1170 def create(self, cr, user, vals, context=None):
1171 if vals.get('product_id'):
1172 return super(pos_order_line, self).create(cr, user, vals, context=context)
1175 def write(self, cr, user, ids, values, context=None):
1176 if 'product_id' in values and not values['product_id']:
1178 return super(pos_order_line, self).write(cr, user, ids, values, context=context)
1180 def _scan_product(self, cr, uid, ean, qty, order):
1181 # search pricelist_id
1182 product_obj = self.pool.get('product.product')
1183 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1184 if not pricelist_id:
1189 product_id = product_obj.search(cr, uid, [('ean13','=', ean)])
1193 # search price product
1194 product = product_obj.read(cr, uid, product_id)
1195 product_name = product[0]['name']
1196 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1198 order_line_ids = self.search(cr, uid, [('name', '=', product_name), ('order_id', '=' ,order)])
1201 order_line_id = order_line_ids[0]
1202 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1205 vals = {'product_id': product_id[0],
1206 'price_unit': price,
1208 'name': product_name,
1211 line_id = self.create(cr, uid, vals)
1213 raise osv.except_osv(_('Error'), _('Create line failed !'))
1219 line_id = self.write(cr, uid, order_line_id, vals)
1221 raise osv.except_osv(_('Error'), _('Modify line failed !'))
1222 line_id = order_line_id
1224 price_line = float(qty) * float(price)
1226 'name': product_name,
1227 'product_id': product_id[0],
1229 'price_line': price_line ,
1235 class product_product(osv.osv):
1236 _inherit = 'product.product'
1238 'income_pdt': fields.boolean('Product for Input'),
1239 'expense_pdt': fields.boolean('Product for expenses'),
1240 'am_out': fields.boolean('Control for Output Operations'),
1241 'disc_controle': fields.boolean('Discount Control'),
1244 'disc_controle': True,
1248 class stock_picking(osv.osv):
1249 _inherit = 'stock.picking'
1251 'pos_order': fields.many2one('pos.order', 'Pos order'),
1256 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: