Odoo13: How to assign followers to a record via Controller - odoo

In my webform controller, I am attempting to assign email addresses entered in a webform to a given record. This is the snippet of code in my controller responsible for that
if 'followers' in request.params:
raw_emails = request.httprequest.form.get('followers').split(',')
emails = [user.strip() for user in raw_emails]
#emails = ['foo#bar.com', 'foo2#bar.com',..]
for email in emails:
follower = request.env['res.users'].search(
[('email', '=', email)])
if bool(follower):
reg = {
'res_id': new_ticket.id,
'res_model': 'helpdesk.ticket',
'partner_id': follower.id
}
request.env['mail.followers'].create(reg)
else:
message = "TO DO: Add {} to the system and make the user a follower of this ticket".format(
email)
new_ticket.message_post(body=message)
With this I get strange results i.e after entering "user A" as a follower on the webform, "user B" gets added as a follower. I'm thinking the problem might be from the wrong user record being loaded into the follower variable but I'm not seeing why. Any feedback would be really appreciated.

You can use the message_subscribe method to add followers to a record set.
def message_subscribe(self, partner_ids=None, channel_ids=None, subtype_ids=None):
    """ Main public API to add followers to a record set. Its main purpose is
    to perform access rights checks before calling _message_subscribe. """
You have already an example in the account move, in message_new method that add a list of partners.
# Assign followers.
all_followers_ids = set(partner.id for partner in followers + senders + partners if is_internal_partner(partner))
move.message_subscribe(list(all_followers_ids))

Related

how only display other user ID on the two columns user 1 and user 2 after filtering authenticated user ID from the table and adding it to a new column

I'm creating a one-on-one chat, but there are two columns: user 1 and user 2.
The user may be in user 1 or user 2, and I want to show him or her the chats from people who have contacted him or him, but the table returned as
and I just want to retrieve the other user id not the authenticated user, who is 51
so l want to select either user 1 or user 2 which has the other user id.
the code I implemented
$room = Chat::where([
['user_1',Auth::id()]
])->orWhere([
['user_2',Auth::id()]
])->latest()->get();
// dd($room);
return view('users.chats',[
'room_id'=>$room,
// 'messages'=>Message::oldest()->where('chat_id',$room->chat_id)->get(),
'selectedUser' => false
]);
How can I create a new column called "other user" and only retrieve the other user's ID?
Running it through php on array filter fixed the problem.
$room = Chat::where([
['user_1',Auth::id()]
])->orWhere([
['user_2',Auth::id()]
])->latest()->get();
$users = array();
foreach($room as $item){
array_push($users,$item->user_1,$item->user_2);
}
$fillterdUsers = array_filter($users,function($val){
return $val !== auth()->id();
});
return view('users.chats',[
'room_id'=>$fillterdUsers,
// 'messages'=>Message::oldest()->where('chat_id',$room->chat_id)->get(),
'selectedUser' => false
]);

How to retrieve array of results of (has-many) relationship

I have users table (id,email...etc)
and related table user_devices(user_id,device_id)
user has many devices
In User Model
public function userDevices()
{
return $this->hasMany(userDevicess::class, 'user_devices');
}
In controller
$userdevices=$user->with('userDevices')->where('device_id',$request->device_id)->get();
But it not works!
What I want:
foreach($userdevices as $userdevice)
echo userdevice->email;
Thanks

Permission of ir.config_paramenter in odoo 12

