class RetailMachine(geo_model.GeoModel): """GEO OSV SAMPLE""" _name = "geoengine.demo.automatic.retailing.machine" the_point = geo_fields.GeoPoint('Coordinate') the_line = geo_fields.GeoLine('Power supply line', index=True) total_sales = fields.Float('Total sale', index=True) money_level = fields.Char('Money level', size=32, index=True) state = fields.Selection([('hs', 'HS'), ('ok', 'OK')], 'State', index=True) name = fields.Char('Serial number', size=64, required=True) zip_id = fields.Many2one('dummy.zip') @api.onchange('the_point') def onchange_geo_point(self): """ Exemple of on change on the point Lookup in zips if the code is within an area. Change the zip_id field accordingly """ if self.the_point: x, y = geojson.loads(self.the_point).coordinates point = "POINT({} {})".format(x, y) zip_match = self.env['dummy.zip'].geo_search(geo_domain=[ ('the_geom', 'geo_contains', point) ], limit=1) if zip_match: self.zip_id = zip_match[0]
class ProjectProject(geo_model.GeoModel): """Add geo_point to project.project""" _inherit = 'project.project' geo_point = fields.GeoPoint('Addresses coordinate', related='partner_id.geo_point')
class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function field""" _inherit = "res.partner" @api.one def geocode_address(self): """Get the latitude and longitude by requesting "mapquestapi" see http://open.mapquestapi.com/geocoding/ """ url = 'http://nominatim.openstreetmap.org/search' pay_load = { 'limit': 1, 'format': 'json', 'street': self.street or '', 'postalCode': self.zip or '', 'city': self.city or '', 'state': self.state_id and self.state_id.name or '', 'country': self.country_id and self.country_id.name or '', 'countryCodes': self.country_id and self.country_id.code or ''} request_result = requests.get(url, params=pay_load) try: request_result.raise_for_status() except Exception as e: _logger.exception('Geocoding error') raise exceptions.Warning(_( 'Geocoding error. \n %s') % e.message) vals = request_result.json() vals = vals and vals[0] or {} self.write({ 'partner_latitude': vals.get('lat'), 'partner_longitude': vals.get('lon'), 'date_localization': fields.Date.today()}) @api.one def geo_localize(self): self.geocode_address() return True @api.one @api.depends('partner_latitude', 'partner_longitude') def _get_geo_point(self): """ Set the `geo_point` of the partner depending of its `partner_latitude` and its `partner_longitude` **Notes** If one of those parameters is not set then reset the partner's geo_point and do not recompute it """ if not self.partner_latitude or not self.partner_longitude: self.geo_point = False else: self.geo_point = geo_fields.GeoPoint.from_latlon( self.env.cr, self.partner_latitude, self.partner_longitude) geo_point = geo_fields.GeoPoint( readonly=True, store=True, compute='_get_geo_point')
class RetailMachine(geo_model.GeoModel): """GEO OSV SAMPLE""" _name = "geoengine.demo.automatic.retailing.machine" the_point = geo_fields.GeoPoint('Coordinate') the_line = geo_fields.GeoLine('Power supply line', index=True) total_sales = fields.Float('Total sale', index=True) money_level = fields.Char('Money level', size=32, index=True) state = fields.Selection([('hs', 'HS'), ('ok', 'OK')], 'State', index=True) name = fields.Char('Serial number', size=64, required=True)
class isp(geo_model.GeoModel): """WRITE A DOCSTRING.""" _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = "ISP Conexion Point" _name = "isp" name = fields.Char(string="Name", required=True) point = geo_fields.GeoPoint('Coordinate') # default="POINT(-6082100.6566597 -2937391.931423402)" line = geo_fields.GeoLine(string='Line') type = fields.Selection([('client', 'Client'), ('wireless', 'Wireless'), ('fiber_box', 'Fiber Box'), ('fiber', 'Fiber')], string="Type", default="client") contract_id = fields.Many2one('account.analytic.account', string="Contract") devices_ids = fields.One2many('isp.device', 'place_id', string="Devices in this place")
class Dustbin(geo_model.GeoModel): _name = "dustbin.dustbin" the_point = geo_fields.GeoPoint('Coordinate') long = fields.Float("Longitude", digits=(16, 6)) lat = fields.Float("Latitude", digits=(16, 6)) name = fields.Char('Dustbin Name', size=64, required=True) code = fields.Many2one('dustbin.code', 'Dustbin Code', required=True) type = fields.Selection([('view', 'View'), ('normal', 'Normal')], 'Type', default='normal', readonly=True) state = fields.Selection([('empty', 'Empty'), ('full', 'Full')], 'Status', index=True, required=True) thepoi = fields.Char(compute='_compute_char') @api.depends('long', 'lat') def _compute_geo(self): latitude = self.lat and float(self.lat) longitude = self.long and float(self.long) self.the_point = geo_fields.GeoPoint.from_latlon( self.env.cr, latitude, longitude) @api.depends('the_point') def _compute_char(self): self.thepoi = str(self.the_point) ''' if self.lat and self.long: self.lat = self.lat and float(self.lat) self.lon = self.long and float(self.long) #(field.GeoPoint.from_latlon(self.env.cr, self.lat, self.long)) ''' _sql_constraints = [ ('code_unique', 'UNIQUE(code)', "The Dustbin Code must be unique"), ('name_unique', 'UNIQUE(name)', "The Dustbin Name must be unique"), ]
class ResPartner(geo_model.GeoModel): """Auto geo coding of addresses""" _inherit = "res.partner" geo_point = fields.GeoPoint('Addresses coordinate', readonly=True) addr_accuracy = fields2.Char('Address Accuracy', readonly=True) def _can_geocode(self): usr = self.env['res.users'] return usr.browse(self.env.uid).company_id.enable_geocoding def _get_point_from_reply(self, answer): """Parse geoname answer code inspired by geopy library""" def get_first_text(node, tag_names, strip=None): """Get the text value of the first child of ``node`` with tag ``tag_name``. The text is stripped using the value of ``strip``.""" if isinstance(tag_names, basestring): tag_names = [tag_names] if node: while tag_names: nodes = node.getElementsByTagName(tag_names.pop(0)) if nodes: child = nodes[0].firstChild return child and child.nodeValue.strip(strip) def parse_code(code): latitude = get_first_text(code, 'lat') or None longitude = get_first_text(code, 'lng') or None latitude = latitude and float(latitude) longitude = longitude and float(longitude) accuracy = get_first_text(code, 'location_type') or 'PRECISE' return latitude, longitude, accuracy res = answer.read() if not isinstance(res, basestring): return False doc = xml.dom.minidom.parseString(res) codes = doc.getElementsByTagName('result') if len(codes) < 1: logger.warn("Geonaming failed: %s", res) return False for code in codes: address = get_first_text(code, 'formatted_address') if self.country_id.name in address: latitude, longitude, accuracy = parse_code(code) else: latitude = False longitude = False if not latitude or not longitude: latitude, longitude, accuracy = parse_code(codes[0]) if accuracy != 'APPROXIMATE': accuracy = 'PRECISE' self.addr_accuracy = accuracy return fields.GeoPoint.from_latlon(self.env.cr, latitude, longitude) @api.multi def geocode_from_geonames(self, strict=True, context=None): base_url = u'https://maps.googleapis.com/maps/api/geocode/xml?address=' API_KEY = self.env['ir.config_parameter'].get_param('google.maps.api') for partner in self: logger.info('geolocalizing %s', partner.name) address = '' if partner.street: address += unidecode.unidecode(partner.street) elif partner.parent_id and partner.parent_id.street: address += unidecode.unidecode(partner.parent_id.street) if partner.city: address += '+' + unidecode.unidecode(partner.city) elif partner.parent_id and partner.parent_id.city: address += unidecode.unidecode(partner.parent_id.city) if partner.country_id.name: address += '+' + unidecode.unidecode(partner.country_id.name) elif partner.parent_id and partner.parent_id.country_id.name: address += '+' + unidecode.unidecode( partner.parent_id.country_id.name) address = address.replace(' ', '+') # address = unidecode.unidecode(address) url = base_url + address + '&key=' + API_KEY try: answer = urlopen(url) partner.geo_point = self._get_point_from_reply(answer) except: logger.info('error - %s ', partner.name) logger.info('%s - %s, %s', partner.name, partner.street, partner.city) @api.multi def geocode_partner(self): # TODO: se podría llamar a la función de arriba ya que hace lo mismo base_url = u'https://maps.googleapis.com/maps/api/geocode/xml?address=' API_KEY = self.env['ir.config_parameter'].get_param('google.maps.api') for partner in self: logger.info('geolocalizing %s', partner.name) address = '' if partner.street: address += unidecode.unidecode(partner.street) elif partner.parent_id and partner.parent_id.street: address += unidecode.unidecode(partner.parent_id.street) if partner.city: address += '+' + unidecode.unidecode(partner.city) elif partner.parent_id and partner.parent_id.city: address += unidecode.unidecode(partner.parent_id.city) if partner.country_id.name: address += '+' + unidecode.unidecode(partner.country_id.name) elif partner.parent_id and partner.parent_id.country_id.name: address += '+' + unidecode.unidecode( partner.parent_id.country_id.name) address = address.replace(' ', '+') # address = unidecode.unidecode(address) url = base_url + address + '&key=' + API_KEY try: answer = urlopen(url) partner.geo_point = self._get_point_from_reply(answer) except: logger.info('error - %s ', partner.name) logger.info('%s - %s, %s', partner.name, partner.street, partner.city) @api.multi def write(self, vals): res = super(ResPartner, self).write(vals) do_geocode = self._can_geocode() if do_geocode and \ set(('country_id', 'city', 'zip')).intersection(vals): self.geocode_from_geonames() return res @api.model @api.returns('self', lambda value: value.id) def create(self, vals): res = super(ResPartner, self).create(vals) do_geocode = self._can_geocode() if do_geocode: res.geocode_from_geonames() return res
def geocode_address(self): self.write({ 'task_latitude': self.task_latitude, 'task_longitude': self.task_longitude, }) @api.one def geo_localize(self): self.geocode_address() return True @api.one @api.depends('task_latitude', 'task_longitude') def _get_geo_point(self): if not self.task_latitude or not self.task_longitude: self.geo_point = False else: try: self.geo_point = fields.GeoPoint.from_latlon( self.env.cr, self.task_latitude, self.task_longitude) except Exception, e: raise osv.except_osv( ('Alert!'), ('Invalid Latitude or Longitude. \n%s' % (e))) geo_point = fields.GeoPoint(string='Addresses Coordinate', readonly=True, store=True, compute='_get_geo_point') task_latitude = oe_fields.Float(string='Latitude', digits=(16, 5)) task_longitude = oe_fields.Float(string='Longitude', digits=(16, 5))
class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _inherit = "res.partner" geo_point = fields.GeoPoint("Address coordinates")
class TmsPlace(geo_model.GeoModel): _name = 'tms.place' _description = 'Cities / Places' name = fields.Char('Place', size=64, required=True, select=True) complete_name = fields.Char(compute='_compute_complete_name') state_id = fields.Many2one('res.country.state', string='State Name') country_id = fields.Many2one('res.country', related='state_id.country_id', string='Country') latitude = fields.Float('Latitude', required=False, digits=(20, 10), help='GPS Latitude') longitude = fields.Float('Longitude', required=False, digits=(20, 10), help='GPS Longitude') point = geo_fields.GeoPoint(string='Coordinate', store=True, compute='_compute_point') @api.multi def get_coordinates(self): for rec in self: address = (rec.name + "," + rec.state_id.name + "," + rec.country_id.name) google_url = ('http://maps.googleapis.com/maps/api/geocode/json?' + 'address=' + address.encode('utf-8') + '&sensor=false') try: result = json.load(my_urllib.urlopen(google_url)) if result['status'] == 'OK': location = result['results'][0]['geometry']['location'] self.latitude = location['lat'] self.longitude = location['lng'] except: raise UserError(_("Google Maps is not available.")) @api.multi def open_in_google(self): for place in self: url = ("/tms/static/src/googlemaps/get_place_from_coords.html?" + str(place.latitude) + ',' + str(place.longitude)) return { 'type': 'ir.actions.act_url', 'url': url, 'nodestroy': True, 'target': 'new' } @api.depends('name', 'state_id') def _compute_complete_name(self): for rec in self: if rec.state_id: rec.complete_name = rec.name + ', ' + rec.state_id.name else: rec.complete_name = rec.name @api.depends('latitude', 'longitude') def _compute_point(self): for rec in self: rec.point = geo_fields.GeoPoint.from_latlon( self.env.cr, rec.latitude, rec.longitude)
class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _inherit = "res.partner" geo_point = fields.GeoPoint('Addresses coordinate') addr_accuracy = fields2.Char('Address Accuracy', readonly=True)
class hr_employee(geo_model.GeoModel, osv.osv): _inherit = "hr.employee" @api.one def geocode_address(self): """Get the latitude and longitude by requesting "mapquestapi" see http://open.mapquestapi.com/geocoding/ """ url = 'http://nominatim.openstreetmap.org/search' pay_load = { 'limit': 1, 'format': 'json', 'postalCode': self.zip or '', 'city': self.city or '', 'country': self.country and self.country.name or '', 'countryCodes': self.country and self.country.code or '' } request_result = requests.get(url, params=pay_load) try: request_result.raise_for_status() except Exception as e: _logger.exception('Geocoding error') raise exceptions.Warning(_('Geocoding error. \n %s') % e.message) vals = request_result.json() vals = vals and vals[0] or {} self.write({ 'employee_latitude': vals.get('lat'), 'employee_longitude': vals.get('lon'), }) @api.one def geo_localize(self): self.geocode_address() return True @api.one @api.depends('employee_latitude', 'employee_longitude') def _get_geo_point(self): if not self.employee_latitude or not self.employee_longitude: self.geo_point = False else: self.geo_point = fields.GeoPoint.from_latlon( self.env.cr, self.employee_latitude, self.employee_longitude) geo_point = fields.GeoPoint(string='Addresses Coordinate', readonly=True, store=True, compute='_get_geo_point') city = oe_fields.Char(related='address_home_id.city', string='City', store=True) zip = oe_fields.Char(related='address_home_id.zip', string='Zip', store=True) country = oe_fields.Many2one('res.country', string='Country', related='address_home_id.country_id', store=True) employee_latitude = oe_fields.Float( related='address_home_id.partner_latitude', string='Latitude', store=True) employee_longitude = oe_fields.Float( related='address_home_id.partner_longitude', string='Longitude', store=True)
class SaleOrder(geo_model.GeoModel): """Add geo_point to sale.order""" _inherit = "sale.order" geo_point = fields.GeoPoint( 'Addresses coordinate', related='partner_invoice_id.geo_point')
class product_template(osv.osv, geo_model.GeoModel): _inherit = "product.template" @api.one def geocode_address(self): """Get the latitude and longitude by requesting "mapquestapi" see http://open.mapquestapi.com/geocoding/ """ url = 'http://nominatim.openstreetmap.org/search' pay_load = { 'limit': 1, 'format': 'json', 'postalCode': self.zip or '', 'city': self.city or '', 'country': self.country and self.country.name or '', 'countryCodes': self.country and self.country.code or '' } request_result = requests.get(url, params=pay_load) try: request_result.raise_for_status() except Exception as e: _logger.exception('Geocoding error') raise exceptions.Warning(_('Geocoding error. \n %s') % e.message) vals = request_result.json() vals = vals and vals[0] or {} self.write({ 'product_latitude': vals.get('lat'), 'product_longitude': vals.get('lon'), }) @api.one def geo_localize(self): self.geocode_address() return True @api.one @api.depends('product_latitude', 'product_longitude') def _get_geo_point(self): if not self.product_latitude or not self.product_longitude: self.geo_point = False else: self.geo_point = fields.GeoPoint.from_latlon( self.env.cr, self.product_latitude, self.product_longitude) @api.multi def onchange_state(self, state_id): if state_id: state = self.env['res.country.state'].browse(state_id) return {'value': {'country_id': state.country_id.id}} return {} geo_point = fields.GeoPoint(string='Addresses Coordinate', readonly=True, store=True, compute='_get_geo_point') street = oe_fields.Char(string='Street') street2 = oe_fields.Char(string='Street2') city = oe_fields.Char(string='City') zip = oe_fields.Char(string='Zip') state = oe_fields.Many2one('res.country.state', string='State') country = oe_fields.Many2one('res.country', string='Country') product_latitude = oe_fields.Float(string='Latitude', digits=(16, 5)) product_longitude = oe_fields.Float(string='Longitude', digits=(16, 5)) date_localization = oe_fields.Date(string='Geo Localization Date') is_property = oe_fields.Boolean(string='Is Property?') def geo_localize(self, cr, uid, ids, context=None): for product in self.browse(cr, uid, ids): if not product: continue result = geo_find( geo_query_address(street=product.street, zip=product.zip, city=product.city, state=product.state.name, country=product.country.name)) if result: self.write(cr, uid, [product.id], { 'product_latitude': result[0], 'product_longitude': result[1], 'date_localization': osv_fields.date.context_today( self, cr, uid, context=context) }, context=context) return True
class ResPartner(geo_model.GeoModel): """Auto geo coding of addresses""" _inherit = "res.partner" geo_point = fields.GeoPoint( 'Addresses coordinate', readonly=True) def _can_geocode(self): usr = self.env['res.users'] return usr.browse(self.env.uid).company_id.enable_geocoding def _get_point_from_reply(self, answer): """Parse geoname answer code inspired by geopy library""" def get_first_text(node, tag_names, strip=None): """Get the text value of the first child of ``node`` with tag ``tag_name``. The text is stripped using the value of ``strip``.""" if isinstance(tag_names, basestring): tag_names = [tag_names] if node: while tag_names: nodes = node.getElementsByTagName(tag_names.pop(0)) if nodes: child = nodes[0].firstChild return child and child.nodeValue.strip(strip) def parse_code(code): latitude = get_first_text(code, 'lat') or None longitude = get_first_text(code, 'lng') or None latitude = latitude and float(latitude) longitude = longitude and float(longitude) return latitude, longitude res = answer.read() if not isinstance(res, basestring): return False doc = xml.dom.minidom.parseString(res) codes = doc.getElementsByTagName('code') if len(codes) < 1: logger.warn("Geonaming failed: %s", res) return False latitude, longitude = parse_code(codes[0]) return fields.GeoPoint.from_latlon(self.env.cr, latitude, longitude) @api.multi def geocode_from_geonames(self, srid='900913', strict=True, context=None): context = context or {} base_url = u'http://ws.geonames.org/postalCodeSearch?' config_parameter_obj = self.env['ir.config_parameter'] username = config_parameter_obj.get_param( 'geoengine_geonames_username') if not username: raise ValidationError( _('A username is required to access ' 'http://ws.geonames.org/ \n' 'Please provides a valid one by setting a ' 'value in System Paramter for the key ' '"geoengine_geonames_username"')) filters = {} for add in self: logger.info('geolocalize %s', add.name) country_code = add.country_id.code or \ self.env.user.company_id.country_id.code if country_code and (add.city or add.zip): filters[u'country'] = country_code.encode('utf-8') filters[u'username'] = username.encode('utf-8') if add.city: filters[u'placename'] = add.city.encode('utf-8') if add.zip: filters[u'postalcode'] = add.zip.encode('utf-8') filters[u'maxRows'] = u'1' try: url = base_url + urlencode(filters) answer = urlopen(url) add.geo_point = self._get_point_from_reply(answer) except Exception, exc: logger.exception('error while updating geocodes') if strict: raise except_orm(_('Geoencoding fails'), str(exc))
class Parking(geo_model.GeoModel): _name = 'parking.parking' name = fields.Char('Name') parking_number = fields.Integer('Parking number', unique=True, required=True) parking_type = fields.Selection([ ('STANDARD', 'STANDARD'), ('PREFERENCE', 'PREFERENCE'), ('VIP', 'VIP'), ], 'Parking type', required=True, default='STANDARD') zone_id = fields.Many2one('parking.zone', string="Zone", ondelete='restrict', required=True) street_id = fields.Many2one('parking.street', string="Street", ondelete='restrict', required=True) next_street_id = fields.Many2one('parking.street', string="Next street", ondelete='restrict', required=True) previous_street_id = fields.Many2one('parking.street', string="Previous street", ondelete='restrict', required=True) latitude = fields.Float('Latitude') longitude = fields.Float('Longitude') free_at = fields.Datetime('Free at') description = fields.Char('Description') active = fields.Boolean('Active', required=True, default=True) status = fields.Char('Status', compute='_get_status') last_ticket_start_time = fields.Float( 'Start time', compute='_get_last_ticket_start_time', store=True) last_ticket_end_time = fields.Float('End time', compute='_get_last_ticket_end_time', store=True) today_tickets_count = fields.Integer('Today tickets count', compute='_get_today_tickets_count') last_ticket_amount = fields.Float('Last ticket amount', digits=(8, 2), compute='_get_last_ticket_amount') last_ticket_date = fields.Datetime('Last ticket date', compute='_get_last_ticket_date') today_tickets_amount = fields.Float('Today tickets amount', digits=(8, 2), compute='_get_today_tickets_amount') coordinate = geo_fields.GeoPoint('Coordinate') @api.one def _get_status(self): dt_now = datetime.utcnow() - timedelta(hours=4) self.status = 'Liberado' if self.free_at and dt_now < datetime.strptime(self.free_at, "%Y-%m-%d %H:%M:%S"): self.status = 'Ocupado' # if not self.free_at or dt_now >= datetime.strptime(self.free_at, "%Y-%m-%d %H:%M:%S"): # self.status = 'Liberado' # elif dt_now >= datetime.strptime(self.free_at, "%Y-%m-%d %H:%M:%S"): # self.status = 'Liberado' # else: # self.status = 'Ocupado' @api.one def _get_last_ticket_start_time(self): if self.status == 'Ocupado': last_ticket = self.env['parking.ticket'].search( [('parking_id', '=', self.id)], order="id desc", limit=1) if len(last_ticket) > 0: str_time = last_ticket[0].start_time[11:16].split(":") self.last_ticket_start_time = float( str_time[0]) + float(str_time[1]) / 60 # start_dt = datetime.strptime(last_ticket[0].start_time, "%Y-%m-%d %H:%M:%S") # self.last_ticket_start_time = datetime.strftime(start_dt, "%H:%M") @api.one def _get_last_ticket_end_time(self): if self.status == 'Ocupado': last_ticket = self.env['parking.ticket'].search( [('parking_id', '=', self.id)], order="id desc", limit=1) if len(last_ticket) > 0: str_time = last_ticket[0].end_time[11:16].split(":") self.last_ticket_end_time = float( str_time[0]) + float(str_time[1]) / 60 # end_dt = datetime.strptime(last_ticket[0].end_time, "%Y-%m-%d %H:%M:%S") # self.last_ticket_end_time = datetime.strftime(end_dt, "%H:%M") @api.one def _get_today_tickets_count(self): today = date.today().strftime(DF) self.today_tickets_count = self.env['parking.ticket'] \ .search_count([('parking_id', '=', self.id), ('create_date', '>=', today)]) @api.one def _get_last_ticket_amount(self): last_ticket = self.env['parking.ticket'].search( [('parking_id', '=', self.id)], order="id desc", limit=1) if len(last_ticket) > 0: self.last_ticket_amount = last_ticket[0].price_hour_id.price @api.one def _get_last_ticket_date(self): last_ticket = self.env['parking.ticket'].search( [('parking_id', '=', self.id)], order="id desc", limit=1) if len(last_ticket) > 0: self.last_ticket_date = last_ticket[0].start_time @api.one def _get_today_tickets_amount(self): today = date.today().strftime(DF) today_tickets = self.env['parking.ticket']\ .search([('parking_id', '=', self.id), ('create_date', '>=', today)]) for ticket in today_tickets: self.today_tickets_amount += ticket.price_hour_id.price @api.onchange('coordinate') def get_latitude(self): if self.coordinate: x, y = geojson.loads(self.coordinate).coordinates self.latitude = x self.longitude = y @api.onchange('street_id', 'parking_number') def _get_name(self): if self.street_id: self.name = self.street_id.code + str(self.parking_number).zfill(3) _sql_constraints = [ ('number_parking_uniq', 'unique(street_id, parking_number)', 'The number of the parking must be unique per street!'), ]
class mail_message(geo_model.GeoModel): _inherit = "mail.message" """ Inherit Mail Meassage from Geo model to generate Map view """ msg_id = fields.Integer() vehicle = fields.Char("Vehicle") device = fields.Char("Device") send_time = fields.Datetime("Send Time") received_time = fields.Datetime("Received Time") content = fields.Char("Content") image_data = fields.Binary("Image") latitude = fields.Integer("Latitude", size=11) longitude = fields.Integer("Longitude") timesheet_created = fields.Boolean("") the_point = geo_fields.GeoPoint('Coordinate') @api.model def automated_message_method(self): """ Automation Action method which fetch messages from Android My sQL database which is configure in settings""" config = self.env['base.config.settings'].search([], limit=1) try: if config.android_db_conf: db = MySQLdb.connect(host=config.host, port=config.port, user=config.user, passwd=config.password or '', db=config.db) cur = db.cursor() cur.execute("""SELECT * FROM message;""") for d in cur: res_id = False body = d[8] if d[2] and ":" in d[2]: task = d[2].split(':')[1] res_id = self.env['project.task'].search([('name', '=', task.strip())], limit=1) author = self.env['res.users'].search([('name', '=', d[3].strip())], limit=1) if not author: author = self.env['res.users'].create({'name': d[3].strip(), 'login': d[3].strip()}) dt = str(datetime.today().year) + " " + d[6] date = datetime.strptime(dt, '%Y %d %b %H:%M').strftime('%Y-%m-%d %H:%M:%S') if res_id: if not self.env['mail.message'].search([('res_id', '=', res_id.id), ('msg_id', '=', d[0])]): if not self.env['mail.message'].search([('content', '=', d[8]), ('received_time', '=', str(d[7]))]): self.env['mail.message'].create({ 'body': body, 'model': 'project.task', 'res_id': res_id.id, 'message_type': 'comment', 'author_id': author.partner_id.id, 'msg_id': d[0], 'content': d[8], 'vehicle': d[4], 'device': d[5], 'send_time': date, 'received_time': d[7] or False, 'image_data': str(d[10]).encode('hex'), 'latitude': d[11], 'longitude': d[12]}) db.commit() db.close() else: raise UserError("Please, configure Android database setting in General settings.") except Exception, e: msg = u"%s" % e raise UserError(msg) return True
class RoutePlanLocation(geo_model.GeoModel): """Add geo_point to route.plan.location""" _inherit = "route.plan.location" geo_point = fields.GeoPoint('Addresses coordinate', related='location_id.geo_point')