openerp 7 create method override - openerp-7

I am new OpenERP 7 programming. I have created a booking module that allows a guest to book more than one room. I want to be able to change the room status from available to booked when creating the new reservation. The solution to this kind of scenario seems to be overriding the create or write ORM methods for openERP.
I completely don't know how to incorporate this in my code. Below is part of my code.
class reservation(osv.osv):
_columns = {
'name': fields.char('Reservation No', required=True, select=True, readonly=True),
'date_order':fields.datetime('Date Ordered', required=True, readonly=True),
'reserved_rooms': fields.one2many('hotel.reservation.line','line_id', 'Reserved Rooms'),
'state': fields.selection([('draft', 'Draft'),('confirmed','Confirmed'),('cancelled','Cancelled'),('done','Done')], 'State',readonly=True),
}
reservation()
_defaults = {
'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid,'hotel.reservation'),
'state': lambda *a: 'draft',
'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S')
}
The reservation is created with the default state as draft. How and where in my code do i put and use the create or write method? Thanks.

Try following,
class reservation(osv.osv):
_columns = {
'name': fields.char('Reservation No', required=True, select=True, readonly=True),
'date_order':fields.datetime('Date Ordered', required=True, readonly=True),
'reserved_rooms': fields.one2many('hotel.reservation.line','line_id', 'Reserved Rooms'),
'state': fields.selection([('draft', 'Draft'),('confirmed','Confirmed'),('cancelled','Cancelled'),('done','Done')], 'State',readonly=True),
}
_defaults = {
'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid,'hotel.reservation'),
'state': lambda *a: 'draft',
'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S')
}
def create(self, cr, uid, vals, context=None):
###Add your code here
####update status in vals
return super(reservation,self).create(cr, uid, vals, context=context)
def write(self, cr, uid, ids, vals, context=None):
###Add your code here
####update status in vals
## you will get only those fields into the vals which are updated.
return super(reservation,self).write(cr, uid, ids, vals, context=context)

Related

Odoo : OpenERP7 _prepare_purchase_order_line method equivalent in Odoo 12

I'm working on migrating an old module from OpenERP 7 to Odoo 12. I'm stuck in this method called _prepare_purchase_order_line, you can find it in model purchase.requisition.
Here is its code :
def make_purchase_order(self, cr, uid, ids, partner_id, context=None):
"""
Create New RFQ for Supplier
"""
context = dict(context or {})
assert partner_id, 'Supplier should be specified'
purchase_order = self.pool.get('purchase.order')
purchase_order_line = self.pool.get('purchase.order.line')
res_partner = self.pool.get('res.partner')
supplier = res_partner.browse(cr, uid, partner_id, context=context)
res = {}
for requisition in self.browse(cr, uid, ids, context=context):
if not requisition.multiple_rfq_per_supplier and supplier.id in filter(lambda x: x, [rfq.state != 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]):
raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state)
context.update({'mail_create_nolog': True})
purchase_id = purchase_order.create(cr, uid, self._prepare_purchase_order(cr, uid, requisition, supplier, context=context), context=context)
purchase_order.message_post(cr, uid, [purchase_id], body=_("RFQ created"), context=context)
res[requisition.id] = purchase_id
for line in requisition.line_ids:
purchase_order_line.create(cr, uid, self._prepare_purchase_order_line(cr, uid, requisition, line, purchase_id, supplier, context=context), context=context)
return res
I want to know what is the equivalent of this method in Odoo 12.
Can you help me?
I can see this method exist with the same name in odoo 12 but it is in purchase.requisition.line model.
#api.multi
def _prepare_purchase_order_line(self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False):
self.ensure_one()
requisition = self.requisition_id
if requisition.schedule_date:
date_planned = datetime.combine(requisition.schedule_date, time.min)
else:
date_planned = datetime.now()
return {
'name': name,
'product_id': self.product_id.id,
'product_uom': self.product_id.uom_po_id.id,
'product_qty': product_qty,
'price_unit': price_unit,
'taxes_id': [(6, 0, taxes_ids)],
'date_planned': date_planned,
'account_analytic_id': self.account_analytic_id.id,
'analytic_tag_ids': self.analytic_tag_ids.ids,
'move_dest_ids': self.move_dest_id and [(4, self.move_dest_id.id)] or []
}

How to use many2one field in the function in openerp

how can I use many2one field in the function?
this is my code:
def _get_unit(self, cr, uid, ids, fields,arg, context=None):
res = {}
list_data = []
for record in self.browse(cr, uid, ids,unit):
list_data.append(record[unit.id])
return super(learning_course, self)._get_unit(cr, uid, ids, context=context)
_columns = {
'unit': fields.many2one('hr.department', 'unit'),
'department': fields.function(_get_unit, string='department' , store=True ,type='many2one' ,relation='hr.department'),
}
def onchange_user(self, cr, uid, ids, user_id, context=None):
unit = False
if user_id:
unit = self.pool.get('res.users').browse(cr, uid, user_id, context=context).context_department_id.id
return {'value': {'unit' : unit }}
return {'value': {} }
but I get this error:
for record in self.browse(cr, uid, ids,unit):
AttributeError: 'browse_record_list' object has no attribute 'id'
what should I do?
def _get_unit(self, cr, uid, ids, prop, unknow_none, context=None):
res = {}
for record in self.browse(cr, uid, ids):
res [record.id] = record.user_id.context_department_id.id
return res
_columns = {
'user_id': fields.many2one('res.users', 'user', readonly=True),
'unit_id': fields.function(_get_unit, string='dep' , store=True ,type='many2one',relation='hr.department'),
}

Add a custom button without close odoo 9 wizard?

Good day,
I've been working on the lot and serial number module in odoo 9.
I changed the sequence that the module has as default and I substituted it with the generation of an UUID, but when I call this component in the received items part, when I click on the button that generates the UUID the app suddenly returns to the window that I used to call it without letting me to save the UUID that I generated.
Here's my code:
class stock_production_lot(osv.osv):
_name = 'stock.production.lot'
_inherit = ['mail.thread']
_description = 'Lot/Serial'
_columns = {
'name': fields.char('Serial Number', required=True, help="Unique Serial Number"),
'x_num_serie_': fields.char('No. de serie', required=False, help="No. de serie del producto"),
'ref': fields.char('Internal Reference', help="Internal reference number in case it differs from the manufacturer's serial number"),
'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', 'in', ['product', 'consu'])]),
'quant_ids': fields.one2many('stock.quant', 'lot_id', 'Quants', readonly=True),
'create_date': fields.datetime('Creation Date'),
}
_defaults = {
'name': lambda x, y, z, c: x.pool.get('ir.sequence').next_by_code(y, z, 'stock.lot.serial'),
'x_num_serie_':None,
'product_id': lambda x, y, z, c: c.get('product_id', False),
}
_sql_constraints = [
('name_ref_uniq', 'unique (name, product_id)', 'The combination of serial number and product must be unique !'),
]
def action_traceability(self, cr, uid, ids, context=None):
""" It traces the information of lots
#param self: The object pointer.
#param cr: A database cursor
#param uid: ID of the user currently logged in
#param ids: List of IDs selected
#param context: A standard dictionary
#return: A dictionary of values
"""
quant_obj = self.pool.get("stock.quant")
quants = quant_obj.search(cr, uid, [('lot_id', 'in', ids)], context=context)
moves = set()
for quant in quant_obj.browse(cr, uid, quants, context=context):
moves |= {move.id for move in quant.history_ids}
if moves:
return {
'domain': "[('id','in',[" + ','.join(map(str, list(moves))) + "])]",
'name': _('Traceability'),
'view_mode': 'tree,form',
'view_type': 'form',
'context': {'tree_view_ref': 'stock.view_move_tree'},
'res_model': 'stock.move',
'type': 'ir.actions.act_window',
}
return False
def action_generate_uuid(self, cr, uid, ids, context=None):
print "< action_generate_uuid >"
_uuid = (uuid.uuid1()).hex
obj = self.browse(cr, uid, ids,context=context)
print "< obj.name >",obj.name
for item in self.browse(cr, uid, ids,context=context):
if item.name:
item.name = _uuid
item.x_num_serie_ = _uuid
print "< name >",item.name
print "< x_num_serie_>",item.x_num_serie_
else:
print "< falta un elemento >"
return None
I'll really appreciate any idea on what is happening and how can I avoid it.
Best regards,
Alain
The default behaviour is to close upon the pressing of any button and execution of the function associated with the button. The work around is to have the button execute a function and then return an action bringing up the exact same wizard.
You can set context to open the wizard again with all the form values populated.
Here is an example:
class MyWizard(models.TransientModel):
_name = 'myaddon.mywizard'
def _get_default_char(self):
return self._context.get('mychar',"")
mychar = fields.Char(string="My Char", default=_get_default_char)
#api.multi
def my_button(self):
# Execute Function Here
# reload wizard with context
return {
'view_type': 'form',
'view_mode': 'form',
'res_model': 'myaddon.mywizard',
'type': 'ir.actions.act_window',
'target': 'new',
'res_id': self.id,
'context': '{"default_mychar":'HELLO WORLD'}',
}

Displaying custom message

I'm trying to display a custom message box from my custom module called 'xx_project'
The code below is from a class I made that contains the warning. I then want to call this warning from my custom module 'xx_project'
class warning(osv.osv_memory):
_name = 'warning'
_description = 'warning'
_columns = {
'type': fields.selection(WARNING_TYPES, string='Type', readonly=True),
'title': fields.char(string="Title", size=100, readonly=True),
'message': fields.text(string="Message", readonly=True),
}
_req_name = 'title'
def _get_view_id(self, cr, uid):
"""Get the view id
#return: view id, or False if no view found
"""
res = self.pool.get('ir.model.data').get_object_reference(cr, uid,
'xx_project', 'warning_form')
return res and res[1] or False
def message(self, cr, uid, id, context):
message = self.browse(cr, uid, id)
message_type = [t[1] for t in WARNING_TYPES if message.type == t[0]][0]
print '%s: %s' % (_(message_type), _(message.title))
res = {
'name': '%s: %s' % (_(message_type), _(message.title)),
'view_type': 'form',
'view_mode': 'form',
'view_id': self._get_view_id(cr, uid),
'res_model': 'warning',
'domain': [],
'context': context,
'type': 'ir.actions.act_window',
'target': 'new',
'res_id': message.id
}
return res
def info(self, cr, uid, title, message, context=None):
id = self.create(cr, uid, {'title': title, 'message': message, 'type': 'info'})
res = self.message(cr, uid, id, context)
return res
And then finally in xx_project I have a field named 'xx_message' that calls the function 'get_message'.
get_message looks like this:
def get_message(self, cr, uid, ids, name, args, context=None):
return self.pool.get('warning').info(cr, uid, title='Export imformation',
message="%s products Created, %s products Updated " % (
"test", "test"))
And 'xx_message':
_columns = {
'xx_message': fields.function(get_message)
}
I keep getting a Keyerror when I try and run this code, any ideas?

take field date from another database

in ticket.py. I have two class. class deposit.line and res_partner (inherit). I want to take the date of the class deposit.line but its function in the class res_partner(inherit)
def _compute_dept2(self, cr, uid, ids, amount, arg, context=None):
result = {}
obj2 = self.pool.get('deposit.line')
for record in obj2.deposit_line:
temp1 = record.date
print temp1
print result
return result
but the results of its existing print false. what wrong ? please correct my code
PS:
My explanation is less good. but look at my code,surely knowing my explanation.
THIS MY COMPLETE CODE:
class deposit_line(osv.osv):
_name ="deposit.line"
_description = "Deposit Line"
_columns = {
'name': fields.char('Name', size=64),
'ref': fields.char('Reference', size=64),
'amount': fields.float('Amount'),
'date': fields.date('Date', required=True),
'deposit_id': fields.many2one('res.partner', 'Deposit ', required=True, ondelete='cascade'),
}
deposit_line()
class res_partner(osv.osv):
_inherit = 'res.partner'
def _compute_age(self, cr, uid, ids,date_birth,age,arg, context=None):
result = {}
for r in self.browse(cr, uid, ids, context=context):
age=0
if r.date_birth:
age = (datetime.now()-datetime.strptime(r.date_birth,"%Y-%m-%d")).days/365.25
result[r.id] = age
return result
def _compute_dept(self, cr, uid, ids, deposit, available, arg, context=None):
result = {}
for r in self.browse(cr, uid, ids, context=context):
avail=0
temp = r.available
if r.deposit:
avail = r.deposit + temp
result[r.id] = avail
return result
def _compute_dept2(self, cr, uid, ids, amount, arg, context=None):
result = {}
obj2 = self.pool.get('deposit.line')
for record in obj2.deposit_line:
temp1 = record.date
print temp1
print result
return result
_columns = {
'speaker': fields.boolean('Leader'),
'event_ids': fields.one2many('event.event','main_speaker_id', readonly=True),
'event_registration_ids': fields.one2many('event.registration','partner_id', readonly=True),
'airline': fields.boolean('Airlines'),
'hotel': fields.boolean('Hotel'),
'date_birth': fields.date('Date of Birth'),
'id_no': fields.char('ID. No', size=20),
'id_expired': fields.date('Expired Date'),
'sex':fields.selection([('male','Male'),('female','Female')],'Sex'),
'age' : fields.function(_compute_age, type='float', method=True, store=True, string='Age', readonly=True),
'deposit': fields.function(_compute_dept2, type='float', method=True, store=True, string='Deposit', readonly=True),
'available': fields.function(_compute_dept, type='float', method=True, store=True, string='Available', readonly=True),
'deposit_ids':fields.one2many('deposit.line', 'deposit_id', 'Deposit Line'),
}
res_partner()
Since you have one2many field for deposit_line defined in the res.partner model, you do not need the to access deposit_line object directly.
def _compute_dept2(self, cr, uid, ids, amount, arg, context=None):
result = {}
for partner in self.browse(cr, uid, id, context=context)
result[partner.id]=0
for deposit_line in partner.deposit_ids:
result[partner.id] += deposit_line.amount
return result
After line 3, you forgot to:
obj2.browse(cr, uid, ids, context=context)
You should learn to use the debugger:
Add the line import pdb; pdb.set_trace() where you want to place a breakpoint. When the Python reaches the breakpoint it stops at the console with a (pdb) prompt. There type p obj to print variable obj, n to step to the next instruction, and hfor help. You might find more info in this post and in the docs.