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 ##############################################################################
24 from osv import fields, osv
25 from mx import DateTime
26 from tools.translate import _
27 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"
37 'name': fields.char('Description', size=64),
38 'code': fields.char('Code', size=64),
39 'journal_id': fields.many2one('account.journal', "Journal")
43 class pos_company_discount(osv.osv):
45 """ Company Discount and Cashboxes """
47 _inherit = 'res.company'
49 'company_discount': fields.float('Max Discount(%)', digits_compute= dp.get_precision('Point Of Sale')),
50 'max_diff': fields.float('Max Difference for Cashboxes', digits_compute= dp.get_precision('Point Of Sale Discount')),
53 pos_company_discount()
56 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"
64 _order = "date_order desc"
67 def unlink(self, cr, uid, ids, context=None):
68 for rec in self.browse(cr, uid, ids, context=context):
69 for rec_statement in rec.statement_ids:
70 if (rec_statement.statement_id and rec_statement.statement_id.state=='confirm') or rec.state=='done':
71 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
72 return super(pos_order, self).unlink(cr, uid, ids, context=context)
74 def onchange_partner_pricelist(self, cr, uid, ids, part, context=None):
76 """ Changed price list on_change of partner_id"""
80 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
81 return {'value':{'pricelist_id': pricelist}}
83 def _amount_total(self, cr, uid, ids, field_name, arg, context=None):
85 """ Calculates amount_tax of order line
86 @param field_names: Names of fields.
87 @return: Dictionary of values """
93 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
96 LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
97 WHERE p.id IN %s GROUP BY p.id """,(tuple(ids),))
98 res = dict(cr.fetchall())
99 for rec in self.browse(cr, uid, ids, context):
101 and rec.partner_id.property_account_position \
102 and rec.partner_id.property_account_position.tax_ids:
103 res[rec.id] = res[rec.id] - rec.amount_tax
105 res[rec.id] = res[rec.id] + rec.amount_tax
108 def _get_date_payment2(self, cr, uid, ids, context, *a):
110 # Todo need to check this function
111 """ Find payment Date
113 @param field_names: Names of fields.
114 @return: Dictionary of values """
117 pay_obj = self.pool.get('account.bank.statement')
118 stat_obj_line = self.pool.get('account.bank.statement.line')
121 for order in self.browse(cr, uid, ids):
122 cr.execute("select date_payment from pos_order where id=%d"%(order.id))
124 date_p=date_p and date_p[0] or None
128 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))
130 val= val and val[0] or None
132 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))
134 val=val and val[0] or None
139 def _get_date_payment(self, cr, uid, ids, context, *a):
141 """ Find Validation Date
142 @return: Dictionary of values """
145 pay_obj = self.pool.get('pos.payment')
148 for order in self.browse(cr, uid, ids):
149 cr.execute("select date_validation from pos_order where id=%d"%(order.id))
151 date_p=date_p and date_p[0] or None
155 discount_allowed=order.company_id.company_discount
156 for line in order.lines:
157 if line.discount > discount_allowed:
158 return {order.id: None }
159 if order.amount_paid == order.amount_total and not date_p:
160 cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
162 val=val and val[0] or None
163 if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
164 for o in order.invoice_id.move_id.line_id:
166 if val<o.date_created:
172 def _amount_all(self, cr, uid, ids, name, args, context=None):
173 tax_obj = self.pool.get('account.tax')
174 cur_obj = self.pool.get('res.currency')
176 for order in self.browse(cr, uid, ids):
183 cur_obj = self.pool.get('res.currency')
184 cur = order.pricelist_id.currency_id
185 for payment in order.statement_ids:
186 res[order.id]['amount_paid'] += payment.amount
187 for payment in order.payments:
188 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
189 for line in order.lines:
190 if order.price_type!='tax_excluded':
191 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
192 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
194 (1-(line.discount or 0.0)/100.0), line.qty),
195 res[order.id]['amount_tax'])
196 elif line.qty != 0.0:
197 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']:
199 res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
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=None):
236 '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'),
288 'user_salesman_id': fields.many2one('res.users', 'Cashier', 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, string='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',states={'draft': [('readonly', False)]},readonly=True),
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 'note': fields.text('Internal Notes'),
312 'nb_print': fields.integer('Number of Print', readonly=True),
313 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True, ),
314 'invoice_wanted': fields.boolean('Create Invoice'),
315 'note_2': fields.char('Customer Note',size=64),
316 'type_rec': fields.char('Type of Receipt',size=64),
317 'remboursed': fields.boolean('Remboursed'),
318 'contract_number': fields.char('Contract Number', size=512, select=1),
319 'journal_entry': fields.boolean('Journal Entry'),
323 def _select_pricelist(self, cr, uid, context):
325 """ To get default pricelist for the order"
326 @param name: Names of fields.
327 @return: pricelist ID
329 pricelist = self.pool.get('product.pricelist').search(cr, uid, [('name', '=', 'Public Pricelist')])
335 def _journal_default(self, cr, uid, context=None):
336 """ To get default pricelist for the order"
337 @param name: Names of fields.
340 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
342 return journal_list[0]
347 'user_salesman_id':lambda self, cr, uid, context: uid,
348 'user_id': lambda self, cr, uid, context: uid,
349 'sale_manager': lambda self, cr, uid, context: uid,
350 'state': lambda *a: 'draft',
351 'price_type': lambda *a: 'tax_excluded',
352 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
353 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
354 'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
355 'nb_print': lambda *a: 0,
356 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
357 'sale_journal': _sale_journal_get,
358 'invoice_wanted': lambda *a: False,
359 'shop_id': _shop_get,
360 'pricelist_id': _select_pricelist,
364 def test_order_lines(self, cr, uid, order, context=None):
365 """ Test order line is created or not for the order "
366 @param name: Names of fields.
370 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
372 wf_service = netsvc.LocalService("workflow")
373 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
376 def dummy_button(self, cr, uid, order, context=None):
379 def test_paid(self, cr, uid, ids, context=None):
381 """ Test all amount is paid for this order
384 for order in self.browse(cr, uid, ids, context):
385 if order.lines and not order.amount_total:
387 if (not order.lines) or (not order.statement_ids) or \
388 Decimal(str(order.amount_total))!=Decimal(str(order.amount_paid)):
392 def _get_qty_differences(self, orders, old_picking):
394 """check if the customer changed the product quantity """
398 for line in order.lines:
399 order_dict[line.product_id.id] = line
401 # check the quantity differences:
403 for line in old_picking.move_lines:
404 order_line = order_dict.get(line.product_id.id)
407 qty_to_delete_from_original_picking = line.product_qty
408 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
409 elif line.product_qty != order_line.qty:
411 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
412 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
416 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
418 """if the customer changes the product quantity, split the picking in two"""
420 # create a copy of the original picking and adjust the product qty:
421 picking_model = self.pool.get('stock.picking')
423 'note': "Partial picking from customer", # add a note to tell why we create a new picking
424 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
427 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
428 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
430 for line in new_picking.move_lines:
431 p_id = line.product_id.id
432 if p_id in diff_dict:
433 diff = diff_dict[p_id]
436 if deleted: # product has been deleted (customer didn't took it):
437 # delete this product from old picking:
438 for old_line in old_picking.move_lines:
439 if old_line.product_id.id == p_id:
440 old_line.write({'state': 'draft'}, context=context) # cannot delete if not draft
441 old_line.unlink(context=context)
442 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
443 # subtract qty from old picking:
444 for old_line in old_picking.move_lines:
445 if old_line.product_id.id == p_id:
446 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
447 # add qty to new picking:
448 line.write({'product_qty': qty_to_del}, context=context)
449 else: # product hasn't changed (customer took it without any change):
450 # delete this product from new picking:
451 line.unlink(context=context)
453 # delete it in the new picking:
454 line.unlink(context=context)
456 def create_picking(self, cr, uid, ids, context=None):
457 """Create a picking for each order and validate it."""
459 picking_obj = self.pool.get('stock.picking')
460 property_obj=self.pool.get("ir.property")
461 move_obj=self.pool.get('stock.move')
462 pick_name=self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
463 orders = self.browse(cr, uid, ids, context)
465 if not order.picking_id:
467 picking_id = picking_obj.create(cr, uid, {
469 'origin': order.name,
472 'move_type': 'direct',
473 'note': 'POS notes ' + (order.note or ""),
474 'invoice_state': 'none',
475 'auto_picking': True,
476 'pos_order': order.id,
478 self.write(cr, uid, [order.id], {'picking_id': picking_id})
480 picking_id = order.picking_id.id
481 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
482 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
485 # split the picking (if product quantity has changed):
486 diff_dict = self._get_qty_differences(orders, picking)
488 self._split_picking(cr, uid, ids, context, picking, diff_dict)
491 for line in order.lines:
492 if line.product_id and line.product_id.type=='service':
494 prop_ids = property_obj.search(cr, uid, [('name', '=', 'property_stock_customer')])
495 val = property_obj.browse(cr, uid, prop_ids[0]).value_reference
496 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))
498 location_id=res and res[0] or None
499 stock_dest_id = val.id
501 location_id, stock_dest_id = stock_dest_id, location_id
503 move_obj.create(cr, uid, {
504 'name': 'Stock move (POS %d)' % (order.id, ),
505 'product_uom': line.product_id.uom_id.id,
506 'product_uos': line.product_id.uom_id.id,
507 'picking_id': picking_id,
508 'product_id': line.product_id.id,
509 'product_uos_qty': abs(line.qty),
510 'product_qty': abs(line.qty),
511 'tracking_id': False,
512 'pos_line_id': line.id,
514 'location_id': location_id,
515 'location_dest_id': stock_dest_id,
518 wf_service = netsvc.LocalService("workflow")
519 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
520 self.pool.get('stock.picking').force_assign(cr, uid, [picking_id], context)
524 def set_to_draft(self, cr, uid, ids, *args):
526 """ Changes order state to draft
532 self.write(cr, uid, ids, {'state': 'draft'})
534 wf_service = netsvc.LocalService("workflow")
536 wf_service.trg_create(uid, 'pos.order', i, cr)
539 def button_invalidate(self, cr, uid, ids, *args):
541 """ Check the access for the sale order
544 res_obj = self.pool.get('res.company')
546 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
548 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
550 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
553 def cancel_order(self, cr, uid, ids, context=None):
555 """ Changes order state to cancel
558 self.write(cr, uid, ids, {'state': 'cancel'})
559 self.cancel_picking(cr, uid, ids, context=context)
562 def add_payment(self, cr, uid, order_id, data, context=None):
564 """Create a new payment for the order"""
566 res_obj = self.pool.get('res.company')
567 statement_obj= self.pool.get('account.bank.statement')
568 statementl_obj = self.pool.get('account.bank.statement.line')
569 prod_obj = self.pool.get('product.product')
570 property_obj=self.pool.get('ir.property')
572 curr_c=self.pool.get('res.users').browse(cr, uid, uid).company_id
573 curr_company=curr_c.id
574 order = self.browse(cr, uid, order_id, context)
575 if not order.num_sale and data['num_sale']:
576 self.write(cr,uid,order_id,{'num_sale': data['num_sale']})
579 'amount': data['amount'],
581 if 'payment_date' in data.keys():
582 args['date'] = data['payment_date']
583 if 'payment_name' in data.keys():
584 args['name'] = data['payment_name'] + ' ' +order.name
585 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
586 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
587 if data.get('is_acc',False):
588 args['is_acc']=data['is_acc']
589 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
590 if not args['account_id']:
591 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')%(prod_obj.browse(cr,uid, data['product_id']).name))
592 args['partner_id'] = order.partner_id and order.partner_id.id or None
593 args['ref'] = order.contract_number or None
595 statement_id = statement_obj.search(cr,uid, [
596 ('journal_id', '=', data['journal']),
597 ('company_id', '=', curr_company),
598 ('user_id', '=', uid),
599 ('state', '=', 'open')])
600 if len(statement_id)==0:
601 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
603 statement_id=statement_id[0]
604 args['statement_id']= statement_id
605 args['pos_statement_id']= order_id
606 args['journal_id']= data['journal']
607 statement_line_id = statementl_obj.create(cr, uid, args)
608 ids_new.append(statement_id)
610 wf_service = netsvc.LocalService("workflow")
611 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
612 wf_service.trg_write(uid, 'pos.order', order_id, cr)
616 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
618 """Create a new order line the order"""
620 line_obj = self.pool.get('pos.order.line')
621 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
623 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
624 product = values['partner_id'] and values['partner_id'][0]
626 price = line_obj.price_by_product(cr, uid, [],
627 pricelist, product_id, qty, product)
629 order_line_id = line_obj.create(cr, uid, {
630 'order_id': order_id,
631 'product_id': product_id,
635 wf_service = netsvc.LocalService("workflow")
636 wf_service.trg_write(uid, 'pos.order', order_id, cr)
640 def refund(self, cr, uid, ids, context=None):
641 """Create a copy of order for refund order"""
643 line_obj = self.pool.get('pos.order.line')
645 for order in self.browse(cr, uid, ids):
646 clone_id = self.copy(cr, uid, order.id, {
647 'name': order.name + ' REFUND',
648 'date_order': time.strftime('%Y-%m-%d'),
650 'note': 'REFUND\n'+ (order.note or ''),
653 'statement_ids': False,
655 clone_list.append(clone_id)
658 for clone in self.browse(cr, uid, clone_list):
659 for order_line in clone.lines:
660 line_obj.write(cr, uid, [order_line.id], {
661 'qty': -order_line.qty
665 def action_invoice(self, cr, uid, ids, context=None):
666 """Create a invoice of order """
668 res_obj = self.pool.get('res.company')
669 inv_ref = self.pool.get('account.invoice')
670 inv_line_ref = self.pool.get('account.invoice.line')
671 product_obj= self.pool.get('product.product')
674 for order in self.pool.get('pos.order').browse(cr, uid, ids, context):
675 curr_c = order.user_salesman_id.company_id
677 inv_ids.append(order.invoice_id.id)
680 if not order.partner_id:
681 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
683 acc= order.partner_id.property_account_receivable.id
685 'name': 'Invoice from POS: '+order.name,
686 'origin': order.name,
688 'journal_id':order.sale_journal.id or None,
689 'type': 'out_invoice',
690 'reference': order.name,
691 'partner_id': order.partner_id.id,
692 'comment': order.note or '',
694 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
695 if not inv.get('account_id', None):
696 inv['account_id'] = acc
697 inv_id = inv_ref.create(cr, uid, inv, context)
699 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
700 inv_ids.append(inv_id)
701 for line in order.lines:
703 'invoice_id': inv_id,
704 'product_id': line.product_id.id,
705 'quantity': line.qty,
707 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
709 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
711 line.product_id.uom_id.id,
712 line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
713 inv_line['price_unit'] = line.price_unit
714 inv_line['discount'] = line.discount
715 inv_line['account_id'] = acc
716 inv_line['name'] = inv_name
718 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
719 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
720 inv_line_ref.create(cr, uid, inv_line, context)
723 wf_service = netsvc.LocalService("workflow")
724 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
727 def create_account_move(self, cr, uid, ids, context=None):
729 """Create a account move line of order """
731 account_move_obj = self.pool.get('account.move')
732 account_move_line_obj = self.pool.get('account.move.line')
733 account_period_obj = self.pool.get('account.period')
734 account_tax_obj = self.pool.get('account.tax')
735 res_obj=self.pool.get('res.users')
736 property_obj=self.pool.get('ir.property')
737 period = account_period_obj.find(cr, uid, context=context)[0]
739 for order in self.browse(cr, uid, ids, context=context):
740 curr_c =res_obj.browse(cr, uid, uid).company_id
741 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
742 comp_id=comp_id and comp_id.id or False
745 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
747 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
749 # Create an entry for the sale
750 move_id = account_move_obj.create(cr, uid, {
751 'journal_id': order.sale_journal.id,
755 # Create an move for each order line
756 for line in order.lines:
759 taxes = [t for t in line.product_id.taxes_id]
760 if order.price_type=='tax_excluded':
761 computed_taxes = account_tax_obj.compute_all(
762 cr, uid, taxes, line.price_unit, line.qty)['taxes']
764 computed_taxes = account_tax_obj.compute_inv(
765 cr, uid, taxes, line.price_unit, line.qty)
767 for tax in computed_taxes:
768 tax_amount += round(tax['amount'], 2)
769 group_key = (tax['tax_code_id'],
771 tax['account_collected_id'])
773 if group_key in group_tax:
774 group_tax[group_key] += round(tax['amount'], 2)
776 group_tax[group_key] = round(tax['amount'], 2)
777 if order.price_type!='tax_excluded':
778 amount = line.price_subtotal - tax_amount
780 amount = line.price_subtotal
782 # Search for the income account
783 if line.product_id.property_account_income.id:
784 income_account = line.\
785 product_id.property_account_income.id
786 elif line.product_id.categ_id.\
787 property_account_income_categ.id:
788 income_account = line.product_id.categ_id.\
789 property_account_income_categ.id
791 raise osv.except_osv(_('Error !'), _('There is no income '\
792 'account defined for this product: "%s" (id:%d)') \
793 % (line.product_id.name, line.product_id.id, ))
796 # Empty the tax list as long as there is no tax code:
799 while computed_taxes:
800 tax = computed_taxes.pop(0)
802 tax_code_id = tax['base_code_id']
803 tax_amount = line.price_subtotal * tax['base_sign']
805 tax_code_id = tax['ref_base_code_id']
806 tax_amount = line.price_subtotal * tax['ref_base_sign']
807 # If there is one we stop
811 # Create a move for the line
812 account_move_line_obj.create(cr, uid, {
813 'name': "aa"+order.name,
814 'date': order.date_order[:10],
815 'ref': order.contract_number or order.name,
816 'quantity': line.qty,
817 'product_id':line.product_id.id,
819 'account_id': income_account,
820 'company_id': comp_id,
821 'credit': ((amount>0) and amount) or 0.0,
822 'debit': ((amount<0) and -amount) or 0.0,
823 'journal_id': order.sale_journal.id,
825 'tax_code_id': tax_code_id,
826 'tax_amount': tax_amount,
829 # For each remaining tax with a code, whe create a move line
830 for tax in computed_taxes:
832 tax_code_id = tax['base_code_id']
833 tax_amount = line.price_subtotal * tax['base_sign']
835 tax_code_id = tax['ref_base_code_id']
836 tax_amount = line.price_subtotal * tax['ref_base_sign']
840 account_move_line_obj.create(cr, uid, {
841 'name': "bb"+order.name,
842 'date': order.date_order[:10],
843 'ref': order.contract_number or order.name,
844 'product_id':line.product_id.id,
845 'quantity': line.qty,
847 'account_id': income_account,
848 'company_id': comp_id,
851 'journal_id': order.sale_journal.id,
853 'tax_code_id': tax_code_id,
854 'tax_amount': tax_amount,
858 # Create a move for each tax group
859 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
860 for key, amount in group_tax.items():
861 account_move_line_obj.create(cr, uid, {
862 'name':"cc"+order.name,
863 'date': order.date_order[:10],
864 'ref': order.contract_number or order.name,
866 'company_id': comp_id,
867 'quantity': line.qty,
868 'product_id':line.product_id.id,
869 'account_id': key[account_pos],
870 'credit': ((amount>0) and amount) or 0.0,
871 'debit': ((amount<0) and -amount) or 0.0,
872 'journal_id': order.sale_journal.id,
874 'tax_code_id': key[tax_code_pos],
875 'tax_amount': amount,
879 to_reconcile.append(account_move_line_obj.create(cr, uid, {
880 'name': "dd"+order.name,
881 'date': order.date_order[:10],
882 'ref': order.contract_number or order.name,
884 'company_id': comp_id,
885 'account_id': order_account,
886 'credit': ((order.amount_total<0) and -order.amount_total)\
888 'debit': ((order.amount_total>0) and order.amount_total)\
890 'journal_id': order.sale_journal.id,
895 # search the account receivable for the payments:
896 account_receivable = order.sale_journal.default_credit_account_id.id
897 if not account_receivable:
898 raise osv.except_osv(_('Error !'),
899 _('There is no receivable account defined for this journal:'\
900 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
902 for payment in order.statement_ids:
907 payment.statement_id.journal_id.default_debit_account_id.id
910 payment.statement_id.journal_id.default_credit_account_id.id
912 # Create one entry for the payment
915 payment_move_id = account_move_obj.create(cr, uid, {
916 'journal_id': payment.statement_id.journal_id.id,
920 for stat_l in order.statement_ids:
921 if stat_l.is_acc and len(stat_l.move_ids):
922 for st in stat_l.move_ids:
925 account_move_line_obj.copy(cr, uid, s.id, {
927 'statement_id': False,
930 account_move_line_obj.copy(cr, uid, s.id, {
931 'statement_id': False,
932 'account_id':order_account
935 self.write(cr,uid,order.id,{'state':'done'})
938 def cancel_picking(self, cr, uid, ids, context=None):
939 for order in self.browse(cr, uid, ids, context=context):
940 for picking in order.pickings:
941 self.pool.get('stock.picking').unlink(cr, uid, [picking.id], context)
945 def action_payment(self, cr, uid, ids, context=None):
946 vals = {'state': 'payment'}
947 sequence_obj=self.pool.get('ir.sequence')
948 for pos in self.browse(cr, uid, ids):
949 create_contract_nb = False
950 for line in pos.lines:
951 if line.product_id.product_type == 'MD':
952 create_contract_nb = True
954 if create_contract_nb:
955 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
956 vals['contract_number'] ='%s-%s' % (pos.user_salesman_id.login, seq)
957 self.write(cr, uid, ids, vals)
959 def action_paid(self, cr, uid, ids, context=None):
962 if context.get('flag',False):
963 self.create_picking(cr, uid, ids, context=None)
964 self.write(cr, uid, ids, {'state': 'paid'})
969 def action_cancel(self, cr, uid, ids, context=None):
970 self.write(cr, uid, ids, {'state': 'cancel'})
973 def action_done(self, cr, uid, ids, context=None):
974 for order in self.browse(cr, uid, ids, context=context):
975 if not order.journal_entry:
976 self.create_account_move(cr, uid, ids, context=None)
979 def compute_state(self, cr, uid, id):
980 cr.execute("select act.id, act.name from wkf_activity act "
981 "inner join wkf_workitem item on act.id=item.act_id "
982 "inner join wkf_instance inst on item.inst_id=inst.id "
983 "inner join wkf on inst.wkf_id=wkf.id "
984 "where wkf.osv='pos.order' and inst.res_id=%s "
985 "order by act.name", (id,))
986 return [name for id, name in cr.fetchall()]
990 class account_bank_statement(osv.osv):
991 _inherit = 'account.bank.statement'
993 'user_id': fields.many2one('res.users',ondelete='cascade',string='User', readonly=True),
996 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
998 account_bank_statement()
1000 class account_bank_statement_line(osv.osv):
1001 _inherit = 'account.bank.statement.line'
1002 def _get_statement_journal(self, cr, uid, ids, context, *a):
1004 for line in self.browse(cr, uid, ids):
1005 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
1008 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
1009 'am_out':fields.boolean("To count"),
1010 'is_acc':fields.boolean("Is accompte"),
1011 'pos_statement_id': fields.many2one('pos.order',ondelete='cascade'),
1013 account_bank_statement_line()
1015 class pos_order_line(osv.osv):
1016 _name = "pos.order.line"
1017 _description = "Lines of Point of Sale"
1019 def _get_amount(self, cr, uid, ids, field_name, arg, context):
1021 for line in self.browse(cr, uid, ids):
1022 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)
1026 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context):
1027 res = dict.fromkeys(ids, 0.0)
1028 account_tax_obj = self.pool.get('account.tax')
1029 for line in self.browse(cr, uid, ids):
1031 taxes = [t for t in line.product_id.taxes_id]
1034 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
1035 for tax in computed_taxes:
1036 tax_amount += tax['amount']
1037 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)
1038 if line.discount!=0.0:
1039 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1041 res[line.id]=line.price_unit*line.qty
1042 res[line.id] = res[line.id] + tax_amount
1045 def _amount_line(self, cr, uid, ids, field_name, arg, context):
1048 for line in self.browse(cr, uid, ids):
1049 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)
1050 if line.discount!=0.0:
1051 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1053 res[line.id]=line.price_unit*line.qty
1056 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1060 raise osv.except_osv(_('No Pricelist !'),
1061 _('You have to select a pricelist in the sale form !\n' \
1062 'Please set one before choosing a product.'))
1063 p_obj = self.pool.get('product.product').browse(cr,uid,[product_id])[0]
1064 uom_id=p_obj.uom_po_id.id
1065 price = self.pool.get('product.pricelist').price_get(cr, uid,
1066 [pricelist], product_id, qty or 1.0, partner_id,{'uom': uom_id})[pricelist]
1067 unit_price=price or p_obj.list_price
1068 if unit_price is False:
1069 raise osv.except_osv(_('No valid pricelist line found !'),
1070 _("Couldn't find a pricelist line matching this product" \
1071 " and quantity.\nYou have to change either the product," \
1072 " the quantity or the pricelist."))
1075 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1076 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1077 self.write(cr,uid,ids,{'price_unit':price})
1078 pos_stot = (price * qty)
1079 return {'value': {'price_unit': price,'price_subtotal_incl': pos_stot}}
1081 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist,qty,partner_id, product_id,*a):
1082 prod_obj = self.pool.get('product.product')
1083 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1086 prod_id=prod_obj.browse(cr,uid,product_id).disc_controle
1088 if (disc != 0.0 or prod_id) and price_f>0:
1089 disc=100-(price/price_f*100)
1090 return {'value':{'discount':disc, 'price_unit':price_f}}
1093 def onchange_dis(self, cr, uid,ids, qty, price_subtotal_incl, discount,*a):
1094 price_sub = price_subtotal_incl
1095 sub_total_discount = price_sub-(price_subtotal_incl*(discount*0.01))
1096 return {'value': {'price_subtotal_incl':sub_total_discount}}
1098 def onchange_ded(self, cr, uid,ids, val_ded,price_u,*a):
1099 pos_order = self.pool.get('pos.order.line')
1100 res_obj = self.pool.get('res.users')
1101 res_company = self.pool.get('res.company')
1102 comp = res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1104 if val_ded and price_u:
1105 val=100.0*val_ded/price_u
1107 return {'value': {'discount':val, 'notice':'' }}
1108 return {'value': {'discount':val}}
1110 def onchange_discount(self, cr, uid,ids, discount,price,*a):
1111 pos_order = self.pool.get('pos.order.line')
1112 res_obj = self.pool.get('res.users')
1113 res_company = self.pool.get('res.company')
1114 company_disc = pos_order.browse(cr,uid,ids)
1116 if not company_disc:
1117 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1119 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
1121 if discount > comp :
1122 return {'value': {'notice':'','price_ded':price*discount*0.01 or 0.0 }}
1124 return {'value': {'notice':'Minimum Discount','price_ded':price*discount*0.01 or 0.0 }}
1126 return {'value': {'notice':'No Discount', 'price_ded':price*discount*0.01 or 0.0}}
1128 def onchange_qty(self, cr, uid, ids, discount, qty, price, context=None):
1129 subtotal = qty * price
1131 subtotal = subtotal - (subtotal * discount / 100)
1132 return {'value': {'price_subtotal_incl': subtotal}}
1135 'name': fields.char('Line Description', size=512),
1136 'company_id':fields.many2one('res.company', 'Company', required=True),
1137 'notice': fields.char('Discount Notice', size=128, required=True),
1138 'serial_number': fields.char('Serial Number', size=128),
1139 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1140 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1141 'price_ded': fields.float('Discount(Amount)',digits_compute=dp.get_precision('Point Of Sale')),
1142 'qty': fields.float('Quantity'),
1143 'qty_rfd': fields.float('Refunded Quantity'),
1144 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal w/o Tax'),
1145 'price_subtotal_incl': fields.function(_amount_line_ttc, method=True, string='Subtotal'),
1146 'discount': fields.float('Discount (%)', digits=(16, 2)),
1147 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1148 'create_date': fields.datetime('Creation Date', readonly=True),
1152 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1153 'qty': lambda *a: 1,
1154 'discount': lambda *a: 0.0,
1155 'price_ded': lambda *a: 0.0,
1156 'notice': lambda *a: 'No Discount',
1157 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1160 def create(self, cr, user, vals, context=None):
1161 if vals.get('product_id'):
1162 return super(pos_order_line, self).create(cr, user, vals, context)
1165 def write(self, cr, user, ids, values, context=None):
1166 if 'product_id' in values and not values['product_id']:
1168 return super(pos_order_line, self).write(cr, user, ids, values, context)
1170 def _scan_product(self, cr, uid, ean, qty, order):
1171 # search pricelist_id
1172 product_obj=self.pool.get('product.product')
1173 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1174 if not pricelist_id:
1179 product_id = product_obj.search(cr, uid, [('ean13','=', ean)])
1183 # search price product
1184 product =product_obj.read(cr, uid, product_id)
1185 product_name = product[0]['name']
1186 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1188 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
1191 order_line_id = order_line_ids[0]
1192 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1195 vals = {'product_id': product_id[0],
1196 'price_unit': price,
1198 'name': product_name,
1201 line_id = self.create(cr, uid, vals)
1203 raise osv.except_osv(_('Error'), _('Create line failed !'))
1209 line_id = self.write(cr, uid, order_line_id, vals)
1211 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
1212 line_id = order_line_id
1214 price_line = float(qty)*float(price)
1216 'name': product_name,
1217 'product_id': product_id[0],
1219 'price_line': price_line ,
1226 class pos_payment(osv.osv):
1227 _name = 'pos.payment'
1228 _description = 'Pos Payment'
1230 def _journal_get(self, cr, uid, context=None):
1231 obj = self.pool.get('account.journal')
1232 ids = obj.search(cr, uid, [('type', '=', 'cash')])
1233 res = obj.read(cr, uid, ids, ['id', 'name'], context)
1234 res = [(r['id'], r['name']) for r in res]
1237 def _journal_default(self, cr, uid, context=None):
1238 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
1240 return journal_list[0]
1245 'name': fields.char('Description', size=64),
1246 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
1247 'journal_id': fields.many2one('account.journal', "Journal", required=True),
1248 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
1249 'payment_nb': fields.char('Piece Number', size=32),
1250 'payment_name': fields.char('Payment Name', size=32),
1251 'payment_date': fields.date('Payment Date', required=True),
1252 'amount': fields.float('Amount', required=True),
1255 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
1256 'journal_id': _journal_default,
1257 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
1260 def create(self, cr, user, vals, context=None):
1261 if vals.get('journal_id') and vals.get('amount'):
1262 return super(pos_payment, self).create(cr, user, vals, context)
1265 def write(self, cr, user, ids, values, context=None):
1266 if 'amount' in values and not values['amount']:
1268 if 'journal_id' in values and not values['journal_id']:
1270 return super(pos_payment, self).write(cr, user, ids, values, context)
1274 class account_move_line(osv.osv):
1276 _inherit = 'account.move.line'
1277 def create(self, cr, user, vals, context=None):
1278 pos_obj = self.pool.get('pos.order')
1279 val_name = vals.get('name', '')
1280 val_ref = vals.get('ref', '')
1281 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1282 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1283 name_pos = aaa.groups()[0]
1284 pos_id = name_pos.replace('POS ','')
1285 if pos_id and pos_id.isdigit():
1286 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1287 pos_curr = pos_curr and pos_curr.contract_number or ''
1288 vals['ref'] = pos_curr or vals.get('ref')
1289 return super(account_move_line, self).create(cr, user, vals, context)
1294 class account_move(osv.osv):
1296 _inherit = 'account.move'
1297 def create(self, cr, user, vals, context=None):
1298 pos_obj = self.pool.get('pos.order')
1299 val_name = vals.get('name', '')
1300 val_ref = vals.get('ref', '')
1301 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1302 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1303 name_pos = aaa.groups()[0]
1304 pos_id = name_pos.replace('POS ','')
1305 if pos_id and pos_id.isdigit():
1306 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1307 pos_curr = pos_curr and pos_curr.contract_number or ''
1308 vals['ref'] = pos_curr or vals.get('ref')
1309 return super(account_move, self).create(cr, user, vals, context)
1314 class product_product(osv.osv):
1315 _inherit = 'product.product'
1317 'income_pdt': fields.boolean('Product for Incoming'),
1318 'expense_pdt': fields.boolean('Product for expenses'),
1319 'am_out': fields.boolean('Controle for Outgoing Operations'),
1320 'disc_controle': fields.boolean('Discount Controle '),
1323 'disc_controle': lambda *a: True,
1327 class stock_picking(osv.osv):
1329 _inherit = 'stock.picking'
1331 'pos_order': fields.many2one('pos.order', 'Pos order'),
1335 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: