0
votes

I have a problem when I try to modify informations for a res.partner but only in this file, in my other modules .write is working...

I know it's going into the write and that it brings the informations but it just doesn't save.

Also it was working before but for no obvious reason it's no more working.

Anyone have an idea of what could possibly cause that?

# -*- coding: utf-8 -*-
from openerp import models, fields, api, tools, exceptions
from openerp.exceptions import Warning
import json, urllib, time


class MAJClientsWizard(models.Model):
    _name = "maj.clients"

    @api.one
    def maj_clients(self):
        erreur = ""
        clients = self.env["res.partner"].search([['is_company', '=', True], ['customer', '=', True]])
        for client in clients:
            retour = maj_coordonnees(client)
            if retour:
                erreur += retour + ", "
        if erreur:
            raise Warning("Les détaillants qui ont une erreur dans leur code postal sont: ", erreur, "Tous les autres ont été mis à jour!")
        else:
            raise Warning("Tous les détaillants ont été mis à jour avec succès!")


def maj_coordonnees(client):
    if client.date_localization < time.strftime("%Y-%m-%d"):
        if client.zip:
            result = geo_find(client.zip)

            if result:
                client.write({
                    'partner_latitude': result[0],
                    'partner_longitude': result[1],
                    'date_localization': (time.strftime("%Y-%m-%d"))
               })
            else:
                return client.name
        else:
            return client.name


def geo_find(addr):
    url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&key=*****&address='
    url += urllib.quote(addr.encode('utf8'))

    try:
        result = json.load(urllib.urlopen(url))
    except Exception, e:
        return 'Network error, Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).' + e
    if result['status'] != 'OK':
        return None

    try:
        geo = result['results'][0]['geometry']['location']
        return float(geo['lat']), float(geo['lng'])
    except (KeyError, ValueError):
        return None
1

1 Answers

0
votes

Obviously it would not work. In a nutshell reason is that you're raising error from the function and this makes Odoo think that things go wrong in your function and the actual write to database does not happen (what happens instead is a rollback). To make sure that data gets written to the database, you should call commit() function explicitly before raising an error, like so:

class MAJClientsWizard(models.Model):
    _name = "maj.clients"

    @api.one
    def maj_clients(self):
        erreur = ""
        clients = self.env["res.partner"].search([['is_company', '=', True], ['customer', '=', True]])
        for client in clients:
            retour = maj_coordonnees(client)
            if retour:
                erreur += retour + ", "

        self.env.cr.commit() #NOTE: commit changes to database before raising an error in order to prevent rollback

        if erreur:
            raise Warning("Les détaillants qui ont une erreur dans leur code postal sont: ", erreur, "Tous les autres ont été mis à jour!")
        else:
            raise Warning("Tous les détaillants ont été mis à jour avec succès!")

P.S.
Although it's not related to the issue reported, I would note that in general @api.multi should be used instead of @api.one for performance reasons.