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