Auto fill some fields in form when you found id of other form, odoo 8.0 - forms

I try to create a simple function who try to fill specific fields in own form when I select the ID of patient registered in other form/module. I put an example:
Module Registro:
(create patient)
(automatic generation ID and visible)
-Nombre:
-Email:
-Teléfono:
(save)
Admisión module:
(Open new form)
-ID: select id
(function for auto fill the next fields)
-Nombre: nombre (registro)
-Email: email(registro)
-Teléfono: teléfono(registro)
Use the new API Odoo 8.0 I try this, but doesn't work with message: error 500 type.
función autocompletar campos
#api.onchange('telefono_contacto','persona_contacto','email','nombre_acompanante') # mete campos a afectar
def autofill(self):
# comdición; si esta con el id seleccionado
# self.id_anamnesis
# llenar los campos con los correspondientes del id
# self.telefono_contacto =''
# self.persona_contacto = ''
# self.email = ''
# self.nombre_acompanante = ''
pass # aquí la lógica
(La plataforma es Odoo 8.0, S.O: Ubuntu 14.04)
Thank you and best reegards,
Marco García Baturan.

product_id = fields.Many2one("myproduct.model",string="Product", required=True)
description = fields.Char("Description", related="product_id.description", store=True)
It is done using related="......"
What I have done is When I select my product it will automatically
set description of that particular product.
So you need to add related where you want to auto fill.
If you set store=True then description is store into database.

Related

jasper reports - msg function not accepting more than 4 parameters including pattern

So it seems i can't create a string from properties file with more than 3 parameters plus the pattern:
msg(str("lifeletter."+$P{COD_DOC}+".message"),$P{PR_YEAR},$P{MODULE_NAME},$F{benefit_value},$F{accumulated_value})
I get this error:
The method msg(String, Object, Object, Object) in the type JREvaluator is not applicable for the arguments (String, String, String, String, String)
value = msg(str("lifeletter."+((java.lang.String)parameter_COD_DOC.getValue())+".message"),((java.lang.String)parameter_PR_YEAR.getValue()),((java.lang.String)parameter_MODULE_NAME.getValue()),((java.lang.String)field_benefit_value.getValue()),((java.lang.String)field_accumulated_value.getValue())); //$JR_EXPR_ID=10$
If i remove the last param(accumulated_value {3}) it will work
here is the .properties file entry:
letter.product.message = Caro Cliente, Vimos pela presente informar que, em {0} , foi atribuida participação nos resultados ao seu {1} no valor de {2}. \
Desta forma, o valor acumulado atual da participação nos resultados é de {3}.
I solved this by using the java class MessageFormat:
new MessageFormat(str("pattern")).format(new Object[]{"value 1","value 2", "value 3","value 4"})

How i can save a log with powershell in format pdf?

