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={}):
69 for rec in self.browse(cr, uid, ids, context=context):
70 for rec_statement in rec.statement_ids:
71 if (rec_statement.statement_id and rec_statement.statement_id.state=='confirm') or rec.state=='done':
72 raise osv.except_osv(_('Invalid action !'), _('Cannot delete a point of sale which is closed or contains confirmed cashboxes!'))
73 return super(pos_order, self).unlink(cr, uid, ids, context=context)
75 def onchange_partner_pricelist(self, cr, uid, ids, part, context={}):
77 """ Changed price list on_change of partner_id"""
81 pricelist = self.pool.get('res.partner').browse(cr, uid, part).property_product_pricelist.id
82 return {'value':{'pricelist_id': pricelist}}
84 def _amount_total(self, cr, uid, ids, field_name, arg, context):
86 """ Calculates amount_tax of order line
87 @param field_names: Names of fields.
88 @return: Dictionary of values """
94 l.price_unit*l.qty*(1-(l.discount/100.0)))::decimal(16,2), 0
97 LEFT OUTER JOIN pos_order_line l ON (p.id=l.order_id)
98 WHERE p.id IN %s GROUP BY p.id """,(tuple(ids),))
99 res = dict(cr.fetchall())
100 for rec in self.browse(cr, uid, ids, context):
102 and rec.partner_id.property_account_position \
103 and rec.partner_id.property_account_position.tax_ids:
104 res[rec.id] = res[rec.id] - rec.amount_tax
106 res[rec.id] = res[rec.id] + rec.amount_tax
109 def _get_date_payment2(self, cr, uid, ids, context, *a):
111 # Todo need to check this function
112 """ Find payment Date
114 @param field_names: Names of fields.
115 @return: Dictionary of values """
118 pay_obj = self.pool.get('account.bank.statement')
119 stat_obj_line = self.pool.get('account.bank.statement.line')
122 for order in self.browse(cr, uid, ids):
123 cr.execute("select date_payment from pos_order where id=%d"%(order.id))
125 date_p=date_p and date_p[0] or None
129 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))
131 val= val and val[0] or None
133 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))
135 val=val and val[0] or None
140 def _get_date_payment(self, cr, uid, ids, context, *a):
142 """ Find Validation Date
143 @return: Dictionary of values """
146 pay_obj = self.pool.get('pos.payment')
149 for order in self.browse(cr, uid, ids):
150 cr.execute("select date_validation from pos_order where id=%d"%(order.id))
152 date_p=date_p and date_p[0] or None
156 discount_allowed=order.company_id.company_discount
157 for line in order.lines:
158 if line.discount > discount_allowed:
159 return {order.id: None }
160 if order.amount_paid == order.amount_total and not date_p:
161 cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
163 val=val and val[0] or None
164 if order.invoice_id and order.invoice_id.move_id and not date_p and not val:
165 for o in order.invoice_id.move_id.line_id:
167 if val<o.date_created:
173 def _amount_all(self, cr, uid, ids, name, args, context=None):
174 tax_obj = self.pool.get('account.tax')
175 cur_obj = self.pool.get('res.currency')
177 for order in self.browse(cr, uid, ids):
184 cur_obj = self.pool.get('res.currency')
185 cur = order.pricelist_id.currency_id
186 for payment in order.statement_ids:
187 res[order.id]['amount_paid'] += payment.amount
188 for payment in order.payments:
189 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
190 for line in order.lines:
191 if order.price_type!='tax_excluded':
192 res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2),
193 tax_obj.compute_inv(cr, uid, line.product_id.taxes_id,
195 (1-(line.discount or 0.0)/100.0), line.qty),
196 res[order.id]['amount_tax'])
197 elif line.qty != 0.0:
198 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']:
200 res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val)
205 def _sale_journal_get(self, cr, uid, context):
207 """ To get sale journal for this order"
210 journal_obj = self.pool.get('account.journal')
211 res = journal_obj.search(cr, uid,
212 [('type', '=', 'sale')], limit=1)
218 def _shop_get(self, cr, uid, context):
220 """ To get Shop for this order"
223 company = self.pool.get('res.users').browse(cr, uid, uid, context).company_id
224 res = self.pool.get('sale.shop').search(cr, uid, [])
229 def copy(self, cr, uid, id, default=None, context={}):
238 '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'),
290 'user_salesman_id': fields.many2one('res.users', 'Cashier', 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',states={'draft': [('readonly', False)]},readonly=True),
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'),('refused', 'Refused')], string='State', readonly=True, method=True, store=True),
314 'note': fields.text('Internal Notes'),
315 'nb_print': fields.integer('Number of Print', readonly=True),
316 'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True, ),
317 'invoice_wanted': fields.boolean('Create Invoice'),
318 'note_2': fields.char('Customer Note',size=64),
319 'type_rec': fields.char('Type of Receipt',size=64),
320 'remboursed': fields.boolean('Remboursed'),
321 'contract_number': fields.char('Contract Number', size=512, select=1),
322 'journal_entry': fields.boolean('Journal Entry'),
326 def _select_pricelist(self, cr, uid, context):
328 """ To get default pricelist for the order"
329 @param name: Names of fields.
330 @return: pricelist ID
332 pricelist = self.pool.get('product.pricelist').search(cr, uid, [('name', '=', 'Public Pricelist')])
338 def _journal_default(self, cr, uid, context={}):
340 """ To get default pricelist for the order"
341 @param name: Names of fields.
344 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
346 return journal_list[0]
351 'user_salesman_id':lambda self, cr, uid, context: uid,
352 'user_id': lambda self, cr, uid, context: uid,
353 'sale_manager': lambda self, cr, uid, context: uid,
354 'state': lambda *a: 'draft',
355 'price_type': lambda *a: 'tax_excluded',
356 # 'state_2': lambda *a: 'to_verify',
357 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
358 'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
359 'date_validity': lambda *a: (DateTime.now() + DateTime.RelativeDateTime(months=+6)).strftime('%Y-%m-%d'),
360 'nb_print': lambda *a: 0,
361 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
362 'sale_journal': _sale_journal_get,
363 'invoice_wanted': lambda *a: False,
364 'shop_id': _shop_get,
365 'pricelist_id': _select_pricelist,
369 def test_order_lines(self, cr, uid, order, context={}):
371 """ Test order line is created or not for the order "
372 @param name: Names of fields.
376 raise osv.except_osv(_('Error'), _('No order lines defined for this sale.'))
378 wf_service = netsvc.LocalService("workflow")
379 wf_service.trg_validate(uid, 'pos.order', order.id, 'paid', cr)
382 def dummy_button(self, cr, uid, order, context={}):
385 def test_paid(self, cr, uid, ids, context=None):
387 """ Test all amount is paid for this order
390 for order in self.browse(cr, uid, ids, context):
391 if order.lines and not order.amount_total:
393 if (not order.lines) or (not order.statement_ids) or \
394 Decimal(str(order.amount_total))!=Decimal(str(order.amount_paid)):
398 def _get_qty_differences(self, orders, old_picking):
400 """check if the customer changed the product quantity """
404 for line in order.lines:
405 order_dict[line.product_id.id] = line
407 # check the quantity differences:
409 for line in old_picking.move_lines:
410 order_line = order_dict.get(line.product_id.id)
413 qty_to_delete_from_original_picking = line.product_qty
414 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
415 elif line.product_qty != order_line.qty:
417 qty_to_delete_from_original_picking = line.product_qty - order_line.qty
418 diff_dict[line.product_id.id] = (deleted, qty_to_delete_from_original_picking)
422 def _split_picking(self, cr, uid, ids, context, old_picking, diff_dict):
424 """if the customer changes the product quantity, split the picking in two"""
426 # create a copy of the original picking and adjust the product qty:
427 picking_model = self.pool.get('stock.picking')
429 'note': "Partial picking from customer", # add a note to tell why we create a new picking
430 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out'), # increment the sequence
433 new_picking_id = picking_model.copy(cr, uid, old_picking.id, defaults) # state = 'draft'
434 new_picking = picking_model.browse(cr, uid, new_picking_id, context)
436 for line in new_picking.move_lines:
437 p_id = line.product_id.id
438 if p_id in diff_dict:
439 diff = diff_dict[p_id]
442 if deleted: # product has been deleted (customer didn't took it):
443 # delete this product 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({'state': 'draft'}, context=context) # cannot delete if not draft
447 old_line.unlink(context=context)
448 elif qty_to_del > 0: # product qty has been modified (customer took less than the ordered quantity):
449 # subtract qty from old picking:
450 for old_line in old_picking.move_lines:
451 if old_line.product_id.id == p_id:
452 old_line.write({'product_qty': old_line.product_qty - qty_to_del}, context=context)
453 # add qty to new picking:
454 line.write({'product_qty': qty_to_del}, context=context)
455 else: # product hasn't changed (customer took it without any change):
456 # delete this product from new picking:
457 line.unlink(context=context)
459 # delete it in the new picking:
460 line.unlink(context=context)
462 def create_picking(self, cr, uid, ids, context={}):
464 """Create a picking for each order and validate it."""
466 picking_obj = self.pool.get('stock.picking')
467 pick_name=self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
468 orders = self.browse(cr, uid, ids, context)
470 if not order.picking_id:
472 picking_id = picking_obj.create(cr, uid, {
474 'origin': order.name,
477 'move_type': 'direct',
478 'note': 'POS notes ' + (order.note or ""),
479 'invoice_state': 'none',
480 'auto_picking': True,
481 'pos_order': order.id,
483 self.write(cr, uid, [order.id], {'picking_id': picking_id})
485 picking_id = order.picking_id.id
486 picking_obj.write(cr, uid, [picking_id], {'auto_picking': True})
487 picking = picking_obj.browse(cr, uid, [picking_id], context)[0]
490 # split the picking (if product quantity has changed):
491 diff_dict = self._get_qty_differences(orders, picking)
493 self._split_picking(cr, uid, ids, context, picking, diff_dict)
496 for line in order.lines:
497 if line.product_id and line.product_id.type=='service':
499 prop_ids = self.pool.get("ir.property").search(cr, uid, [('name', '=', 'property_stock_customer')])
500 val = self.pool.get("ir.property").browse(cr, uid, prop_ids[0]).value_reference
501 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))
503 location_id=res and res[0] or None
504 # 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
505 stock_dest_id = val.id
507 location_id, stock_dest_id = stock_dest_id, location_id
509 self.pool.get('stock.move').create(cr, uid, {
510 'name': 'Stock move (POS %d)' % (order.id, ),
511 'product_uom': line.product_id.uom_id.id,
512 'product_uos': line.product_id.uom_id.id,
513 'picking_id': picking_id,
514 'product_id': line.product_id.id,
515 'product_uos_qty': abs(line.qty),
516 'product_qty': abs(line.qty),
517 'tracking_id': False,
518 'pos_line_id': line.id,
520 'location_id': location_id,
521 'location_dest_id': stock_dest_id,
524 wf_service = netsvc.LocalService("workflow")
525 wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
526 self.pool.get('stock.picking').force_assign(cr, uid, [picking_id], context)
530 def set_to_draft(self, cr, uid, ids, *args):
532 """ Changes order state to draft
538 self.write(cr, uid, ids, {'state': 'draft'})
540 wf_service = netsvc.LocalService("workflow")
542 wf_service.trg_create(uid, 'pos.order', i, cr)
545 def button_invalidate(self, cr, uid, ids, *args):
547 """ Check the access for the sale order
550 res_obj = self.pool.get('res.company')
552 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
554 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
556 raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
559 # def button_validate(self, cr, uid, ids, *args):
561 # """ Check the access for the sale order and update the date_validation
564 # res_obj = self.pool.get('res.company')
566 # 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 # except Exception, e:
568 # raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
570 # raise osv.except_osv(_('Error'), _('You don\'t have enough access to validate this sale!'))
571 # for order in self.browse(cr, uid, ids):
572 # if not order.date_validation:
573 # cr.execute("select max(date) from account_bank_statement_line where pos_statement_id=%d"%(order.id))
575 # val=val and val[0] or None
577 # cr.execute("Update pos_order set date_validation='%s', state_2 ='%s' where id = %d"%(val, 'accepted', order.id))
581 def cancel_order(self, cr, uid, ids, context=None):
583 """ Changes order state to cancel
586 self.write(cr, uid, ids, {'state': 'cancel'})
587 self.cancel_picking(cr, uid, ids, context={})
590 def add_payment(self, cr, uid, order_id, data, context=None):
592 """Create a new payment for the order"""
594 res_obj = self.pool.get('res.company')
595 statementl_obj = self.pool.get('account.bank.statement.line')
596 prod_obj = self.pool.get('product.product')
598 curr_c=self.pool.get('res.users').browse(cr, uid, uid).company_id
599 curr_company=curr_c.id
600 order = self.browse(cr, uid, order_id, context)
601 if not order.num_sale and data['num_sale']:
602 self.write(cr,uid,order_id,{'num_sale': data['num_sale']})
604 # if order.invoice_wanted and not order.partner_id:
605 # raise osv.except_osv(_('Error'), _('Cannot create invoice without a partner.'))
607 'amount': data['amount'],
609 if 'payment_date' in data.keys():
610 args['date'] = data['payment_date']
611 if 'payment_name' in data.keys():
612 args['name'] = data['payment_name'] + ' ' +order.name
613 account_def = self.pool.get('ir.property').get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
614 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
615 if data.get('is_acc',False):
616 args['is_acc']=data['is_acc']
617 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
618 if not args['account_id']:
619 raise osv.except_osv(_('Error'), _('Please provide an account for the product: %s')%(prod_obj.browse(cr,uid, data['product_id']).name))
620 args['partner_id'] = order.partner_id and order.partner_id.id or None
621 args['ref'] = order.contract_number or None
623 statement_obj= self.pool.get('account.bank.statement')
624 statement_id = statement_obj.search(cr,uid, [
625 ('journal_id', '=', data['journal']),
626 ('company_id', '=', curr_company),
627 ('user_id', '=', uid),
628 ('state', '=', 'open')])
629 if len(statement_id)==0:
630 raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
632 statement_id=statement_id[0]
633 args['statement_id']= statement_id
634 args['pos_statement_id']= order_id
635 args['journal_id']= data['journal']
636 statement_line_id = statementl_obj.create(cr, uid, args)
637 ids_new.append(statement_id)
639 wf_service = netsvc.LocalService("workflow")
640 wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
641 wf_service.trg_write(uid, 'pos.order', order_id, cr)
645 def add_product(self, cr, uid, order_id, product_id, qty, context=None):
647 """Create a new order line the order"""
649 line_obj = self.pool.get('pos.order.line')
650 values = self.read(cr, uid, order_id, ['partner_id', 'pricelist_id'])
652 pricelist = values['pricelist_id'] and values['pricelist_id'][0]
653 product = values['partner_id'] and values['partner_id'][0]
655 price = line_obj.price_by_product(cr, uid, [],
656 pricelist, product_id, qty, product)
658 order_line_id = line_obj.create(cr, uid, {
659 'order_id': order_id,
660 'product_id': product_id,
664 wf_service = netsvc.LocalService("workflow")
665 wf_service.trg_write(uid, 'pos.order', order_id, cr)
669 def refund(self, cr, uid, ids, context={}):
671 """Create a copy of order for refund order"""
674 line_obj = self.pool.get('pos.order.line')
676 for order in self.browse(cr, uid, ids):
677 clone_id = self.copy(cr, uid, order.id, {
678 'name': order.name + ' REFUND',
679 'date_order': time.strftime('%Y-%m-%d'),
681 'note': 'REFUND\n'+ (order.note or ''),
684 'statement_ids': False,
686 clone_list.append(clone_id)
689 for clone in self.browse(cr, uid, clone_list):
690 for order_line in clone.lines:
691 line_obj.write(cr, uid, [order_line.id], {
692 'qty': -order_line.qty
696 def action_invoice(self, cr, uid, ids, context={}):
698 """Create a invoice of order """
700 res_obj = self.pool.get('res.company')
701 inv_ref = self.pool.get('account.invoice')
702 inv_line_ref = self.pool.get('account.invoice.line')
703 product_obj= self.pool.get('product.product')
706 for order in self.pool.get('pos.order').browse(cr, uid, ids, context):
707 curr_c = order.user_salesman_id.company_id
709 inv_ids.append(order.invoice_id.id)
712 if not order.partner_id:
713 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
715 acc= order.partner_id.property_account_receivable.id
717 'name': 'Invoice from POS: '+order.name,
718 'origin': order.name,
720 'journal_id':order.sale_journal.id or None,
721 'type': 'out_invoice',
722 'reference': order.name,
723 'partner_id': order.partner_id.id,
724 'comment': order.note or '',
726 inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
727 if not inv.get('account_id', None):
728 inv['account_id'] = acc
729 inv_id = inv_ref.create(cr, uid, inv, context)
731 self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'})
732 inv_ids.append(inv_id)
733 for line in order.lines:
735 'invoice_id': inv_id,
736 'product_id': line.product_id.id,
737 'quantity': line.qty,
739 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
741 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
743 line.product_id.uom_id.id,
744 line.qty, partner_id = order.partner_id.id, fposition_id=order.partner_id.property_account_position.id)['value'])
745 inv_line['price_unit'] = line.price_unit
746 inv_line['discount'] = line.discount
747 inv_line['account_id'] = acc
748 inv_line['name'] = inv_name
750 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
751 and [(6, 0, inv_line['invoice_line_tax_id'])] or []
752 inv_line_ref.create(cr, uid, inv_line, context)
755 wf_service = netsvc.LocalService("workflow")
756 wf_service.trg_validate(uid, 'account.invoice', i, 'invoice_open', cr)
759 def create_account_move(self, cr, uid, ids, context=None):
761 """Create a account move line of order """
763 account_move_obj = self.pool.get('account.move')
764 account_move_line_obj = self.pool.get('account.move.line')
765 account_period_obj = self.pool.get('account.period')
766 account_tax_obj = self.pool.get('account.tax')
767 res_obj=self.pool.get('res.users')
768 property_obj=self.pool.get('ir.property')
769 period = account_period_obj.find(cr, uid, context=context)[0]
771 for order in self.browse(cr, uid, ids, context=context):
772 curr_c =res_obj.browse(cr, uid, uid).company_id
773 comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
774 comp_id=comp_id and comp_id.id or False
777 account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
779 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
781 # Create an entry for the sale
782 move_id = account_move_obj.create(cr, uid, {
783 'journal_id': order.sale_journal.id,
787 # Create an move for each order line
788 for line in order.lines:
791 taxes = [t for t in line.product_id.taxes_id]
792 if order.price_type=='tax_excluded':
793 computed_taxes = account_tax_obj.compute_all(
794 cr, uid, taxes, line.price_unit, line.qty)['taxes']
796 computed_taxes = account_tax_obj.compute_inv(
797 cr, uid, taxes, line.price_unit, line.qty)
799 for tax in computed_taxes:
800 tax_amount += round(tax['amount'], 2)
801 group_key = (tax['tax_code_id'],
803 tax['account_collected_id'])
805 if group_key in group_tax:
806 group_tax[group_key] += round(tax['amount'], 2)
808 group_tax[group_key] = round(tax['amount'], 2)
809 if order.price_type!='tax_excluded':
810 amount = line.price_subtotal - tax_amount
812 amount = line.price_subtotal
814 # Search for the income account
815 if line.product_id.property_account_income.id:
816 income_account = line.\
817 product_id.property_account_income.id
818 elif line.product_id.categ_id.\
819 property_account_income_categ.id:
820 income_account = line.product_id.categ_id.\
821 property_account_income_categ.id
823 raise osv.except_osv(_('Error !'), _('There is no income '\
824 'account defined for this product: "%s" (id:%d)') \
825 % (line.product_id.name, line.product_id.id, ))
828 # Empty the tax list as long as there is no tax code:
831 while computed_taxes:
832 tax = computed_taxes.pop(0)
834 tax_code_id = tax['base_code_id']
835 tax_amount = line.price_subtotal * tax['base_sign']
837 tax_code_id = tax['ref_base_code_id']
838 tax_amount = line.price_subtotal * tax['ref_base_sign']
839 # If there is one we stop
843 # Create a move for the line
844 account_move_line_obj.create(cr, uid, {
845 'name': "aa"+order.name,
846 'date': order.date_order[:10],
847 'ref': order.contract_number or order.name,
848 'quantity': line.qty,
849 'product_id':line.product_id.id,
851 'account_id': income_account,
852 'company_id': comp_id,
853 'credit': ((amount>0) and amount) or 0.0,
854 'debit': ((amount<0) and -amount) or 0.0,
855 'journal_id': order.sale_journal.id,
857 'tax_code_id': tax_code_id,
858 'tax_amount': tax_amount,
861 # For each remaining tax with a code, whe create a move line
862 for tax in computed_taxes:
864 tax_code_id = tax['base_code_id']
865 tax_amount = line.price_subtotal * tax['base_sign']
867 tax_code_id = tax['ref_base_code_id']
868 tax_amount = line.price_subtotal * tax['ref_base_sign']
872 account_move_line_obj.create(cr, uid, {
873 'name': "bb"+order.name,
874 'date': order.date_order[:10],
875 'ref': order.contract_number or order.name,
876 'product_id':line.product_id.id,
877 'quantity': line.qty,
879 'account_id': income_account,
880 'company_id': comp_id,
883 'journal_id': order.sale_journal.id,
885 'tax_code_id': tax_code_id,
886 'tax_amount': tax_amount,
890 # Create a move for each tax group
891 (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
892 for key, amount in group_tax.items():
893 account_move_line_obj.create(cr, uid, {
894 'name':"cc"+order.name,
895 'date': order.date_order[:10],
896 'ref': order.contract_number or order.name,
898 'company_id': comp_id,
899 'quantity': line.qty,
900 'product_id':line.product_id.id,
901 'account_id': key[account_pos],
902 'credit': ((amount>0) and amount) or 0.0,
903 'debit': ((amount<0) and -amount) or 0.0,
904 'journal_id': order.sale_journal.id,
906 'tax_code_id': key[tax_code_pos],
907 'tax_amount': amount,
911 to_reconcile.append(account_move_line_obj.create(cr, uid, {
912 'name': "dd"+order.name,
913 'date': order.date_order[:10],
914 'ref': order.contract_number or order.name,
916 'company_id': comp_id,
917 'account_id': order_account,
918 'credit': ((order.amount_total<0) and -order.amount_total)\
920 'debit': ((order.amount_total>0) and order.amount_total)\
922 'journal_id': order.sale_journal.id,
927 # search the account receivable for the payments:
928 account_receivable = order.sale_journal.default_credit_account_id.id
929 if not account_receivable:
930 raise osv.except_osv(_('Error !'),
931 _('There is no receivable account defined for this journal:'\
932 ' "%s" (id:%d)') % (order.sale_journal.name, order.sale_journal.id, ))
934 for payment in order.statement_ids:
939 payment.statement_id.journal_id.default_debit_account_id.id
942 payment.statement_id.journal_id.default_credit_account_id.id
944 # Create one entry for the payment
947 payment_move_id = account_move_obj.create(cr, uid, {
948 'journal_id': payment.statement_id.journal_id.id,
952 for stat_l in order.statement_ids:
953 if stat_l.is_acc and len(stat_l.move_ids):
954 for st in stat_l.move_ids:
957 account_move_line_obj.copy(cr, uid, s.id, { 'debit': s.credit,
958 'statement_id': False,
960 account_move_line_obj.copy(cr, uid, s.id, {
961 'statement_id': False,
962 'account_id':order_account
965 self.write(cr,uid,order.id,{'state':'done'})
968 def cancel_picking(self, cr, uid, ids, context=None):
969 for order in self.browse(cr, uid, ids, context=context):
970 for picking in order.pickings:
971 self.pool.get('stock.picking').unlink(cr, uid, [picking.id], context)
975 def action_payment(self, cr, uid, ids, context=None):
976 vals = {'state': 'payment'}
977 sequence_obj=self.pool.get('ir.sequence')
978 for pos in self.browse(cr, uid, ids):
979 create_contract_nb = False
980 for line in pos.lines:
981 if line.product_id.product_type == 'MD':
982 create_contract_nb = True
984 if create_contract_nb:
985 seq = sequence_obj.get(cr, uid, 'pos.user_%s' % pos.user_salesman_id.login)
986 vals['contract_number'] ='%s-%s' % (pos.user_salesman_id.login, seq)
987 self.write(cr, uid, ids, vals)
989 def action_paid(self, cr, uid, ids, context=None):
992 if context.get('flag',False):
993 self.create_picking(cr, uid, ids, context={})
994 self.write(cr, uid, ids, {'state': 'paid'})
999 def action_cancel(self, cr, uid, ids, context=None):
1000 self.write(cr, uid, ids, {'state': 'cancel'})
1003 def action_done(self, cr, uid, ids, context=None):
1004 for order in self.browse(cr, uid, ids, context=context):
1005 if not order.journal_entry:
1006 self.create_account_move(cr, uid, ids, context={})
1009 def compute_state(self, cr, uid, id):
1010 cr.execute("select act.id, act.name from wkf_activity act "
1011 "inner join wkf_workitem item on act.id=item.act_id "
1012 "inner join wkf_instance inst on item.inst_id=inst.id "
1013 "inner join wkf on inst.wkf_id=wkf.id "
1014 "where wkf.osv='pos.order' and inst.res_id=%s "
1015 "order by act.name", (id,))
1016 return [name for id, name in cr.fetchall()]
1020 class account_bank_statement(osv.osv):
1021 _inherit = 'account.bank.statement'
1023 'user_id': fields.many2one('res.users',ondelete='cascade',string='User', readonly=True),
1026 'user_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).id
1028 account_bank_statement()
1030 class account_bank_statement_line(osv.osv):
1031 _inherit = 'account.bank.statement.line'
1032 def _get_statement_journal(self, cr, uid, ids, context, *a):
1034 for line in self.browse(cr, uid, ids):
1035 res[line.id] = line.statement_id and line.statement_id.journal_id and line.statement_id.journal_id.name or None
1038 'journal_id': fields.function(_get_statement_journal, method=True,store=True, string='Journal', type='char', size=64),
1039 'am_out':fields.boolean("To count"),
1040 'is_acc':fields.boolean("Is accompte"),
1041 'pos_statement_id': fields.many2one('pos.order',ondelete='cascade'),
1043 account_bank_statement_line()
1045 class pos_order_line(osv.osv):
1046 _name = "pos.order.line"
1047 _description = "Lines of Point of Sale"
1049 def _get_amount(self, cr, uid, ids, field_name, arg, context):
1051 for line in self.browse(cr, uid, ids):
1052 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)
1056 def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context):
1057 res = dict.fromkeys(ids, 0.0)
1058 account_tax_obj = self.pool.get('account.tax')
1059 for line in self.browse(cr, uid, ids):
1061 taxes = [t for t in line.product_id.taxes_id]
1064 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
1065 for tax in computed_taxes:
1066 tax_amount += tax['amount']
1067 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)
1068 if line.discount!=0.0:
1069 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1071 res[line.id]=line.price_unit*line.qty
1072 res[line.id] = res[line.id] + tax_amount
1075 def _amount_line(self, cr, uid, ids, field_name, arg, context):
1078 for line in self.browse(cr, uid, ids):
1079 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)
1080 if line.discount!=0.0:
1081 res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0)
1083 res[line.id]=line.price_unit*line.qty
1086 def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1090 raise osv.except_osv(_('No Pricelist !'),
1091 _('You have to select a pricelist in the sale form !\n' \
1092 'Please set one before choosing a product.'))
1093 p_obj = self.pool.get('product.product').browse(cr,uid,[product_id])[0]
1094 uom_id=p_obj.uom_po_id.id
1095 price = self.pool.get('product.pricelist').price_get(cr, uid,
1096 [pricelist], product_id, qty or 1.0, partner_id,{'uom': uom_id})[pricelist]
1097 unit_price=price or p_obj.list_price
1098 if unit_price is False:
1099 raise osv.except_osv(_('No valid pricelist line found !'),
1100 _("Couldn't find a pricelist line matching this product" \
1101 " and quantity.\nYou have to change either the product," \
1102 " the quantity or the pricelist."))
1105 def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False):
1106 price = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1107 self.write(cr,uid,ids,{'price_unit':price})
1108 pos_stot = (price * qty)
1109 return {'value': {'price_unit': price,'price_subtotal_incl': pos_stot}}
1111 def onchange_subtotal(self, cr, uid, ids, discount, price, pricelist,qty,partner_id, product_id,*a):
1112 prod_obj = self.pool.get('product.product')
1113 price_f = self.price_by_product(cr, uid, ids, pricelist, product_id, qty, partner_id)
1116 prod_id=prod_obj.browse(cr,uid,product_id).disc_controle
1118 if (disc != 0.0 or prod_id) and price_f>0:
1119 disc=100-(price/price_f*100)
1120 return {'value':{'discount':disc, 'price_unit':price_f}}
1123 def onchange_dis(self, cr, uid,ids, qty, price_subtotal_incl, discount,*a):
1124 price_sub = price_subtotal_incl
1125 sub_total_discount = price_sub-(price_subtotal_incl*(discount*0.01))
1126 return {'value': {'price_subtotal_incl':sub_total_discount}}
1128 def onchange_ded(self, cr, uid,ids, val_ded,price_u,*a):
1129 pos_order = self.pool.get('pos.order.line')
1130 res_obj = self.pool.get('res.users')
1131 res_company = self.pool.get('res.company')
1132 comp = res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1134 if val_ded and price_u:
1135 val=100.0*val_ded/price_u
1137 return {'value': {'discount':val, 'notice':'' }}
1138 return {'value': {'discount':val}}
1140 def onchange_discount(self, cr, uid,ids, discount,price,*a):
1141 pos_order = self.pool.get('pos.order.line')
1142 res_obj = self.pool.get('res.users')
1143 res_company = self.pool.get('res.company')
1144 company_disc = pos_order.browse(cr,uid,ids)
1146 if not company_disc:
1147 comp=res_obj.browse(cr,uid,uid).company_id.company_discount or 0.0
1149 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
1151 if discount > comp :
1152 return {'value': {'notice':'','price_ded':price*discount*0.01 or 0.0 }}
1154 return {'value': {'notice':'Minimum Discount','price_ded':price*discount*0.01 or 0.0 }}
1156 return {'value': {'notice':'No Discount', 'price_ded':price*discount*0.01 or 0.0}}
1158 'name': fields.char('Line Description', size=512),
1159 'company_id':fields.many2one('res.company', 'Company', required=True),
1160 'notice': fields.char('Discount Notice', size=128, required=True),
1161 'serial_number': fields.char('Serial Number', size=128),
1162 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1163 'price_unit': fields.function(_get_amount, method=True, string='Unit Price', store=True),
1164 'price_ded': fields.float('Discount(Amount)',digits_compute=dp.get_precision('Point Of Sale')),
1165 'qty': fields.float('Quantity'),
1166 'qty_rfd': fields.float('Refunded Quantity'),
1167 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal w/o Tax'),
1168 'price_subtotal_incl': fields.function(_amount_line_ttc, method=True, string='Subtotal'),
1169 'discount': fields.float('Discount (%)', digits=(16, 2)),
1170 'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1171 'create_date': fields.datetime('Creation Date', readonly=True),
1175 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1176 'qty': lambda *a: 1,
1177 'discount': lambda *a: 0.0,
1178 'price_ded': lambda *a: 0.0,
1179 'notice': lambda *a: 'No Discount',
1180 'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1183 # def _check_qty(self, cr, uid, ids):
1184 # lines = self.browse(cr, uid, ids)
1185 # for line in lines:
1191 # (_check_qty, 'Order quantity cannot be negative or zero !', ['qty']),
1194 def create(self, cr, user, vals, context={}):
1195 if vals.get('product_id'):
1196 return super(pos_order_line, self).create(cr, user, vals, context)
1199 def write(self, cr, user, ids, values, context={}):
1200 if 'product_id' in values and not values['product_id']:
1202 return super(pos_order_line, self).write(cr, user, ids, values, context)
1204 def _scan_product(self, cr, uid, ean, qty, order):
1205 # search pricelist_id
1206 pricelist_id = self.pool.get('pos.order').read(cr, uid, [order], ['pricelist_id'] )
1207 if not pricelist_id:
1212 product_id = self.pool.get('product.product').search(cr, uid, [('ean13','=', ean)])
1216 # search price product
1217 product = self.pool.get('product.product').read(cr, uid, product_id)
1218 product_name = product[0]['name']
1219 price = self.price_by_product(cr, uid, 0, pricelist_id[0]['pricelist_id'][0], product_id[0], 1)
1221 order_line_ids = self.search(cr, uid, [('name','=',product_name),('order_id','=',order)])
1224 order_line_id = order_line_ids[0]
1225 qty += self.read(cr, uid, order_line_ids[0], ['qty'])['qty']
1228 vals = {'product_id': product_id[0],
1229 'price_unit': price,
1231 'name': product_name,
1234 line_id = self.create(cr, uid, vals)
1236 raise osv.except_osv(_('Error'), _('Create line failed !'))
1242 line_id = self.write(cr, uid, order_line_id, vals)
1244 raise wizard.except_wizard(_('Error'), _('Modify line failed !'))
1245 line_id = order_line_id
1247 price_line = float(qty)*float(price)
1248 return {'name': product_name, 'product_id': product_id[0], 'price': price, 'price_line': price_line ,'qty': qty }
1253 class pos_payment(osv.osv):
1254 _name = 'pos.payment'
1255 _description = 'Pos Payment'
1257 def _journal_get(self, cr, uid, context={}):
1258 obj = self.pool.get('account.journal')
1259 ids = obj.search(cr, uid, [('type', '=', 'cash')])
1260 res = obj.read(cr, uid, ids, ['id', 'name'], context)
1261 res = [(r['id'], r['name']) for r in res]
1264 def _journal_default(self, cr, uid, context={}):
1265 journal_list = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')])
1267 return journal_list[0]
1272 'name': fields.char('Description', size=64),
1273 'order_id': fields.many2one('pos.order', 'Order Ref', required=True, ondelete='cascade'),
1274 'journal_id': fields.many2one('account.journal', "Journal", required=True),
1275 'payment_id': fields.many2one('account.payment.term','Payment Term', select=True),
1276 'payment_nb': fields.char('Piece Number', size=32),
1277 'payment_name': fields.char('Payment Name', size=32),
1278 'payment_date': fields.date('Payment Date', required=True),
1279 'amount': fields.float('Amount', required=True),
1282 'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.payment'),
1283 'journal_id': _journal_default,
1284 'payment_date': lambda *a: time.strftime('%Y-%m-%d'),
1287 def create(self, cr, user, vals, context={}):
1288 if vals.get('journal_id') and vals.get('amount'):
1289 return super(pos_payment, self).create(cr, user, vals, context)
1292 def write(self, cr, user, ids, values, context={}):
1293 if 'amount' in values and not values['amount']:
1295 if 'journal_id' in values and not values['journal_id']:
1297 return super(pos_payment, self).write(cr, user, ids, values, context)
1301 class account_move_line(osv.osv):
1303 _inherit = 'account.move.line'
1304 def create(self, cr, user, vals, context={}):
1305 pos_obj = self.pool.get('pos.order')
1306 val_name = vals.get('name', '')
1307 val_ref = vals.get('ref', '')
1308 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1309 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1310 name_pos = aaa.groups()[0]
1311 pos_id = name_pos.replace('POS ','')
1312 if pos_id and pos_id.isdigit():
1313 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1314 pos_curr = pos_curr and pos_curr.contract_number or ''
1315 vals['ref'] = pos_curr or vals.get('ref')
1316 return super(account_move_line, self).create(cr, user, vals, context)
1321 class account_move(osv.osv):
1323 _inherit = 'account.move'
1325 def create(self, cr, user, vals, context={}):
1326 pos_obj = self.pool.get('pos.order')
1327 val_name = vals.get('name', '')
1328 val_ref = vals.get('ref', '')
1329 if (val_name and 'POS' in val_name) and (val_ref and 'PACK' in val_ref):
1330 aaa = re.search(r'Stock move.\((.*)\)', vals.get('name'))
1331 name_pos = aaa.groups()[0]
1332 pos_id = name_pos.replace('POS ','')
1333 if pos_id and pos_id.isdigit():
1334 pos_curr = pos_obj.browse(cr,user,int(pos_id))
1335 pos_curr = pos_curr and pos_curr.contract_number or ''
1336 vals['ref'] = pos_curr or vals.get('ref')
1337 return super(account_move, self).create(cr, user, vals, context)
1342 class product_product(osv.osv):
1343 _inherit = 'product.product'
1345 'income_pdt': fields.boolean('Product for Incoming'),
1346 'expense_pdt': fields.boolean('Product for expenses'),
1347 'am_out': fields.boolean('Controle for Outgoing Operations'),
1348 'disc_controle': fields.boolean('Discount Controle '),
1351 'disc_controle': lambda *a: True,
1355 class stock_picking(osv.osv):
1357 _inherit = 'stock.picking'
1359 'pos_order': fields.many2one('pos.order', 'Pos order'),
1363 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: