1 package FS::cust_location;
2 use base qw( FS::geocode_Mixin FS::Record );
5 use vars qw( $import $DEBUG $conf $label_prefix );
7 use Date::Format qw( time2str );
9 use FS::UID qw( dbh driver_name );
10 use FS::Record qw( qsearch qsearchs );
12 use FS::prospect_main;
14 use FS::cust_main_county;
22 FS::UID->install_callback( sub {
23 $conf = FS::Conf->new;
24 $label_prefix = $conf->config('cust_location-label_prefix') || '';
29 FS::cust_location - Object methods for cust_location records
33 use FS::cust_location;
35 $record = new FS::cust_location \%hash;
36 $record = new FS::cust_location { 'column' => 'value' };
38 $error = $record->insert;
40 $error = $new_record->replace($old_record);
42 $error = $record->delete;
44 $error = $record->check;
48 An FS::cust_location object represents a customer location. FS::cust_location
49 inherits from FS::Record. The following fields are currently supported:
63 Address line one (required)
67 Address line two (optional)
75 County (optional, see L<FS::cust_main_county>)
79 State (see L<FS::cust_main_county>)
87 Country (see L<FS::cust_main_county>)
95 Tax district code (optional)
99 Disabled flag; set to 'Y' to disable the location.
109 Creates a new location. To add the location to the database, see L<"insert">.
111 Note that this stores the hash reference, not a distinct copy of the hash it
112 points to. You can ask the object for a copy with the I<hash> method.
116 sub table { 'cust_location'; }
120 Finds an existing location matching the customer and address values in this
121 location, if one exists, and sets the contents of this location equal to that
122 one (including its locationnum).
124 If an existing location is not found, this one I<will> be inserted. (This is a
125 change from the "new_or_existing" method that this replaces.)
127 The following fields are considered "essential" and I<must> match: custnum,
128 address1, address2, city, county, state, zip, country, location_number,
129 location_type, location_kind. Disabled locations will be found only if this
130 location is set to disabled.
132 All other fields are considered "non-essential" and will be ignored in
133 finding a matching location. If the existing location doesn't match
134 in these fields, it will be updated in-place to match.
136 Returns an error string if inserting or updating a location failed.
138 It is unfortunately hard to determine if this created a new location or not.
145 warn "find_or_insert:\n".Dumper($self) if $DEBUG;
147 my @essential = (qw(custnum address1 address2 city county state zip country
148 location_number location_type location_kind disabled));
150 # I don't think this is necessary
151 #if ( !$self->coord_auto and $self->latitude and $self->longitude ) {
152 # push @essential, qw(latitude longitude);
153 # # but NOT coord_auto; if the latitude and longitude match the geocoded
154 # # values then that's good enough
157 # put nonempty, nonessential fields/values into this hash
158 my %nonempty = map { $_ => $self->get($_) }
159 grep {$self->get($_)} $self->fields;
160 delete @nonempty{@essential};
161 delete $nonempty{'locationnum'};
163 my %hash = map { $_ => $self->get($_) } @essential;
164 my @matches = qsearch('cust_location', \%hash);
166 # we no longer reject matches for having different values in nonessential
167 # fields; we just alter the record to match
169 my $old = $matches[0];
170 warn "found existing location #".$old->locationnum."\n" if $DEBUG;
171 foreach my $field (keys %nonempty) {
172 if ($old->get($field) ne $nonempty{$field}) {
173 warn "altering $field to match requested location" if $DEBUG;
174 $old->set($field, $nonempty{$field});
178 if ( $old->modified ) {
179 warn "updating non-essential fields\n" if $DEBUG;
180 my $error = $old->replace;
181 return $error if $error;
183 # set $self equal to $old
184 foreach ($self->fields) {
185 $self->set($_, $old->get($_));
190 # didn't find a match
191 warn "not found; inserting new location\n" if $DEBUG;
192 return $self->insert;
197 Adds this record to the database. If there is an error, returns the error,
198 otherwise returns false.
205 if ( $self->censustract ) {
206 $self->set('censusyear' => $conf->config('census_year') || 2012);
209 my $oldAutoCommit = $FS::UID::AutoCommit;
210 local $FS::UID::AutoCommit = 0;
213 my $error = $self->SUPER::insert(@_);
215 $dbh->rollback if $oldAutoCommit;
219 #false laziness with cust_main, will go away eventually
220 if ( !$import and $conf->config('tax_district_method') ) {
222 my $queue = new FS::queue {
223 'job' => 'FS::geocode_Mixin::process_district_update'
225 $error = $queue->insert( ref($self), $self->locationnum );
227 $dbh->rollback if $oldAutoCommit;
233 # cust_location exports
234 #my $export_args = $options{'export_args'} || [];
237 map qsearch( 'part_export', {exportnum=>$_} ),
238 $conf->config('cust_location-exports'); #, $agentnum
240 foreach my $part_export ( @part_export ) {
241 my $error = $part_export->export_insert($self); #, @$export_args);
243 $dbh->rollback if $oldAutoCommit;
244 return "exporting to ". $part_export->exporttype.
245 " (transaction rolled back): $error";
250 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
256 Delete this record from the database.
258 =item replace OLD_RECORD
260 Replaces the OLD_RECORD with this one in the database. If there is an error,
261 returns the error, otherwise returns false.
268 $old ||= $self->replace_old;
269 # the following fields are immutable
270 foreach (qw(address1 address2 city state zip country)) {
271 if ( $self->$_ ne $old->$_ ) {
272 return "can't change cust_location field $_";
276 my $oldAutoCommit = $FS::UID::AutoCommit;
277 local $FS::UID::AutoCommit = 0;
280 my $error = $self->SUPER::replace($old);
282 $dbh->rollback if $oldAutoCommit;
286 # cust_location exports
287 #my $export_args = $options{'export_args'} || [];
290 map qsearch( 'part_export', {exportnum=>$_} ),
291 $conf->config('cust_location-exports'); #, $agentnum
293 foreach my $part_export ( @part_export ) {
294 my $error = $part_export->export_replace($self, $old); #, @$export_args);
296 $dbh->rollback if $oldAutoCommit;
297 return "exporting to ". $part_export->exporttype.
298 " (transaction rolled back): $error";
303 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
310 Checks all fields to make sure this is a valid location. If there is
311 an error, returns the error, otherwise returns false. Called by the insert
319 return '' if $self->disabled; # so that disabling locations never fails
322 $self->ut_numbern('locationnum')
323 || $self->ut_foreign_keyn('prospectnum', 'prospect_main', 'prospectnum')
324 || $self->ut_foreign_keyn('custnum', 'cust_main', 'custnum')
325 || $self->ut_text('address1')
326 || $self->ut_textn('address2')
327 || $self->ut_text('city')
328 || $self->ut_textn('county')
329 || $self->ut_textn('state')
330 || $self->ut_country('country')
331 || (!$import && $self->ut_zip('zip', $self->country))
332 || $self->ut_coordn('latitude')
333 || $self->ut_coordn('longitude')
334 || $self->ut_enum('coord_auto', [ '', 'Y' ])
335 || $self->ut_enum('addr_clean', [ '', 'Y' ])
336 || $self->ut_alphan('location_type')
337 || $self->ut_textn('location_number')
338 || $self->ut_enum('location_kind', [ '', 'R', 'B' ] )
339 || $self->ut_alphan('geocode')
340 || $self->ut_alphan('district')
341 || $self->ut_numbern('censusyear')
343 return $error if $error;
344 if ( $self->censustract ne '' ) {
345 $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
346 or return "Illegal census tract: ". $self->censustract;
348 $self->censustract("$1.$2");
351 if ( $conf->exists('cust_main-require_address2') and
352 !$self->ship_address2 =~ /\S/ ) {
353 return "Unit # is required";
356 # tricky...we have to allow for the customer to not be inserted yet
357 return "No prospect or customer!" unless $self->prospectnum
359 || $self->get('custnum_pending');
360 return "Prospect and customer!" if $self->prospectnum && $self->custnum;
362 return 'Location kind is required'
363 if $self->prospectnum
364 && $conf->exists('prospect_main-alt_address_format')
365 && ! $self->location_kind;
367 unless ( $import or qsearch('cust_main_county', {
368 'country' => $self->country,
371 return "Unknown state/county/country: ".
372 $self->state. "/". $self->county. "/". $self->country
373 unless qsearch('cust_main_county',{
374 'state' => $self->state,
375 'county' => $self->county,
376 'country' => $self->country,
380 # set coordinates, unless we already have them
381 if (!$import and !$self->latitude and !$self->longitude) {
390 Returns this locations's full country name
396 code2country($self->country);
401 Synonym for location_label
407 $self->location_label(@_);
410 =item has_ship_address
412 Returns false since cust_location objects do not have a separate shipping
417 sub has_ship_address {
423 Returns a list of key/value pairs, with the following keys: address1, address2,
424 city, county, state, zip, country, geocode, location_type, location_number,
429 =item disable_if_unused
431 Sets the "disabled" flag on the location if it is no longer in use as a
432 prospect location, package location, or a customer's billing or default
437 sub disable_if_unused {
440 my $locationnum = $self->locationnum;
441 return '' if FS::cust_main->count('bill_locationnum = '.$locationnum.' OR
442 ship_locationnum = '.$locationnum)
443 or FS::contact->count( 'locationnum = '.$locationnum)
444 or FS::cust_pkg->count('cancel IS NULL AND
445 locationnum = '.$locationnum)
447 $self->disabled('Y');
454 Takes a new L<FS::cust_location> object. Moves all packages that use the
455 existing location to the new one, then sets the "disabled" flag on the old
456 location. Returns nothing on success, an error message on error.
464 warn "move_to:\nFROM:".Dumper($old)."\nTO:".Dumper($new) if $DEBUG;
466 local $SIG{HUP} = 'IGNORE';
467 local $SIG{INT} = 'IGNORE';
468 local $SIG{QUIT} = 'IGNORE';
469 local $SIG{TERM} = 'IGNORE';
470 local $SIG{TSTP} = 'IGNORE';
471 local $SIG{PIPE} = 'IGNORE';
473 my $oldAutoCommit = $FS::UID::AutoCommit;
474 local $FS::UID::AutoCommit = 0;
478 # prevent this from failing because of pkg_svc quantity limits
479 local( $FS::cust_svc::ignore_quantity ) = 1;
481 if ( !$new->locationnum ) {
482 $error = $new->insert;
484 $dbh->rollback if $oldAutoCommit;
485 return "Error creating location: $error";
487 } elsif ( $new->locationnum == $old->locationnum ) {
488 # then they're the same location; the normal result of doing a minor
490 $dbh->commit if $oldAutoCommit;
494 # find all packages that have the old location as their service address,
495 # and aren't canceled,
496 # and aren't supplemental to another package.
497 my @pkgs = qsearch('cust_pkg', {
498 'locationnum' => $old->locationnum,
502 foreach my $cust_pkg (@pkgs) {
503 # don't move one-time charges that have already been charged
504 next if $cust_pkg->part_pkg->freq eq '0'
505 and ($cust_pkg->setup || 0) > 0;
507 $error = $cust_pkg->change(
508 'locationnum' => $new->locationnum,
511 if ( $error and not ref($error) ) {
512 $dbh->rollback if $oldAutoCommit;
513 return "Error moving pkgnum ".$cust_pkg->pkgnum.": $error";
517 $error = $old->disable_if_unused;
519 $dbh->rollback if $oldAutoCommit;
520 return "Error disabling old location: $error";
523 $dbh->commit if $oldAutoCommit;
529 Attempts to parse data for location_type and location_number from address1
537 return '' if $self->get('location_type')
538 || $self->get('location_number');
541 if ( 1 ) { #ikano, switch on via config
542 { no warnings 'void';
543 eval { 'use FS::part_export::ikano;' };
546 %parse = FS::part_export::ikano->location_types_parse;
551 foreach my $from ('address1', 'address2') {
552 foreach my $parse ( keys %parse ) {
553 my $value = $self->get($from);
554 if ( $value =~ s/(^|\W+)$parse\W+(\w+)\W*$//i ) {
555 $self->set('location_type', $parse{$parse});
556 $self->set('location_number', $2);
557 $self->set($from, $value);
563 #nothing matched, no changes
564 $self->get('address2')
565 ? "Can't parse unit type and number from address2"
571 Moves data from location_type and location_number to the end of address1.
578 #false laziness w/geocode_Mixin.pm::line
579 my $lt = $self->get('location_type');
583 if ( 1 ) { #ikano, switch on via config
584 { no warnings 'void';
585 eval { 'use FS::part_export::ikano;' };
588 %location_type = FS::part_export::ikano->location_types;
590 %location_type = (); #?
593 $self->address1( $self->address1. ' '. $location_type{$lt} || $lt );
594 $self->location_type('');
597 if ( length($self->location_number) ) {
598 $self->address1( $self->address1. ' '. $self->location_number );
599 $self->location_number('');
607 Returns the label of the location object, with an optional site ID
608 string (based on the cust_location-label_prefix config option).
613 my( $self, %opt ) = @_;
615 my $cust_or_prospect = $opt{cust_main} || $opt{prospect_main};
616 unless ( $cust_or_prospect ) {
617 if ( $self->custnum ) {
618 $cust_or_prospect = FS::cust_main->by_key($self->custnum);
619 } elsif ( $self->prospectnum ) {
620 $cust_or_prospect = FS::prospect_main->by_key($self->prospectnum);
625 if ( $label_prefix eq 'CoStAg' ) {
626 my $agent = $conf->config('cust_main-custnum-display_prefix',
627 $cust_or_prospect->agentnum)
628 || $cust_or_prospect->agent->agent;
629 # else this location is invalid
630 $prefix = uc( join('',
632 ($self->state =~ /^(..)/),
634 sprintf('%05d', $self->locationnum)
637 elsif ( ( $opt{'cust_main'} || $self->custnum )
638 && $self->locationnum == $cust_or_prospect->ship_locationnum ) {
639 $prefix = 'Default service location';
642 $prefix .= ($opt{join_string} || ': ') if $prefix;
643 $prefix . $self->SUPER::location_label(%opt);
646 =item county_state_county
648 Returns a string consisting of just the county, state and country.
652 sub county_state_country {
654 my $label = $self->country;
655 $label = $self->state.", $label" if $self->state;
656 $label = $self->county." County, $label" if $self->county;
666 return '' unless $self->custnum;
667 qsearchs('cust_main', { 'custnum' => $self->custnum } );
674 =item in_county_sql OPTIONS
676 Returns an SQL expression to test membership in a cust_main_county
677 geographic area. By default, this requires district, city, county,
678 state, and country to match exactly. Pass "ornull => 1" to allow
679 partial matches where some fields are NULL in the cust_main_county
680 record but not in the location.
682 Pass "param => 1" to receive a parameterized expression (rather than
683 one that requires a join to cust_main_county) and a list of parameter
689 # replaces FS::cust_pkg::location_sql
690 my ($class, %opt) = @_;
691 my $ornull = $opt{ornull} ? ' OR ? IS NULL' : '';
692 my $x = $ornull ? 3 : 2;
693 my @fields = (('district') x 3,
699 my $text = (driver_name =~ /^mysql/i) ? 'char' : 'text';
702 "cust_location.district = ? OR ? = '' OR CAST(? AS $text) IS NULL",
703 "cust_location.city = ? OR ? = '' OR CAST(? AS $text) IS NULL",
704 "cust_location.county = ? OR (? = '' AND cust_location.county IS NULL) $ornull",
705 "cust_location.state = ? OR (? = '' AND cust_location.state IS NULL ) $ornull",
706 "cust_location.country = ?"
708 my $sql = join(' AND ', map "($_)\n", @where);
710 return $sql, @fields;
713 # do the substitution here
715 $sql =~ s/\?/cust_main_county.$_/;
716 $sql =~ s/cust_main_county.$_ = ''/cust_main_county.$_ IS NULL/;
728 =item process_censustract_update LOCATIONNUM
730 Queueable function to update the census tract to the current year (as set in
731 the 'census_year' configuration variable) and retrieve the new tract code.
735 sub process_censustract_update {
736 eval "use FS::GeocodeCache";
738 my $locationnum = shift;
740 qsearchs( 'cust_location', { locationnum => $locationnum })
741 or die "locationnum '$locationnum' not found!\n";
743 my $new_year = $conf->config('census_year') or return;
744 my $loc = FS::GeocodeCache->new( $cust_location->location_hash );
745 $loc->set_censustract;
746 my $error = $loc->get('censustract_error');
747 die $error if $error;
748 $cust_location->set('censustract', $loc->get('censustract'));
749 $cust_location->set('censusyear', $new_year);
750 $error = $cust_location->replace;
751 die $error if $error;
755 =item process_set_coord
757 Queueable function to find and fill in coordinates for all locations that
758 lack them. Because this uses the Google Maps API, it's internally rate
759 limited and must run in a single process.
763 sub process_set_coord {
765 # avoid starting multiple instances of this job
766 my @others = qsearch('queue', {
767 'status' => 'locked',
769 'jobnum' => {op=>'!=', value=>$job->jobnum},
773 $job->update_statustext('finding locations to update');
774 my @missing_coords = qsearch('cust_location', {
780 my $n = scalar @missing_coords;
781 for my $cust_location (@missing_coords) {
782 $cust_location->set_coord;
783 my $error = $cust_location->replace;
785 warn "error geocoding location#".$cust_location->locationnum.": $error\n";
788 $job->update_statustext("updated $i / $n locations");
789 dbh->commit; # so that we don't have to wait for the whole thing to finish
790 # Rate-limit to stay under the Google Maps usage limit (2500/day).
791 # 86,400 / 35 = 2,468 lookups per day.
796 die "failed to update ".$n-$i." locations\n";
801 =item process_standardize [ LOCATIONNUMS ]
803 Performs address standardization on locations with unclean addresses,
804 using whatever method you have configured. If the standardize_* method
805 returns a I<clean> address match, the location will be updated. This is
806 always an in-place update (because the physical location is the same,
807 and is just being referred to by a more accurate name).
809 Disabled locations will be skipped, as nobody cares.
811 If any LOCATIONNUMS are provided, only those locations will be updated.
815 sub process_standardize {
817 my @others = qsearch('queue', {
818 'status' => 'locked',
820 'jobnum' => {op=>'!=', value=>$job->jobnum},
823 my @locationnums = grep /^\d+$/, @_;
824 my $where = "AND locationnum IN(".join(',',@locationnums).")"
825 if scalar(@locationnums);
826 my @locations = qsearch({
827 table => 'cust_location',
828 hashref => { addr_clean => '', disabled => '' },
831 my $n_todo = scalar(@locations);
836 eval "use Text::CSV";
837 open $log, '>', "$FS::UID::cache_dir/process_standardize-" .
838 time2str('%Y%m%d',time) .
840 my $csv = Text::CSV->new({binary => 1, eol => "\n"});
842 foreach my $cust_location (@locations) {
843 $job->update_statustext( int(100 * $n_done/$n_todo) . ",$n_done / $n_todo locations" ) if $job;
844 my $result = FS::GeocodeCache->standardize($cust_location);
845 if ( $result->{addr_clean} and !$result->{error} ) {
846 my @cols = ($cust_location->locationnum);
847 foreach (keys %$result) {
848 push @cols, $cust_location->get($_), $result->{$_};
849 $cust_location->set($_, $result->{$_});
851 # bypass immutable field restrictions
852 my $error = $cust_location->FS::Record::replace;
853 warn "location ".$cust_location->locationnum.": $error\n" if $error;
854 $csv->print($log, \@cols);
857 dbh->commit; # so that we can resume if interrupted
866 L<FS::cust_main_county>, L<FS::cust_pkg>, L<FS::Record>,
867 schema.html from the base documentation.