user-defined site ID / location codes per location, RT#30856, RT#27545
[freeside.git] / FS / FS / cust_main / Location.pm
1 package FS::cust_main::Location;
2
3 use strict;
4 use vars qw( $DEBUG $me @location_fields );
5 use FS::Record qw(qsearch qsearchs);
6 use FS::UID qw(dbh);
7 use FS::Cursor;
8 use FS::cust_location;
9
10 use Carp qw(carp);
11
12 $DEBUG = 0;
13 $me = '[FS::cust_main::Location]';
14
15 my $init = 0;
16 BEGIN {
17   # set up accessors for location fields
18   if (!$init) {
19     no strict 'refs';
20     @location_fields = qw(
21       locationname
22       address1 address2 city county state zip country
23       district latitude longitude coord_auto censustract censusyear geocode
24       addr_clean
25     );
26
27     foreach my $f (@location_fields) {
28       *{"FS::cust_main::Location::$f"} = sub {
29         carp "WARNING: tried to set cust_main.$f with accessor" if (@_ > 1);
30         my $l = shift->bill_location;
31         $l ? $l->$f : '';
32       };
33       *{"FS::cust_main::Location::ship_$f"} = sub {
34         carp "WARNING: tried to set cust_main.ship_$f with accessor" if (@_ > 1);
35         my $l = shift->ship_location;
36         $l ? $l->$f : '';
37       };
38     }
39     $init++;
40   }
41 }
42
43 #debugging shim--probably a performance hit, so remove this at some point
44 sub get {
45   my $self = shift;
46   my $field = shift;
47   if ( $DEBUG and grep (/^(ship_)?($field)$/, @location_fields) ) {
48     carp "WARNING: tried to get() location field $field";
49     $self->$field;
50   }
51   $self->FS::Record::get($field);
52 }
53
54 =head1 NAME
55
56 FS::cust_main::Location - Location-related methods for cust_main
57
58 =head1 DESCRIPTION
59
60 These methods are available on FS::cust_main objects;
61
62 =head1 METHODS
63
64 =over 4
65
66 =item bill_location
67
68 Returns an L<FS::cust_location> object for the customer's billing address.
69
70 =cut
71
72 sub bill_location {
73   my $self = shift;
74   $self->hashref->{bill_location} 
75     ||= FS::cust_location->by_key($self->bill_locationnum)
76     # degraded mode--let the system keep running during upgrades
77     ||  FS::cust_location->new({
78         map { $_ => $self->get($_) } @location_fields
79       })
80 }
81
82 =item ship_location
83
84 Returns an L<FS::cust_location> object for the customer's service address.
85
86 =cut
87
88 sub ship_location {
89   my $self = shift;
90   $self->hashref->{ship_location}
91     ||= FS::cust_location->by_key($self->ship_locationnum)
92     ||  FS::cust_location->new({
93         map { $_ => $self->get('ship_'.$_) || $self->get($_) } @location_fields
94       })
95
96 }
97
98 =item location TYPE
99
100 An alternative way of saying "bill_location or ship_location, depending on 
101 if TYPE is 'bill' or 'ship'".
102
103 =cut
104
105 sub location {
106   my $self = shift;
107   return $self->bill_location if $_[0] eq 'bill';
108   return $self->ship_location if $_[0] eq 'ship';
109   die "bad location type '$_[0]'";
110 }
111
112 =back
113
114 =head1 CLASS METHODS
115
116 =over 4
117
118 =item location_fields
119
120 Returns a list of fields found in the location objects.  All of these fields
121 can be read (but not written) by calling them as methods on the 
122 L<FS::cust_main> object (prefixed with 'ship_' for the service address 
123 fields).
124
125 =cut
126
127 sub location_fields { @location_fields }
128
129 sub _upgrade_data {
130   my $class = shift;
131   my %opt = @_;
132
133   eval "use FS::contact;
134         use FS::contact_class;
135         use FS::contact_phone;
136         use FS::phone_type";
137
138   local $FS::cust_location::import = 1;
139   local $DEBUG = 0;
140   my $error;
141
142   # Step 0: set up contact classes and phone types
143   my $service_contact_class = 
144     qsearchs('contact_class', { classname => 'Service'})
145     || new FS::contact_class { classname => 'Service'};
146
147   if ( !$service_contact_class->classnum ) {
148     warn "Creating service contact class.\n";
149     $error = $service_contact_class->insert;
150     die "error creating contact class for Service: $error" if $error;
151   }
152   my %phone_type = ( # fudge slightly
153     daytime => 'Work',
154     night   => 'Home',
155     mobile  => 'Mobile',
156     fax     => 'Fax'
157   );
158   my $w = 10;
159   foreach (keys %phone_type) {
160     $phone_type{$_} = qsearchs('phone_type', { typename => $phone_type{$_}})
161                       || new FS::phone_type  { typename => $phone_type{$_},
162                                                weight   => $w };
163     # just in case someone still doesn't have these
164     if ( !$phone_type{$_}->phonetypenum ) {
165       $error = $phone_type{$_}->insert;
166       die "error creating phone type '$_': $error" if $error;
167     }
168   }
169
170   my $num_to_upgrade = FS::cust_main->count('bill_locationnum is null or ship_locationnum is null');
171   my $num_jobs = FS::queue->count('job = \'FS::cust_main::Location::process_upgrade_location\' and status != \'failed\'');
172   if ( $num_to_upgrade > 0 ) {
173     warn "Need to migrate $num_to_upgrade customer locations.\n";
174
175     if ( $opt{queue} ) {
176       if ( $num_jobs > 0 ) {
177         warn "Upgrade already queued.\n";
178       } else {
179         warn "Scheduling upgrade.\n";
180         my $job = FS::queue->new({ job => 'FS::cust_main::Location::process_upgrade_location' });
181         $job->insert;
182       }
183     } else { #do it now
184       process_upgrade_location();
185     }
186
187   }
188
189   # repair an error in earlier upgrades
190   if (!FS::upgrade_journal->is_done('cust_location_censustract_repair')
191        and FS::Conf->new->exists('cust_main-require_censustract') ) {
192
193     foreach my $cust_location (
194       qsearch('cust_location', { 'censustract' => '' })
195     ) {
196       my $custnum = $cust_location->custnum;
197       next if !$custnum; # avoid doing this for prospect locations
198       my $address1 = $cust_location->address1;
199       # find the last history record that had that address
200       my $last_h = qsearchs({
201           table     => 'h_cust_main',
202           extra_sql => " WHERE custnum = $custnum AND address1 = ".
203                         dbh->quote($address1) .
204                         " AND censustract IS NOT NULL",
205           order_by  => " ORDER BY history_date DESC LIMIT 1",
206       });
207       if (!$last_h) {
208         # this is normal; just means it never had a census tract before
209         next;
210       }
211       $cust_location->set('censustract' => $last_h->get('censustract'));
212       $cust_location->set('censusyear'  => $last_h->get('censusyear'));
213       my $error = $cust_location->replace;
214       warn "Error setting census tract for customer #$custnum:\n  $error\n"
215         if $error;
216     } # foreach $cust_location
217     FS::upgrade_journal->set_done('cust_location_censustract_repair');
218   }
219 }
220
221 sub process_upgrade_location {
222   my $class = shift;
223
224   my $dbh = dbh;
225   local $FS::cust_main::import = 1;
226   local $FS::cust_location::import = 1;
227   local $FS::contact::skip_fuzzyfiles = 1;
228   local $FS::UID::AutoCommit = 0;
229
230   my $tax_prefix = 'bill_';
231   if ( FS::Conf->new->exists('tax-ship_address') ) {
232     $tax_prefix = 'ship_';
233   }
234
235   # load some records that were created during the initial upgrade
236   my $service_contact_class = 
237     qsearchs('contact_class', { classname => 'Service'});
238
239   my %phone_type = (
240     daytime => 'Work',
241     night   => 'Home',
242     mobile  => 'Mobile',
243     fax     => 'Fax'
244   );
245   foreach (keys %phone_type) {
246     $phone_type{$_} = qsearchs('phone_type', { typename => $phone_type{$_}});
247   }
248
249   my %opt = (
250     tax_prefix            => $tax_prefix,
251     service_contact_class => $service_contact_class,
252     phone_type            => \%phone_type,
253   );
254
255   my $search = FS::Cursor->new('cust_main',
256                         { bill_locationnum => '',
257                           address1         => { op=>'!=', value=>'' }
258                         });
259   while (my $cust_main = $search->fetch) {
260     my $error = $cust_main->upgrade_location(%opt);
261     if ( $error ) {
262       warn "cust#".$cust_main->custnum.": $error\n";
263       $dbh->rollback;
264     } else {
265       # commit as we go
266       $dbh->commit;
267     }
268   }
269 }
270
271 sub upgrade_location { # instance method
272   my $cust_main = shift;
273   my %opt = @_;
274   my $error;
275
276   # Step 1: extract billing and service addresses into cust_location
277   my $custnum = $cust_main->custnum;
278   my $bill_location = FS::cust_location->new(
279     {
280       custnum => $custnum,
281       map { $_ => $cust_main->get($_) } location_fields(),
282     }
283   );
284   $bill_location->set('censustract', '');
285   $bill_location->set('censusyear', '');
286    # properly goes with ship_location; if they're the same, will be set
287    # on ship_location before inserting either one
288   my $ship_location = $bill_location; # until proven otherwise
289
290   if ( $cust_main->get('ship_address1') ) {
291     # detect duplicates
292     my $same = 1;
293     foreach (location_fields()) {
294       if ( length($cust_main->get("ship_$_")) and
295            $cust_main->get($_) ne $cust_main->get("ship_$_") ) {
296         $same = 0;
297       }
298     }
299
300     if ( !$same ) {
301       $ship_location = FS::cust_location->new(
302         {
303           custnum => $custnum,
304           map { $_ => $cust_main->get("ship_$_") } location_fields()
305         }
306       );
307     } # else it stays equal to $bill_location
308
309     # Step 2: Extract shipping address contact fields into contact
310     my %unlike = map { $_ => 1 }
311       grep { $cust_main->get($_) ne $cust_main->get("ship_$_") }
312       qw( last first company daytime night fax mobile );
313
314     if ( %unlike ) {
315       # then there IS a service contact
316       my $contact = FS::contact->new({
317         'custnum'     => $custnum,
318         'classnum'    => $opt{service_contact_class}->classnum,
319         'locationnum' => $ship_location->locationnum,
320         'last'        => $cust_main->get('ship_last'),
321         'first'       => $cust_main->get('ship_first'),
322       });
323       if ( !$cust_main->get('ship_last') or !$cust_main->get('ship_first') )
324       {
325         warn "customer $custnum has no service contact name; substituting ".
326              "customer name\n";
327         $contact->set('last' => $cust_main->get('last'));
328         $contact->set('first' => $cust_main->get('first'));
329       }
330
331       if ( $unlike{'company'} ) {
332         # there's no contact.company field, but keep a record of it
333         $contact->set(comment => 'Company: '.$cust_main->get('ship_company'));
334       }
335       $error = $contact->insert;
336       return "error migrating service contact for customer $custnum: $error"
337         if $error;
338
339       foreach ( grep { $unlike{$_} } qw( daytime night fax mobile ) ) {
340         my $phone = $cust_main->get("ship_$_");
341         next if !$phone;
342         my $contact_phone = FS::contact_phone->new({
343           'contactnum'    => $contact->contactnum,
344           'phonetypenum'  => $opt{phone_type}->{$_}->phonetypenum,
345           FS::contact::_parse_phonestring( $phone )
346         });
347         $error = $contact_phone->insert;
348         return "error migrating service contact phone for customer $custnum: $error"
349           if $error;
350         $cust_main->set("ship_$_" => '');
351       }
352
353       $cust_main->set("ship_$_" => '') foreach qw(last first company);
354     } #if %unlike
355   } #if ship_address1
356
357   # special case: should go with whichever location is used to calculate
358   # taxes, because that's the one it originally came from
359   if ( my $geocode = $cust_main->get('geocode') ) {
360     $bill_location->set('geocode' => '');
361     $ship_location->set('geocode' => '');
362
363     if ( $opt{tax_prefix} eq 'bill_' ) {
364       $bill_location->set('geocode', $geocode);
365     } elsif ( $opt{tax_prefix} eq 'ship_' ) {
366       $ship_location->set('geocode', $geocode);
367     }
368   }
369
370   # this always goes with the ship_location (whether it's the same as
371   # bill_location or not)
372   $ship_location->set('censustract', $cust_main->get('censustract'));
373   $ship_location->set('censusyear',  $cust_main->get('censusyear'));
374
375   $error = $bill_location->insert;
376   return "error migrating billing address for customer $custnum: $error"
377     if $error;
378
379   $cust_main->set(bill_locationnum => $bill_location->locationnum);
380
381   if (!$ship_location->locationnum) {
382     $error = $ship_location->insert;
383     return "error migrating service address for customer $custnum: $error"
384       if $error;
385   }
386
387   $cust_main->set(ship_locationnum => $ship_location->locationnum);
388
389   # Step 3: Wipe the migrated fields and update the cust_main
390
391   $cust_main->set("ship_$_" => '') foreach location_fields();
392   $cust_main->set($_ => '') foreach location_fields();
393
394   $error = $cust_main->replace;
395   return "error migrating addresses for customer $custnum: $error"
396     if $error;
397
398   # Step 4: set packages at the "default service location" to ship_location
399   my $pkg_search =
400     FS::Cursor->new('cust_pkg', { custnum => $custnum, locationnum => '' });
401   while (my $cust_pkg = $pkg_search->fetch) {
402     # not a location change
403     $cust_pkg->set('locationnum', $cust_main->ship_locationnum);
404     $error = $cust_pkg->replace;
405     return "error migrating package ".$cust_pkg->pkgnum.": $error"
406       if $error;
407   }
408   '';
409
410 }
411
412
413 =back
414
415 =cut
416
417 1;