I got this problem. Why i get this access error and how can i fix it?
Odoo Server Error - Access Error
Sorry, you are not allowed to access
this document. Only users with the following access level are
currently allowed to do that:
Administration/Settings
(Document model: ir.config_parameter) - (Operation: read, User: 21)
Here is my code:
Button submit:
<button string="Confirm" name="button_submit" states="draft" type="object" class="oe_highlight"/>
My python code:
def send_email(self, subject, message_body, email_from, email_to):
template_obj = self.env['mail.mail']
template_data = {
'subject': subject,
'body_html': message_body,
'email_from': email_from,
'email_to': email_to
}
template_id = template_obj.create(template_data)
template_obj.send(template_id)
template_id.send()
#api.multi
def request_recuitment_send_mail(self):
""" Send mail with wizard """
base_url = request.env['ir.config_parameter'].get_param('web.base.url')
base_url += '/web#id=%d&view_type=form&model=%s' % (self.id, self._name)
subject = '''Request recuitment for {}'''.format(self.job_id.name)
message_body = '''
<div style="font-size: medium;">
Dear {},
Please check this link for more information Click here
'''.format(
self.user_id.name,
base_url,
)
email_from = '''HR Recruiment <{}>'''.format(self.approver_id.work_email)
email_to = self.user_id.email
self.send_email(subject, message_body, email_from, email_to)
#api.multi
def button_approve(self):
subject = "Request recruitment for {self.job_id.name} has been approved "
body = '''
Position Request: {}
Quantity of Position: {}
Department: {}
Expected Gross Salary: {}
'''.format(
self.job_id.name,
self.quantity,
self.department_id.name,
self.salary_cross_expected
)
self.env['mail.message'].create({'message_type': "notification",
"subtype": self.env.ref("mail.mt_comment").id,
'body': body,
'subject': subject,
'needaction_partner_ids': [(4, self.user_id.partner_id.id,)],
'model': self._name,
'res_id': self.id,
})
self.request_recuitment_approved_send_mail()
self.write({'state': 'approved'})
It should be safe to use sudo() in this case:
request.env['ir.config_parameter'].sudo().get_param('web.base.url')
"Normal" Users don't have any rights on model ir.config_parameter (System parameters). Only the admin (one of its default access groups) or the superuser can read such parameters.
About sudo([flag=True]) from the current documentation (Odoo 15):
Returns a new version of this recordset with superuser mode enabled or disabled, depending on flag. The superuser mode does not change the current user, and simply bypasses access rights checks.
IMPORTANT: I'm not completely sure when it was changed, but IIRC the "current user change" was removed since Odoo 13. So for Odoo 12 sudo will change the current user, which for example will have impacts on default values on creation, created message authors, and so on.
In your case that's irrelevant, because you're only getting the base url or the parameter value, and that's it.

how to change the created by <user> in log to OdooBot when creating a record using odoo external API

I'm trying to create a new lead from external landing page
The code work as expected so far on Odoo 13.0+e-20200524
url = ODOO_URL
db = ODOO_DB
username = ODOO_USERNAME
password = ODOO_PASSWORD
kwargs = {
'name': 'hello world',
}
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
print(uid)
models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))
id = models.execute_kw(db, uid, password, 'crm.lead', 'create', [{
'name': kwargs.get('name'),
'user_id': 1,
}])
print(id)
But the log of the lead showing that my user created that lead (which is properly right)
Change the created user to OdooBot in the view - screenshot
My question is:
How can I change the created user to OdooBot instead of my user?
PS: I already searched around and tried bellow parameters without luck:
'user_login': "OdooBot",
'create_uid': [1],
'write_uid': [1],
uid represent a key role of User to create a record using xmlrpc.
You can change uid and it will log with that User.

Openerp get partner category tags

I have 2 fields in my custom module:
'originator_id' : fields.many2one("res.partner",string="Originator", required=True),
'originator_category_ids' : fields.many2many('res.partner.category',
'module_category_rel',
'module_id',
'category_id',
'Categories'),
I want to set the domain for the many2many field "originator_category_ids" according to the selected "originator_id" which is a partner_id. I wrote an onchange method to define the domain dynamically:
def get_domain_originator_category_ids(self,cr,uid,ids,originator_id,context=None):
if originator_id:
obj = self.pool.get('res.partner').browse(cr, uid, originator_id)
return {'domain':{'originator_category_ids':[('id','in',obj.category_id)]}}
But above doesn't work.
Your support will be much appreciated.
This is worked for me, but it is a temporary solution until I find a better one. The solution consist on looping on categories and compare with the selected partner in the partner_ids field:
def get_domain_originator_category_ids(self,cr,uid,ids,originator_id,context=None):
category_obj = self.pool.get('res.partner.category')
category_ids = category_obj.search(cr, uid,[], context=context)
res=[]
for cateory in category_obj.browse(cr, uid, category_ids, context=context):
for partner_id in cateory.partner_ids:
if partner_id.id == originator_id:
res.append(cateory.id)
return {'domain':{'originator_category_ids':[('id','in',res)]}}
If you get a better solution please post it.