Programacion Interactiva

Descubre una Nueva y Poderosa Herramienta.

FrameWork de Nueva Generacion

Acceso a tu Informacion desde cualquier Dispositivo con Navegador.

Enfoque en el Backend

Frontend de forma facil con Odoo y XML.

Creacion de Verticales

Creacion de nuevas Verticales Conquistando nuevos Mercados.

Tu marca aqui mismo

Llega a miles de personas.

Publicidad

miƩrcoles, 21 de octubre de 2015

Enviar Mensajes al Archivo Log de Odoo



Logging


    Muchas veces programamos en odoo y la mejor manera de hacer un debug es enviando prints con python y estos se muestran en la terminal, pero esta tĆ©cnica solo funciona cuando no utilizamos un archivo que guarde el log del Servidor.
    En caso necesario de que necesitemos estar analizando el comportamiento de alguna funciĆ³n en un Servidor de ProducciĆ³n, podemos hacer uso de la libreria loggin, la cual te permite enviar mensajes al logfile (Archivo Log).
1. Importando libreria logging
Esta libreria es propia de Python no de Odoo y funciona con cualquier aplicaciĆ³n hecha en ese mismo Lenguaje de ProgramaciĆ³n.
1. #Importamos la libreria logger
2. import logging
3. #Definimos la Variable Global
4. _logger = logging.getLogger(__name__)

2. Usamos la libreria loggin para enviar los mensajes.

Para la librerƭa loggin existen 5 mƩtodos de enviar los mensajes al log:
  • logger.debug: Utilizado para el modo debug.
  • logger.info: Este metodo es el mas utilizado, para enviar informaciĆ³n al log como si se tratara de un print.
  • logger.warning: Como su nombre lo indica para enviar un mensaje de Advertencia.
  • logger.error:  Utilizado en errores causados por configuraciĆ³nes, no poder actualizar algun registro, etc..
  • logger.critical: Este modo de mensaje es para alertar de un fallo total de la AplicaciĆ³n.
Ejemplos :
1. _logger.debug("Mensaje Debug")
2. _logger.info("Mensaje Informativo o Print")
3. _logger.warning("Mensaje de Advertencia")
4. _logger.error("Mensaje de Error, fallo menor.")
5. _logger.critical("Mensaje con un Error Fatal.")

Logging output terminal

viernes, 16 de octubre de 2015

Solucion a la Impresion sin Estilos de Reportes Qweb (WkhtmltoPdf, Css, Formato,etc..)

SoluciĆ³n a la ImpresiĆ³n de Reportes Qweb sin Estilos


    Hoy quiero hacer menciĆ³n a un error que nunca me habĆ­a sucedido y que me tenia frustrado pase varios dĆ­as investigando para encontrar la soluciĆ³n, el error sucedĆ­a en la impresiĆ³n de reportes hechos con Qweb estos se generaban sin formato y sin estilo, al principio como todo analista trate de identificar el Problema, primero probando la versiĆ³n de la librerĆ­a Wkhtmltopdf, esto sin tener ningĆŗn Ć©xito, segundo revisando y borrando archivos temporales, cache del servidor, etc. Buscando en foros, grupos y demĆ”s encontrĆ© parte de la soluciĆ³n y revisando el cĆ³digo del modulo report complemente la soluciĆ³n final.


La imagen anterior muestra la salida de mi reportes Qweb, como observamos no tiene Estilos.

La soluciĆ³n.

Existen 2 formas de solucionar este error:

1. Modificando el ParĆ”metro del Sistema llamado web.base.url  y verificar que en el valor no usemos un alias o una ip diferente a localhost.

En caso de que tengan un alias como la imagen anterior http://poncesoft.noip.com:9069 debemos cambiarla por http://localhost:9069.

2. La segunda forma de solucionar este error es aƱadiendo un nuevo parĆ”metro llamado report.url  y con el valor mencionado anteriormente http://localhost:9069.
Estos parĆ”metros indican al sistema la direcciĆ³n fĆ­sica para tomar los estilos del reporte.

Resultado Final:


Nota: Los parĆ”metros del Sistema estĆ”n ubicados en ConfiguraciĆ³n --> ParĆ”metros --> ParĆ”metros del Sistema.





miƩrcoles, 7 de octubre de 2015

Modificar Acciones para agregar o Reemplazar Atributos

Modificar Acciones en Odoo desde XML



    En odoo muchas veces necesitamos poner algĆŗn filtro nuevo creado por nosotros y usarlo por defecto en acciones creadas por algĆŗn otro modulo, esto es muy sencillo simplemente usamos el atributo ID como referencia,  este tipo de "herencia" se compone del nombre del modulo que contiene el registro, seguido de un punto y el ID de la acciĆ³n.

