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