Actually i make one test unit that print this result:
info: serving app on http://127.0.0.1:4000
Usuario
superagent: Enable experimental feature http2
✓ realiza um registro de usuário (511ms)
✓ realiza login com o usuário registrado (142ms)
✓ realiza login com dados incorretos (145ms)
PASSED
total : 3
passed : 3
time : 2s
If i try to export this log in format .txt i have several problems with special characters and accents, as you can see:
adonis test > yourfile.txt
When i open the "yourfile.txt":
[32minfo[39m: serving app on http://127.0.0.1:4000
Usuario
Ô£ô realiza um registro de usu├írio (456ms)
Ô£ô realiza login com o usu├írio registrado (135ms)
Ô£ô realiza login com dados incorretos (126ms)
PASSED
total : 3
passed : 3
time : 1s
I'm thinking if there's a way to export this log in pdf to workaround this problem or if there's a way to show the special characters/accents correctly.
if i do a adonis test > yourfile.pdf the pdf generated is broken.
This may have to do with OutputEncoding.
Try:
$enc = [Console]::OutputEncoding
[Console]::OutputEncoding = [text.encoding]::utf8
adonis test | Out-File yourfile.txt -Encoding utf8 -Force
[Console]::OutputEncoding = $enc

sqlalchemy many to many relationships (the value of a duplicate key breaks the unique constraint) flask_user role

can you help me,
when i run this script it works well
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')
# User authentication information. The collation='NOCASE' is required
# to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.
email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
email_confirmed_at = db.Column(db.DateTime())
password = db.Column(db.String(255), nullable=False, server_default='')
# User information
first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
# Define the relationship to Role via UserRoles
roles = db.relationship('Role', secondary='user_roles')
# Define the Role data-model
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
# Define the UserRoles association table
class UserRoles(db.Model):
__tablename__ = 'user_roles'
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))
# Setup Flask-User and specify the User data-model
user_manager = UserManager(app, db, User)
# Create all database tables
db.create_all()
# Create 'member#example.com' user with no roles
if not User.query.filter(User.email == 'member#example.com').first():
user = User(
email='member#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
db.session.add(user)
db.session.commit()
# Create 'admin#example.com' user with 'Admin' and 'Agent' roles
if not User.query.filter(User.email == 'admin#example.com').first():
user = User(
email='admin#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
at this stage the code is working without problems but the problem is just after when I add another user with a role that already exists
in this case the Admin role or the Agent role
for example if I add the code below an error message displays
if not User.query.filter(User.email == 'admin2#example.com').first():
user = User(
email='admin2#example.com',
email_confirmed_at=datetime.datetime.utcnow(),
password=user_manager.hash_password('Password1'),
)
user.roles.append(Role(name='Admin'))
user.roles.append(Role(name='Agent'))
db.session.add(user)
db.session.commit()
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) ERREUR: la valeur d'une clé dupliquée rompt la contrainte unique « roles_name_key »
DETAIL: La clé « (name)=(Admin) » existe déjà.
[SQL: 'INSERT INTO roles (name) VALUES (%(name)s) RETURNING roles.id'] [parameters: {'name': 'Admin'}] (Background on this error at: http://sqlalche.
me/e/gkpj)
I tried db driver different (pg8000, pygresql, py-postgresql) and still the same problem,
as the error message shows the problem because of the name value which is unique
name = db.Column (db.String (50), unique = True)
can you explain to me what is the error that I made, and what is the role of this part of code
# Define the relationship to Role via UserRoles
roles = db.relationship ('Role', secondary = 'user_roles')
I use flask with flask_user

Slack API: Retrieve all member emails from a slack channel

Given the name of a slack channel, is there a way to retrieve a list of emails of all the members in that channel? I tried looking in the slack api docs but couldn't find the method I need to make this happen (https://api.slack.com/methods).
Provided you have the necessary scopes you can retrieved the emails of all members of a channel starting with the channel name as follows:
Call channels.list to get the list of all channels and to convert the channel name to its ID
Call channels.info of the desired channel with channel ID to get the list of its members.
Call users.list to retrieve the list of all Slack users including their profile information and email
Match the channel member list with the user list by user ID to get the correct users and emails
Note that this also works for private channels using groups.list and groups.info, but only if the user or bot related to the access token is a member of that private channel.
Update 2019
Would strongly recommend to rather use the newer conversations.* methods, instead of channels.* and groups.*, because they are more flexible and they are some cases where the older methods will not work (e.g. converted channels).
Here's a version that works with Python 2 or 3 using up-to-date APIs.
import os
import requests
SLACK_API_TOKEN='xoxb-TOKENID' # Your token here
CHANNEL_NAME='general' # Your channel here
channel_list = requests.get('https://slack.com/api/conversations.list?token=%s&types=%s' % (SLACK_API_TOKEN, 'public_channel,private_channel,im,mpim')).json()['channels']
for c in channel_list:
if 'name' in c and c['name'] == CHANNEL_NAME:
channel = c
members = requests.get('https://slack.com/api/conversations.members?token=%s&channel=%s' % (SLACK_API_TOKEN, channel['id'])).json()['members']
users_list = requests.get('https://slack.com/api/users.list?token=%s' % SLACK_API_TOKEN).json()['members']
for user in users_list:
if "email" in user['profile'] and user['id'] in members:
print(user['profile']['email'])
Note that you'll need to create a Slack App with an OAuth API token and the following scopes authorized for this to work for all of the various types of conversations:
channels:read
groups:read
im:read
mpim:read
users:read
users:read.email
Also, to read from private channels or chats, you'll need to add your app to the Workspace and "/invite appname" for each channel you're interested in.
Note: channels.list, channels.info, users.list are deprecated (retire and cease functioning on November 25, 2020).
Replace to conversations.list, conversations.members, users.info
You can get the email like this way:
conversations.list - Get the list of Channel Id (public or private)
conversations.members - Get the list of Member Id by Channel Id
users.info - Get the Email by Member Id
Here's the python code:
import requests
SLACK_API_TOKEN = "" # get one from https://api.slack.com/docs/oauth-test-tokens
CHANNEL_NAME = ""
# channel_list = requests.get('https://slack.com/api/channels.list?token=%s' % SLACK_API_TOKEN).json()['channels']
# channel = filter(lambda c: c['name'] == CHANNEL_NAME, channel_list)[0]
# channel_info = requests.get('https://slack.com/api/channels.info?token=%s&channel=%s' % (SLACK_API_TOKEN, channel['id'])).json()['channel']
# members = channel_info['members']
channel_list = requests.get('https://slack.com/api/groups.list?token=%s' % SLACK_API_TOKEN).json()['groups']
channel = filter(lambda c: c['name'] == CHANNEL_NAME, channel_list)[0]
channel_info = requests.get('https://slack.com/api/groups.info?token=%s&channel=%s' % (SLACK_API_TOKEN, channel['id'])).json()['group']
print channel_info
members = channel_info['members']
users_list = requests.get('https://slack.com/api/users.list?token=%s' % SLACK_API_TOKEN).json()['members']
users = filter(lambda u: u['id'] in members, users_list)
for user in users:
first_name, last_name = '', ''
if user['real_name']:
first_name = user['real_name']
if ' ' in user['real_name']:
first_name, last_name = user['real_name'].split()
# print "%s,%s,%s" % (first_name, last_name, user['profile']['email'])
print "%s" % (user['profile']['email'])
I just made a small Ruby script, what retrieves all members from a slack channel and returns it in CSV format.
Script: https://github.com/olivernadj/toolbox/tree/master/slack-members
Example:
$ ./membersof.rb -t xoxp-123456789A-BCDEF01234-56789ABCDE-F012345678 -g QWERTYUIO
first_name,last_name,email
John,Doe,john.doe#example.com
Jane,Doe,jane.doe#example.com
Based on the answer by #Lam, I modified it to work with python3.
import requests
SLACK_API_TOKEN = "" # get one from https://api.slack.com/docs/oauth-test-tokens
CHANNEL_NAME = ""
# channel_list = requests.get('https://slack.com/api/channels.list?token=%s' % SLACK_API_TOKEN).json()['channels']
# channel = filter(lambda c: c['name'] == CHANNEL_NAME, channel_list)[0]
# channel_info = requests.get('https://slack.com/api/channels.info?token=%s&channel=%s' % (SLACK_API_TOKEN, channel['id'])).json()['channel']
# members = channel_info['members']
channel_list = requests.get('https://slack.com/api/groups.list?token=%s' % SLACK_API_TOKEN).json()['groups']
for c in channel_list:
if c['name'] == CHANNEL_NAME:
channel = c
channel_info = requests.get('https://slack.com/api/groups.info?token=%s&channel=%s' % (SLACK_API_TOKEN, channel['id'])).json()['group']
print(channel_info)
members = channel_info['members']
users_list = requests.get('https://slack.com/api/users.list?token=%s' % SLACK_API_TOKEN).json()['members']
for user in users_list:
if "email" in user['profile']:
print(user['profile']['email'])
Ruby solution using slack-ruby-client:
Scopes:
channels:read
users.profile:read
users:read.email
users:read
require 'slack-ruby-client'
Slack.configure do |config|
config.token = ENV['SLACK_TOKEN_IN_BASH_PROFILE']
end
client = Slack::Web::Client.new
CH = '#channel-name'
client.conversations_members(channel: CH).members.each do |user|
puts client.users_profile_get(user: user).profile.email
end
I'm not sure if these are all outdated but I couldn't get any of them to work. The best way I found to do it was to use the client.conversations_members method to find all user IDs and then get emails for those users.
import slack
def get_channel_emails(channel_id:str)-> list:
client = slack.WebClient(token=os.getenv("SLACK_TOKEN"))
result = client.conversations_members(channel= channel_id)
emails = []
for user in result['members']:
info = client.users_info(user = user).data
if 'email' in info['user']['profile'].keys():
emails.append(info['user']['profile']['email'])
return emails
Some notable roadblocks are:
The slack package is actually slackclient so use pip install slackclient instead
The channel_id is not the channel name but the code slack gives to the channel. It can be found in the web browser version path and is formatted CXXXXXXXXXX.
If without coding you require to get emails of all users from Slack channel:
Go to Channel settings, there is a option for "Copy member email address".
With Slack API:
conversations.list - Get the list of Channel Id (public or private)
conversations.members - Get the list of Member Id by Channel Id
users.info - Get the Email by Member Id
with python3 and package 'slackclient'
HERE
pip3 install slackclient
def get_channel_emails(channel_id: str):
slack_api_bot_token = 'YOUR_BOT_TOKEN'
## Require BOT permission ##
# channels:read
# groups:read
# im:read
# mpim:read
# users:read
client = slack.WebClient(token=slack_api_bot_token)
result = client.conversations_members(channel=channel_id)
i = 0
for user in result['members']:
#print(user)
info = client.users_info(user=user).data
i = i + 1
#print(info)
member_id = info['user']['id']
team_id = info['user']['team_id']
display_name = info['user']['name']
real_name = info['user']['real_name']
phone = info['user']['profile']['phone']
email = info['user']['profile']['email']
if not member_id:
member_id = 'null'
elif not team_id:
team_id = 'null'
elif not display_name:
display_name = 'null'
elif not real_name:
real_name = 'null'
elif not phone:
phone = 'null'
elif not email:
email = 'null'
print(f'{i},{real_name},{display_name},{team_id},{member_id},{email},{phone}')
def main():
#channel id: https://app.slack.com/huddle/TB37ZG064/CB3CF4A7B
#if end of URL string starts with "C", it means CHANNEL
get_channel_emails('CB3CF4A7B')

Capybara failing with ionic app

I'm doing integration tests with Capybara on a Ionic app that use rails in backend, and I'm having a problem after I signin successfully, the second visit does nothing and I have a timeout while waiting for angular.
# test_helper.rb
Dir[Rails.root.join("test/helpers/**/*.rb")].each { |f| require f }
require 'capybara/rails'
require 'capybara/poltergeist'
if ENV['VIEW_IN_BROWSER'] == "true"
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :firefox)
end
else
Capybara.javascript_driver = :poltergeist
end
Capybara.server_port = 3000 # serveur rails en mode test
Capybara.always_include_port = true
Capybara.default_max_wait_time = 5
Capybara.raise_server_errors = false
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
include Capybara::Angular::DSL
def setup
super
end
def teardown
super
Capybara.reset_sessions!
Capybara.use_default_driver
end
end
My helper :
#test/helpers/ionic_helper.rb
module IonicHelper
include Warden::Test::Helpers
Warden.test_mode!
def on_ionic_app
Capybara.app_host = 'http://localhost:5000' # Serveur ionic
begin
yield
rescue => error
puts error
ensure
Capybara.app_host = 'http://localhost:4321' # serveur ionic en mode intégration continue
end
end
def user_log_in
user = FactoryGirl.create(:user)
visit(Capybara.app_host+"/#/app/signin")
fill_in "email", with: user.email
fill_in "password", with: user.password
click_on "Connexion"
end
end
The first problem is that I have to specify Capybara.app_host to the visit mehod to hit the good ionic port (5000) I cannot figure why.
My second problem is is this test :
# reseau_test.rb
require "test_helper"
class ReseauTest < ActionDispatch::IntegrationTest
include IonicHelper
test "On s'assure que tous les elements en mode connecté soient présents" do
Capybara.current_driver = Capybara.javascript_driver
on_ionic_app do
user_log_in
visit(Capybara.app_host+"/#/app/network")
assert page.has_css?('span.count.following.text-center.ng-binding'), "Il doit y avoir un chiffre pour le nombre d'abonnements"
assert page.has_content?('Abonnements'), "Il doit y avoir le texte 'Abonnements'"
assert page.has_css?('span.count.follower.ng-binding'), "Il doit y avoir un chiffre pour le nombre d'abonnés"
assert page.has_content?('Abonnés'), "Il doit y avoir le texte 'Abonnés'"
end
end
end
If I remove user_log_in the tests work fine, but this page have to be seen with a logged user, and when I test it, it fails with timeout while waiting for angular. I can put the Capybara.default_max_wait_time to 30 it fails the same way.
First problem: The reason you're having issues with app_host is because you're specifying Capybara.always_include_port = true. What this does is force the port being visited to be set to the port Capybara is running a server on unless the address passed to visit has a non-default port specified. Since it doesn't look like you ever want visit to connect directly to the server being run by Capybara you should set remove it or set it to Capybara.always_include_port = false. With it false you can just set Capybara.app_host as needed and it should be used as the default start for visit
Your second issue is being caused by the JS capybara-angular is running in the page never showing the page as ready. Check for errors in your JS that could be preventing capybara-angular to have issues, or look at https://github.com/wrozka/capybara-angular/issues/20