summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorIT Fixcomart <it@fixcomart.co.id>2025-06-16 01:56:39 +0000
committerIT Fixcomart <it@fixcomart.co.id>2025-06-16 01:56:39 +0000
commite9c34b1f97d79b48809430e8cabf7a74b7685e42 (patch)
tree1d10af0775f56b1960076915b15e54fafbabbd41
parent36c3d73ce1e7a0f644d79fcbf957bd0cb3137e82 (diff)
parent6e2419c226eb74ea5c14d21f441d570829a20021 (diff)
Merged in biteship-v1 (pull request #335)
(andri) on map view
-rw-r--r--indoteknik_custom/models/res_partner.py254
-rw-r--r--indoteknik_custom/views/res_partner.xml4
2 files changed, 129 insertions, 129 deletions
diff --git a/indoteknik_custom/models/res_partner.py b/indoteknik_custom/models/res_partner.py
index 1786efa3..a8ce95d1 100644
--- a/indoteknik_custom/models/res_partner.py
+++ b/indoteknik_custom/models/res_partner.py
@@ -148,7 +148,7 @@ class ResPartner(models.Model):
date_payment_terms_purchase = fields.Datetime(string='Date Update Payment Terms')
longtitude = fields.Char(string='Longtitude')
latitude = fields.Char(string='Latitude')
- # map_view = fields.Char(string='Map')
+ map_view = fields.Char(string='Map')
address_map = fields.Char(string='Address Map', help='Alamat ini diisi otomatis berdasarkan koordinat pin pada peta. Silakan koreksi dan ubah jika terdapat ketidaksesuaian', tracking=3)
company_type = fields.Selection(string='Company Type',
selection=[('person', 'Individual'), ('company', 'Company')],
@@ -549,130 +549,130 @@ class ResPartner(models.Model):
'target': 'current',
}
- # def geocode_address(self):
- # for rec in self:
- # # Daftar field penting
- # required_fields = {
- # 'Alamat Jalan (street)': rec.street,
- # 'Kelurahan': rec.kelurahan_id.name if rec.kelurahan_id else '',
- # 'Kecamatan': rec.kecamatan_id.name if rec.kecamatan_id else '',
- # 'Kota': rec.kota_id.name if rec.kota_id else '',
- # 'Kode Pos': rec.zip,
- # 'Provinsi': rec.state_id.name if rec.state_id else '',
- # }
+ def geocode_address(self):
+ for rec in self:
+ # Daftar field penting
+ required_fields = {
+ 'Alamat Jalan (street)': rec.street,
+ 'Kelurahan': rec.kelurahan_id.name if rec.kelurahan_id else '',
+ 'Kecamatan': rec.kecamatan_id.name if rec.kecamatan_id else '',
+ 'Kota': rec.kota_id.name if rec.kota_id else '',
+ 'Kode Pos': rec.zip,
+ 'Provinsi': rec.state_id.name if rec.state_id else '',
+ }
+
+ # Cek jika ada yang kosong
+ missing = [label for label, val in required_fields.items() if not val]
+ if missing:
+ raise UserError(
+ "Alamat tidak lengkap. Mohon lengkapi field berikut:\n- " + "\n- ".join(missing)
+ )
+
+ # Susun alamat lengkap
+ address = ', '.join([
+ required_fields['Alamat Jalan (street)'],
+ required_fields['Kelurahan'],
+ required_fields['Kecamatan'],
+ required_fields['Kota'],
+ required_fields['Kode Pos'],
+ required_fields['Provinsi'],
+ ])
+
+ # Ambil API Key
+ api_key = self.env['ir.config_parameter'].sudo().get_param('google.maps.api_key')
+ if not api_key:
+ raise UserError("API Key Google Maps belum dikonfigurasi. Silakan isi melalui Settings.")
+
+ # Request ke Google Maps
+ url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={api_key}'
+ response = requests.get(url)
+
+ if response.ok:
+ result = response.json()
+ if result.get('results'):
+ location = result['results'][0]['geometry']['location']
+ formatted_address = result['results'][0].get('formatted_address', '')
+
+ rec.latitude = location['lat']
+ rec.longtitude = location['lng']
+ rec.address_map = formatted_address # ✅ Simpan alamat lengkap
+ else:
+ raise UserError("Tidak ditemukan hasil geocode untuk alamat tersebut.")
+ else:
+ raise UserError("Permintaan ke Google Maps gagal. Periksa koneksi internet atau API Key.")
- # # Cek jika ada yang kosong
- # missing = [label for label, val in required_fields.items() if not val]
- # if missing:
- # raise UserError(
- # "Alamat tidak lengkap. Mohon lengkapi field berikut:\n- " + "\n- ".join(missing)
- # )
-
- # # Susun alamat lengkap
- # address = ', '.join([
- # required_fields['Alamat Jalan (street)'],
- # required_fields['Kelurahan'],
- # required_fields['Kecamatan'],
- # required_fields['Kota'],
- # required_fields['Kode Pos'],
- # required_fields['Provinsi'],
- # ])
-
- # # Ambil API Key
- # api_key = self.env['ir.config_parameter'].sudo().get_param('google.maps.api_key')
- # if not api_key:
- # raise UserError("API Key Google Maps belum dikonfigurasi. Silakan isi melalui Settings.")
-
- # # Request ke Google Maps
- # url = f'https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={api_key}'
- # response = requests.get(url)
-
- # if response.ok:
- # result = response.json()
- # if result.get('results'):
- # location = result['results'][0]['geometry']['location']
- # formatted_address = result['results'][0].get('formatted_address', '')
-
- # rec.latitude = location['lat']
- # rec.longtitude = location['lng']
- # rec.address_map = formatted_address # ✅ Simpan alamat lengkap
- # else:
- # raise UserError("Tidak ditemukan hasil geocode untuk alamat tersebut.")
- # else:
- # raise UserError("Permintaan ke Google Maps gagal. Periksa koneksi internet atau API Key.")
-
- # def _update_address_from_coords(self):
- # for rec in self:
- # if rec.latitude and rec.longtitude:
- # try:
- # components, formatted, parsed = rec._reverse_geocode(rec.latitude, rec.longtitude)
- # if not parsed:
- # continue
-
- # updates = {
- # 'street': parsed.get('road') or '',
- # 'zip': parsed.get('postcode') or '',
- # 'address_map': formatted or '',
- # }
-
- # state = self.env['res.country.state'].search([('name', 'ilike', parsed.get('state'))], limit=1)
- # if state:
- # updates['state_id'] = state.id
-
- # kota = self.env['vit.kota'].search([('name', 'ilike', parsed.get('city'))], limit=1)
- # if kota:
- # updates['kota_id'] = kota.id
-
- # kec = self.env['vit.kecamatan'].search([('name', 'ilike', parsed.get('district'))], limit=1)
- # if kec:
- # updates['kecamatan_id'] = kec.id
-
- # kel = self.env['vit.kelurahan'].search([('name', 'ilike', parsed.get('suburb'))], limit=1)
- # if kel:
- # updates['kelurahan_id'] = kel.id
-
- # rec.update(updates)
-
- # except Exception as e:
- # raise UserError(f"Gagal update alamat dari koordinat: {str(e)}")
-
-
- # def _reverse_geocode(self, lat, lng):
- # api_key = self.env['ir.config_parameter'].sudo().get_param('google.maps.api_key')
- # if not api_key:
- # raise UserError("API Key Google Maps belum dikonfigurasi.")
-
- # url = f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{lng}&key={api_key}'
- # response = requests.get(url)
- # if response.ok:
- # result = response.json()
- # if result.get('results'):
- # components = result['results'][0]['address_components']
- # formatted = result['results'][0]['formatted_address']
- # return components, formatted, self._parse_google_address(components)
- # return {}, '', {}
-
- # def _parse_google_address(self, components):
- # def get(types):
- # for comp in components:
- # if types in comp['types']:
- # return comp['long_name']
- # return ''
-
- # street_number = get('street_number')
- # route = get('route')
- # neighborhood = get('neighborhood') # Bisa jadi nama RW
- # subpremise = get('subpremise') # Bisa jadi no kamar/ruko
-
- # # Gabungkan informasi jalan
- # road = " ".join(filter(None, [route, street_number, subpremise, neighborhood]))
-
- # return {
- # 'road': road.strip(),
- # 'postcode': get('postal_code'),
- # 'state': get('administrative_area_level_1'),
- # 'city': get('administrative_area_level_2') or get('locality'),
- # 'district': get('administrative_area_level_3'),
- # 'suburb': get('administrative_area_level_4'),
- # 'formatted': get('formatted_address'),
- # }
+ def _update_address_from_coords(self):
+ for rec in self:
+ if rec.latitude and rec.longtitude:
+ try:
+ components, formatted, parsed = rec._reverse_geocode(rec.latitude, rec.longtitude)
+ if not parsed:
+ continue
+
+ updates = {
+ 'street': parsed.get('road') or '',
+ 'zip': parsed.get('postcode') or '',
+ 'address_map': formatted or '',
+ }
+
+ state = self.env['res.country.state'].search([('name', 'ilike', parsed.get('state'))], limit=1)
+ if state:
+ updates['state_id'] = state.id
+
+ kota = self.env['vit.kota'].search([('name', 'ilike', parsed.get('city'))], limit=1)
+ if kota:
+ updates['kota_id'] = kota.id
+
+ kec = self.env['vit.kecamatan'].search([('name', 'ilike', parsed.get('district'))], limit=1)
+ if kec:
+ updates['kecamatan_id'] = kec.id
+
+ kel = self.env['vit.kelurahan'].search([('name', 'ilike', parsed.get('suburb'))], limit=1)
+ if kel:
+ updates['kelurahan_id'] = kel.id
+
+ rec.update(updates)
+
+ except Exception as e:
+ raise UserError(f"Gagal update alamat dari koordinat: {str(e)}")
+
+
+ def _reverse_geocode(self, lat, lng):
+ api_key = self.env['ir.config_parameter'].sudo().get_param('google.maps.api_key')
+ if not api_key:
+ raise UserError("API Key Google Maps belum dikonfigurasi.")
+
+ url = f'https://maps.googleapis.com/maps/api/geocode/json?latlng={lat},{lng}&key={api_key}'
+ response = requests.get(url)
+ if response.ok:
+ result = response.json()
+ if result.get('results'):
+ components = result['results'][0]['address_components']
+ formatted = result['results'][0]['formatted_address']
+ return components, formatted, self._parse_google_address(components)
+ return {}, '', {}
+
+ def _parse_google_address(self, components):
+ def get(types):
+ for comp in components:
+ if types in comp['types']:
+ return comp['long_name']
+ return ''
+
+ street_number = get('street_number')
+ route = get('route')
+ neighborhood = get('neighborhood') # Bisa jadi nama RW
+ subpremise = get('subpremise') # Bisa jadi no kamar/ruko
+
+ # Gabungkan informasi jalan
+ road = " ".join(filter(None, [route, street_number, subpremise, neighborhood]))
+
+ return {
+ 'road': road.strip(),
+ 'postcode': get('postal_code'),
+ 'state': get('administrative_area_level_1'),
+ 'city': get('administrative_area_level_2') or get('locality'),
+ 'district': get('administrative_area_level_3'),
+ 'suburb': get('administrative_area_level_4'),
+ 'formatted': get('formatted_address'),
+ }
diff --git a/indoteknik_custom/views/res_partner.xml b/indoteknik_custom/views/res_partner.xml
index 7405e27b..2a4b03a7 100644
--- a/indoteknik_custom/views/res_partner.xml
+++ b/indoteknik_custom/views/res_partner.xml
@@ -70,9 +70,9 @@
<!-- <group>
<button name="geocode_address" type="object" string="Get Pin Point Location" class="btn btn-primary"/>
</group> -->
- <!-- <div style="margin: 16px 0;">
+ <div style="margin: 16px 0;">
<field name="map_view" widget="googlemap" nolabel="1"/>
- </div> -->
+ </div>
<group>
<field name="address_map" readonly="1" force_save="1"/>
<field name="latitude" readonly="1" force_save="1"/>