46f8128aac2ede5a7e0bc727c8c15ff04ba00e81
[freeside.git] / FS / FS / geocode_Mixin.pm
1 package FS::geocode_Mixin;
2
3 use strict;
4 use vars qw( $DEBUG $me );
5 use Carp;
6 use Locale::Country ();
7 use Geo::Coder::Googlev3; #compile time for now, until others are supported
8 use FS::Record qw( qsearchs qsearch );
9 use FS::Conf;
10 use FS::cust_pkg;
11 use FS::cust_location;
12 use FS::cust_tax_location;
13 use FS::part_pkg;
14 use FS::part_pkg_taxclass;
15
16 $DEBUG = 0;
17 $me = '[FS::geocode_Mixin]';
18
19 =head1 NAME
20
21 FS::geocode_Mixin - Mixin class for records that contain address and other
22 location fields.
23
24 =head1 SYNOPSIS
25
26   package FS::some_table;
27   use base ( FS::geocode_Mixin FS::Record );
28
29 =head1 DESCRIPTION
30
31 FS::geocode_Mixin - This is a mixin class for records that contain address
32 and other location fields.
33
34 =head1 METHODS
35
36 =over 4
37
38 =cut
39
40 =item location_hash
41
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.
45
46 =cut
47
48 #geocode dependent on tax-ship_address config
49
50 sub location_hash {
51   my $self = shift;
52   my $prefix = $self->has_ship_address ? 'ship_' : '';
53
54   map { my $method = ($_ eq 'geocode') ? $_ : $prefix.$_;
55         $_ => $self->get($method);
56       }
57       qw( address1 address2 city county state zip country geocode 
58         location_type location_number location_kind );
59 }
60
61 =item location_label [ OPTION => VALUE ... ]
62
63 Returns the label of the service location (see analog in L<FS::cust_location>) for this customer.
64
65 Options are
66
67 =over 4
68
69 =item join_string
70
71 used to separate the address elements (defaults to ', ')
72
73 =item escape_function
74
75 a callback used for escaping the text of the address elements
76
77 =back
78
79 =cut
80
81 sub location_label {
82   my $self = shift;
83   my %opt = @_;
84
85   my $separator = $opt{join_string} || ', ';
86   my $escape = $opt{escape_function} || sub{ shift };
87   my $ds = $opt{double_space} || '  ';
88   my $line = '';
89   my $cydefault = 
90     $opt{'countrydefault'} || FS::Conf->new->config('countrydefault') || 'US';
91   my $prefix = $self->has_ship_address ? 'ship_' : '';
92
93   my $notfirst = 0;
94   foreach (qw ( address1 address2 ) ) {
95     my $method = "$prefix$_";
96     $line .= ($notfirst ? $separator : ''). &$escape($self->$method)
97       if $self->$method;
98     $notfirst++;
99   }
100
101   my $lt = $self->get($prefix.'location_type');
102   if ( $lt ) {
103     my %location_type;
104     if ( 1 ) { #ikano, switch on via config
105       { no warnings 'void';
106         eval { 'use FS::part_export::ikano;' };
107         die $@ if $@;
108       }
109       %location_type = FS::part_export::ikano->location_types;
110     } else {
111       %location_type = (); #?
112     }
113
114     $line .= ' '.&$escape( $location_type{$lt} || $lt );
115   }
116
117   $line .= ' '. &$escape($self->get($prefix.'location_number'))
118     if $self->get($prefix.'location_number');
119
120   $notfirst = 0;
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';
127       $notfirst++;
128     }
129   }
130   $line .= $separator. &$escape($self->country_full)
131     if $self->country ne $cydefault;
132
133   $line;
134 }
135
136 =item country_full
137
138 Returns the full country name.
139
140 =cut
141
142 sub country_full {
143   my $self = shift;
144   $self->code2country($self->get('country'));
145 }
146
147 sub code2country {
148   my( $self, $country ) = @_;
149
150   #a hash?  not expecting an explosion of business from unrecognized countries..
151   return 'KKTC' if $country eq 'XC';
152                                            
153   Locale::Country::code2country($country);
154 }
155
156 =item set_coord
157
158 Look up the coordinates of the location using (currently) the Google Maps
159 API and set the 'latitude' and 'longitude' fields accordingly.
160
161 =cut
162
163 sub set_coord {
164   my $self = shift;
165
166   #my $module = FS::Conf->new->config('geocode_module') || 'Geo::Coder::Googlev3';
167
168   my $geocoder = Geo::Coder::Googlev3->new;
169
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'). ','.
176       $self->country_full
177     );
178   };
179   if ( $@ ) {
180     warn "geocoding error: $@\n";
181     return;
182   }
183
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');
189   }
190
191 }
192
193 =item geocode DATA_VENDOR
194
195 Returns a value for the customer location as encoded by DATA_VENDOR.
196 Currently this only makes sense for "CCH" as DATA_VENDOR.
197
198 =cut
199
200 sub geocode {
201   my ($self, $data_vendor) = (shift, shift);  #always cch for now
202
203   my $geocode = $self->get('geocode');  #XXX only one data_vendor for geocode
204   return $geocode if $geocode;
205
206   if ( $self->isa('FS::cust_main') ) {
207     warn "WARNING: FS::cust_main->geocode deprecated";
208
209     # do the best we can
210     my $m = FS::Conf->new->exists('tax-ship_address') ? 'ship_location'
211                                                       : 'bill_location';
212     my $location = $self->$m or return '';
213     return $location->geocode($data_vendor);
214   }
215
216   my($zip,$plus4) = split /-/, $self->get('zip')
217     if $self->country eq 'US';
218
219   $zip ||= '';
220   $plus4 ||= '';
221   #CCH specific location stuff
222   my $extra_sql = $plus4 ? "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'"
223                          : '';
224
225   my @cust_tax_location =
226     qsearch( {
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
231              }
232            );
233   $geocode = $cust_tax_location[0]->geocode
234     if scalar(@cust_tax_location);
235
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;
240
241   $geocode;
242 }
243
244 =item process_district_update CLASS ID
245
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.
249
250 =cut
251
252 # this is run from the job queue so I'm not transactionizing it.
253
254 sub process_district_update {
255   my $class = shift;
256   my $id = shift;
257   my $log = FS::Log->new('FS::cust_location::process_district_update');
258
259   eval "use FS::Misc::Geo qw(get_district); use FS::Conf; use $class;";
260   die $@ if $@;
261   die "$class has no location data" if !$class->can('location_hash');
262
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";
267
268   # dies on error, fine
269   my $tax_info = get_district({ $self->location_hash }, $method);
270   return unless $tax_info;
271
272   $self->set('district', $tax_info->{'district'} );
273   my $error = $self->replace;
274   die $error if $error;
275
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
279
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', {
286       %hash,
287       'taxclass' => $taxclass
288     });
289
290     if ( scalar(@existing) == 0 ) {
291
292       # then create one with the assigned tax name, and the tax rate from
293       # the lookup.
294       my $new = new FS::cust_main_county({
295         %hash,
296         'taxclass'      => $taxclass,
297         'taxname'       => $taxname,
298         'tax'           => $tax_info->{tax},
299         'exempt_amount' => 0,
300       });
301       $log->info("creating tax rate for district ".$tax_info->{'district'});
302       $error = $new->insert;
303
304     } else {
305
306       my $to_update = $existing[0];
307       # if there's somehow more than one, find the best candidate to be
308       # updated:
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 ) {
316               $to_update = $_;
317             } elsif ( $_->tax == 0 and $to_update->tax > 0 ) {
318               next;
319             } elsif ( $_->taxname eq $taxname and $to_update->tax ne $taxname ) {
320               $to_update = $_;
321             }
322           }
323         }
324         # don't remove the excess records here; upgrade does that.
325       }
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
331       } else {
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;
335       }
336     }
337
338     die $error if $error;
339
340   } # foreach $taxclass
341
342   return;
343 }
344
345 =back
346
347 =head1 BUGS
348
349 =head1 SEE ALSO
350
351 L<FS::Record>, schema.html from the base documentation.
352
353 =cut
354
355 1;
356