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')
176 cur_obj = self.pool.get('res.currency')
178 for order in self.browse(cr, uid, ids):
185 cur_obj = self.pool.get('res.currency')
186 cur = order.pricelist_id.currency_id
187 for payment in order.statement_ids:
188 res[order.id]['amount_paid'] += payment.amount
189 for payment in order.payments:
190 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
191 for line in order.lines:
192 if order.price_type!='tax_excluded':
193 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
194 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
196 (1-(line.discount or 0.0)/100.0), line.qty),
197 res[order.id]['amount_tax'])
199 for c in tax_obj.compute_all(cr, uid, line.product_id.taxes_id, line.price_unit * (1-(line.discount or 0.0)/100.0), line.qty, line.product_id, line.order_id.partner_id)['taxes']:
201 res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
206 def _sale_journal_get(self, cr, uid, context):
208 """ To get sale journal for this order"
211 journal_obj = self.pool.get('account.journal')
212 res = journal_obj.search(cr, uid,
213 [('type', '=', 'sale')], limit=1)
219 def _shop_get(self, cr, uid, context):
221 """ To get Shop for this order"
224 company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id
225 res = self.pool.get('sale.shop').search(cr, uid, [])
230 def copy(self, cr, uid, id, default=None, context={}):
239 'account_move': False,
244 return super(pos_order, self).copy(cr, uid, id, default, context)
246 def _get_v( self, cr, uid, ids,*a):
248 """ Changed the Validation state of order
252 res_company = self.pool.get('res.company')
253 res_obj = self.pool.get('res.users')
254 company_disc=self.browse(cr,uid,ids)
256 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
258 comp= company_disc[0] and company_disc[0].company_id and company_disc[0].company_id.company_discount or 0.0
259 cr.execute("select discount from pos_order_line where order_id=%s and discount <= %s"%(ids[0],comp))
261 cr.execute("select discount from pos_order_line where order_id=%s and discount > %s"%(ids[0],comp))
263 cr.execute("select journal_id from account_bank_statement_line where pos_statement_id=%s "%(ids[0]))
267 cr.execute("select id from account_journal where name= '%s' and special_journal='t'"%(r[0]))
269 is_special=res3 and res3[0] or None
271 list_jrnl.append(is_special)
273 for order in self.browse(cr, uid, ids):
274 if order.state in ('paid','done','invoiced') and res and not res2 and not len(list_jrnl):
275 r[order.id] = 'accepted'
279 'name': fields.char('Order Description', size=64, required=True,
280 states={'draft': [('readonly', False)]}, readonly=True),
281 'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
282 'num_sale': fields.char('Internal Note', size=64),
283 'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
284 states={'draft': [('readonly', False)]}, readonly=True),
285 'date_order': fields.datetime('Date Ordered', readonly=True),
286 'date_validation': fields.function(_get_date_payment, method=True, string='Validation Date', type='date', store=True),
287 'date_payment': fields.function(_get_date_payment2, method=True, string='Payment Date', type='date', store=True),
288 'date_validity': fields.date('Validity Date', required=True),
289 'user_id': fields.many2one('res.users', 'Connected Salesman', readonly=True),
290 'user_salesman_id': fields.many2one('res.users', 'Salesman', required=True),
291 'sale_manager': fields.many2one('res.users', 'Salesman Manager'),
292 'amount_tax': fields.function(_amount_all, method=True, string='Taxes',digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
293 'amount_total': fields.function(_amount_total, method=True, string='Total'),
294 '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'),
295 'amount_return': fields.function(_amount_all, 'Returned', method=True,digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
296 'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
297 'price_type': fields.selection([
298 ('tax_excluded','Tax excluded')
299 ], 'Price method', required=True),
300 'statement_ids': fields.one2many('account.bank.statement.line','pos_statement_id','Payments'),
301 'payments': fields.one2many('pos.payment', 'order_id', 'Order Payments', states={'draft': [('readonly', False)]}, readonly=True),
302 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
303 'partner_id': fields.many2one( 'res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
304 'state': fields.selection([('draft', 'Draft'), ('payment', 'Payment'),
305 ('advance','Advance'),
306 ('paid', 'Paid'), ('done', 'Done'), ('invoiced', 'Invoiced'), ('cancel', 'Cancel')],
307 'State', readonly=True, ),
308 'invoice_id': fields.many2one('account.invoice', 'Invoice'),
309 'account_move': fields.many2one('account.move', 'Account Entry', readonly=True),
310 'pickings': fields.one2many('stock.picking', 'pos_order', 'Picking', readonly=True),
311 'picking_id': fields.many2one('stock.picking', 'Last Output Picking', readonly=True),
312 'first_name': fields.char('First Name', size=64),
313 'state_2': fields.function(_get_v,type='selection',selection=[('to_verify', 'To Verify'), ('accepted', 'Accepted'),
314 ('refused', 'Refused')], string='State', readonly=True, method=True, store=True),
315 'note': fields.text('Internal Notes'),
316 'nb_print': fields.integer('Number of Print', readonly=True),
317 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True, ),
318 'invoice_wanted': fields.boolean('Create Invoice'),
319 'note_2': fields.char('Customer Note',size=64),
320 'type_rec': fields.char('Type of Receipt',size=64),
321 'remboursed': fields.boolean('Remboursed'),
322 'contract_number': fields.char('Contract Number', size=512, select=1),
323 'journal_entry': fields.boolean('Journal Entry'),
327 def _select_pricelist(self, cr, uid, context):
329 """ To get default pricelist for the order"
330 @param name: Names of fields.
331 @return: pricelist ID
333 pricelist = self.pool.get('product.pricelist').search(cr, uid, [('name', '=', 'Public Pricelist')])
339 def _journal_default(self, cr, uid, context={}):
341 """ To get default pricelist for the order"
342 @param name: Names of fields.
345 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
347 return journal_list[0]
352 'user_salesman_id':lambda self, cr, uid, context: uid,
353 'user_id': lambda self, cr, uid, context: uid,
354 'sale_manager': lambda self, cr, uid, context: uid,
355 'state': lambda *a: 'draft',
356 'price_type': lambda *a: 'tax_excluded',
357 'state_2': lambda *a: 'to_verify',
358 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
359 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
360 'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
361 'nb_print': lambda *a: 0,
362 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
363 'sale_journal': _sale_journal_get,
364 'invoice_wanted': lambda *a: False,
365 'shop_id': _shop_get,
366 'pricelist_id': _select_pricelist,
370 def test_order_lines(self, cr, uid, order, context={}):
372 """ Test order line is created or not for the order "
373 @param name: Names of fields.
377 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
379 wf_service = netsvc.LocalService("workflow")
380 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
383 def dummy_button(self, cr, uid, order, context={}):
386 def test_paid(self, cr, uid, ids, context=None):
388 """ Test all amount is paid for this order
391 for order in self.browse(cr, uid, ids, context):
392 if order.lines and not order.amount_total:
394 if (not order.lines) or (not order.statement_ids) or \
395 Decimal(str(order.amount_total))!=Decimal(str(order.amount_paid)):
399 def _get_qty_differences(self, orders, old_picking):
401 """check if the customer changed the product quantity """
405 for line in order.lines:
406 order_dict[line.product_id.id] = line
408 # check the quantity differences:
410 for line in old_picking.move_lines:
411 order_line = order_dict.get(line.product_id.id)
414 qty_to_delete_from_original_picking = line.product_qty
415 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
416 elif line.product_qty != order_line.qty:
418 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
419 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
423 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
425 """if the customer changes the product quantity, split the picking in two"""
427 # create a copy of the original picking and adjust the product qty:
428 picking_model = self.pool.get('stock.picking')
430 'note': "Partial picking from customer", # add a note to tell why we create a new picking
431 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
434 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
435 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
437 for line in new_picking.move_lines:
438 p_id = line.product_id.id
439 if p_id in diff_dict:
440 diff = diff_dict[p_id]
443 if deleted: # product has been deleted (customer didn't took it):
444 # delete this product from old picking:
445 for old_line in old_picking.move_lines:
446 if old_line.product_id.id == p_id:
447 old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
448 old_line.unlink(context=context)
449 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
450 # subtract qty from old picking:
451 for old_line in old_picking.move_lines:
452 if old_line.product_id.id == p_id:
453 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
454 # add qty to new picking:
455 line.write({'product_qty': qty_to_del}, context=context)
456 else: # product hasn't changed (customer took it without any change):
457 # delete this product from new picking:
458 line.unlink(context=context)
460 # delete it in the new picking:
461 line.unlink(context=context)
463 def create_picking(self, cr, uid, ids, context={}):
465 """Create a picking for each order and validate it."""
467 picking_obj = self.pool.get('stock.picking')
468 pick_name=self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
469 orders = self.browse(cr, uid, ids, context)
471 if not order.picking_id:
473 picking_id = picking_obj.create(cr, uid, {
475 'origin': order.name,
478 'move_type': 'direct',
479 'note': 'POS notes ' + (order.note or ""),
480 'invoice_state': 'none',
481 'auto_picking': True,
482 'pos_order': order.id,
484 self.write(cr, uid, [order.id], {'picking_id': picking_id})
486 picking_id = order.picking_id.id
487 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
488 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
491 # split the picking (if product quantity has changed):
492 diff_dict = self._get_qty_differences(orders, picking)
494 self._split_picking(cr, uid, ids, context, picking, diff_dict)
497 for line in order.lines:
498 if line.product_id and line.product_id.type=='service':
500 prop_ids = self.pool.get("ir.property").search(cr, uid, [('name', '=', 'property_stock_customer')])
501 val = self.pool.get("ir.property").browse(cr, uid, prop_ids[0]).value_reference
502 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))
504 location_id=res and res[0] or None
505 # 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
506 stock_dest_id = val.id
508 location_id, stock_dest_id = stock_dest_id, location_id
510 self.pool.get('stock.move').create(cr, uid, {
511 'name': 'Stock move (POS %d)' % (order.id, ),
512 'product_uom': line.product_id.uom_id.id,
513 'product_uos': line.product_id.uom_id.id,
514 'picking_id': picking_id,
515 'product_id': line.product_id.id,
516 'product_uos_qty': abs(line.qty),
517 'product_qty': abs(line.qty),
518 'tracking_id': False,
519 'pos_line_id': line.id,
521 'location_id': location_id,
522 'location_dest_id': stock_dest_id,
525 wf_service = netsvc.LocalService("workflow")
526 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
527 self.pool.get('stock.picking').force_assign(cr, uid, [picking_id], context)
531 def set_to_draft(self, cr, uid, ids, *args):
533 """ Changes order state to draft
539 self.write(cr, uid, ids, {'state': 'draft'})
541 wf_service = netsvc.LocalService("workflow")
543 wf_service.trg_create(uid, 'pos.order', i, cr)
546 def button_invalidate(self, cr, uid, ids, *args):
548 """ Check the access for the sale order
551 res_obj = self.pool.get('res.company')
553 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
555 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
557 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
560 def button_validate(self, cr, uid, ids, *args):
562 """ Check the access for the sale order and update the date_validation
565 res_obj = self.pool.get('res.company')
567 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
569 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
571 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
572 for order in self.browse(cr, uid, ids):
573 if not order.date_validation:
574 cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
576 val=val and val[0] or None
578 cr.execute("Update pos_order set date_validation='%s' where id = %d"%(val, order.id))
582 def cancel_order(self, cr, uid, ids, context=None):
584 """ Changes order state to cancel
587 self.write(cr, uid, ids, {'state': 'cancel'})
588 self.cancel_picking(cr, uid, ids, context={})
591 def add_payment(self, cr, uid, order_id, data, context=None):
593 """Create a new payment for the order"""
595 res_obj = self.pool.get('res.company')
596 statementl_obj = self.pool.get('account.bank.statement.line')
597 prod_obj = self.pool.get('product.product')
599 curr_c=self.pool.get('res.users').browse(cr, uid, uid).company_id
600 curr_company=curr_c.id
601 order = self.browse(cr, uid, order_id, context)
602 if not order.num_sale and data['num_sale']:
603 self.write(cr,uid,order_id,{'num_sale': data['num_sale']})
605 if order.invoice_wanted and not order.partner_id:
606 raise osv.except_osv(_('Error'), _('Cannot create invoice without a partner.'))
608 'amount': data['amount'],
610 if 'payment_date' in data.keys():
611 args['date'] = data['payment_date']
612 if 'payment_name' in data.keys():
613 args['name'] = data['payment_name'] + ' ' +order.name
614 account_def = self.pool.get('ir.property').get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
615 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
616 if data.get('is_acc',False):
617 args['is_acc']=data['is_acc']
618 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
619 if not args['account_id']:
620 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')%(prod_obj.browse(cr,uid, data['product_id']).name))
621 args['partner_id'] = order.partner_id and order.partner_id.id or None
622 args['ref'] = order.contract_number or None
624 statement_obj= self.pool.get('account.bank.statement')
625 statement_id = statement_obj.search(cr,uid, [
626 ('journal_id', '=', data['journal']),
627 ('company_id', '=', curr_company),
628 ('user_id', '=', uid),
629 ('state', '=', 'open')])
630 if len(statement_id)==0:
631 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
633 statement_id=statement_id[0]
634 args['statement_id']= statement_id
635 args['pos_statement_id']= order_id
636 args['journal_id']= data['journal']
637 statement_line_id = statementl_obj.create(cr, uid, args)
638 ids_new.append(statement_id)
640 wf_service = netsvc.LocalService("workflow")
641 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
642 wf_service.trg_write(uid, 'pos.order', order_id, cr)
646 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
648 """Create a new order line the order"""
650 line_obj = self.pool.get('pos.order.line')
651 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
653 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
654 product = values['partner_id'] and values['partner_id'][0]
656 price = line_obj.price_by_product(cr, uid, [],
657 pricelist, product_id, qty, product)
659 order_line_id = line_obj.create(cr, uid, {
660 'order_id': order_id,
661 'product_id': product_id,
665 wf_service = netsvc.LocalService("workflow")
666 wf_service.trg_write(uid, 'pos.order', order_id, cr)
670 def refund(self, cr, uid, ids, context={}):
672 """Create a copy of order for refund order"""
675 line_obj = self.pool.get('pos.order.line')
677 for order in self.browse(cr, uid, ids):
678 clone_id = self.copy(cr, uid, order.id, {
679 'name': order.name + ' REFUND',
680 'date_order': time.strftime('%Y-%m-%d'),
682 'note': 'REFUND\n'+ (order.note or ''),
685 'statement_ids': False,
687 clone_list.append(clone_id)
690 for clone in self.browse(cr, uid, clone_list):
691 for order_line in clone.lines:
692 line_obj.write(cr, uid, [order_line.id], {
693 'qty': -order_line.qty
697 def action_invoice(self, cr, uid, ids, context={}):
699 """Create a invoice of order """
701 res_obj = self.pool.get('res.company')
702 inv_ref = self.pool.get('account.invoice')
703 inv_line_ref = self.pool.get('account.invoice.line')
704 product_obj= self.pool.get('product.product')
707 for order in self.browse(cr, uid, ids, context):
708 curr_c = order.user_salesman_id.company_id
710 inv_ids.append(order.invoice_id.id)
713 if not order.partner_id:
714 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
716 acc= order.partner_id.property_account_receivable.id
718 'name': 'Invoice from POS: '+order.name,
719 'origin': order.name,
721 'journal_id':order.sale_journal.id or None,
722 'type': 'out_invoice',
723 'reference': order.name,
724 'partner_id': order.partner_id.id,
725 'comment': order.note or '',
727 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
728 if not inv.get('account_id', None):
729 inv['account_id'] = acc
730 inv_id = inv_ref.create(cr, uid, inv, context)
732 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
733 inv_ids.append(inv_id)
734 for line in order.lines:
736 'invoice_id': inv_id,
737 'product_id': line.product_id.id,
738 'quantity': line.qty,
740 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
742 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
744 line.product_id.uom_id.id,
745 line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
746 inv_line['price_unit'] = line.price_unit
747 inv_line['discount'] = line.discount
748 inv_line['account_id'] = acc
749 inv_line['name'] = inv_name
751 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
752 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
753 inv_line_ref.create(cr, uid, inv_line, context)
756 wf_service = netsvc.LocalService("workflow")
757 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
760 def create_account_move(self, cr, uid, ids, context=None):
762 """Create a account move line of order """
764 account_move_obj = self.pool.get('account.move')
765 account_move_line_obj = self.pool.get('account.move.line')
766 account_period_obj = self.pool.get('account.period')
767 account_tax_obj = self.pool.get('account.tax')
768 res_obj=self.pool.get('res.users')
769 property_obj=self.pool.get('ir.property')
770 period = account_period_obj.find(cr, uid, context=context)[0]
772 for order in self.browse(cr, uid, ids, context=context):
773 curr_c =res_obj.browse(cr, uid, uid).company_id
774 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
775 comp_id=comp_id and comp_id.id or False
778 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
780 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
782 # Create an entry for the sale
783 move_id = account_move_obj.create(cr, uid, {
784 'journal_id': order.sale_journal.id,
788 # Create an move for each order line
789 for line in order.lines:
792 taxes = [t for t in line.product_id.taxes_id]
793 if order.price_type=='tax_excluded':
794 computed_taxes = account_tax_obj.compute_all(
795 cr, uid, taxes, line.price_unit, line.qty)['taxes']
797 computed_taxes = account_tax_obj.compute_inv(
798 cr, uid, taxes, line.price_unit, line.qty)
800 for tax in computed_taxes:
801 tax_amount += round(tax['amount'], 2)
802 group_key = (tax['tax_code_id'],
804 tax['account_collected_id'])
806 if group_key in group_tax:
807 group_tax[group_key] += round(tax['amount'], 2)
809 group_tax[group_key] = round(tax['amount'], 2)
810 if order.price_type!='tax_excluded':
811 amount = line.price_subtotal - tax_amount
813 amount = line.price_subtotal
815 # Search for the income account
816 if line.product_id.property_account_income.id:
817 income_account = line.\
818 product_id.property_account_income.id
819 elif line.product_id.categ_id.\
820 property_account_income_categ.id:
821 income_account = line.product_id.categ_id.\
822 property_account_income_categ.id
824 raise osv.except_osv(_('Error !'), _('There is no income '\
825 'account defined for this product: "%s" (id:%d)') \
826 % (line.product_id.name, line.product_id.id, ))
829 # Empty the tax list as long as there is no tax code:
832 while computed_taxes:
833 tax = computed_taxes.pop(0)
835 tax_code_id = tax['base_code_id']
836 tax_amount = line.price_subtotal * tax['base_sign']
838 tax_code_id = tax['ref_base_code_id']
839 tax_amount = line.price_subtotal * tax['ref_base_sign']
840 # If there is one we stop
844 # Create a move for the line
845 account_move_line_obj.create(cr, uid, {
846 'name': "aa"+order.name,
847 'date': order.date_order,
848 'ref': order.contract_number or order.name,
849 'quantity': line.qty,
850 'product_id':line.product_id.id,
852 'account_id': income_account,
853 'company_id': comp_id,
854 'credit': ((amount>0) and amount) or 0.0,
855 'debit': ((amount<0) and -amount) or 0.0,
856 'journal_id': order.sale_journal.id,
858 'tax_code_id': tax_code_id,
859 'tax_amount': tax_amount,
862 # For each remaining tax with a code, whe create a move line
863 for tax in computed_taxes:
865 tax_code_id = tax['base_code_id']
866 tax_amount = line.price_subtotal * tax['base_sign']
868 tax_code_id = tax['ref_base_code_id']
869 tax_amount = line.price_subtotal * tax['ref_base_sign']
873 account_move_line_obj.create(cr, uid, {
874 'name': "bb"+order.name,
875 'date': order.date_order,
876 'ref': order.contract_number or order.name,
877 'product_id':line.product_id.id,
878 'quantity': line.qty,
880 'account_id': income_account,
881 'company_id': comp_id,
884 'journal_id': order.sale_journal.id,
886 'tax_code_id': tax_code_id,
887 'tax_amount': tax_amount,
891 # Create a move for each tax group
892 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
893 for key, amount in group_tax.items():
894 account_move_line_obj.create(cr, uid, {
895 'name':"cc"+order.name,
896 'date': order.date_order,
897 'ref': order.contract_number or order.name,
899 'company_id': comp_id,
900 'quantity': line.qty,
901 'product_id':line.product_id.id,
902 'account_id': key[account_pos],
903 'credit': ((amount>0) and amount) or 0.0,
904 'debit': ((amount<0) and -amount) or 0.0,
905 'journal_id': order.sale_journal.id,
907 'tax_code_id': key[tax_code_pos],
908 'tax_amount': amount,
912 to_reconcile.append(account_move_line_obj.create(cr, uid, {
913 'name': "dd"+order.name,
914 'date': order.date_order,
915 'ref': order.contract_number or order.name,
917 'company_id': comp_id,
918 'account_id': order_account,
919 'credit': ((order.amount_total<0) and -order.amount_total)\
921 'debit': ((order.amount_total>0) and order.amount_total)\
923 'journal_id': order.sale_journal.id,
928 # search the account receivable for the payments:
929 account_receivable = order.sale_journal.default_credit_account_id.id
930 if not account_receivable:
931 raise osv.except_osv(_('Error !'),
932 _('There is no receivable account defined for this journal:'\
933 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
935 for payment in order.statement_ids:
940 payment.statement_id.journal_id.default_debit_account_id.id
943 payment.statement_id.journal_id.default_credit_account_id.id
945 # Create one entry for the payment
948 payment_move_id = account_move_obj.create(cr, uid, {
949 'journal_id': payment.statement_id.journal_id.id,
953 for stat_l in order.statement_ids:
954 if stat_l.is_acc and len(stat_l.move_ids):
955 for st in stat_l.move_ids:
958 account_move_line_obj.copy(cr, uid, s.id, { 'debit': s.credit,
959 'statement_id': False,
961 account_move_line_obj.copy(cr, uid, s.id, {
962 'statement_id': False,
963 'account_id':order_account
966 self.write(cr,uid,order.id,{'state':'done'})
969 def cancel_picking(self, cr, uid, ids, context=None):
970 for order in self.browse(cr, uid, ids, context=context):
971 for picking in order.pickings:
972 self.pool.get('stock.picking').unlink(cr, uid, [picking.id], context)
976 def action_payment(self, cr, uid, ids, context=None):
977 vals = {'state': 'payment'}
978 sequence_obj=self.pool.get('ir.sequence')
979 for pos in self.browse(cr, uid, ids):
980 create_contract_nb = False
981 for line in pos.lines:
982 if line.product_id.product_type == 'MD':
983 create_contract_nb = True
985 if create_contract_nb:
986 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
987 vals['contract_number'] ='%s-%s' % (pos.user_salesman_id.login, seq)
988 self.write(cr, uid, ids, vals)
990 def action_paid(self, cr, uid, ids, context=None):
993 if context.get('flag',False):
994 self.create_picking(cr, uid, ids, context={})
995 self.write(cr, uid, ids, {'state': 'paid'})
1000 def action_cancel(self, cr, uid, ids, context=None):
1001 self.write(cr, uid, ids, {'state': 'cancel'})
1004 def action_done(self, cr, uid, ids, context=None):
1005 for order in self.browse(cr, uid, ids, context=context):
1006 if not order.journal_entry:
1007 self.create_account_move(cr, uid, ids, context={})
1010 def compute_state(self, cr, uid, id):
1011 cr.execute("select act.id, act.name from wkf_activity act "
1012 "inner join wkf_workitem item on act.id=item.act_id "
1013 "inner join wkf_instance inst on item.inst_id=inst.id "
1014 "inner join wkf on inst.wkf_id=wkf.id "
1015 "where wkf.osv='pos.order' and inst.res_id=%s "
1016 "order by act.name", (id,))
1017 return [name for id, name in cr.fetchall()]
1021 class account_bank_statement(osv.osv):
1022 _inherit = 'account.bank.statement'
1024 'user_id': fields.many2one('res.users',ondelete='cascade',string='User', readonly=True),
1027 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
1029 account_bank_statement()
1031 class account_bank_statement_line(osv.osv):
1032 _inherit = 'account.bank.statement.line'
1033 def _get_statement_journal(self, cr, uid, ids, context, *a):
1035 for line in self.browse(cr, uid, ids):
1036 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
1039 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
1040 'am_out':fields.boolean("To count"),
1041 'is_acc':fields.boolean("Is accompte"),
1042 'pos_statement_id': fields.many2one('pos.order',ondelete='cascade'),
1044 account_bank_statement_line()
1046 class pos_order_line(osv.osv):
1047 _name = "pos.order.line"
1048 _description = "Lines of Point of Sale"
1050 def _get_amount(self, cr, uid, ids, field_name, arg, context):
1052 for line in self.browse(cr, uid, ids):
1053 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)
1057 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context):
1059 account_tax_obj = self.pool.get('account.tax')
1060 for line in self.browse(cr, uid, ids):
1062 taxes = [t for t in line.product_id.taxes_id]
1063 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
1064 for tax in computed_taxes:
1065 tax_amount += tax['amount']
1066 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)
1067 if line.discount!=0.0:
1068 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1070 res[line.id]=line.price_unit*line.qty
1071 res[line.id] = res[line.id] + tax_amount
1074 def _amount_line(self, cr, uid, ids, field_name, arg, context):
1077 for line in self.browse(cr, uid, ids):
1078 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)
1079 if line.discount!=0.0:
1080 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1082 res[line.id]=line.price_unit*line.qty
1085 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1089 raise osv.except_osv(_('No Pricelist !'),
1090 _('You have to select a pricelist in the sale form !\n' \
1091 'Please set one before choosing a product.'))
1092 p_obj = self.pool.get('product.product').browse(cr,uid,[product_id])[0]
1093 uom_id=p_obj.uom_po_id.id
1094 price = self.pool.get('product.pricelist').price_get(cr, uid,
1095 [pricelist], product_id, qty or 1.0, partner_id,{'uom': uom_id})[pricelist]
1096 unit_price=price or p_obj.list_price
1097 if unit_price is False:
1098 raise osv.except_osv(_('No valid pricelist line found !'),
1099 _("Couldn't find a pricelist line matching this product" \
1100 " and quantity.\nYou have to change either the product," \
1101 " the quantity or the pricelist."))
1104 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1105 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1106 self.write(cr,uid,ids,{'price_unit':price})
1107 return {'value': {'price_unit': price}, 'qty': 1}
1109 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist,qty,partner_id, product_id,*a):
1110 prod_obj = self.pool.get('product.product')
1111 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1114 prod_id=prod_obj.browse(cr,uid,product_id).disc_controle
1116 if (disc != 0.0 or prod_id) and price_f>0:
1117 disc=100-(price/price_f*100)
1118 return {'value':{'discount':disc, 'price_unit':price_f}}
1121 def onchange_ded(self, cr, uid,ids, val_ded,price_u,*a):
1122 pos_order = self.pool.get('pos.order.line')
1123 res_obj = self.pool.get('res.users')
1124 res_company = self.pool.get('res.company')
1125 comp = res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1127 if val_ded and price_u:
1128 val=100.0*val_ded/price_u
1130 return {'value': {'discount':val, 'notice':'' }}
1131 return {'value': {'discount':val}}
1133 def onchange_discount(self, cr, uid,ids, discount,price,*a):
1134 pos_order = self.pool.get('pos.order.line')
1135 res_obj = self.pool.get('res.users')
1136 res_company = self.pool.get('res.company')
1137 company_disc = pos_order.browse(cr,uid,ids)
1139 if not company_disc:
1140 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1142 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
1144 if discount > comp :
1145 return {'value': {'notice':'','price_ded':price*discount*0.01 or 0.0 }}
1147 return {'value': {'notice':'Minimum Discount','price_ded':price*discount*0.01 or 0.0 }}
1149 return {'value': {'notice':'No Discount', 'price_ded':price*discount*0.01 or 0.0 }}
1151 'name': fields.char('Line Description', size=512),
1152 'company_id':fields.many2one('res.company', 'Company', required=True),
1153 'notice': fields.char('Discount Notice', size=128, required=True),
1154 'serial_number': fields.char('Serial Number', size=128),
1155 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1156 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1157 'price_ded': fields.float('Discount(Amount)',digits_compute=dp.get_precision('Point Of Sale')),
1158 'qty': fields.float('Quantity'),
1159 'qty_rfd': fields.float('Refunded Quantity'),
1160 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal w/o Tax'),
1161 'price_subtotal_incl': fields.function(_amount_line_ttc, method=True, string='Subtotal'),
1162 'discount': fields.float('Discount (%)', digits=(16, 2)),
1163 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1164 'create_date': fields.datetime('Creation Date', readonly=True),
1168 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1169 'qty': lambda *a: 1,
1170 'discount': lambda *a: 0.0,
1171 'price_ded': lambda *a: 0.0,
1172 'notice': lambda *a: 'No Discount',
1173 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1176 def create(self, cr, user, vals, context={}):
1177 if vals.get('product_id'):
1178 return super(pos_order_line, self).create(cr, user, vals, context)
1181 def write(self, cr, user, ids, values, context={}):
1182 if 'product_id' in values and not values['product_id']:
1184 return super(pos_order_line, self).write(cr, user, ids, values, context)
1186 def _scan_product(self, cr, uid, ean, qty, order):
1187 # search pricelist_id
1188 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1189 if not pricelist_id:
1194 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
1198 # search price product
1199 product = self.pool.get('product.product').read(cr, uid, product_id)
1200 product_name = product[0]['name']
1201 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1203 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
1206 order_line_id = order_line_ids[0]
1207 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1210 vals = {'product_id': product_id[0],
1211 'price_unit': price,
1213 'name': product_name,
1216 line_id = self.create(cr, uid, vals)
1218 raise osv.except_osv(_('Error'), _('Create line failed !'))
1224 line_id = self.write(cr, uid, order_line_id, vals)
1226 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
1227 line_id = order_line_id
1229 price_line = float(qty)*float(price)
1230 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
1235 class pos_payment(osv.osv):
1236 _name = 'pos.payment'
1237 _description = 'Pos Payment'
1239 def _journal_get(self, cr, uid, context={}):
1240 obj = self.pool.get('account.journal')
1241 ids = obj.search(cr, uid, [('type', '=', 'cash')])
1242 res = obj.read(cr, uid, ids, ['id', 'name'], context)
1243 res = [(r['id'], r['name']) for r in res]
1246 def _journal_default(self, cr, uid, context={}):
1247 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
1249 return journal_list[0]
1254 'name': fields.char('Description', size=64),
1255 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
1256 'journal_id': fields.many2one('account.journal', "Journal", required=True),
1257 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
1258 'payment_nb': fields.char('Piece Number', size=32),
1259 'payment_name': fields.char('Payment Name', size=32),
1260 'payment_date': fields.date('Payment Date', required=True),
1261 'amount': fields.float('Amount', required=True),
1264 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
1265 'journal_id': _journal_default,
1266 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
1269 def create(self, cr, user, vals, context={}):
1270 if vals.get('journal_id') and vals.get('amount'):
1271 return super(pos_payment, self).create(cr, user, vals, context)
1274 def write(self, cr, user, ids, values, context={}):
1275 if 'amount' in values and not values['amount']:
1277 if 'journal_id' in values and not values['journal_id']:
1279 return super(pos_payment, self).write(cr, user, ids, values, context)
1283 class account_move_line(osv.osv):
1285 _inherit = 'account.move.line'
1286 def create(self, cr, user, vals, context={}):
1287 pos_obj = self.pool.get('pos.order')
1288 val_name = vals.get('name', '')
1289 val_ref = vals.get('ref', '')
1290 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1291 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1292 name_pos = aaa.groups()[0]
1293 pos_id = name_pos.replace('POS ','')
1294 if pos_id and pos_id.isdigit():
1295 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1296 pos_curr = pos_curr and pos_curr.contract_number or ''
1297 vals['ref'] = pos_curr or vals.get('ref')
1298 return super(account_move_line, self).create(cr, user, vals, context)
1303 class account_move(osv.osv):
1305 _inherit = 'account.move'
1307 def create(self, cr, user, vals, context={}):
1308 pos_obj = self.pool.get('pos.order')
1309 val_name = vals.get('name', '')
1310 val_ref = vals.get('ref', '')
1311 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1312 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1313 name_pos = aaa.groups()[0]
1314 pos_id = name_pos.replace('POS ','')
1315 if pos_id and pos_id.isdigit():
1316 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1317 pos_curr = pos_curr and pos_curr.contract_number or ''
1318 vals['ref'] = pos_curr or vals.get('ref')
1319 return super(account_move, self).create(cr, user, vals, context)
1324 class product_product(osv.osv):
1325 _inherit = 'product.product'
1327 'income_pdt': fields.boolean('Product for Incoming'),
1328 'expense_pdt': fields.boolean('Product for expenses'),
1329 'am_out': fields.boolean('Controle for Outgoing Operations'),
1330 'disc_controle': fields.boolean('Discount Controle '),
1333 'disc_controle': lambda *a: True,
1337 class stock_picking(osv.osv):
1339 _inherit = 'stock.picking'
1341 'pos_order': fields.many2one('pos.order', 'Pos order'),
1345 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: