f38e8efcd01db75d7d23d7479c3d443af3e5f0ce
[freeside.git] / FS / FS / cust_location.pm
1 package FS::cust_location;
2 use base qw( FS::geocode_Mixin FS::Record );
3
4 use strict;
5 use vars qw( $import $DEBUG $conf $label_prefix );
6 use Data::Dumper;
7 use Date::Format qw( time2str );
8 use FS::UID qw( dbh driver_name );
9 use FS::Record qw( qsearch qsearchs );
10 use FS::Conf;
11 use FS::prospect_main;
12 use FS::cust_main;
13 use FS::cust_main_county;
14 use FS::part_export;
15 use FS::GeocodeCache;
16
17 $import = 0;
18
19 $DEBUG = 0;
20
21 FS::UID->install_callback( sub {
22   $conf = FS::Conf->new;
23   $label_prefix = $conf->config('cust_location-label_prefix') || '';
24 });
25
26 =head1 NAME
27
28 FS::cust_location - Object methods for cust_location records
29
30 =head1 SYNOPSIS
31
32   use FS::cust_location;
33
34   $record = new FS::cust_location \%hash;
35   $record = new FS::cust_location { 'column' => 'value' };
36
37   $error = $record->insert;
38
39   $error = $new_record->replace($old_record);
40
41   $error = $record->delete;
42
43   $error = $record->check;
44
45 =head1 DESCRIPTION
46
47 An FS::cust_location object represents a customer location.  FS::cust_location
48 inherits from FS::Record.  The following fields are currently supported:
49
50 =over 4
51
52 =item locationnum
53
54 primary key
55
56 =item custnum
57
58 custnum
59
60 =item address1
61
62 Address line one (required)
63
64 =item address2
65
66 Address line two (optional)
67
68 =item city
69
70 City (if cust_main-no_city_in_address config is set when inserting, this will be forced blank)
71
72 =item county
73
74 County (optional, see L<FS::cust_main_county>)
75
76 =item state
77
78 State (see L<FS::cust_main_county>)
79
80 =item zip
81
82 Zip
83
84 =item country
85
86 Country (see L<FS::cust_main_county>)
87
88 =item geocode
89
90 Geocode
91
92 =item district
93
94 Tax district code (optional)
95
96 =item incorporated
97
98 Incorporated city flag: set to 'Y' if the address is in the legal borders 
99 of an incorporated city.
100
101 =item disabled
102
103 Disabled flag; set to 'Y' to disable the location.
104
105 =back
106
107 =head1 METHODS
108
109 =over 4
110
111 =item new HASHREF
112
113 Creates a new location.  To add the location to the database, see L<"insert">.
114
115 Note that this stores the hash reference, not a distinct copy of the hash it
116 points to.  You can ask the object for a copy with the I<hash> method.
117
118 =cut
119
120 sub table { 'cust_location'; }
121
122 =item find_or_insert
123
124 Finds an existing location matching the customer and address values in this
125 location, if one exists, and sets the contents of this location equal to that
126 one (including its locationnum).
127
128 If an existing location is not found, this one I<will> be inserted.  (This is a
129 change from the "new_or_existing" method that this replaces.)
130
131 The following fields are considered "essential" and I<must> match: custnum,
132 address1, address2, city, county, state, zip, country, location_number,
133 location_type, location_kind.  Disabled locations will be found only if this
134 location is set to disabled.
135
136 All other fields are considered "non-essential" and will be ignored in 
137 finding a matching location.  If the existing location doesn't match 
138 in these fields, it will be updated in-place to match.
139
140 Returns an error string if inserting or updating a location failed.
141
142 It is unfortunately hard to determine if this created a new location or not.
143
144 =cut
145
146 sub find_or_insert {
147   my $self = shift;
148
149   warn "find_or_insert:\n".Dumper($self) if $DEBUG;
150
151   my @essential = (qw(custnum address1 address2 city county state zip country
152     location_number location_type location_kind disabled));
153
154   if ($conf->exists('cust_main-no_city_in_address')) {
155     warn "Warning: passed city to find_or_insert when cust_main-no_city_in_address is configured, ignoring it"
156       if $self->get('city');
157     $self->set('city','');
158   }
159
160   # I don't think this is necessary
161   #if ( !$self->coord_auto and $self->latitude and $self->longitude ) {
162   #  push @essential, qw(latitude longitude);
163   #  # but NOT coord_auto; if the latitude and longitude match the geocoded
164   #  # values then that's good enough
165   #}
166
167   # put nonempty, nonessential fields/values into this hash
168   my %nonempty = map { $_ => $self->get($_) }
169                  grep {$self->get($_)} $self->fields;
170   delete @nonempty{@essential};
171   delete $nonempty{'locationnum'};
172
173   my %hash = map { $_ => $self->get($_) } @essential;
174   my @matches = qsearch('cust_location', \%hash);
175
176   # we no longer reject matches for having different values in nonessential
177   # fields; we just alter the record to match
178   if ( @matches ) {
179     my $old = $matches[0];
180     warn "found existing location #".$old->locationnum."\n" if $DEBUG;
181     foreach my $field (keys %nonempty) {
182       if ($old->get($field) ne $nonempty{$field}) {
183         warn "altering $field to match requested location" if $DEBUG;
184         $old->set($field, $nonempty{$field});
185       }
186     } # foreach $field
187
188     if ( $old->modified ) {
189       warn "updating non-essential fields\n" if $DEBUG;
190       my $error = $old->replace;
191       return $error if $error;
192     }
193     # set $self equal to $old
194     foreach ($self->fields) {
195       $self->set($_, $old->get($_));
196     }
197     return "";
198   }
199
200   # didn't find a match
201   warn "not found; inserting new location\n" if $DEBUG;
202   return $self->insert;
203 }
204
205 =item insert
206
207 Adds this record to the database.  If there is an error, returns the error,
208 otherwise returns false.
209
210 =cut
211
212 sub insert {
213   my $self = shift;
214
215   if ($conf->exists('cust_main-no_city_in_address')) {
216     warn "Warning: passed city to insert when cust_main-no_city_in_address is configured, ignoring it"
217       if $self->get('city');
218     $self->set('city','');
219   }
220
221   if ( $self->censustract ) {
222     $self->set('censusyear' => $conf->config('census_year') || 2012);
223   }
224
225   my $oldAutoCommit = $FS::UID::AutoCommit;
226   local $FS::UID::AutoCommit = 0;
227   my $dbh = dbh;
228
229   my $error = $self->SUPER::insert(@_);
230   if ( $error ) {
231     $dbh->rollback if $oldAutoCommit;
232     return $error;
233   }
234
235   #false laziness with cust_main, will go away eventually
236   if ( !$import and $conf->config('tax_district_method') ) {
237
238     my $queue = new FS::queue {
239       'job' => 'FS::geocode_Mixin::process_district_update'
240     };
241     $error = $queue->insert( ref($self), $self->locationnum );
242     if ( $error ) {
243       $dbh->rollback if $oldAutoCommit;
244       return $error;
245     }
246
247   }
248
249   # cust_location exports
250   #my $export_args = $options{'export_args'} || [];
251
252   # don't export custnum_pending cases, let follow-up replace handle that
253   if ($self->custnum || $self->prospectnum) {
254     my @part_export =
255       map qsearch( 'part_export', {exportnum=>$_} ),
256         $conf->config('cust_location-exports'); #, $agentnum
257
258     foreach my $part_export ( @part_export ) {
259       my $error = $part_export->export_insert($self); #, @$export_args);
260       if ( $error ) {
261         $dbh->rollback if $oldAutoCommit;
262         return "exporting to ". $part_export->exporttype.
263                " (transaction rolled back): $error";
264       }
265     }
266   }
267
268   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
269   '';
270 }
271
272 =item delete
273
274 Delete this record from the database.
275
276 =item replace OLD_RECORD
277
278 Replaces the OLD_RECORD with this one in the database.  If there is an error,
279 returns the error, otherwise returns false.
280
281 =cut
282
283 sub replace {
284   my $self = shift;
285   my $old = shift;
286   $old ||= $self->replace_old;
287
288   warn "Warning: passed city to replace when cust_main-no_city_in_address is configured"
289     if $conf->exists('cust_main-no_city_in_address') && $self->get('city');
290
291   # the following fields are immutable if this is a customer location. if
292   # it's a prospect location, then there are no active packages, no billing
293   # history, no taxes, and in general no reason to keep the old location
294   # around.
295   if ( $self->custnum ) {
296     foreach (qw(address1 address2 city state zip country)) {
297       if ( $self->$_ ne $old->$_ ) {
298         return "can't change cust_location field $_";
299       }
300     }
301   }
302
303   my $oldAutoCommit = $FS::UID::AutoCommit;
304   local $FS::UID::AutoCommit = 0;
305   my $dbh = dbh;
306
307   my $error = $self->SUPER::replace($old);
308   if ( $error ) {
309     $dbh->rollback if $oldAutoCommit;
310     return $error;
311   }
312
313   # cust_location exports
314   #my $export_args = $options{'export_args'} || [];
315
316   # don't export custnum_pending cases, let follow-up replace handle that
317   if ($self->custnum || $self->prospectnum) {
318     my @part_export =
319       map qsearch( 'part_export', {exportnum=>$_} ),
320         $conf->config('cust_location-exports'); #, $agentnum
321
322     foreach my $part_export ( @part_export ) {
323       my $error = $part_export->export_replace($self, $old); #, @$export_args);
324       if ( $error ) {
325         $dbh->rollback if $oldAutoCommit;
326         return "exporting to ". $part_export->exporttype.
327                " (transaction rolled back): $error";
328       }
329     }
330   }
331
332   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
333   '';
334 }
335
336
337 =item check
338
339 Checks all fields to make sure this is a valid location.  If there is
340 an error, returns the error, otherwise returns false.  Called by the insert
341 and replace methods.
342
343 =cut
344
345 sub check {
346   my $self = shift;
347
348   return '' if $self->disabled; # so that disabling locations never fails
349
350   my $error = 
351     $self->ut_numbern('locationnum')
352     || $self->ut_foreign_keyn('prospectnum', 'prospect_main', 'prospectnum')
353     || $self->ut_foreign_keyn('custnum', 'cust_main', 'custnum')
354     || $self->ut_textn('locationname')
355     || $self->ut_text('address1')
356     || $self->ut_textn('address2')
357     || ($conf->exists('cust_main-no_city_in_address') 
358         ? $self->ut_textn('city') 
359         : $self->ut_text('city'))
360     || $self->ut_textn('county')
361     || $self->ut_textn('state')
362     || $self->ut_country('country')
363     || (!$import && $self->ut_zip('zip', $self->country))
364     || $self->ut_coordn('latitude')
365     || $self->ut_coordn('longitude')
366     || $self->ut_enum('coord_auto', [ '', 'Y' ])
367     || $self->ut_enum('addr_clean', [ '', 'Y' ])
368     || $self->ut_alphan('location_type')
369     || $self->ut_textn('location_number')
370     || $self->ut_enum('location_kind', [ '', 'R', 'B' ] )
371     || $self->ut_alphan('geocode')
372     || $self->ut_alphan('district')
373     || $self->ut_numbern('censusyear')
374     || $self->ut_flag('incorporated')
375   ;
376   return $error if $error;
377   if ( $self->censustract ne '' ) {
378     $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
379       or return "Illegal census tract: ". $self->censustract;
380
381     $self->censustract("$1.$2");
382   }
383
384   if ( $conf->exists('cust_main-require_address2') and 
385        !$self->ship_address2 =~ /\S/ ) {
386     return "Unit # is required";
387   }
388
389   # tricky...we have to allow for the customer to not be inserted yet
390   return "No prospect or customer!" unless $self->prospectnum 
391                                         || $self->custnum
392                                         || $self->get('custnum_pending');
393   return "Prospect and customer!"       if $self->prospectnum && $self->custnum;
394
395   return 'Location kind is required'
396     if $self->prospectnum
397     && $conf->exists('prospect_main-alt_address_format')
398     && ! $self->location_kind;
399
400   unless ( $import or qsearch('cust_main_county', {
401     'country' => $self->country,
402     'state'   => '',
403    } ) ) {
404     return "Unknown state/county/country: ".
405       $self->state. "/". $self->county. "/". $self->country
406       unless qsearch('cust_main_county',{
407         'state'   => $self->state,
408         'county'  => $self->county,
409         'country' => $self->country,
410       } );
411   }
412
413   # set coordinates, unless we already have them
414   if (!$import and !$self->latitude and !$self->longitude) {
415     $self->set_coord;
416   }
417
418   $self->SUPER::check;
419 }
420
421 =item country_full
422
423 Returns this location's full country name
424
425 =cut
426
427 #moved to geocode_Mixin.pm
428
429 =item line
430
431 Synonym for location_label
432
433 =cut
434
435 sub line {
436   my $self = shift;
437   $self->location_label(@_);
438 }
439
440 =item has_ship_address
441
442 Returns false since cust_location objects do not have a separate shipping
443 address.
444
445 =cut
446
447 sub has_ship_address {
448   '';
449 }
450
451 =item location_hash
452
453 Returns a list of key/value pairs, with the following keys: address1, address2,
454 city, county, state, zip, country, geocode, location_type, location_number,
455 location_kind.
456
457 =cut
458
459 =item disable_if_unused
460
461 Sets the "disabled" flag on the location if it is no longer in use as a 
462 prospect location, package location, or a customer's billing or default
463 service address.
464
465 =cut
466
467 sub disable_if_unused {
468
469   my $self = shift;
470   my $locationnum = $self->locationnum;
471   return '' if FS::cust_main->count('bill_locationnum = '.$locationnum.' OR
472                                      ship_locationnum = '.$locationnum)
473             or FS::contact->count(      'locationnum  = '.$locationnum)
474             or FS::cust_pkg->count('cancel IS NULL AND 
475                                          locationnum  = '.$locationnum)
476           ;
477   $self->disabled('Y');
478   $self->replace;
479
480 }
481
482 =item move_to
483
484 Takes a new L<FS::cust_location> object.  Moves all packages that use the 
485 existing location to the new one, then sets the "disabled" flag on the old
486 location.  Returns nothing on success, an error message on error.
487
488 =cut
489
490 sub move_to {
491   my $old = shift;
492   my $new = shift;
493   
494   warn "move_to:\nFROM:".Dumper($old)."\nTO:".Dumper($new) if $DEBUG;
495
496   local $SIG{HUP} = 'IGNORE';
497   local $SIG{INT} = 'IGNORE';
498   local $SIG{QUIT} = 'IGNORE';
499   local $SIG{TERM} = 'IGNORE';
500   local $SIG{TSTP} = 'IGNORE';
501   local $SIG{PIPE} = 'IGNORE';
502
503   my $oldAutoCommit = $FS::UID::AutoCommit;
504   local $FS::UID::AutoCommit = 0;
505   my $dbh = dbh;
506   my $error = '';
507
508   # prevent this from failing because of pkg_svc quantity limits
509   local( $FS::cust_svc::ignore_quantity ) = 1;
510
511   if ( !$new->locationnum ) {
512     $error = $new->insert;
513     if ( $error ) {
514       $dbh->rollback if $oldAutoCommit;
515       return "Error creating location: $error";
516     }
517   } elsif ( $new->locationnum == $old->locationnum ) {
518     # then they're the same location; the normal result of doing a minor
519     # location edit
520     $dbh->commit if $oldAutoCommit;
521     return '';
522   }
523
524   # find all packages that have the old location as their service address,
525   # and aren't canceled,
526   # and aren't supplemental to another package.
527   my @pkgs = qsearch('cust_pkg', { 
528       'locationnum' => $old->locationnum,
529       'cancel'      => '',
530       'main_pkgnum' => '',
531     });
532   foreach my $cust_pkg (@pkgs) {
533     # don't move one-time charges that have already been charged
534     next if $cust_pkg->part_pkg->freq eq '0'
535             and ($cust_pkg->setup || 0) > 0;
536
537     $error = $cust_pkg->change(
538       'locationnum' => $new->locationnum,
539       'keep_dates'  => 1
540     );
541     if ( $error and not ref($error) ) {
542       $dbh->rollback if $oldAutoCommit;
543       return "Error moving pkgnum ".$cust_pkg->pkgnum.": $error";
544     }
545   }
546
547   $error = $old->disable_if_unused;
548   if ( $error ) {
549     $dbh->rollback if $oldAutoCommit;
550     return "Error disabling old location: $error";
551   }
552
553   $dbh->commit if $oldAutoCommit;
554   '';
555 }
556
557 =item alternize
558
559 Attempts to parse data for location_type and location_number from address1
560 and address2.
561
562 =cut
563
564 sub alternize {
565   my $self = shift;
566
567   return '' if $self->get('location_type')
568             || $self->get('location_number');
569
570   my %parse;
571   if ( 1 ) { #ikano, switch on via config
572     { no warnings 'void';
573       eval { 'use FS::part_export::ikano;' };
574       die $@ if $@;
575     }
576     %parse = FS::part_export::ikano->location_types_parse;
577   } else {
578     %parse = (); #?
579   }
580
581   foreach my $from ('address1', 'address2') {
582     foreach my $parse ( keys %parse ) {
583       my $value = $self->get($from);
584       if ( $value =~ s/(^|\W+)$parse\W+(\w+)\W*$//i ) {
585         $self->set('location_type', $parse{$parse});
586         $self->set('location_number', $2);
587         $self->set($from, $value);
588         return '';
589       }
590     }
591   }
592
593   #nothing matched, no changes
594   $self->get('address2')
595     ? "Can't parse unit type and number from address2"
596     : '';
597 }
598
599 =item dealternize
600
601 Moves data from location_type and location_number to the end of address1.
602
603 =cut
604
605 sub dealternize {
606   my $self = shift;
607
608   #false laziness w/geocode_Mixin.pm::line
609   my $lt = $self->get('location_type');
610   if ( $lt ) {
611
612     my %location_type;
613     if ( 1 ) { #ikano, switch on via config
614       { no warnings 'void';
615         eval { 'use FS::part_export::ikano;' };
616         die $@ if $@;
617       }
618       %location_type = FS::part_export::ikano->location_types;
619     } else {
620       %location_type = (); #?
621     }
622
623     $self->address1( $self->address1. ' '. $location_type{$lt} || $lt );
624     $self->location_type('');
625   }
626
627   if ( length($self->location_number) ) {
628     $self->address1( $self->address1. ' '. $self->location_number );
629     $self->location_number('');
630   }
631  
632   '';
633 }
634
635 =item location_label
636
637 Returns the label of the location object.
638
639 Options:
640
641 =over 4
642
643 =item cust_main
644
645 Customer object (see L<FS::cust_main>)
646
647 =item prospect_main
648
649 Prospect object (see L<FS::prospect_main>)
650
651 =item join_string
652
653 String used to join location elements
654
655 =item no_prefix
656
657 Don't label the default service location as "Default service location".
658 May become the default at some point.
659
660 =back
661
662 =cut
663
664 sub location_label {
665   my( $self, %opt ) = @_;
666
667   my $prefix = $self->label_prefix(%opt);
668   $prefix .= ($opt{join_string} ||  ': ') if $prefix;
669   $prefix = '' if $opt{'no_prefix'};
670
671   $prefix . $self->SUPER::location_label(%opt);
672 }
673
674 =item label_prefix
675
676 Returns the optional site ID string (based on the cust_location-label_prefix
677 config option), "Default service location", or the empty string.
678
679 Options:
680
681 =over 4
682
683 =item cust_main
684
685 Customer object (see L<FS::cust_main>)
686
687 =item prospect_main
688
689 Prospect object (see L<FS::prospect_main>)
690
691 =back
692
693 =cut
694
695 sub label_prefix {
696   my( $self, %opt ) = @_;
697
698   my $cust_or_prospect = $opt{cust_main} || $opt{prospect_main};
699   unless ( $cust_or_prospect ) {
700     if ( $self->custnum ) {
701       $cust_or_prospect = FS::cust_main->by_key($self->custnum);
702     } elsif ( $self->prospectnum ) {
703       $cust_or_prospect = FS::prospect_main->by_key($self->prospectnum);
704     }
705   }
706
707   my $prefix = '';
708   if ( $label_prefix eq 'CoStAg' ) {
709     my $agent = $conf->config('cust_main-custnum-display_prefix',
710                   $cust_or_prospect->agentnum)
711                 || $cust_or_prospect->agent->agent;
712     # else this location is invalid
713     $prefix = uc( join('',
714         $self->country,
715         ($self->state =~ /^(..)/),
716         ($agent =~ /^(..)/),
717         sprintf('%05d', $self->locationnum)
718     ) );
719
720   } elsif ( $label_prefix eq '_location' && $self->locationname ) {
721     $prefix = $self->locationname;
722
723   } elsif (    ( $opt{'cust_main'} || $self->custnum )
724           && $self->locationnum == $cust_or_prospect->ship_locationnum ) {
725     $prefix = 'Default service location';
726   }
727
728   $prefix;
729 }
730
731 =item county_state_country
732
733 Returns a string consisting of just the county, state and country.
734
735 =cut
736
737 sub county_state_country {
738   my $self = shift;
739   my $label = $self->country;
740   $label = $self->state.", $label" if $self->state;
741   $label = $self->county." County, $label" if $self->county;
742   $label;
743 }
744
745 =back
746
747 =head2 SUBROUTINES
748
749 =over 4
750
751 =item process_censustract_update LOCATIONNUM
752
753 Queueable function to update the census tract to the current year (as set in 
754 the 'census_year' configuration variable) and retrieve the new tract code.
755
756 =cut
757
758 sub process_censustract_update {
759   eval "use FS::GeocodeCache";
760   die $@ if $@;
761   my $locationnum = shift;
762   my $cust_location = 
763     qsearchs( 'cust_location', { locationnum => $locationnum })
764       or die "locationnum '$locationnum' not found!\n";
765
766   my $new_year = $conf->config('census_year') or return;
767   my $loc = FS::GeocodeCache->new( $cust_location->location_hash );
768   $loc->set_censustract;
769   my $error = $loc->get('censustract_error');
770   die $error if $error;
771   $cust_location->set('censustract', $loc->get('censustract'));
772   $cust_location->set('censusyear',  $new_year);
773   $error = $cust_location->replace;
774   die $error if $error;
775   return;
776 }
777
778 =item process_set_coord
779
780 Queueable function to find and fill in coordinates for all locations that 
781 lack them.  Because this uses the Google Maps API, it's internally rate
782 limited and must run in a single process.
783
784 =cut
785
786 sub process_set_coord {
787   my $job = shift;
788   # avoid starting multiple instances of this job
789   my @others = qsearch('queue', {
790       'status'  => 'locked',
791       'job'     => $job->job,
792       'jobnum'  => {op=>'!=', value=>$job->jobnum},
793   });
794   return if @others;
795
796   $job->update_statustext('finding locations to update');
797   my @missing_coords = qsearch('cust_location', {
798       'disabled'  => '',
799       'latitude'  => '',
800       'longitude' => '',
801   });
802   my $i = 0;
803   my $n = scalar @missing_coords;
804   for my $cust_location (@missing_coords) {
805     $cust_location->set_coord;
806     my $error = $cust_location->replace;
807     if ( $error ) {
808       warn "error geocoding location#".$cust_location->locationnum.": $error\n";
809     } else {
810       $i++;
811       $job->update_statustext("updated $i / $n locations");
812       dbh->commit; # so that we don't have to wait for the whole thing to finish
813       # Rate-limit to stay under the Google Maps usage limit (2500/day).
814       # 86,400 / 35 = 2,468 lookups per day.
815     }
816     sleep 35;
817   }
818   if ( $i < $n ) {
819     die "failed to update ".$n-$i." locations\n";
820   }
821   return;
822 }
823
824 =item process_standardize [ LOCATIONNUMS ]
825
826 Performs address standardization on locations with unclean addresses,
827 using whatever method you have configured.  If the standardize_* method 
828 returns a I<clean> address match, the location will be updated.  This is 
829 always an in-place update (because the physical location is the same, 
830 and is just being referred to by a more accurate name).
831
832 Disabled locations will be skipped, as nobody cares.
833
834 If any LOCATIONNUMS are provided, only those locations will be updated.
835
836 =cut
837
838 sub process_standardize {
839   my $job = shift;
840   my @others = qsearch('queue', {
841       'status'  => 'locked',
842       'job'     => $job->job,
843       'jobnum'  => {op=>'!=', value=>$job->jobnum},
844   });
845   return if @others;
846   my @locationnums = grep /^\d+$/, @_;
847   my $where = "AND locationnum IN(".join(',',@locationnums).")"
848     if scalar(@locationnums);
849   my @locations = qsearch({
850       table     => 'cust_location',
851       hashref   => { addr_clean => '', disabled => '' },
852       extra_sql => $where,
853   });
854   my $n_todo = scalar(@locations);
855   my $n_done = 0;
856
857   # special: log this
858   my $log;
859   eval "use Text::CSV";
860   open $log, '>', "$FS::UID::cache_dir/process_standardize-" . 
861                   time2str('%Y%m%d',time) .
862                   ".csv";
863   my $csv = Text::CSV->new({binary => 1, eol => "\n"});
864
865   foreach my $cust_location (@locations) {
866     $job->update_statustext( int(100 * $n_done/$n_todo) . ",$n_done / $n_todo locations" ) if $job;
867     my $result = FS::GeocodeCache->standardize($cust_location);
868     if ( $result->{addr_clean} and !$result->{error} ) {
869       my @cols = ($cust_location->locationnum);
870       foreach (keys %$result) {
871         push @cols, $cust_location->get($_), $result->{$_};
872         $cust_location->set($_, $result->{$_});
873       }
874       # bypass immutable field restrictions
875       my $error = $cust_location->FS::Record::replace;
876       warn "location ".$cust_location->locationnum.": $error\n" if $error;
877       $csv->print($log, \@cols);
878     }
879     $n_done++;
880     dbh->commit; # so that we can resume if interrupted
881   }
882   close $log;
883 }
884
885 =head1 BUGS
886
887 =head1 SEE ALSO
888
889 L<FS::cust_main_county>, L<FS::cust_pkg>, L<FS::Record>,
890 schema.html from the base documentation.
891
892 =cut
893
894 1;
895