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 Affero 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 _
28 from decimal import Decimal
31 import decimal_precision as dp
33 class pos_config_journal(osv.osv):
34 """ Point of Sale journal configuration"""
35 _name = 'pos.config.journal'
36 _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")
44 class pos_company_discount(osv.osv):
46 """ Company Discount and Cashboxes """
48 _inherit = 'res.company'
50 'company_discount': fields.float('Max Discount(%)', digits_compute= dp.get_precision('Point Of Sale')),
51 'max_diff': fields.float('Max Difference for Cashboxes', digits_compute= dp.get_precision('Point Of Sale Discount')),
54 pos_company_discount()
57 class pos_order(osv.osv):
59 """ Point of sale gives business owners a convenient way of checking out customers
60 and of recording sales """
63 _description = "Point of Sale"
64 _order = "date_order, create_date desc"
65 _order = "date_order desc"
68 def unlink(self, cr, uid, ids, context={}):
70 for rec in self.browse(cr, uid, ids, context=context):
71 for rec_statement in rec.statement_ids:
72 if (rec_statement.statement_id and rec_statement.statement_id.state=='confirm') or rec.state=='done':
73 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
74 return super(pos_order, self).unlink(cr, uid, ids, context=context)
76 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
78 """ Changed price list on_change of partner_id"""
82 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
83 return {'value':{'pricelist_id': pricelist}}
85 def _amount_total(self, cr, uid, ids, field_name, arg, context):
87 """ Calculates amount_tax of order line
88 @param field_names: Names of fields.
89 @return: Dictionary of values """
95 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
98 LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
99 WHERE p.id =ANY(%s) GROUP BY p.id """,(ids,))
100 res = dict(cr.fetchall())
101 for rec in self.browse(cr, uid, ids, context):
103 and rec.partner_id.property_account_position \
104 and rec.partner_id.property_account_position.tax_ids:
105 res[rec.id] = res[rec.id] - rec.amount_tax
107 res[rec.id] = res[rec.id] + rec.amount_tax
110 def _get_date_payment2(self, cr, uid, ids, context, *a):
112 # Todo need to check this function
113 """ Find payment Date
115 @param field_names: Names of fields.
116 @return: Dictionary of values """
119 pay_obj = self.pool.get('account.bank.statement')
120 stat_obj_line = self.pool.get('account.bank.statement.line')
123 for order in self.browse(cr, uid, ids):
124 cr.execute("select date_payment from pos_order where id=%d"%(order.id))
126 date_p=date_p and date_p[0] or None
130 cr.execute(" SELECT max(l.date) from account_move_line l, account_move m, account_invoice i, account_move_reconcile r, pos_order o where i.move_id=m.id and l.move_id=m.id and l.reconcile_id=r.id and o.id=%d and o.invoice_id=i.id"%(order.id))
132 val= val and val[0] or None
134 cr.execute("select max(date) from account_bank_statement_line l, account_bank_statement_reconcile s where l.pos_statement_id=%d and l.reconcile_id=s.id"%(order.id))
136 val=val and val[0] or None
141 def _get_date_payment(self, cr, uid, ids, context, *a):
143 """ Find Validation Date
144 @return: Dictionary of values """
147 pay_obj = self.pool.get('pos.payment')
150 for order in self.browse(cr, uid, ids):
151 cr.execute("select date_validation from pos_order where id=%d"%(order.id))
153 date_p=date_p and date_p[0] or None
157 discount_allowed=order.company_id.company_discount
158 for line in order.lines:
159 if line.discount > discount_allowed:
160 return {order.id: None }
161 if order.amount_paid == order.amount_total and not date_p:
162 cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
164 val=val and val[0] or None
165 if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
166 for o in order.invoice_id.move_id.line_id:
168 if val<o.date_created:
174 def _amount_all(self, cr, uid, ids, name, args, context=None):
175 tax_obj = self.pool.get('account.tax')
177 for order in self.browse(cr, uid, ids):
183 for payment in order.statement_ids:
184 res[order.id]['amount_paid'] += payment.amount
185 for payment in order.payments:
186 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
187 for line in order.lines:
188 if order.price_type!='tax_excluded':
189 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
190 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
192 (1-(line.discount or 0.0)/100.0), line.qty),
193 res[order.id]['amount_tax'])
195 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
196 tax_obj.compute_all(cr, uid, line.product_id.taxes_id,
198 (1-(line.discount or 0.0)/100.0), line.qty),
199 res[order.id]['amount_tax'])
204 def _sale_journal_get(self, cr, uid, context):
206 """ To get sale journal for this order"
209 journal_obj = self.pool.get('account.journal')
210 res = journal_obj.search(cr, uid,
211 [('type', '=', 'sale')], limit=1)
217 def _shop_get(self, cr, uid, context):
219 """ To get Shop for this order"
222 company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id
223 res = self.pool.get('sale.shop').search(cr, uid, [])
228 def copy(self, cr, uid, id, default=None, context={}):
237 'account_move': False,
242 return super(pos_order, self).copy(cr, uid, id, default, context)
244 def _get_v( self, cr, uid, ids,*a):
246 """ Changed the Validation state of order
250 res_company = self.pool.get('res.company')
251 res_obj = self.pool.get('res.users')
252 company_disc=self.browse(cr,uid,ids)
254 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
256 comp= company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
257 cr.execute("select discount from pos_order_line where order_id=%s and discount <= %s"%(ids[0],comp))
259 cr.execute("select discount from pos_order_line where order_id=%s and discount > %s"%(ids[0],comp))
261 cr.execute("select journal_id from account_bank_statement_line where pos_statement_id=%s "%(ids[0]))
265 cr.execute("select id from account_journal where name= '%s' and special_journal='t'"%(r[0]))
267 is_special=res3 and res3[0] or None
269 list_jrnl.append(is_special)
271 for order in self.browse(cr, uid, ids):
272 if order.state in ('paid','done','invoiced') and res and not res2 and not len(list_jrnl):
273 r[order.id] = 'accepted'
277 'name': fields.char('Order Description', size=64, required=True,
278 states={'draft': [('readonly', False)]}, readonly=True),
279 'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
280 'num_sale': fields.char('Internal Note', size=64),
281 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
282 states={'draft': [('readonly', False)]}, readonly=True),
283 'date_order': fields.datetime('Date Ordered', readonly=True),
284 'date_validation': fields.function(_get_date_payment, method=True, string='Validation Date', type='date', store=True),
285 'date_payment': fields.function(_get_date_payment2, method=True, string='Payment Date', type='date', store=True),
286 'date_validity': fields.date('Validity Date', required=True),
287 'user_id': fields.many2one('res.users', 'Connected Salesman', readonly=True),
288 'user_salesman_id': fields.many2one('res.users', 'Salesman', required=True),
289 'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
290 'amount_tax': fields.function(_amount_all, method=True, string='Taxes',digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
291 'amount_total': fields.function(_amount_total, method=True, string='Total'),
292 'amount_paid': fields.function(_amount_all, 'Paid', states={'draft': [('readonly', False)]}, readonly=True, method=True,digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
293 'amount_return': fields.function(_amount_all, 'Returned', method=True,digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
294 'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
295 'price_type': fields.selection([
296 ('tax_excluded','Tax excluded')
297 ], 'Price method', required=True),
298 'statement_ids': fields.one2many('account.bank.statement.line','pos_statement_id','Payments'),
299 'payments': fields.one2many('pos.payment', 'order_id', 'Order Payments', states={'draft': [('readonly', False)]}, readonly=True),
300 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
301 'partner_id': fields.many2one( 'res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
302 'state': fields.selection([('draft', 'Draft'), ('payment', 'Payment'),
303 ('advance','Advance'),
304 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced'), ('cancel', 'Cancel')],
305 'State', readonly=True, ),
306 'invoice_id': fields.many2one('account.invoice', 'Invoice'),
307 'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
308 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
309 'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
310 'first_name': fields.char('First Name', size=64),
311 'state_2': fields.function(_get_v,type='selection',selection=[('to_verify', 'To Verify'), ('accepted', 'Accepted'),
312 ('refused', 'Refused')], string='State', readonly=True, method=True, store=True),
313 'note': fields.text('Internal Notes'),
314 'nb_print': fields.integer('Number of Print', readonly=True),
315 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True, ),
316 'invoice_wanted': fields.boolean('Create Invoice'),
317 'note_2': fields.char('Customer Note',size=64),
318 'type_rec': fields.char('Type of Receipt',size=64),
319 'remboursed': fields.boolean('Remboursed'),
320 'contract_number': fields.char('Contract Number', size=512, select=1),
321 'journal_entry': fields.boolean('Journal Entry'),
325 def _select_pricelist(self, cr, uid, context):
327 """ To get default pricelist for the order"
328 @param name: Names of fields.
329 @return: pricelist ID
331 pricelist = self.pool.get('product.pricelist').search(cr, uid, [('name', '=', 'Public Pricelist')])
337 def _journal_default(self, cr, uid, context={}):
339 """ To get default pricelist for the order"
340 @param name: Names of fields.
343 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
345 return journal_list[0]
350 'user_salesman_id':lambda self, cr, uid, context: uid,
351 'user_id': lambda self, cr, uid, context: uid,
352 'sale_manager': lambda self, cr, uid, context: uid,
353 'state': lambda *a: 'draft',
354 'price_type': lambda *a: 'tax_excluded',
355 'state_2': lambda *a: 'to_verify',
356 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
357 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
358 'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
359 'nb_print': lambda *a: 0,
360 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
361 'sale_journal': _sale_journal_get,
362 'invoice_wanted': lambda *a: False,
363 'shop_id': _shop_get,
364 'pricelist_id': _select_pricelist,
368 def test_order_lines(self, cr, uid, order, context={}):
370 """ Test order line is created or not for the order "
371 @param name: Names of fields.
375 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
377 wf_service = netsvc.LocalService("workflow")
378 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
381 def dummy_button(self, cr, uid, order, context={}):
384 def test_paid(self, cr, uid, ids, context=None):
386 """ Test all amount is paid for this order
389 for order in self.browse(cr, uid, ids, context):
390 if order.lines and not order.amount_total:
392 if (not order.lines) or (not order.statement_ids) or \
393 Decimal(str(order.amount_total))!=Decimal(str(order.amount_paid)):
397 def _get_qty_differences(self, orders, old_picking):
399 """check if the customer changed the product quantity """
403 for line in order.lines:
404 order_dict[line.product_id.id] = line
406 # check the quantity differences:
408 for line in old_picking.move_lines:
409 order_line = order_dict.get(line.product_id.id)
412 qty_to_delete_from_original_picking = line.product_qty
413 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
414 elif line.product_qty != order_line.qty:
416 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
417 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
421 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
423 """if the customer changes the product quantity, split the picking in two"""
425 # create a copy of the original picking and adjust the product qty:
426 picking_model = self.pool.get('stock.picking')
428 'note': "Partial picking from customer", # add a note to tell why we create a new picking
429 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
432 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
433 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
435 for line in new_picking.move_lines:
436 p_id = line.product_id.id
437 if p_id in diff_dict:
438 diff = diff_dict[p_id]
441 if deleted: # product has been deleted (customer didn't took it):
442 # delete this product from old picking:
443 for old_line in old_picking.move_lines:
444 if old_line.product_id.id == p_id:
445 old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
446 old_line.unlink(context=context)
447 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
448 # subtract qty from old picking:
449 for old_line in old_picking.move_lines:
450 if old_line.product_id.id == p_id:
451 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
452 # add qty to new picking:
453 line.write({'product_qty': qty_to_del}, context=context)
454 else: # product hasn't changed (customer took it without any change):
455 # delete this product from new picking:
456 line.unlink(context=context)
458 # delete it in the new picking:
459 line.unlink(context=context)
461 def create_picking(self, cr, uid, ids, context={}):
463 """Create a picking for each order and validate it."""
465 picking_obj = self.pool.get('stock.picking')
466 pick_name=self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
467 orders = self.browse(cr, uid, ids, context)
469 if not order.picking_id:
471 picking_id = picking_obj.create(cr, uid, {
473 'origin': order.name,
476 'move_type': 'direct',
477 'note': 'POS notes ' + (order.note or ""),
478 'invoice_state': 'none',
479 'auto_picking': True,
480 'pos_order': order.id,
482 self.write(cr, uid, [order.id], {'picking_id': picking_id})
484 picking_id = order.picking_id.id
485 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
486 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
489 # split the picking (if product quantity has changed):
490 diff_dict = self._get_qty_differences(orders, picking)
492 self._split_picking(cr, uid, ids, context, picking, diff_dict)
495 for line in order.lines:
496 if line.product_id and line.product_id.type=='service':
498 prop_ids = self.pool.get("ir.property").search(cr, uid, [('name', '=', 'property_stock_customer')])
499 val = self.pool.get("ir.property").browse(cr, uid, prop_ids[0]).value_reference
500 cr.execute("select s.id from stock_location s, stock_warehouse w where w.lot_stock_id=s.id and w.id= %d "%(order.shop_id.warehouse_id.id))
502 location_id=res and res[0] or None
503 # location_id = order and order.shop_id and order.shop_id.warehouse_id and order.shop_id.warehouse_id.lot_stock_id.id or None
504 stock_dest_id = val.id
506 location_id, stock_dest_id = stock_dest_id, location_id
508 self.pool.get('stock.move').create(cr, uid, {
509 'name': 'Stock move (POS %d)' % (order.id, ),
510 'product_uom': line.product_id.uom_id.id,
511 'product_uos': line.product_id.uom_id.id,
512 'picking_id': picking_id,
513 'product_id': line.product_id.id,
514 'product_uos_qty': abs(line.qty),
515 'product_qty': abs(line.qty),
516 'tracking_id': False,
517 'pos_line_id': line.id,
519 'location_id': location_id,
520 'location_dest_id': stock_dest_id,
523 wf_service = netsvc.LocalService("workflow")
524 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
525 self.pool.get('stock.picking').force_assign(cr, uid, [picking_id], context)
529 def set_to_draft(self, cr, uid, ids, *args):
531 """ Changes order state to draft
537 self.write(cr, uid, ids, {'state': 'draft'})
539 wf_service = netsvc.LocalService("workflow")
541 wf_service.trg_create(uid, 'pos.order', i, cr)
544 def button_invalidate(self, cr, uid, ids, *args):
546 """ Check the access for the sale order
549 res_obj = self.pool.get('res.company')
551 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
553 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
555 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
558 def button_validate(self, cr, uid, ids, *args):
560 """ Check the access for the sale order and update the date_validation
563 res_obj = self.pool.get('res.company')
565 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
567 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
569 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
570 for order in self.browse(cr, uid, ids):
571 if not order.date_validation:
572 cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
574 val=val and val[0] or None
576 cr.execute("Update pos_order set date_validation='%s' where id = %d"%(val, order.id))
580 def cancel_order(self, cr, uid, ids, context=None):
582 """ Changes order state to cancel
585 self.write(cr, uid, ids, {'state': 'cancel'})
586 self.cancel_picking(cr, uid, ids, context={})
589 def add_payment(self, cr, uid, order_id, data, context=None):
591 """Create a new payment for the order"""
593 res_obj = self.pool.get('res.company')
594 statementl_obj = self.pool.get('account.bank.statement.line')
595 prod_obj = self.pool.get('product.product')
597 curr_c=self.pool.get('res.users').browse(cr, uid, uid).company_id
598 curr_company=curr_c.id
599 order = self.browse(cr, uid, order_id, context)
600 if not order.num_sale and data['num_sale']:
601 self.write(cr,uid,order_id,{'num_sale': data['num_sale']})
603 if order.invoice_wanted and not order.partner_id:
604 raise osv.except_osv(_('Error'), _('Cannot create invoice without a partner.'))
606 'amount': data['amount'],
608 if 'payment_date' in data.keys():
609 args['date'] = data['payment_date']
610 if 'payment_name' in data.keys():
611 args['name'] = data['payment_name'] + ' ' +order.name
612 account_def = self.pool.get('ir.property').get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
613 args['account_id'] = order.partner_id and order.partner_id.property_account_receivable and order.partner_id.property_account_receivable.id or account_def.id or curr_c.account_receivable.id
614 if data.get('is_acc',False):
615 args['is_acc']=data['is_acc']
616 args['account_id']= prod_obj.browse(cr,uid, data['product_id']).property_account_income and prod_obj.browse(cr,uid, data['product_id']).property_account_income.id
617 if not args['account_id']:
618 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')%(prod_obj.browse(cr,uid, data['product_id']).name))
619 args['partner_id'] = order.partner_id and order.partner_id.id or None
620 args['ref'] = order.contract_number or None
622 statement_obj= self.pool.get('account.bank.statement')
623 statement_id = statement_obj.search(cr,uid, [
624 ('journal_id', '=', data['journal']),
625 ('company_id', '=', curr_company),
626 ('user_id', '=', uid),
627 ('state', '=', 'open')])
628 if len(statement_id)==0:
629 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
631 statement_id=statement_id[0]
632 args['statement_id']= statement_id
633 args['pos_statement_id']= order_id
634 args['journal_id']= data['journal']
635 statement_line_id = statementl_obj.create(cr, uid, args)
636 ids_new.append(statement_id)
638 wf_service = netsvc.LocalService("workflow")
639 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
640 wf_service.trg_write(uid, 'pos.order', order_id, cr)
644 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
646 """Create a new order line the order"""
648 line_obj = self.pool.get('pos.order.line')
649 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
651 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
652 product = values['partner_id'] and values['partner_id'][0]
654 price = line_obj.price_by_product(cr, uid, [],
655 pricelist, product_id, qty, product)
657 order_line_id = line_obj.create(cr, uid, {
658 'order_id': order_id,
659 'product_id': product_id,
663 wf_service = netsvc.LocalService("workflow")
664 wf_service.trg_write(uid, 'pos.order', order_id, cr)
668 def refund(self, cr, uid, ids, context={}):
670 """Create a copy of order for refund order"""
673 line_obj = self.pool.get('pos.order.line')
675 for order in self.browse(cr, uid, ids):
676 clone_id = self.copy(cr, uid, order.id, {
677 'name': order.name + ' REFUND',
678 'date_order': time.strftime('%Y-%m-%d'),
680 'note': 'REFUND\n'+ (order.note or ''),
683 'statement_ids': False,
685 clone_list.append(clone_id)
688 for clone in self.browse(cr, uid, clone_list):
689 for order_line in clone.lines:
690 line_obj.write(cr, uid, [order_line.id], {
691 'qty': -order_line.qty
695 def action_invoice(self, cr, uid, ids, context={}):
697 """Create a invoice of order """
699 res_obj = self.pool.get('res.company')
700 inv_ref = self.pool.get('account.invoice')
701 inv_line_ref = self.pool.get('account.invoice.line')
702 product_obj= self.pool.get('product.product')
705 for order in self.browse(cr, uid, ids, context):
706 curr_c = order.user_salesman_id.company_id
708 inv_ids.append(order.invoice_id.id)
711 if not order.partner_id:
712 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
714 acc= order.partner_id.property_account_receivable.id
716 'name': 'Invoice from POS: '+order.name,
717 'origin': order.name,
719 'journal_id':order.sale_journal.id or None,
720 'type': 'out_invoice',
721 'reference': order.name,
722 'partner_id': order.partner_id.id,
723 'comment': order.note or '',
725 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
726 if not inv.get('account_id', None):
727 inv['account_id'] = acc
728 inv_id = inv_ref.create(cr, uid, inv, context)
730 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
731 inv_ids.append(inv_id)
732 for line in order.lines:
734 'invoice_id': inv_id,
735 'product_id': line.product_id.id,
736 'quantity': line.qty,
738 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
740 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
742 line.product_id.uom_id.id,
743 line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
744 inv_line['price_unit'] = line.price_unit
745 inv_line['discount'] = line.discount
746 inv_line['account_id'] = acc
747 inv_line['name'] = inv_name
749 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
750 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
751 inv_line_ref.create(cr, uid, inv_line, context)
754 wf_service = netsvc.LocalService("workflow")
755 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
758 def create_account_move(self, cr, uid, ids, context=None):
760 """Create a account move line of order """
762 account_move_obj = self.pool.get('account.move')
763 account_move_line_obj = self.pool.get('account.move.line')
764 account_period_obj = self.pool.get('account.period')
765 account_tax_obj = self.pool.get('account.tax')
766 res_obj=self.pool.get('res.users')
767 property_obj=self.pool.get('ir.property')
768 period = account_period_obj.find(cr, uid, context=context)[0]
770 for order in self.browse(cr, uid, ids, context=context):
771 curr_c =res_obj.browse(cr, uid, uid).company_id
772 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
773 comp_id=comp_id and comp_id.id or False
776 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
778 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
780 # Create an entry for the sale
781 move_id = account_move_obj.create(cr, uid, {
782 'journal_id': order.sale_journal.id,
786 # Create an move for each order line
787 for line in order.lines:
790 taxes = [t for t in line.product_id.taxes_id]
791 if order.price_type=='tax_excluded':
792 computed_taxes = account_tax_objcompute_all(
793 cr, uid, taxes, line.price_unit, line.qty)
795 computed_taxes = account_tax_obj.compute_inv(
796 cr, uid, taxes, line.price_unit, line.qty)
798 for tax in computed_taxes:
799 tax_amount += round(tax['amount'], 2)
800 group_key = (tax['tax_code_id'],
802 tax['account_collected_id'])
804 if group_key in group_tax:
805 group_tax[group_key] += round(tax['amount'], 2)
807 group_tax[group_key] = round(tax['amount'], 2)
808 if order.price_type!='tax_excluded':
809 amount = line.price_subtotal - tax_amount
811 amount = line.price_subtotal
813 # Search for the income account
814 if line.product_id.property_account_income.id:
815 income_account = line.\
816 product_id.property_account_income.id
817 elif line.product_id.categ_id.\
818 property_account_income_categ.id:
819 income_account = line.product_id.categ_id.\
820 property_account_income_categ.id
822 raise osv.except_osv(_('Error !'), _('There is no income '\
823 'account defined for this product: "%s" (id:%d)') \
824 % (line.product_id.name, line.product_id.id, ))
827 # Empty the tax list as long as there is no tax code:
830 while computed_taxes:
831 tax = computed_taxes.pop(0)
833 tax_code_id = tax['base_code_id']
834 tax_amount = line.price_subtotal * tax['base_sign']
836 tax_code_id = tax['ref_base_code_id']
837 tax_amount = line.price_subtotal * tax['ref_base_sign']
838 # If there is one we stop
842 # Create a move for the line
843 account_move_line_obj.create(cr, uid, {
844 'name': "aa"+order.name,
845 'date': order.date_order,
846 'ref': order.contract_number or order.name,
847 'quantity': line.qty,
848 'product_id':line.product_id.id,
850 'account_id': income_account,
851 'company_id': comp_id,
852 'credit': ((amount>0) and amount) or 0.0,
853 'debit': ((amount<0) and -amount) or 0.0,
854 'journal_id': order.sale_journal.id,
856 'tax_code_id': tax_code_id,
857 'tax_amount': tax_amount,
860 # For each remaining tax with a code, whe create a move line
861 for tax in computed_taxes:
863 tax_code_id = tax['base_code_id']
864 tax_amount = line.price_subtotal * tax['base_sign']
866 tax_code_id = tax['ref_base_code_id']
867 tax_amount = line.price_subtotal * tax['ref_base_sign']
871 account_move_line_obj.create(cr, uid, {
872 'name': "bb"+order.name,
873 'date': order.date_order,
874 'ref': order.contract_number or order.name,
875 'product_id':line.product_id.id,
876 'quantity': line.qty,
878 'account_id': income_account,
879 'company_id': comp_id,
882 'journal_id': order.sale_journal.id,
884 'tax_code_id': tax_code_id,
885 'tax_amount': tax_amount,
889 # Create a move for each tax group
890 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
891 for key, amount in group_tax.items():
892 account_move_line_obj.create(cr, uid, {
893 'name':"cc"+order.name,
894 'date': order.date_order,
895 'ref': order.contract_number or order.name,
897 'company_id': comp_id,
898 'quantity': line.qty,
899 'product_id':line.product_id.id,
900 'account_id': key[account_pos],
901 'credit': ((amount>0) and amount) or 0.0,
902 'debit': ((amount<0) and -amount) or 0.0,
903 'journal_id': order.sale_journal.id,
905 'tax_code_id': key[tax_code_pos],
906 'tax_amount': amount,
910 to_reconcile.append(account_move_line_obj.create(cr, uid, {
911 'name': "dd"+order.name,
912 'date': order.date_order,
913 'ref': order.contract_number or order.name,
915 'company_id': comp_id,
916 'account_id': order_account,
917 'credit': ((order.amount_total<0) and -order.amount_total)\
919 'debit': ((order.amount_total>0) and order.amount_total)\
921 'journal_id': order.sale_journal.id,
926 # search the account receivable for the payments:
927 account_receivable = order.sale_journal.default_credit_account_id.id
928 if not account_receivable:
929 raise osv.except_osv(_('Error !'),
930 _('There is no receivable account defined for this journal:'\
931 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
933 for payment in order.statement_ids:
938 payment.statement_id.journal_id.default_debit_account_id.id
941 payment.statement_id.journal_id.default_credit_account_id.id
943 # Create one entry for the payment
946 payment_move_id = account_move_obj.create(cr, uid, {
947 'journal_id': payment.statement_id.journal_id.id,
951 for stat_l in order.statement_ids:
952 if stat_l.is_acc and len(stat_l.move_ids):
953 for st in stat_l.move_ids:
956 account_move_line_obj.copy(cr, uid, s.id, { 'debit': s.credit,
957 'statement_id': False,
959 account_move_line_obj.copy(cr, uid, s.id, {
960 'statement_id': False,
961 'account_id':order_account
964 self.write(cr,uid,order.id,{'state':'done'})
967 def cancel_picking(self, cr, uid, ids, context=None):
968 for order in self.browse(cr, uid, ids, context=context):
969 for picking in order.pickings:
970 self.pool.get('stock.picking').unlink(cr, uid, [picking.id], context)
974 def action_payment(self, cr, uid, ids, context=None):
975 vals = {'state': 'payment'}
976 sequence_obj=self.pool.get('ir.sequence')
977 for pos in self.browse(cr, uid, ids):
978 create_contract_nb = False
979 for line in pos.lines:
980 if line.product_id.product_type == 'MD':
981 create_contract_nb = True
983 if create_contract_nb:
984 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
985 vals['contract_number'] ='%s-%s' % (pos.user_salesman_id.login, seq)
986 self.write(cr, uid, ids, vals)
988 def action_paid(self, cr, uid, ids, context=None):
991 if context.get('flag',False):
992 self.create_picking(cr, uid, ids, context={})
993 self.write(cr, uid, ids, {'state': 'paid'})
998 def action_cancel(self, cr, uid, ids, context=None):
999 self.write(cr, uid, ids, {'state': 'cancel'})
1002 def action_done(self, cr, uid, ids, context=None):
1003 for order in self.browse(cr, uid, ids, context=context):
1004 if not order.journal_entry:
1005 self.create_account_move(cr, uid, ids, context={})
1008 def compute_state(self, cr, uid, id):
1009 cr.execute("select act.id, act.name from wkf_activity act "
1010 "inner join wkf_workitem item on act.id=item.act_id "
1011 "inner join wkf_instance inst on item.inst_id=inst.id "
1012 "inner join wkf on inst.wkf_id=wkf.id "
1013 "where wkf.osv='pos.order' and inst.res_id=%s "
1014 "order by act.name", (id,))
1015 return [name for id, name in cr.fetchall()]
1019 class account_bank_statement(osv.osv):
1020 _inherit = 'account.bank.statement'
1022 'user_id': fields.many2one('res.users',ondelete='cascade',string='User', readonly=True),
1025 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
1027 account_bank_statement()
1029 class account_bank_statement_line(osv.osv):
1030 _inherit = 'account.bank.statement.line'
1031 def _get_statement_journal(self, cr, uid, ids, context, *a):
1033 for line in self.browse(cr, uid, ids):
1034 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
1037 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
1038 'am_out':fields.boolean("To count"),
1039 'is_acc':fields.boolean("Is accompte"),
1040 'pos_statement_id': fields.many2one('pos.order',ondelete='cascade'),
1042 account_bank_statement_line()
1044 class pos_order_line(osv.osv):
1045 _name = "pos.order.line"
1046 _description = "Lines of Point of Sale"
1048 def _get_amount(self, cr, uid, ids, field_name, arg, context):
1050 for line in self.browse(cr, uid, ids):
1051 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)
1055 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context):
1057 account_tax_obj = self.pool.get('account.tax')
1058 for line in self.browse(cr, uid, ids):
1060 taxes = [t for t in line.product_id.taxes_id]
1061 computed_taxes = account_tax_objcompute_all(cr, uid, taxes, line.price_unit, line.qty)
1062 for tax in computed_taxes:
1063 tax_amount += tax['amount']
1064 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)
1065 if line.discount!=0.0:
1066 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1068 res[line.id]=line.price_unit*line.qty
1069 res[line.id] = res[line.id] + tax_amount
1072 def _amount_line(self, cr, uid, ids, field_name, arg, context):
1075 for line in self.browse(cr, uid, ids):
1076 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)
1077 if line.discount!=0.0:
1078 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1080 res[line.id]=line.price_unit*line.qty
1083 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1087 raise osv.except_osv(_('No Pricelist !'),
1088 _('You have to select a pricelist in the sale form !\n' \
1089 'Please set one before choosing a product.'))
1090 p_obj = self.pool.get('product.product').browse(cr,uid,[product_id])[0]
1091 uom_id=p_obj.uom_po_id.id
1092 price = self.pool.get('product.pricelist').price_get(cr, uid,
1093 [pricelist], product_id, qty or 1.0, partner_id,{'uom': uom_id})[pricelist]
1094 unit_price=price or p_obj.list_price
1095 if unit_price is False:
1096 raise osv.except_osv(_('No valid pricelist line found !'),
1097 _("Couldn't find a pricelist line matching this product" \
1098 " and quantity.\nYou have to change either the product," \
1099 " the quantity or the pricelist."))
1102 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1103 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1104 self.write(cr,uid,ids,{'price_unit':price})
1105 return {'value': {'price_unit': price}, 'qty': 1}
1107 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist,qty,partner_id, product_id,*a):
1108 prod_obj = self.pool.get('product.product')
1109 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1112 prod_id=prod_obj.browse(cr,uid,product_id).disc_controle
1114 if (disc != 0.0 or prod_id) and price_f>0:
1115 disc=100-(price/price_f*100)
1116 return {'value':{'discount':disc, 'price_unit':price_f}}
1119 def onchange_ded(self, cr, uid,ids, val_ded,price_u,*a):
1120 pos_order = self.pool.get('pos.order.line')
1121 res_obj = self.pool.get('res.users')
1122 res_company = self.pool.get('res.company')
1123 comp = res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1125 if val_ded and price_u:
1126 val=100.0*val_ded/price_u
1128 return {'value': {'discount':val, 'notice':'' }}
1129 return {'value': {'discount':val}}
1131 def onchange_discount(self, cr, uid,ids, discount,price,*a):
1132 pos_order = self.pool.get('pos.order.line')
1133 res_obj = self.pool.get('res.users')
1134 res_company = self.pool.get('res.company')
1135 company_disc = pos_order.browse(cr,uid,ids)
1137 if not company_disc:
1138 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1140 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
1142 if discount > comp :
1143 return {'value': {'notice':'','price_ded':price*discount*0.01 or 0.0 }}
1145 return {'value': {'notice':'Minimum Discount','price_ded':price*discount*0.01 or 0.0 }}
1147 return {'value': {'notice':'No Discount', 'price_ded':price*discount*0.01 or 0.0 }}
1149 'name': fields.char('Line Description', size=512),
1150 'company_id':fields.many2one('res.company', 'Company', required=True),
1151 'notice': fields.char('Discount Notice', size=128, required=True),
1152 'serial_number': fields.char('Serial Number', size=128),
1153 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1154 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1155 'price_ded': fields.float('Discount(Amount)',digits_compute=dp.get_precision('Point Of Sale')),
1156 'qty': fields.float('Quantity'),
1157 'qty_rfd': fields.float('Refunded Quantity'),
1158 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal w/o Tax'),
1159 'price_subtotal_incl': fields.function(_amount_line_ttc, method=True, string='Subtotal'),
1160 'discount': fields.float('Discount (%)', digits=(16, 2)),
1161 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1162 'create_date': fields.datetime('Creation Date', readonly=True),
1166 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1167 'qty': lambda *a: 1,
1168 'discount': lambda *a: 0.0,
1169 'price_ded': lambda *a: 0.0,
1170 'notice': lambda *a: 'No Discount',
1171 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1174 def create(self, cr, user, vals, context={}):
1175 if vals.get('product_id'):
1176 return super(pos_order_line, self).create(cr, user, vals, context)
1179 def write(self, cr, user, ids, values, context={}):
1180 if 'product_id' in values and not values['product_id']:
1182 return super(pos_order_line, self).write(cr, user, ids, values, context)
1184 def _scan_product(self, cr, uid, ean, qty, order):
1185 # search pricelist_id
1186 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1187 if not pricelist_id:
1192 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
1196 # search price product
1197 product = self.pool.get('product.product').read(cr, uid, product_id)
1198 product_name = product[0]['name']
1199 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1201 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
1204 order_line_id = order_line_ids[0]
1205 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1208 vals = {'product_id': product_id[0],
1209 'price_unit': price,
1211 'name': product_name,
1214 line_id = self.create(cr, uid, vals)
1216 raise osv.except_osv(_('Error'), _('Create line failed !'))
1222 line_id = self.write(cr, uid, order_line_id, vals)
1224 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
1225 line_id = order_line_id
1227 price_line = float(qty)*float(price)
1228 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
1233 class pos_payment(osv.osv):
1234 _name = 'pos.payment'
1235 _description = 'Pos Payment'
1237 def _journal_get(self, cr, uid, context={}):
1238 obj = self.pool.get('account.journal')
1239 ids = obj.search(cr, uid, [('type', '=', 'cash')])
1240 res = obj.read(cr, uid, ids, ['id', 'name'], context)
1241 res = [(r['id'], r['name']) for r in res]
1244 def _journal_default(self, cr, uid, context={}):
1245 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
1247 return journal_list[0]
1252 'name': fields.char('Description', size=64),
1253 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
1254 'journal_id': fields.many2one('account.journal', "Journal", required=True),
1255 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
1256 'payment_nb': fields.char('Piece Number', size=32),
1257 'payment_name': fields.char('Payment Name', size=32),
1258 'payment_date': fields.date('Payment Date', required=True),
1259 'amount': fields.float('Amount', required=True),
1262 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
1263 'journal_id': _journal_default,
1264 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
1267 def create(self, cr, user, vals, context={}):
1268 if vals.get('journal_id') and vals.get('amount'):
1269 return super(pos_payment, self).create(cr, user, vals, context)
1272 def write(self, cr, user, ids, values, context={}):
1273 if 'amount' in values and not values['amount']:
1275 if 'journal_id' in values and not values['journal_id']:
1277 return super(pos_payment, self).write(cr, user, ids, values, context)
1281 class account_move_line(osv.osv):
1283 _inherit = 'account.move.line'
1284 def create(self, cr, user, vals, context={}):
1285 pos_obj = self.pool.get('pos.order')
1286 val_name = vals.get('name', '')
1287 val_ref = vals.get('ref', '')
1288 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1289 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1290 name_pos = aaa.groups()[0]
1291 pos_id = name_pos.replace('POS ','')
1292 if pos_id and pos_id.isdigit():
1293 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1294 pos_curr = pos_curr and pos_curr.contract_number or ''
1295 vals['ref'] = pos_curr or vals.get('ref')
1296 return super(account_move_line, self).create(cr, user, vals, context)
1301 class account_move(osv.osv):
1303 _inherit = 'account.move'
1305 def create(self, cr, user, vals, context={}):
1306 pos_obj = self.pool.get('pos.order')
1307 val_name = vals.get('name', '')
1308 val_ref = vals.get('ref', '')
1309 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1310 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1311 name_pos = aaa.groups()[0]
1312 pos_id = name_pos.replace('POS ','')
1313 if pos_id and pos_id.isdigit():
1314 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1315 pos_curr = pos_curr and pos_curr.contract_number or ''
1316 vals['ref'] = pos_curr or vals.get('ref')
1317 return super(account_move, self).create(cr, user, vals, context)
1322 class product_product(osv.osv):
1323 _inherit = 'product.product'
1325 'income_pdt': fields.boolean('Product for Incoming'),
1326 'expense_pdt': fields.boolean('Product for expenses'),
1327 'am_out': fields.boolean('Controle for Outgoing Operations'),
1328 'disc_controle': fields.boolean('Discount Controle '),
1331 'disc_controle': lambda *a: True,
1335 class stock_picking(osv.osv):
1337 _inherit = 'stock.picking'
1339 'pos_order': fields.many2one('pos.order', 'Pos order'),
1343 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: