4 use base qw( FS::Record );
5 use FS::Record qw( qsearch qsearchs );
6 use Locale::SubCountry;
10 FS::state - Object methods for state/province records
16 $record = new FS::state \%hash;
17 $record = new FS::state { 'column' => 'value' };
19 $error = $record->insert;
21 $error = $new_record->replace($old_record);
23 $error = $record->delete;
25 $error = $record->check;
29 An FS::state object represents a state, province, or other top-level
30 subdivision of a sovereign nation. FS::state inherits from FS::Record.
31 The following fields are currently supported:
41 two-letter country code
45 state code/abbreviation/name (as used in cust_location.state)
49 FIPS 10-4 code (not including country code)
57 sub table { 'state'; }
59 # no external API; this table maintains itself
65 $self->ut_numbern('statenum')
66 || $self->ut_alpha('country')
67 || $self->ut_alpha('state')
68 || $self->ut_alpha('fips')
70 return $error if $error;
80 warn "Updating state and country codes...\n";
82 foreach my $state (qsearch('state')) {
83 $existing{$state->country} ||= {};
84 $existing{$state->country}{$state->state} = $state;
86 my $world = Locale::SubCountry::World->new;
87 foreach my $country_code ($world->all_codes) {
88 my $country = Locale::SubCountry->new($country_code);
89 next unless $country->has_sub_countries;
90 $existing{$country} ||= {};
91 foreach my $state_code ($country->all_codes) {
92 my $fips = $country->FIPS10_4_code($state_code);
93 # we really only need U.S. state codes at this point, so if there's
94 # no FIPS code, ignore it.
95 next if !$fips or $fips eq 'unknown' or $fips =~ /\W/;
96 my $this_state = $existing{$country_code}{$state_code};
98 if ($this_state->fips ne $fips) { # this should never happen...
99 $this_state->set(fips => $fips);
100 my $error = $this_state->replace;
101 die "error updating $country_code/$state_code:\n$error\n" if $error;
103 delete $existing{$country_code}{$state_code};
105 $this_state = FS::state->new({
106 country => $country_code,
107 state => $state_code,
110 my $error = $this_state->insert;
111 die "error inserting $country_code/$state_code:\n$error\n" if $error;
114 # clean up states that no longer exist (does this ever happen?)
115 foreach my $state (values %{ $existing{$country_code} }) {
116 my $error = $state->delete;
117 die "error removing expired state ".$state->country.'/'.$state->state.
118 "\n$error\n" if $error;
120 } # foreach $country_code