Ejemplo:

 <record id="stock.action_move_form2" model="ir.actions.act_window">
            <field name="context">{'search_default_consulta': 1}</field>
</record>



lunes, 5 de octubre de 2015

Imprimir 0.0 cuando el valor es Nulo en Jasper Reports

Print 0.0 when null in Jasper Reports



    Al crear reportes con Jasper Reports un problema muy frecuente era poner el valor 0.0 para campos float, despuĆ©s de buscar y probar las soluciones ofrecidas en foros, en la documentaciĆ³n de Jasper Reports, nunca encontrĆ© una soluciĆ³n real. Pensando y probando con las caracterĆ­sticas que ofrece iReport encontrĆ© una soluciĆ³n muy sencilla, los pasos son muy simples y los describo a continuaciĆ³n:

1. Primero debemos dejar los campos Double o Float de tipo String, no cambiarlo al tipo de dato correcto.

2. AƱadimos el campo al reporte y modificamos el campo Text Field Expression, para convertir el campo a Double de forma manual y en caso de que sea null, retornar null sin ningĆŗn error.

( $F{Field-field0}.isEmpty() ? null : Double.parseDouble($F{Field-field0}) )


Modificamos el campo Expression Class para retornar el tipo de dato correcto:

java.lang.Double

Nota: La conversiĆ³n a Double te permitirĆ” usar la propiedad Pattern y dar formato al campo Double (Currency, # Decimals, etc.)

3. Al campo anterior activar el Campo Blank when null, para que no ponga nigĆŗn texto null en nuestro PDF.


4. AƱadir al reporte un elemento Static Text Field y poner el valor que deseamos que ponga cuando el campo sea 0.0 o null, en mi caso quiero que ponga $ 0.0


5. Para el Texto anterior activaremos el campo Print When Expression, aƱadiendo la expresiĆ³n:

$F{Field-field0}.isEmpty()


Esto harĆ” que cuando el campo sea nulo escriba nuestro Texto y en caso contrario el valor correcto del Campo.

6. Lo Ćŗnico que haremos es encimar los 2 campos, uno encima del otro, asĆ­  el Reporteador pondra un valor u otro cuando tengamos un valor null.


Espero que esta informaciĆ³n los ayude tanto como a mi.


sƔbado, 3 de octubre de 2015

Archivo Configuracion Odoo

odoo.conf for Odoo explained


In one of my previous posts Install OpenERP 7.0 from trunk I’ve written how to start your server with a start scrip just changing the ports and all other default settings. You can also start your server with a specified config file with -c command.
./server/openerp-server -c /path/to/openerp-server.conf
Here is the config file spitted  into parts for easy understanding.

Server startup config – Common options

# Admin password for creating, restoring and backing up databases
admin_passwd = admin

# default CSV separator for import and export
csv_internal_sep = ,

# to compress reports
reportgz = False

# disable loading demo data for modules to be installed (comma-separated, use "all" for all modules)
without_demo = False

# Use this for big data importation, if it crashes you will be able to continue at the current state. Provide a filename to store intermediate importation states.
import_partial = 

# file where the server pid will be stored
pidfile = None

# specify additional addons paths (separated by commas)
addons_path = /full/path/to/addons

# Comma-separated list of server-wide modules default=web
server_wide_modules = None

XML-RPC / HTTP – XML-RPC Configuration

# disable the XML-RPC protocol
xmlrpc = True

# Specify the TCP IP address for the XML-RPC protocol. The empty string binds to all interfaces.
xmlrpc_interface = 

# specify the TCP port for the XML-RPC protocol
xmlrpc_port = 8069

# Enable correct behavior when behind a reverse proxy
proxy_mode = False

XML-RPC / HTTPS – XML-RPC Secure Configuration

# disable the XML-RPC Secure protocol
xmlrpcs = True

# Specify the TCP IP address for the XML-RPC Secure protocol. The empty string binds to all interfaces.
xmlrpcs_interface = 

# specify the TCP port for the XML-RPC Secure protocol
xmlrpcs_port = 8071

# specify the certificate file for the SSL connection
secure_cert_file = server.cert

# specify the private key file for the SSL connection
secure_pkey_file = server.pkey

NET-RPC – NET-RPC Configuration

# enable the NETRPC protocol
netrpc = False

# specify the TCP IP address for the NETRPC protocol
netrpc_interface = 

# specify the TCP port for the NETRPC protocol
netrpc_port = 8070

WEB – Web interface Configuration

# Filter listed database REGEXP
dbfilter = .*

Static HTTP – Static HTTP service

# enable static HTTP service for serving plain HTML files
static_http_enable = False 

# specify the directory containing your static HTML files (e.g '/var/www/')
static_http_document_root = None

# specify the URL root prefix where you want web browsers to access your static HTML files (e.g '/')
static_http_url_prefix = None

Testing Group – Testing Configuration

# Launch a YML test file.
test_file = False

# If set, will save sample of all reports in this directory.
test_report_directory = False

# Enable YAML and unit tests.
test_enable = False

# Commit database changes performed by YAML or XML tests.
test_commit = False

Logging Group – Logging Configuration

# file where the server log will be stored
logfile = None

# do not rotate the logfile
logrotate = True

# Send the log to the syslog server
syslog = False

# setup a handler at LEVEL for a given PREFIX. An empty PREFIX indicates the root logger. This option can be repeated. Example: "openerp.orm:DEBUG" or "werkzeug:CRITICAL" (default: ":INFO")
log_handler = [':INFO']

# specify the level of the logging. Accepted values: info, debug_rpc, warn, test, critical, debug_sql, error, debug, debug_rpc_answer, notset
log_level = info

SMTP Group – SMTP Configuration

# specify the SMTP email address for sending email
email_from = False 

# specify the SMTP server for sending email
smtp_server = localhost 

# specify the SMTP port
smtp_port = 25 

# specify the SMTP server support SSL or not
smtp_ssl = False 

# specify the SMTP username for sending email
smtp_user = False

# specify the SMTP password for sending email
smtp_password = False

Database related options

# specify the database name
db_name = False

# specify the database user name
db_user = openerp

# specify the database password
db_password = False

# specify the pg executable path
pg_path = None

# specify the database host
db_host = False

# specify the database port
db_port = False

# specify the the maximum number of physical connections to posgresql
db_maxconn = 64

# specify a custom database template to create a new database
db_template = template1

Internationalisation options

translate_modules = ['all']

Security-related options

# disable the ability to return the list of databases
list_db = True

Advanced options – Advanced options

# enable debug mode
debug_mode = False

# specify reference timezone for the server (e.g. Europe/Brussels")
timezone = False

# Force a limit on the maximum number of records kept in the virtual osv_memory tables. The default is False, which means no count-based limit. 
osv_memory_count_limit = False 

# Force a limit on the maximum age of records kept in the virtual osv_memory tables. This is a decimal value expressed in hours, and the default is 1 hour.
osv_memory_age_limit = 1.0 

# Maximum number of threads processing concurrently cron jobs (default 2)
max_cron_threads = 2

# Use the unaccent function provided by the database when available.
unaccent = False

Multiprocessing options

# Specify the number of workers, 0 disable prefork mode.
workers = 0

# Maximum allowed virtual memory per worker, when reached the worker be reset after the current request (default 671088640 aka 640MB)
limit_memory_soft = 671088640

# Maximum allowed virtual memory per worker, when reached, any memory allocation will fail (default 805306368 aka 768MB)
limit_memory_hard = 805306368

# Maximum allowed CPU time per request (default 60)
limit_time_cpu = 60

# Maximum allowed Real time per request (default 120)
limit_time_real = 120

# Maximum number of request to be processed per worker (default 8192)
limit_request = 8192
There are few more options that you can find in this file
vi server/openerp/tools/config.py
You can download the config file with all comments from here
Information by : Nikola Stojanoski

viernes, 2 de octubre de 2015

Campos Seleccion Calculados en Odoo

Crear un Campo Calculado de Tipo Seleccion



Si trabajamos con campos calculados en Odoo y nos hemos enfrentado a obtener un valor de un campo SelecciĆ³n o RelaciĆ³n, observamos que en la nueva tabla el resultado es correcto obtenemos el resultado pero no tenemos la etiqueta correcta. Esto se soluciona haciendo uso del atributo "selection".

Ejemplo:
def _get_states(self, cr, uid, ids, fieldnames, args, context=None):
    res = {}
    state = 'draft'
    #### Aqui meteriamos el codigo para obtener el Estado del registro que necesitaramos #####
    return res[ids[0]] = state

lista_estados = [
                ('draft','Borrador')
                ('done','Realizado')
                ]

'state': fields.function(_get_states, type='selection',method=True,  selection=lista_estados, string="Estado"),


La misma regla aplica para los campos Relacion (Related):

lista_estados = [
                ('draft','Borrador')
                ('confirmed','Confirmado')
                ('done','Realizado')
                ('cancel','Cancelado')
                ]

'state': fields.related('invoice_id','state', type='selection',method=True,  selection=lista_estados, string="Estado"),