1 package FS::geocode_Mixin;
4 use vars qw( $DEBUG $me );
6 use Locale::Country ();
7 use Geo::Coder::Googlev3; #compile time for now, until others are supported
8 use FS::Record qw( qsearchs qsearch );
11 use FS::cust_location;
12 use FS::cust_tax_location;
14 use FS::part_pkg_taxclass;
17 $me = '[FS::geocode_Mixin]';
21 FS::geocode_Mixin - Mixin class for records that contain address and other
26 package FS::some_table;
27 use base ( FS::geocode_Mixin FS::Record );
31 FS::geocode_Mixin - This is a mixin class for records that contain address
32 and other location fields.
42 Returns a list of key/value pairs, with the following keys: address1, address2,
43 city, county, state, zip, country, geocode, location_type, location_number,
44 location_kind. The shipping address is used if present.
48 #geocode dependent on tax-ship_address config
52 my $prefix = $self->has_ship_address ? 'ship_' : '';
54 map { my $method = ($_ eq 'geocode') ? $_ : $prefix.$_;
55 $_ => $self->get($method);
57 qw( address1 address2 city county state zip country geocode
58 location_type location_number location_kind );
61 =item location_label [ OPTION => VALUE ... ]
63 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
71 used to separate the address elements (defaults to ', ')
75 a callback used for escaping the text of the address elements
85 my $separator = $opt{join_string} || ', ';
86 my $escape = $opt{escape_function} || sub{ shift };
87 my $ds = $opt{double_space} || ' ';
90 $opt{'countrydefault'} || FS::Conf->new->config('countrydefault') || 'US';
91 my $prefix = $self->has_ship_address ? 'ship_' : '';
94 foreach (qw ( address1 address2 ) ) {
95 my $method = "$prefix$_";
96 $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
101 my $lt = $self->get($prefix.'location_type');
104 if ( 1 ) { #ikano, switch on via config
105 { no warnings 'void';
106 eval { 'use FS::part_export::ikano;' };
109 %location_type = FS::part_export::ikano->location_types;
111 %location_type = (); #?
114 $line .= ' '.&$escape( $location_type{$lt} || $lt );
117 $line .= ' '. &$escape($self->get($prefix.'location_number'))
118 if $self->get($prefix.'location_number');
121 foreach (qw ( city county state zip ) ) {
122 my $method = "$prefix$_";
123 if ( $self->$method ) {
124 $line .= ' (' if $method eq 'county';
125 $line .= ($notfirst ? ' ' : $separator). &$escape($self->$method);
126 $line .= ' )' if $method eq 'county';
130 $line .= $separator. &$escape($self->country_full)
131 if $self->country ne $cydefault;
138 Returns the full country name.
144 $self->code2country($self->get('country'));
148 my( $self, $country ) = @_;
150 #a hash? not expecting an explosion of business from unrecognized countries..
151 return 'KKTC' if $country eq 'XC';
153 Locale::Country::code2country($country);
158 Look up the coordinates of the location using (currently) the Google Maps
159 API and set the 'latitude' and 'longitude' fields accordingly.
166 #my $module = FS::Conf->new->config('geocode_module') || 'Geo::Coder::Googlev3';
168 my $geocoder = Geo::Coder::Googlev3->new;
170 my $location = eval {
171 $geocoder->geocode( location =>
172 $self->get('address1'). ','.
173 ( $self->get('address2') ? $self->get('address2').',' : '' ).
174 $self->get('city'). ','.
175 $self->get('state'). ','.
180 warn "geocoding error: $@\n";
184 my $geo_loc = $location->{'geometry'}{'location'} or return;
185 if ( $geo_loc->{'lat'} && $geo_loc->{'lng'} ) {
186 $self->set('latitude', $geo_loc->{'lat'} );
187 $self->set('longitude', $geo_loc->{'lng'} );
188 $self->set('coord_auto', 'Y');
193 =item geocode DATA_VENDOR
195 Returns a value for the customer location as encoded by DATA_VENDOR.
196 Currently this only makes sense for "CCH" as DATA_VENDOR.
201 my ($self, $data_vendor) = (shift, shift); #always cch for now
203 my $geocode = $self->get('geocode'); #XXX only one data_vendor for geocode
204 return $geocode if $geocode;
206 if ( $self->isa('FS::cust_main') ) {
207 warn "WARNING: FS::cust_main->geocode deprecated";
210 my $m = FS::Conf->new->exists('tax-ship_address') ? 'ship_location'
212 my $location = $self->$m or return '';
213 return $location->geocode($data_vendor);
216 my($zip,$plus4) = split /-/, $self->get('zip')
217 if $self->country eq 'US';
221 #CCH specific location stuff
222 my $extra_sql = $plus4 ? "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'"
225 my @cust_tax_location =
227 'table' => 'cust_tax_location',
228 'hashref' => { 'zip' => $zip, 'data_vendor' => $data_vendor },
229 'extra_sql' => $extra_sql,
230 'order_by' => 'ORDER BY plus4hi',#overlapping with distinct ends
233 $geocode = $cust_tax_location[0]->geocode
234 if scalar(@cust_tax_location);
236 warn "WARNING: customer ". $self->custnum.
237 ": multiple locations for zip ". $self->get("zip").
238 "; using arbitrary geocode $geocode\n"
239 if scalar(@cust_tax_location) > 1;
244 =item process_district_update CLASS ID
246 Queueable function to update the tax district code using the selected method
247 (config 'tax_district_method'). CLASS is either 'FS::cust_main' or
248 'FS::cust_location'; ID is the key in one of those tables.
252 # this is run from the job queue so I'm not transactionizing it.
254 sub process_district_update {
257 my $log = FS::Log->new('FS::cust_location::process_district_update');
259 eval "use FS::Misc::Geo qw(get_district); use FS::Conf; use $class;";
261 die "$class has no location data" if !$class->can('location_hash');
263 my $conf = FS::Conf->new;
264 my $method = $conf->config('tax_district_method')
265 or return; #nothing to do if null
266 my $self = $class->by_key($id) or die "object $id not found";
268 # dies on error, fine
269 my $tax_info = get_district({ $self->location_hash }, $method);
270 return unless $tax_info;
272 $self->set('district', $tax_info->{'district'} );
273 my $error = $self->replace;
274 die $error if $error;
276 my %hash = map { $_ => uc( $tax_info->{$_} ) }
277 qw( district city county state country );
278 $hash{'source'} = $method; # apply the update only to taxes we maintain
280 my @classes = FS::part_pkg_taxclass->taxclass_names;
281 my $taxname = $conf->config('tax_district_taxname');
282 # there must be exactly one cust_main_county for each district+taxclass.
283 # do NOT exclude taxes that are zero.
284 foreach my $taxclass (@classes) {
285 my @existing = qsearch('cust_main_county', {
287 'taxclass' => $taxclass
290 if ( scalar(@existing) == 0 ) {
292 # then create one with the assigned tax name, and the tax rate from
294 my $new = new FS::cust_main_county({
296 'taxclass' => $taxclass,
297 'taxname' => $taxname,
298 'tax' => $tax_info->{tax},
299 'exempt_amount' => 0,
301 $log->info("creating tax rate for district ".$tax_info->{'district'});
302 $error = $new->insert;
306 my $to_update = $existing[0];
307 # if there's somehow more than one, find the best candidate to be
309 # - prefer tax > 0 over tax = 0 (leave disabled records disabled)
310 # - then, prefer taxname = the designated taxname
311 if ( scalar(@existing) > 1 ) {
312 $log->warning("tax district ".$tax_info->{district}." has multiple $method taxes.");
313 foreach (@existing) {
314 if ( $to_update->tax == 0 ) {
315 if ( $_->tax > 0 and $to_update->tax == 0 ) {
317 } elsif ( $_->tax == 0 and $to_update->tax > 0 ) {
319 } elsif ( $_->taxname eq $taxname and $to_update->tax ne $taxname ) {
324 # don't remove the excess records here; upgrade does that.
326 my $taxnum = $to_update->taxnum;
327 if ( $to_update->tax == 0 ) {
328 $log->debug("tax#$taxnum is set to zero; not updating.");
329 } elsif ( $to_update->tax == $tax_info->{tax} ) {
330 # do nothing, no need to update
332 $to_update->set('tax', $tax_info->{tax});
333 $log->info("updating tax#$taxnum with new rate ($tax_info->{tax}).");
334 $error = $to_update->replace;
338 die $error if $error;
340 } # foreach $taxclass
351 L<FS::Record>, schema.html from the base documentation.