560736d4f9c7f37a699ac57a106a171b462e769c
[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 = 
21       qw( address1 address2 city county state zip country district
22         latitude longitude coord_auto censustract censusyear geocode
23         addr_clean );
24
25     foreach my $f (@location_fields) {
26       *{"FS::cust_main::Location::$f"} = sub {
27         carp "WARNING: tried to set cust_main.$f with accessor" if (@_ > 1);
28         my $l = shift->bill_location;
29         $l ? $l->$f : '';
30       };
31       *{"FS::cust_main::Location::ship_$f"} = sub {
32         carp "WARNING: tried to set cust_main.ship_$f with accessor" if (@_ > 1);
33         my $l = shift->ship_location;
34         $l ? $l->$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   eval "use FS::contact;
130         use FS::contact_class;
131         use FS::contact_phone;
132         use FS::phone_type";
133
134   local $FS::cust_location::import = 1;
135   local $DEBUG = 0;
136   my $error;
137
138   # Step 0: set up contact classes and phone types
139   my $service_contact_class = 
140     qsearchs('contact_class', { classname => 'Service'})
141     || new FS::contact_class { classname => 'Service'};
142
143   if ( !$service_contact_class->classnum ) {
144     warn "Creating service contact class.\n";
145     $error = $service_contact_class->insert;
146     die "error creating contact class for Service: $error" if $error;
147   }
148   my %phone_type = ( # fudge slightly
149     daytime => 'Work',
150     night   => 'Home',
151     mobile  => 'Mobile',
152     fax     => 'Fax'
153   );
154   my $w = 10;
155   foreach (keys %phone_type) {
156     $phone_type{$_} = qsearchs('phone_type', { typename => $phone_type{$_}})
157                       || new FS::phone_type  { typename => $phone_type{$_},
158                                                weight   => $w };
159     # just in case someone still doesn't have these
160     if ( !$phone_type{$_}->phonetypenum ) {
161       $error = $phone_type{$_}->insert;
162       die "error creating phone type '$_': $error" if $error;
163     }
164   }
165
166   my $num_to_upgrade = FS::cust_main->count('bill_locationnum is null or ship_locationnum is null');
167   my $num_jobs = FS::queue->count('job = \'FS::cust_main::Location::process_upgrade_location\' and status != \'failed\'');
168   if ( $num_to_upgrade > 0 ) {
169     warn "Need to migrate $num_to_upgrade customer locations.\n";
170     if ( $num_jobs > 0 ) {
171       warn "Upgrade already queued.\n";
172     } else {
173       warn "Scheduling upgrade.\n";
174       my $job = FS::queue->new({ job => 'FS::cust_main::Location::process_upgrade_location' });
175       $job->insert;
176     }
177
178   }
179
180   # repair an error in earlier upgrades
181   if (!FS::upgrade_journal->is_done('cust_location_censustract_repair')
182        and FS::Conf->new->exists('cust_main-require_censustract') ) {
183
184     foreach my $cust_location (
185       qsearch('cust_location', { 'censustract' => '' })
186     ) {
187       my $custnum = $cust_location->custnum;
188       next if !$custnum; # avoid doing this for prospect locations
189       my $address1 = $cust_location->address1;
190       # find the last history record that had that address
191       my $last_h = qsearchs({
192           table     => 'h_cust_main',
193           extra_sql => " WHERE custnum = $custnum AND address1 = ".
194                         dbh->quote($address1) .
195                         " AND censustract IS NOT NULL",
196           order_by  => " ORDER BY history_date DESC LIMIT 1",
197       });
198       if (!$last_h) {
199         # this is normal; just means it never had a census tract before
200         next;
201       }
202       $cust_location->set('censustract' => $last_h->get('censustract'));
203       $cust_location->set('censusyear'  => $last_h->get('censusyear'));
204       my $error = $cust_location->replace;
205       warn "Error setting census tract for customer #$custnum:\n  $error\n"
206         if $error;
207     } # foreach $cust_location
208     FS::upgrade_journal->set_done('cust_location_censustract_repair');
209   }
210 }
211
212 sub process_upgrade_location {
213   my $class = shift;
214
215   my $dbh = dbh;
216   local $FS::cust_location::import = 1;
217   local $FS::UID::AutoCommit = 0;
218
219   my $tax_prefix = 'bill_';
220   if ( FS::Conf->new->exists('tax-ship_address') ) {
221     $tax_prefix = 'ship_';
222   }
223
224   # load some records that were created during the initial upgrade
225   my $service_contact_class = 
226     qsearchs('contact_class', { classname => 'Service'});
227
228   my %phone_type = (
229     daytime => 'Work',
230     night   => 'Home',
231     mobile  => 'Mobile',
232     fax     => 'Fax'
233   );
234   foreach (keys %phone_type) {
235     $phone_type{$_} = qsearchs('phone_type', { typename => $phone_type{$_}});
236   }
237
238   my %opt = (
239     tax_prefix            => $tax_prefix,
240     service_contact_class => $service_contact_class,
241     phone_type            => \%phone_type,
242   );
243
244   my $search = FS::Cursor->new('cust_main',
245                         { bill_locationnum => '',
246                           address1         => { op=>'!=', value=>'' }
247                         });
248   while (my $cust_main = $search->fetch) {
249     my $error = $cust_main->upgrade_location(%opt);
250     if ( $error ) {
251       warn "cust#".$cust_main->custnum.": $error\n";
252       $dbh->rollback;
253     } else {
254       # commit as we go
255       $dbh->commit;
256     }
257   }
258 }
259
260 sub upgrade_location { # instance method
261   my $cust_main = shift;
262   my %opt = @_;
263   my $error;
264
265   # Step 1: extract billing and service addresses into cust_location
266   my $custnum = $cust_main->custnum;
267   my $bill_location = FS::cust_location->new(
268     {
269       custnum => $custnum,
270       map { $_ => $cust_main->get($_) } location_fields(),
271     }
272   );
273   $bill_location->set('censustract', '');
274   $bill_location->set('censusyear', '');
275    # properly goes with ship_location; if they're the same, will be set
276    # on ship_location before inserting either one
277   my $ship_location = $bill_location; # until proven otherwise
278
279   if ( $cust_main->get('ship_address1') ) {
280     # detect duplicates
281     my $same = 1;
282     foreach (location_fields()) {
283       if ( length($cust_main->get("ship_$_")) and
284            $cust_main->get($_) ne $cust_main->get("ship_$_") ) {
285         $same = 0;
286       }
287     }
288
289     if ( !$same ) {
290       $ship_location = FS::cust_location->new(
291         {
292           custnum => $custnum,
293           map { $_ => $cust_main->get("ship_$_") } location_fields()
294         }
295       );
296     } # else it stays equal to $bill_location
297
298     # Step 2: Extract shipping address contact fields into contact
299     my %unlike = map { $_ => 1 }
300       grep { $cust_main->get($_) ne $cust_main->get("ship_$_") }
301       qw( last first company daytime night fax mobile );
302
303     if ( %unlike ) {
304       # then there IS a service contact
305       my $contact = FS::contact->new({
306         'custnum'     => $custnum,
307         'classnum'    => $opt{service_contact_class}->classnum,
308         'locationnum' => $ship_location->locationnum,
309         'last'        => $cust_main->get('ship_last'),
310         'first'       => $cust_main->get('ship_first'),
311       });
312       if ( !$cust_main->get('ship_last') or !$cust_main->get('ship_first') )
313       {
314         warn "customer $custnum has no service contact name; substituting ".
315              "customer name\n";
316         $contact->set('last' => $cust_main->get('last'));
317         $contact->set('first' => $cust_main->get('first'));
318       }
319
320       if ( $unlike{'company'} ) {
321         # there's no contact.company field, but keep a record of it
322         $contact->set(comment => 'Company: '.$cust_main->get('ship_company'));
323       }
324       $error = $contact->insert;
325       return "error migrating service contact for customer $custnum: $error"
326         if $error;
327
328       foreach ( grep { $unlike{$_} } qw( daytime night fax mobile ) ) {
329         my $phone = $cust_main->get("ship_$_");
330         next if !$phone;
331         my $contact_phone = FS::contact_phone->new({
332           'contactnum'    => $contact->contactnum,
333           'phonetypenum'  => $opt{phone_type}->{$_}->phonetypenum,
334           FS::contact::_parse_phonestring( $phone )
335         });
336         $error = $contact_phone->insert;
337         return "error migrating service contact phone for customer $custnum: $error"
338           if $error;
339         $cust_main->set("ship_$_" => '');
340       }
341
342       $cust_main->set("ship_$_" => '') foreach qw(last first company);
343     } #if %unlike
344   } #if ship_address1
345
346   # special case: should go with whichever location is used to calculate
347   # taxes, because that's the one it originally came from
348   if ( my $geocode = $cust_main->get('geocode') ) {
349     $bill_location->set('geocode' => '');
350     $ship_location->set('geocode' => '');
351
352     if ( $opt{tax_prefix} eq 'bill_' ) {
353       $bill_location->set('geocode', $geocode);
354     } elsif ( $opt{tax_prefix} eq 'ship_' ) {
355       $ship_location->set('geocode', $geocode);
356     }
357   }
358
359   # this always goes with the ship_location (whether it's the same as
360   # bill_location or not)
361   $ship_location->set('censustract', $cust_main->get('censustract'));
362   $ship_location->set('censusyear',  $cust_main->get('censusyear'));
363
364   $error = $bill_location->insert;
365   return "error migrating billing address for customer $custnum: $error"
366     if $error;
367
368   $cust_main->set(bill_locationnum => $bill_location->locationnum);
369
370   if (!$ship_location->locationnum) {
371     $error = $ship_location->insert;
372     return "error migrating service address for customer $custnum: $error"
373       if $error;
374   }
375
376   $cust_main->set(ship_locationnum => $ship_location->locationnum);
377
378   # Step 3: Wipe the migrated fields and update the cust_main
379
380   $cust_main->set("ship_$_" => '') foreach location_fields();
381   $cust_main->set($_ => '') foreach location_fields();
382
383   $error = $cust_main->replace;
384   return "error migrating addresses for customer $custnum: $error"
385     if $error;
386
387   # Step 4: set packages at the "default service location" to ship_location
388   my $pkg_search =
389     FS::Cursor->new('cust_pkg', { custnum => $custnum, locationnum => '' });
390   while (my $cust_pkg = $pkg_search->fetch) {
391     # not a location change
392     $cust_pkg->set('locationnum', $cust_main->ship_locationnum);
393     $error = $cust_pkg->replace;
394     return "error migrating package ".$cust_pkg->pkgnum.": $error"
395       if $error;
396   }
397   '';
398
399 }
400
401
402 =back
403
404 =cut
405
406 1;