calculate in_transit_payments correctly for partially complete batches, #37193
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 require 5.006;
4 use strict;
5 use base qw( FS::cust_main::Packages FS::cust_main::Status
6              FS::cust_main::NationalID
7              FS::cust_main::Billing FS::cust_main::Billing_Realtime
8              FS::cust_main::Billing_Discount
9              FS::cust_main::Billing_ThirdParty
10              FS::cust_main::Location
11              FS::cust_main::Credit_Limit
12              FS::otaker_Mixin FS::payinfo_Mixin FS::cust_main_Mixin
13              FS::geocode_Mixin FS::Quotable_Mixin FS::Sales_Mixin
14              FS::o2m_Common
15              FS::Record
16            );
17 use vars qw( $DEBUG $me $conf
18              @encrypted_fields
19              $import
20              $ignore_expired_card $ignore_banned_card $ignore_illegal_zip
21              $skip_fuzzyfiles
22              @paytypes
23            );
24 use Carp;
25 use Scalar::Util qw( blessed );
26 use Time::Local qw(timelocal);
27 use Storable qw(thaw);
28 use MIME::Base64;
29 use Data::Dumper;
30 use Tie::IxHash;
31 use Digest::MD5 qw(md5_base64);
32 use Date::Format;
33 #use Date::Manip;
34 use File::Temp; #qw( tempfile );
35 use Business::CreditCard 0.28;
36 use Locale::Country;
37 use FS::UID qw( getotaker dbh driver_name );
38 use FS::Record qw( qsearchs qsearch dbdef regexp_sql );
39 use FS::Misc qw( generate_email send_email generate_ps do_print money_pretty );
40 use FS::Msgcat qw(gettext);
41 use FS::CurrentUser;
42 use FS::TicketSystem;
43 use FS::payby;
44 use FS::cust_pkg;
45 use FS::cust_svc;
46 use FS::cust_bill;
47 use FS::cust_bill_void;
48 use FS::legacy_cust_bill;
49 use FS::cust_pay;
50 use FS::cust_pay_pending;
51 use FS::cust_pay_void;
52 use FS::cust_pay_batch;
53 use FS::cust_credit;
54 use FS::cust_refund;
55 use FS::part_referral;
56 use FS::cust_main_county;
57 use FS::cust_location;
58 use FS::cust_class;
59 use FS::cust_main_exemption;
60 use FS::cust_tax_adjustment;
61 use FS::cust_tax_location;
62 use FS::agent;
63 use FS::cust_main_invoice;
64 use FS::cust_tag;
65 use FS::prepay_credit;
66 use FS::queue;
67 use FS::part_pkg;
68 use FS::part_export;
69 #use FS::cust_event;
70 use FS::type_pkgs;
71 use FS::payment_gateway;
72 use FS::agent_payment_gateway;
73 use FS::banned_pay;
74 use FS::cust_main_note;
75 use FS::cust_attachment;
76 use FS::contact;
77 use FS::Locales;
78 use FS::upgrade_journal;
79
80 # 1 is mostly method/subroutine entry and options
81 # 2 traces progress of some operations
82 # 3 is even more information including possibly sensitive data
83 $DEBUG = 0;
84 $me = '[FS::cust_main]';
85
86 $import = 0;
87 $ignore_expired_card = 0;
88 $ignore_banned_card = 0;
89
90 $skip_fuzzyfiles = 0;
91
92 @encrypted_fields = ('payinfo', 'paycvv');
93 sub nohistory_fields { ('payinfo', 'paycvv'); }
94
95 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
96
97 #ask FS::UID to run this stuff for us later
98 #$FS::UID::callback{'FS::cust_main'} = sub { 
99 install_callback FS::UID sub { 
100   $conf = new FS::Conf;
101   #yes, need it for stuff below (prolly should be cached)
102 };
103
104 sub _cache {
105   my $self = shift;
106   my ( $hashref, $cache ) = @_;
107   if ( exists $hashref->{'pkgnum'} ) {
108     #@{ $self->{'_pkgnum'} } = ();
109     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
110     $self->{'_pkgnum'} = $subcache;
111     #push @{ $self->{'_pkgnum'} },
112     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
113   }
114 }
115
116 =head1 NAME
117
118 FS::cust_main - Object methods for cust_main records
119
120 =head1 SYNOPSIS
121
122   use FS::cust_main;
123
124   $record = new FS::cust_main \%hash;
125   $record = new FS::cust_main { 'column' => 'value' };
126
127   $error = $record->insert;
128
129   $error = $new_record->replace($old_record);
130
131   $error = $record->delete;
132
133   $error = $record->check;
134
135   @cust_pkg = $record->all_pkgs;
136
137   @cust_pkg = $record->ncancelled_pkgs;
138
139   @cust_pkg = $record->suspended_pkgs;
140
141   $error = $record->bill;
142   $error = $record->bill %options;
143   $error = $record->bill 'time' => $time;
144
145   $error = $record->collect;
146   $error = $record->collect %options;
147   $error = $record->collect 'invoice_time'   => $time,
148                           ;
149
150 =head1 DESCRIPTION
151
152 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
153 FS::Record.  The following fields are currently supported:
154
155 =over 4
156
157 =item custnum
158
159 Primary key (assigned automatically for new customers)
160
161 =item agentnum
162
163 Agent (see L<FS::agent>)
164
165 =item refnum
166
167 Advertising source (see L<FS::part_referral>)
168
169 =item first
170
171 First name
172
173 =item last
174
175 Last name
176
177 =item ss
178
179 Cocial security number (optional)
180
181 =item company
182
183 (optional)
184
185 =item daytime
186
187 phone (optional)
188
189 =item night
190
191 phone (optional)
192
193 =item fax
194
195 phone (optional)
196
197 =item mobile
198
199 phone (optional)
200
201 =item payby
202
203 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
204
205 =item payinfo
206
207 Payment Information (See L<FS::payinfo_Mixin> for data format)
208
209 =item paymask
210
211 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
212
213 =item paycvv
214
215 Card Verification Value, "CVV2" (also known as CVC2 or CID), the 3 or 4 digit number on the back (or front, for American Express) of the credit card
216
217 =item paydate
218
219 Expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
220
221 =item paystart_month
222
223 Start date month (maestro/solo cards only)
224
225 =item paystart_year
226
227 Start date year (maestro/solo cards only)
228
229 =item payissue
230
231 Issue number (maestro/solo cards only)
232
233 =item payname
234
235 Name on card or billing name
236
237 =item payip
238
239 IP address from which payment information was received
240
241 =item tax
242
243 Tax exempt, empty or `Y'
244
245 =item usernum
246
247 Order taker (see L<FS::access_user>)
248
249 =item comments
250
251 Comments (optional)
252
253 =item referral_custnum
254
255 Referring customer number
256
257 =item spool_cdr
258
259 Enable individual CDR spooling, empty or `Y'
260
261 =item dundate
262
263 A suggestion to events (see L<FS::part_bill_event">) to delay until this unix timestamp
264
265 =item squelch_cdr
266
267 Discourage individual CDR printing, empty or `Y'
268
269 =item edit_subject
270
271 Allow self-service editing of ticket subjects, empty or 'Y'
272
273 =item calling_list_exempt
274
275 Do not call, empty or 'Y'
276
277 =item invoice_ship_address
278
279 Display ship_address ("Service address") on invoices for this customer, empty or 'Y'
280
281 =back
282
283 =head1 METHODS
284
285 =over 4
286
287 =item new HASHREF
288
289 Creates a new customer.  To add the customer to the database, see L<"insert">.
290
291 Note that this stores the hash reference, not a distinct copy of the hash it
292 points to.  You can ask the object for a copy with the I<hash> method.
293
294 =cut
295
296 sub table { 'cust_main'; }
297
298 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
299
300 Adds this customer to the database.  If there is an error, returns the error,
301 otherwise returns false.
302
303 Usually the customer's location will not yet exist in the database, and
304 the C<bill_location> and C<ship_location> pseudo-fields must be set to 
305 uninserted L<FS::cust_location> objects.  These will be inserted and linked
306 (in both directions) to the new customer record.  If they're references 
307 to the same object, they will become the same location.
308
309 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
310 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
311 are inserted atomicly, or the transaction is rolled back.  Passing an empty
312 hash reference is equivalent to not supplying this parameter.  There should be
313 a better explanation of this, but until then, here's an example:
314
315   use Tie::RefHash;
316   tie %hash, 'Tie::RefHash'; #this part is important
317   %hash = (
318     $cust_pkg => [ $svc_acct ],
319     ...
320   );
321   $cust_main->insert( \%hash );
322
323 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
324 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
325 expected and rollback the entire transaction; it is not necessary to call 
326 check_invoicing_list first.  The invoicing_list is set after the records in the
327 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
328 invoicing_list destination to the newly-created svc_acct.  Here's an example:
329
330   $cust_main->insert( {}, [ $email, 'POST' ] );
331
332 Currently available options are: I<depend_jobnum>, I<noexport>,
333 I<tax_exemption> and I<prospectnum>.
334
335 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
336 on the supplied jobnum (they will not run until the specific job completes).
337 This can be used to defer provisioning until some action completes (such
338 as running the customer's credit card successfully).
339
340 The I<noexport> option is deprecated.  If I<noexport> is set true, no
341 provisioning jobs (exports) are scheduled.  (You can schedule them later with
342 the B<reexport> method.)
343
344 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
345 of tax names and exemption numbers.  FS::cust_main_exemption records will be
346 created and inserted.
347
348 If I<prospectnum> is set, moves contacts and locations from that prospect.
349
350 =cut
351
352 sub insert {
353   my $self = shift;
354   my $cust_pkgs = @_ ? shift : {};
355   my $invoicing_list = @_ ? shift : '';
356   my %options = @_;
357   warn "$me insert called with options ".
358        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
359     if $DEBUG;
360
361   local $SIG{HUP} = 'IGNORE';
362   local $SIG{INT} = 'IGNORE';
363   local $SIG{QUIT} = 'IGNORE';
364   local $SIG{TERM} = 'IGNORE';
365   local $SIG{TSTP} = 'IGNORE';
366   local $SIG{PIPE} = 'IGNORE';
367
368   my $oldAutoCommit = $FS::UID::AutoCommit;
369   local $FS::UID::AutoCommit = 0;
370   my $dbh = dbh;
371
372   my $prepay_identifier = '';
373   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = (0, 0, 0, 0, 0);
374   my $payby = '';
375   if ( $self->payby eq 'PREPAY' ) {
376
377     $self->payby('BILL');
378     $prepay_identifier = $self->payinfo;
379     $self->payinfo('');
380
381     warn "  looking up prepaid card $prepay_identifier\n"
382       if $DEBUG > 1;
383
384     my $error = $self->get_prepay( $prepay_identifier,
385                                    'amount_ref'     => \$amount,
386                                    'seconds_ref'    => \$seconds,
387                                    'upbytes_ref'    => \$upbytes,
388                                    'downbytes_ref'  => \$downbytes,
389                                    'totalbytes_ref' => \$totalbytes,
390                                  );
391     if ( $error ) {
392       $dbh->rollback if $oldAutoCommit;
393       #return "error applying prepaid card (transaction rolled back): $error";
394       return $error;
395     }
396
397     $payby = 'PREP' if $amount;
398
399   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD|MCHK|PPAL)$/ ) {
400
401     $payby = $1;
402     $self->payby('BILL');
403     $amount = $self->paid;
404
405   }
406
407   # insert locations
408   foreach my $l (qw(bill_location ship_location)) {
409
410     my $loc = delete $self->hashref->{$l} or return "$l not set";
411     
412     if ( !$loc->locationnum ) {
413       # warn the location that we're going to insert it with no custnum
414       $loc->set(custnum_pending => 1);
415       warn "  inserting $l\n"
416         if $DEBUG > 1;
417       my $error = $loc->insert;
418       if ( $error ) {
419         $dbh->rollback if $oldAutoCommit;
420         my $label = $l eq 'ship_location' ? 'service' : 'billing';
421         return "$error (in $label location)";
422       }
423
424     } elsif ( $loc->prospectnum ) {
425
426       $loc->prospectnum('');
427       $loc->set(custnum_pending => 1);
428       my $error = $loc->replace;
429       if ( $error ) {
430         $dbh->rollback if $oldAutoCommit;
431         my $label = $l eq 'ship_location' ? 'service' : 'billing';
432         return "$error (moving $label location)";
433       }
434
435     } elsif ( ($loc->custnum || 0) > 0 ) {
436       # then it somehow belongs to another customer--shouldn't happen
437       $dbh->rollback if $oldAutoCommit;
438       return "$l belongs to customer ".$loc->custnum;
439     }
440     # else it already belongs to this customer 
441     # (happens when ship_location is identical to bill_location)
442
443     $self->set($l.'num', $loc->locationnum);
444
445     if ( $self->get($l.'num') eq '' ) {
446       $dbh->rollback if $oldAutoCommit;
447       return "$l not set";
448     }
449   }
450
451   warn "  inserting $self\n"
452     if $DEBUG > 1;
453
454   $self->signupdate(time) unless $self->signupdate;
455
456   $self->auto_agent_custid()
457     if $conf->config('cust_main-auto_agent_custid') && ! $self->agent_custid;
458
459   my $error = $self->SUPER::insert;
460   if ( $error ) {
461     $dbh->rollback if $oldAutoCommit;
462     #return "inserting cust_main record (transaction rolled back): $error";
463     return $error;
464   }
465
466   # now set cust_location.custnum
467   foreach my $l (qw(bill_location ship_location)) {
468     warn "  setting $l.custnum\n"
469       if $DEBUG > 1;
470     my $loc = $self->$l;
471     unless ( $loc->custnum ) {
472       $loc->set(custnum => $self->custnum);
473       $error ||= $loc->replace;
474     }
475
476     if ( $error ) {
477       $dbh->rollback if $oldAutoCommit;
478       return "error setting $l custnum: $error";
479     }
480   }
481
482   warn "  setting invoicing list\n"
483     if $DEBUG > 1;
484
485   if ( $invoicing_list ) {
486     $error = $self->check_invoicing_list( $invoicing_list );
487     if ( $error ) {
488       $dbh->rollback if $oldAutoCommit;
489       #return "checking invoicing_list (transaction rolled back): $error";
490       return $error;
491     }
492     $self->invoicing_list( $invoicing_list );
493   }
494
495   warn "  setting customer tags\n"
496     if $DEBUG > 1;
497
498   foreach my $tagnum ( @{ $self->tagnum || [] } ) {
499     my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
500                                       'custnum' => $self->custnum };
501     my $error = $cust_tag->insert;
502     if ( $error ) {
503       $dbh->rollback if $oldAutoCommit;
504       return $error;
505     }
506   }
507
508   my $prospectnum = delete $options{'prospectnum'};
509   if ( $prospectnum ) {
510
511     warn "  moving contacts and locations from prospect $prospectnum\n"
512       if $DEBUG > 1;
513
514     my $prospect_main =
515       qsearchs('prospect_main', { 'prospectnum' => $prospectnum } );
516     unless ( $prospect_main ) {
517       $dbh->rollback if $oldAutoCommit;
518       return "Unknown prospectnum $prospectnum";
519     }
520     $prospect_main->custnum($self->custnum);
521     $prospect_main->disabled('Y');
522     my $error = $prospect_main->replace;
523     if ( $error ) {
524       $dbh->rollback if $oldAutoCommit;
525       return $error;
526     }
527
528     my @contact = $prospect_main->contact;
529     my @cust_location = $prospect_main->cust_location;
530     my @qual = $prospect_main->qual;
531
532     foreach my $r ( @contact, @cust_location, @qual ) {
533       $r->prospectnum('');
534       $r->custnum($self->custnum);
535       my $error = $r->replace;
536       if ( $error ) {
537         $dbh->rollback if $oldAutoCommit;
538         return $error;
539       }
540     }
541
542   }
543
544   warn "  setting contacts\n"
545     if $DEBUG > 1;
546
547   if ( my $contact = delete $options{'contact'} ) {
548
549     foreach my $c ( @$contact ) {
550       $c->custnum($self->custnum);
551       my $error = $c->insert;
552       if ( $error ) {
553         $dbh->rollback if $oldAutoCommit;
554         return $error;
555       }
556
557     }
558
559   } elsif ( my $contact_params = delete $options{'contact_params'} ) {
560
561     my $error = $self->process_o2m( 'table'  => 'contact',
562                                     'fields' => FS::contact->cgi_contact_fields,
563                                     'params' => $contact_params,
564                                   );
565     if ( $error ) {
566       $dbh->rollback if $oldAutoCommit;
567       return $error;
568     }
569   }
570
571   warn "  setting cust_main_exemption\n"
572     if $DEBUG > 1;
573
574   my $tax_exemption = delete $options{'tax_exemption'};
575   if ( $tax_exemption ) {
576
577     $tax_exemption = { map { $_ => '' } @$tax_exemption }
578       if ref($tax_exemption) eq 'ARRAY';
579
580     foreach my $taxname ( keys %$tax_exemption ) {
581       my $cust_main_exemption = new FS::cust_main_exemption {
582         'custnum'       => $self->custnum,
583         'taxname'       => $taxname,
584         'exempt_number' => $tax_exemption->{$taxname},
585       };
586       my $error = $cust_main_exemption->insert;
587       if ( $error ) {
588         $dbh->rollback if $oldAutoCommit;
589         return "inserting cust_main_exemption (transaction rolled back): $error";
590       }
591     }
592   }
593
594   warn "  ordering packages\n"
595     if $DEBUG > 1;
596
597   $error = $self->order_pkgs( $cust_pkgs,
598                               %options,
599                               'seconds_ref'    => \$seconds,
600                               'upbytes_ref'    => \$upbytes,
601                               'downbytes_ref'  => \$downbytes,
602                               'totalbytes_ref' => \$totalbytes,
603                             );
604   if ( $error ) {
605     $dbh->rollback if $oldAutoCommit;
606     return $error;
607   }
608
609   if ( $seconds ) {
610     $dbh->rollback if $oldAutoCommit;
611     return "No svc_acct record to apply pre-paid time";
612   }
613   if ( $upbytes || $downbytes || $totalbytes ) {
614     $dbh->rollback if $oldAutoCommit;
615     return "No svc_acct record to apply pre-paid data";
616   }
617
618   if ( $amount ) {
619     warn "  inserting initial $payby payment of $amount\n"
620       if $DEBUG > 1;
621     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
622     if ( $error ) {
623       $dbh->rollback if $oldAutoCommit;
624       return "inserting payment (transaction rolled back): $error";
625     }
626   }
627
628   unless ( $import || $skip_fuzzyfiles ) {
629     warn "  queueing fuzzyfiles update\n"
630       if $DEBUG > 1;
631     $error = $self->queue_fuzzyfiles_update;
632     if ( $error ) {
633       $dbh->rollback if $oldAutoCommit;
634       return "updating fuzzy search cache: $error";
635     }
636   }
637
638   # FS::geocode_Mixin::after_insert or something?
639   if ( $conf->config('tax_district_method') and !$import ) {
640     # if anything non-empty, try to look it up
641     my $queue = new FS::queue {
642       'job'     => 'FS::geocode_Mixin::process_district_update',
643       'custnum' => $self->custnum,
644     };
645     my $error = $queue->insert( ref($self), $self->custnum );
646     if ( $error ) {
647       $dbh->rollback if $oldAutoCommit;
648       return "queueing tax district update: $error";
649     }
650   }
651
652   # cust_main exports!
653   warn "  exporting\n" if $DEBUG > 1;
654
655   my $export_args = $options{'export_args'} || [];
656
657   my @part_export =
658     map qsearch( 'part_export', {exportnum=>$_} ),
659       $conf->config('cust_main-exports'); #, $agentnum
660
661   foreach my $part_export ( @part_export ) {
662     my $error = $part_export->export_insert($self, @$export_args);
663     if ( $error ) {
664       $dbh->rollback if $oldAutoCommit;
665       return "exporting to ". $part_export->exporttype.
666              " (transaction rolled back): $error";
667     }
668   }
669
670   #foreach my $depend_jobnum ( @$depend_jobnums ) {
671   #    warn "[$me] inserting dependancies on supplied job $depend_jobnum\n"
672   #      if $DEBUG;
673   #    foreach my $jobnum ( @jobnums ) {
674   #      my $queue = qsearchs('queue', { 'jobnum' => $jobnum } );
675   #      warn "[$me] inserting dependancy for job $jobnum on $depend_jobnum\n"
676   #        if $DEBUG;
677   #      my $error = $queue->depend_insert($depend_jobnum);
678   #      if ( $error ) {
679   #        $dbh->rollback if $oldAutoCommit;
680   #        return "error queuing job dependancy: $error";
681   #      }
682   #    }
683   #  }
684   #
685   #}
686   #
687   #if ( exists $options{'jobnums'} ) {
688   #  push @{ $options{'jobnums'} }, @jobnums;
689   #}
690
691   warn "  insert complete; committing transaction\n"
692     if $DEBUG > 1;
693
694   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
695   '';
696
697 }
698
699 use File::CounterFile;
700 sub auto_agent_custid {
701   my $self = shift;
702
703   my $format = $conf->config('cust_main-auto_agent_custid');
704   my $agent_custid;
705   if ( $format eq '1YMMXXXXXXXX' ) {
706
707     my $counter = new File::CounterFile 'cust_main.agent_custid';
708     $counter->lock;
709
710     my $ym = 100000000000 + time2str('%y%m00000000', time);
711     if ( $ym > $counter->value ) {
712       $counter->{'value'} = $agent_custid = $ym;
713       $counter->{'updated'} = 1;
714     } else {
715       $agent_custid = $counter->inc;
716     }
717
718     $counter->unlock;
719
720   } else {
721     die "Unknown cust_main-auto_agent_custid format: $format";
722   }
723
724   $self->agent_custid($agent_custid);
725
726 }
727
728 =item PACKAGE METHODS
729
730 Documentation on customer package methods has been moved to
731 L<FS::cust_main::Packages>.
732
733 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
734
735 Recharges this (existing) customer with the specified prepaid card (see
736 L<FS::prepay_credit>), specified either by I<identifier> or as an
737 FS::prepay_credit object.  If there is an error, returns the error, otherwise
738 returns false.
739
740 Optionally, five scalar references can be passed as well.  They will have their
741 values filled in with the amount, number of seconds, and number of upload,
742 download, and total bytes applied by this prepaid card.
743
744 =cut
745
746 #the ref bullshit here should be refactored like get_prepay.  MyAccount.pm is
747 #the only place that uses these args
748 sub recharge_prepay { 
749   my( $self, $prepay_credit, $amountref, $secondsref, 
750       $upbytesref, $downbytesref, $totalbytesref ) = @_;
751
752   local $SIG{HUP} = 'IGNORE';
753   local $SIG{INT} = 'IGNORE';
754   local $SIG{QUIT} = 'IGNORE';
755   local $SIG{TERM} = 'IGNORE';
756   local $SIG{TSTP} = 'IGNORE';
757   local $SIG{PIPE} = 'IGNORE';
758
759   my $oldAutoCommit = $FS::UID::AutoCommit;
760   local $FS::UID::AutoCommit = 0;
761   my $dbh = dbh;
762
763   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
764
765   my $error = $self->get_prepay( $prepay_credit,
766                                  'amount_ref'     => \$amount,
767                                  'seconds_ref'    => \$seconds,
768                                  'upbytes_ref'    => \$upbytes,
769                                  'downbytes_ref'  => \$downbytes,
770                                  'totalbytes_ref' => \$totalbytes,
771                                )
772            || $self->increment_seconds($seconds)
773            || $self->increment_upbytes($upbytes)
774            || $self->increment_downbytes($downbytes)
775            || $self->increment_totalbytes($totalbytes)
776            || $self->insert_cust_pay_prepay( $amount,
777                                              ref($prepay_credit)
778                                                ? $prepay_credit->identifier
779                                                : $prepay_credit
780                                            );
781
782   if ( $error ) {
783     $dbh->rollback if $oldAutoCommit;
784     return $error;
785   }
786
787   if ( defined($amountref)  ) { $$amountref  = $amount;  }
788   if ( defined($secondsref) ) { $$secondsref = $seconds; }
789   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
790   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
791   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
792
793   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
794   '';
795
796 }
797
798 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , OPTION => VALUE ... ]
799
800 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
801 specified either by I<identifier> or as an FS::prepay_credit object.
802
803 Available options are: I<amount_ref>, I<seconds_ref>, I<upbytes_ref>, I<downbytes_ref>, and I<totalbytes_ref>.  The scalars (provided by references) will be
804 incremented by the values of the prepaid card.
805
806 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
807 check or set this customer's I<agentnum>.
808
809 If there is an error, returns the error, otherwise returns false.
810
811 =cut
812
813
814 sub get_prepay {
815   my( $self, $prepay_credit, %opt ) = @_;
816
817   local $SIG{HUP} = 'IGNORE';
818   local $SIG{INT} = 'IGNORE';
819   local $SIG{QUIT} = 'IGNORE';
820   local $SIG{TERM} = 'IGNORE';
821   local $SIG{TSTP} = 'IGNORE';
822   local $SIG{PIPE} = 'IGNORE';
823
824   my $oldAutoCommit = $FS::UID::AutoCommit;
825   local $FS::UID::AutoCommit = 0;
826   my $dbh = dbh;
827
828   unless ( ref($prepay_credit) ) {
829
830     my $identifier = $prepay_credit;
831
832     $prepay_credit = qsearchs(
833       'prepay_credit',
834       { 'identifier' => $identifier },
835       '',
836       'FOR UPDATE'
837     );
838
839     unless ( $prepay_credit ) {
840       $dbh->rollback if $oldAutoCommit;
841       return "Invalid prepaid card: ". $identifier;
842     }
843
844   }
845
846   if ( $prepay_credit->agentnum ) {
847     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
848       $dbh->rollback if $oldAutoCommit;
849       return "prepaid card not valid for agent ". $self->agentnum;
850     }
851     $self->agentnum($prepay_credit->agentnum);
852   }
853
854   my $error = $prepay_credit->delete;
855   if ( $error ) {
856     $dbh->rollback if $oldAutoCommit;
857     return "removing prepay_credit (transaction rolled back): $error";
858   }
859
860   ${ $opt{$_.'_ref'} } += $prepay_credit->$_()
861     for grep $opt{$_.'_ref'}, qw( amount seconds upbytes downbytes totalbytes );
862
863   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
864   '';
865
866 }
867
868 =item increment_upbytes SECONDS
869
870 Updates this customer's single or primary account (see L<FS::svc_acct>) by
871 the specified number of upbytes.  If there is an error, returns the error,
872 otherwise returns false.
873
874 =cut
875
876 sub increment_upbytes {
877   _increment_column( shift, 'upbytes', @_);
878 }
879
880 =item increment_downbytes SECONDS
881
882 Updates this customer's single or primary account (see L<FS::svc_acct>) by
883 the specified number of downbytes.  If there is an error, returns the error,
884 otherwise returns false.
885
886 =cut
887
888 sub increment_downbytes {
889   _increment_column( shift, 'downbytes', @_);
890 }
891
892 =item increment_totalbytes SECONDS
893
894 Updates this customer's single or primary account (see L<FS::svc_acct>) by
895 the specified number of totalbytes.  If there is an error, returns the error,
896 otherwise returns false.
897
898 =cut
899
900 sub increment_totalbytes {
901   _increment_column( shift, 'totalbytes', @_);
902 }
903
904 =item increment_seconds SECONDS
905
906 Updates this customer's single or primary account (see L<FS::svc_acct>) by
907 the specified number of seconds.  If there is an error, returns the error,
908 otherwise returns false.
909
910 =cut
911
912 sub increment_seconds {
913   _increment_column( shift, 'seconds', @_);
914 }
915
916 =item _increment_column AMOUNT
917
918 Updates this customer's single or primary account (see L<FS::svc_acct>) by
919 the specified number of seconds or bytes.  If there is an error, returns
920 the error, otherwise returns false.
921
922 =cut
923
924 sub _increment_column {
925   my( $self, $column, $amount ) = @_;
926   warn "$me increment_column called: $column, $amount\n"
927     if $DEBUG;
928
929   return '' unless $amount;
930
931   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
932                       $self->ncancelled_pkgs;
933
934   if ( ! @cust_pkg ) {
935     return 'No packages with primary or single services found'.
936            ' to apply pre-paid time';
937   } elsif ( scalar(@cust_pkg) > 1 ) {
938     #maybe have a way to specify the package/account?
939     return 'Multiple packages found to apply pre-paid time';
940   }
941
942   my $cust_pkg = $cust_pkg[0];
943   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
944     if $DEBUG > 1;
945
946   my @cust_svc =
947     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
948
949   if ( ! @cust_svc ) {
950     return 'No account found to apply pre-paid time';
951   } elsif ( scalar(@cust_svc) > 1 ) {
952     return 'Multiple accounts found to apply pre-paid time';
953   }
954   
955   my $svc_acct = $cust_svc[0]->svc_x;
956   warn "  found service svcnum ". $svc_acct->pkgnum.
957        ' ('. $svc_acct->email. ")\n"
958     if $DEBUG > 1;
959
960   $column = "increment_$column";
961   $svc_acct->$column($amount);
962
963 }
964
965 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
966
967 Inserts a prepayment in the specified amount for this customer.  An optional
968 second argument can specify the prepayment identifier for tracking purposes.
969 If there is an error, returns the error, otherwise returns false.
970
971 =cut
972
973 sub insert_cust_pay_prepay {
974   shift->insert_cust_pay('PREP', @_);
975 }
976
977 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
978
979 Inserts a cash payment in the specified amount for this customer.  An optional
980 second argument can specify the payment identifier for tracking purposes.
981 If there is an error, returns the error, otherwise returns false.
982
983 =cut
984
985 sub insert_cust_pay_cash {
986   shift->insert_cust_pay('CASH', @_);
987 }
988
989 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
990
991 Inserts a Western Union payment in the specified amount for this customer.  An
992 optional second argument can specify the prepayment identifier for tracking
993 purposes.  If there is an error, returns the error, otherwise returns false.
994
995 =cut
996
997 sub insert_cust_pay_west {
998   shift->insert_cust_pay('WEST', @_);
999 }
1000
1001 sub insert_cust_pay {
1002   my( $self, $payby, $amount ) = splice(@_, 0, 3);
1003   my $payinfo = scalar(@_) ? shift : '';
1004
1005   my $cust_pay = new FS::cust_pay {
1006     'custnum' => $self->custnum,
1007     'paid'    => sprintf('%.2f', $amount),
1008     #'_date'   => #date the prepaid card was purchased???
1009     'payby'   => $payby,
1010     'payinfo' => $payinfo,
1011   };
1012   $cust_pay->insert;
1013
1014 }
1015
1016 =item reexport
1017
1018 This method is deprecated.  See the I<depend_jobnum> option to the insert and
1019 order_pkgs methods for a better way to defer provisioning.
1020
1021 Re-schedules all exports by calling the B<reexport> method of all associated
1022 packages (see L<FS::cust_pkg>).  If there is an error, returns the error;
1023 otherwise returns false.
1024
1025 =cut
1026
1027 sub reexport {
1028   my $self = shift;
1029
1030   carp "WARNING: FS::cust_main::reexport is deprectated; ".
1031        "use the depend_jobnum option to insert or order_pkgs to delay export";
1032
1033   local $SIG{HUP} = 'IGNORE';
1034   local $SIG{INT} = 'IGNORE';
1035   local $SIG{QUIT} = 'IGNORE';
1036   local $SIG{TERM} = 'IGNORE';
1037   local $SIG{TSTP} = 'IGNORE';
1038   local $SIG{PIPE} = 'IGNORE';
1039
1040   my $oldAutoCommit = $FS::UID::AutoCommit;
1041   local $FS::UID::AutoCommit = 0;
1042   my $dbh = dbh;
1043
1044   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
1045     my $error = $cust_pkg->reexport;
1046     if ( $error ) {
1047       $dbh->rollback if $oldAutoCommit;
1048       return $error;
1049     }
1050   }
1051
1052   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1053   '';
1054
1055 }
1056
1057 =item delete [ OPTION => VALUE ... ]
1058
1059 This deletes the customer.  If there is an error, returns the error, otherwise
1060 returns false.
1061
1062 This will completely remove all traces of the customer record.  This is not
1063 what you want when a customer cancels service; for that, cancel all of the
1064 customer's packages (see L</cancel>).
1065
1066 If the customer has any uncancelled packages, you need to pass a new (valid)
1067 customer number for those packages to be transferred to, as the "new_customer"
1068 option.  Cancelled packages will be deleted.  Did I mention that this is NOT
1069 what you want when a customer cancels service and that you really should be
1070 looking at L<FS::cust_pkg/cancel>?  
1071
1072 You can't delete a customer with invoices (see L<FS::cust_bill>),
1073 statements (see L<FS::cust_statement>), credits (see L<FS::cust_credit>),
1074 payments (see L<FS::cust_pay>) or refunds (see L<FS::cust_refund>), unless you
1075 set the "delete_financials" option to a true value.
1076
1077 =cut
1078
1079 sub delete {
1080   my( $self, %opt ) = @_;
1081
1082   local $SIG{HUP} = 'IGNORE';
1083   local $SIG{INT} = 'IGNORE';
1084   local $SIG{QUIT} = 'IGNORE';
1085   local $SIG{TERM} = 'IGNORE';
1086   local $SIG{TSTP} = 'IGNORE';
1087   local $SIG{PIPE} = 'IGNORE';
1088
1089   my $oldAutoCommit = $FS::UID::AutoCommit;
1090   local $FS::UID::AutoCommit = 0;
1091   my $dbh = dbh;
1092
1093   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1094      $dbh->rollback if $oldAutoCommit;
1095      return "Can't delete a master agent customer";
1096   }
1097
1098   #use FS::access_user
1099   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1100      $dbh->rollback if $oldAutoCommit;
1101      return "Can't delete a master employee customer";
1102   }
1103
1104   tie my %financial_tables, 'Tie::IxHash',
1105     'cust_bill'      => 'invoices',
1106     'cust_statement' => 'statements',
1107     'cust_credit'    => 'credits',
1108     'cust_pay'       => 'payments',
1109     'cust_refund'    => 'refunds',
1110   ;
1111    
1112   foreach my $table ( keys %financial_tables ) {
1113
1114     my @records = $self->$table();
1115
1116     if ( @records && ! $opt{'delete_financials'} ) {
1117       $dbh->rollback if $oldAutoCommit;
1118       return "Can't delete a customer with ". $financial_tables{$table};
1119     }
1120
1121     foreach my $record ( @records ) {
1122       my $error = $record->delete;
1123       if ( $error ) {
1124         $dbh->rollback if $oldAutoCommit;
1125         return "Error deleting ". $financial_tables{$table}. ": $error\n";
1126       }
1127     }
1128
1129   }
1130
1131   my @cust_pkg = $self->ncancelled_pkgs;
1132   if ( @cust_pkg ) {
1133     my $new_custnum = $opt{'new_custnum'};
1134     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1135       $dbh->rollback if $oldAutoCommit;
1136       return "Invalid new customer number: $new_custnum";
1137     }
1138     foreach my $cust_pkg ( @cust_pkg ) {
1139       my %hash = $cust_pkg->hash;
1140       $hash{'custnum'} = $new_custnum;
1141       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1142       my $error = $new_cust_pkg->replace($cust_pkg,
1143                                          options => { $cust_pkg->options },
1144                                         );
1145       if ( $error ) {
1146         $dbh->rollback if $oldAutoCommit;
1147         return $error;
1148       }
1149     }
1150   }
1151   my @cancelled_cust_pkg = $self->all_pkgs;
1152   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1153     my $error = $cust_pkg->delete;
1154     if ( $error ) {
1155       $dbh->rollback if $oldAutoCommit;
1156       return $error;
1157     }
1158   }
1159
1160   #cust_tax_adjustment in financials?
1161   #cust_pay_pending?  ouch
1162   #cust_recon?
1163   foreach my $table (qw(
1164     cust_main_invoice cust_main_exemption cust_tag cust_attachment contact
1165     cust_location cust_main_note cust_tax_adjustment
1166     cust_pay_void cust_pay_batch queue cust_tax_exempt
1167   )) {
1168     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1169       my $error = $record->delete;
1170       if ( $error ) {
1171         $dbh->rollback if $oldAutoCommit;
1172         return $error;
1173       }
1174     }
1175   }
1176
1177   my $sth = $dbh->prepare(
1178     'UPDATE cust_main SET referral_custnum = NULL WHERE referral_custnum = ?'
1179   ) or do {
1180     my $errstr = $dbh->errstr;
1181     $dbh->rollback if $oldAutoCommit;
1182     return $errstr;
1183   };
1184   $sth->execute($self->custnum) or do {
1185     my $errstr = $sth->errstr;
1186     $dbh->rollback if $oldAutoCommit;
1187     return $errstr;
1188   };
1189
1190   #tickets
1191
1192   my $ticket_dbh = '';
1193   if ($conf->config('ticket_system') eq 'RT_Internal') {
1194     $ticket_dbh = $dbh;
1195   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1196     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1197     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1198       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1199   }
1200
1201   if ( $ticket_dbh ) {
1202
1203     my $ticket_sth = $ticket_dbh->prepare(
1204       'DELETE FROM Links WHERE Target = ?'
1205     ) or do {
1206       my $errstr = $ticket_dbh->errstr;
1207       $dbh->rollback if $oldAutoCommit;
1208       return $errstr;
1209     };
1210     $ticket_sth->execute('freeside://freeside/cust_main/'.$self->custnum)
1211       or do {
1212         my $errstr = $ticket_sth->errstr;
1213         $dbh->rollback if $oldAutoCommit;
1214         return $errstr;
1215       };
1216
1217     #check and see if the customer is the only link on the ticket, and
1218     #if so, set the ticket to deleted status in RT?
1219     #maybe someday, for now this will at least fix tickets not displaying
1220
1221   }
1222
1223   #delete the customer record
1224
1225   my $error = $self->SUPER::delete;
1226   if ( $error ) {
1227     $dbh->rollback if $oldAutoCommit;
1228     return $error;
1229   }
1230
1231   # cust_main exports!
1232
1233   #my $export_args = $options{'export_args'} || [];
1234
1235   my @part_export =
1236     map qsearch( 'part_export', {exportnum=>$_} ),
1237       $conf->config('cust_main-exports'); #, $agentnum
1238
1239   foreach my $part_export ( @part_export ) {
1240     my $error = $part_export->export_delete( $self ); #, @$export_args);
1241     if ( $error ) {
1242       $dbh->rollback if $oldAutoCommit;
1243       return "exporting to ". $part_export->exporttype.
1244              " (transaction rolled back): $error";
1245     }
1246   }
1247
1248   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1249   '';
1250
1251 }
1252
1253 =item merge NEW_CUSTNUM [ , OPTION => VALUE ... ]
1254
1255 This merges this customer into the provided new custnum, and then deletes the
1256 customer.  If there is an error, returns the error, otherwise returns false.
1257
1258 The source customer's name, company name, phone numbers, agent,
1259 referring customer, customer class, advertising source, order taker, and
1260 billing information (except balance) are discarded.
1261
1262 All packages are moved to the target customer.  Packages with package locations
1263 are preserved.  Packages without package locations are moved to a new package
1264 location with the source customer's service/shipping address.
1265
1266 All invoices, statements, payments, credits and refunds are moved to the target
1267 customer.  The source customer's balance is added to the target customer.
1268
1269 All notes, attachments, tickets and customer tags are moved to the target
1270 customer.
1271
1272 Change history is not currently moved.
1273
1274 =cut
1275
1276 sub merge {
1277   my( $self, $new_custnum, %opt ) = @_;
1278
1279   return "Can't merge a customer into self" if $self->custnum == $new_custnum;
1280
1281   my $new_cust_main = qsearchs( 'cust_main', { 'custnum' => $new_custnum } )
1282     or return "Invalid new customer number: $new_custnum";
1283
1284   return 'Access denied: "Merge customer across agents" access right required to merge into a customer of a different agent'
1285     if $self->agentnum != $new_cust_main->agentnum 
1286     && ! $FS::CurrentUser::CurrentUser->access_right('Merge customer across agents');
1287
1288   local $SIG{HUP} = 'IGNORE';
1289   local $SIG{INT} = 'IGNORE';
1290   local $SIG{QUIT} = 'IGNORE';
1291   local $SIG{TERM} = 'IGNORE';
1292   local $SIG{TSTP} = 'IGNORE';
1293   local $SIG{PIPE} = 'IGNORE';
1294
1295   my $oldAutoCommit = $FS::UID::AutoCommit;
1296   local $FS::UID::AutoCommit = 0;
1297   my $dbh = dbh;
1298
1299   if ( qsearch('agent', { 'agent_custnum' => $self->custnum } ) ) {
1300      $dbh->rollback if $oldAutoCommit;
1301      return "Can't merge a master agent customer";
1302   }
1303
1304   #use FS::access_user
1305   if ( qsearch('access_user', { 'user_custnum' => $self->custnum } ) ) {
1306      $dbh->rollback if $oldAutoCommit;
1307      return "Can't merge a master employee customer";
1308   }
1309
1310   if ( qsearch('cust_pay_pending', { 'custnum' => $self->custnum,
1311                                      'status'  => { op=>'!=', value=>'done' },
1312                                    }
1313               )
1314   ) {
1315      $dbh->rollback if $oldAutoCommit;
1316      return "Can't merge a customer with pending payments";
1317   }
1318
1319   tie my %financial_tables, 'Tie::IxHash',
1320     'cust_bill'         => 'invoices',
1321     'cust_bill_void'    => 'voided invoices',
1322     'cust_statement'    => 'statements',
1323     'cust_credit'       => 'credits',
1324     'cust_credit_void'  => 'voided credits',
1325     'cust_pay'          => 'payments',
1326     'cust_pay_void'     => 'voided payments',
1327     'cust_refund'       => 'refunds',
1328   ;
1329    
1330   foreach my $table ( keys %financial_tables ) {
1331
1332     my @records = $self->$table();
1333
1334     foreach my $record ( @records ) {
1335       $record->custnum($new_custnum);
1336       my $error = $record->replace;
1337       if ( $error ) {
1338         $dbh->rollback if $oldAutoCommit;
1339         return "Error merging ". $financial_tables{$table}. ": $error\n";
1340       }
1341     }
1342
1343   }
1344
1345   my $name = $self->ship_name; #?
1346
1347   my $locationnum = '';
1348   foreach my $cust_pkg ( $self->all_pkgs ) {
1349     $cust_pkg->custnum($new_custnum);
1350
1351     unless ( $cust_pkg->locationnum ) {
1352       unless ( $locationnum ) {
1353         my $cust_location = new FS::cust_location {
1354           $self->location_hash,
1355           'custnum' => $new_custnum,
1356         };
1357         my $error = $cust_location->insert;
1358         if ( $error ) {
1359           $dbh->rollback if $oldAutoCommit;
1360           return $error;
1361         }
1362         $locationnum = $cust_location->locationnum;
1363       }
1364       $cust_pkg->locationnum($locationnum);
1365     }
1366
1367     my $error = $cust_pkg->replace;
1368     if ( $error ) {
1369       $dbh->rollback if $oldAutoCommit;
1370       return $error;
1371     }
1372
1373     # add customer (ship) name to svc_phone.phone_name if blank
1374     my @cust_svc = $cust_pkg->cust_svc;
1375     foreach my $cust_svc (@cust_svc) {
1376       my($label, $value, $svcdb) = $cust_svc->label;
1377       next unless $svcdb eq 'svc_phone';
1378       my $svc_phone = $cust_svc->svc_x;
1379       next if $svc_phone->phone_name;
1380       $svc_phone->phone_name($name);
1381       my $error = $svc_phone->replace;
1382       if ( $error ) {
1383         $dbh->rollback if $oldAutoCommit;
1384         return $error;
1385       }
1386     }
1387
1388   }
1389
1390   #not considered:
1391   # cust_tax_exempt (texas tax exemptions)
1392   # cust_recon (some sort of not-well understood thing for OnPac)
1393
1394   #these are moved over
1395   foreach my $table (qw(
1396     cust_tag cust_location contact cust_attachment cust_main_note
1397     cust_tax_adjustment cust_pay_batch queue
1398   )) {
1399     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1400       $record->custnum($new_custnum);
1401       my $error = $record->replace;
1402       if ( $error ) {
1403         $dbh->rollback if $oldAutoCommit;
1404         return $error;
1405       }
1406     }
1407   }
1408
1409   #these aren't preserved
1410   foreach my $table (qw(
1411     cust_main_exemption cust_main_invoice
1412   )) {
1413     foreach my $record ( qsearch( $table, { 'custnum' => $self->custnum } ) ) {
1414       my $error = $record->delete;
1415       if ( $error ) {
1416         $dbh->rollback if $oldAutoCommit;
1417         return $error;
1418       }
1419     }
1420   }
1421
1422
1423   my $sth = $dbh->prepare(
1424     'UPDATE cust_main SET referral_custnum = ? WHERE referral_custnum = ?'
1425   ) or do {
1426     my $errstr = $dbh->errstr;
1427     $dbh->rollback if $oldAutoCommit;
1428     return $errstr;
1429   };
1430   $sth->execute($new_custnum, $self->custnum) or do {
1431     my $errstr = $sth->errstr;
1432     $dbh->rollback if $oldAutoCommit;
1433     return $errstr;
1434   };
1435
1436   #tickets
1437
1438   my $ticket_dbh = '';
1439   if ($conf->config('ticket_system') eq 'RT_Internal') {
1440     $ticket_dbh = $dbh;
1441   } elsif ($conf->config('ticket_system') eq 'RT_External') {
1442     my ($datasrc, $user, $pass) = $conf->config('ticket_system-rt_external_datasrc');
1443     $ticket_dbh = DBI->connect($datasrc, $user, $pass, { 'ChopBlanks' => 1 });
1444       #or die "RT_External DBI->connect error: $DBI::errstr\n";
1445   }
1446
1447   if ( $ticket_dbh ) {
1448
1449     my $ticket_sth = $ticket_dbh->prepare(
1450       'UPDATE Links SET Target = ? WHERE Target = ?'
1451     ) or do {
1452       my $errstr = $ticket_dbh->errstr;
1453       $dbh->rollback if $oldAutoCommit;
1454       return $errstr;
1455     };
1456     $ticket_sth->execute('freeside://freeside/cust_main/'.$new_custnum,
1457                          'freeside://freeside/cust_main/'.$self->custnum)
1458       or do {
1459         my $errstr = $ticket_sth->errstr;
1460         $dbh->rollback if $oldAutoCommit;
1461         return $errstr;
1462       };
1463
1464   }
1465
1466   #delete the customer record
1467
1468   my $error = $self->delete;
1469   if ( $error ) {
1470     $dbh->rollback if $oldAutoCommit;
1471     return $error;
1472   }
1473
1474   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1475   '';
1476
1477 }
1478
1479 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
1480
1481 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1482 returns the error, otherwise returns false.
1483
1484 To change the customer's address, set the pseudo-fields C<bill_location> and
1485 C<ship_location>.  The address will still only change if at least one of the
1486 address fields differs from the existing values.
1487
1488 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1489 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
1490 expected and rollback the entire transaction; it is not necessary to call 
1491 check_invoicing_list first.  Here's an example:
1492
1493   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1494
1495 Currently available options are: I<tax_exemption>.
1496
1497 The I<tax_exemption> option can be set to an arrayref of tax names or a hashref
1498 of tax names and exemption numbers.  FS::cust_main_exemption records will be
1499 deleted and inserted as appropriate.
1500
1501 =cut
1502
1503 sub replace {
1504   my $self = shift;
1505
1506   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1507               ? shift
1508               : $self->replace_old;
1509
1510   my @param = @_;
1511
1512   warn "$me replace called\n"
1513     if $DEBUG;
1514
1515   my $curuser = $FS::CurrentUser::CurrentUser;
1516   if (    $self->payby eq 'COMP'
1517        && $self->payby ne $old->payby
1518        && ! $curuser->access_right('Complimentary customer')
1519      )
1520   {
1521     return "You are not permitted to create complimentary accounts.";
1522   }
1523
1524   local($ignore_expired_card) = 1
1525     if $old->payby  =~ /^(CARD|DCRD)$/
1526     && $self->payby =~ /^(CARD|DCRD)$/
1527     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1528
1529   local($ignore_banned_card) = 1
1530     if (    $old->payby  =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
1531          || $old->payby  =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
1532     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1533
1534   return "Invoicing locale is required"
1535     if $old->locale
1536     && ! $self->locale
1537     && $conf->exists('cust_main-require_locale');
1538
1539   local $SIG{HUP} = 'IGNORE';
1540   local $SIG{INT} = 'IGNORE';
1541   local $SIG{QUIT} = 'IGNORE';
1542   local $SIG{TERM} = 'IGNORE';
1543   local $SIG{TSTP} = 'IGNORE';
1544   local $SIG{PIPE} = 'IGNORE';
1545
1546   my $oldAutoCommit = $FS::UID::AutoCommit;
1547   local $FS::UID::AutoCommit = 0;
1548   my $dbh = dbh;
1549
1550   for my $l (qw(bill_location ship_location)) {
1551     my $old_loc = $old->$l;
1552     my $new_loc = $self->$l;
1553
1554     # find the existing location if there is one
1555     $new_loc->set('custnum' => $self->custnum);
1556     my $error = $new_loc->find_or_insert;
1557     if ( $error ) {
1558       $dbh->rollback if $oldAutoCommit;
1559       return $error;
1560     }
1561     $self->set($l.'num', $new_loc->locationnum);
1562   } #for $l
1563
1564   # replace the customer record
1565   my $error = $self->SUPER::replace($old);
1566
1567   if ( $error ) {
1568     $dbh->rollback if $oldAutoCommit;
1569     return $error;
1570   }
1571
1572   # now move packages to the new service location
1573   $self->set('ship_location', ''); #flush cache
1574   if ( $old->ship_locationnum and # should only be null during upgrade...
1575        $old->ship_locationnum != $self->ship_locationnum ) {
1576     $error = $old->ship_location->move_to($self->ship_location);
1577     if ( $error ) {
1578       $dbh->rollback if $oldAutoCommit;
1579       return $error;
1580     }
1581   }
1582   # don't move packages based on the billing location, but 
1583   # disable it if it's no longer in use
1584   if ( $old->bill_locationnum and
1585        $old->bill_locationnum != $self->bill_locationnum ) {
1586     $error = $old->bill_location->disable_if_unused;
1587     if ( $error ) {
1588       $dbh->rollback if $oldAutoCommit;
1589       return $error;
1590     }
1591   }
1592
1593   if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1594     my $invoicing_list = shift @param;
1595     $error = $self->check_invoicing_list( $invoicing_list );
1596     if ( $error ) {
1597       $dbh->rollback if $oldAutoCommit;
1598       return $error;
1599     }
1600     $self->invoicing_list( $invoicing_list );
1601   }
1602
1603   if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1604
1605     #this could be more efficient than deleting and re-inserting, if it matters
1606     foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1607       my $error = $cust_tag->delete;
1608       if ( $error ) {
1609         $dbh->rollback if $oldAutoCommit;
1610         return $error;
1611       }
1612     }
1613     foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1614       my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
1615                                         'custnum' => $self->custnum };
1616       my $error = $cust_tag->insert;
1617       if ( $error ) {
1618         $dbh->rollback if $oldAutoCommit;
1619         return $error;
1620       }
1621     }
1622
1623   }
1624
1625   my %options = @param;
1626
1627   my $tax_exemption = delete $options{'tax_exemption'};
1628   if ( $tax_exemption ) {
1629
1630     $tax_exemption = { map { $_ => '' } @$tax_exemption }
1631       if ref($tax_exemption) eq 'ARRAY';
1632
1633     my %cust_main_exemption =
1634       map { $_->taxname => $_ }
1635           qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1636
1637     foreach my $taxname ( keys %$tax_exemption ) {
1638
1639       if ( $cust_main_exemption{$taxname} && 
1640            $cust_main_exemption{$taxname}->exempt_number eq $tax_exemption->{$taxname}
1641          )
1642       {
1643         delete $cust_main_exemption{$taxname};
1644         next;
1645       }
1646
1647       my $cust_main_exemption = new FS::cust_main_exemption {
1648         'custnum'       => $self->custnum,
1649         'taxname'       => $taxname,
1650         'exempt_number' => $tax_exemption->{$taxname},
1651       };
1652       my $error = $cust_main_exemption->insert;
1653       if ( $error ) {
1654         $dbh->rollback if $oldAutoCommit;
1655         return "inserting cust_main_exemption (transaction rolled back): $error";
1656       }
1657     }
1658
1659     foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1660       my $error = $cust_main_exemption->delete;
1661       if ( $error ) {
1662         $dbh->rollback if $oldAutoCommit;
1663         return "deleting cust_main_exemption (transaction rolled back): $error";
1664       }
1665     }
1666
1667   }
1668
1669   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1670        && ( ( $self->get('payinfo') ne $old->get('payinfo')
1671               && $self->get('payinfo') !~ /^99\d{14}$/ 
1672             )
1673             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1674           )
1675      )
1676   {
1677
1678     # card/check/lec info has changed, want to retry realtime_ invoice events
1679     my $error = $self->retry_realtime;
1680     if ( $error ) {
1681       $dbh->rollback if $oldAutoCommit;
1682       return $error;
1683     }
1684   }
1685
1686   unless ( $import || $skip_fuzzyfiles ) {
1687     $error = $self->queue_fuzzyfiles_update;
1688     if ( $error ) {
1689       $dbh->rollback if $oldAutoCommit;
1690       return "updating fuzzy search cache: $error";
1691     }
1692   }
1693
1694   # tax district update in cust_location
1695
1696   # cust_main exports!
1697
1698   my $export_args = $options{'export_args'} || [];
1699
1700   my @part_export =
1701     map qsearch( 'part_export', {exportnum=>$_} ),
1702       $conf->config('cust_main-exports'); #, $agentnum
1703
1704   foreach my $part_export ( @part_export ) {
1705     my $error = $part_export->export_replace( $self, $old, @$export_args);
1706     if ( $error ) {
1707       $dbh->rollback if $oldAutoCommit;
1708       return "exporting to ". $part_export->exporttype.
1709              " (transaction rolled back): $error";
1710     }
1711   }
1712
1713   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1714   '';
1715
1716 }
1717
1718 =item queue_fuzzyfiles_update
1719
1720 Used by insert & replace to update the fuzzy search cache
1721
1722 =cut
1723
1724 use FS::cust_main::Search;
1725 sub queue_fuzzyfiles_update {
1726   my $self = shift;
1727
1728   local $SIG{HUP} = 'IGNORE';
1729   local $SIG{INT} = 'IGNORE';
1730   local $SIG{QUIT} = 'IGNORE';
1731   local $SIG{TERM} = 'IGNORE';
1732   local $SIG{TSTP} = 'IGNORE';
1733   local $SIG{PIPE} = 'IGNORE';
1734
1735   my $oldAutoCommit = $FS::UID::AutoCommit;
1736   local $FS::UID::AutoCommit = 0;
1737   my $dbh = dbh;
1738
1739   foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
1740     my $queue = new FS::queue { 
1741       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1742     };
1743     my @args = "cust_main.$field", $self->get($field);
1744     my $error = $queue->insert( @args );
1745     if ( $error ) {
1746       $dbh->rollback if $oldAutoCommit;
1747       return "queueing job (transaction rolled back): $error";
1748     }
1749   }
1750
1751   my @locations = $self->bill_location;
1752   push @locations, $self->ship_location if $self->has_ship_address;
1753   foreach my $location (@locations) {
1754     my $queue = new FS::queue { 
1755       'job' => 'FS::cust_main::Search::append_fuzzyfiles_fuzzyfield'
1756     };
1757     my @args = 'cust_location.address1', $location->address1;
1758     my $error = $queue->insert( @args );
1759     if ( $error ) {
1760       $dbh->rollback if $oldAutoCommit;
1761       return "queueing job (transaction rolled back): $error";
1762     }
1763   }
1764
1765   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1766   '';
1767
1768 }
1769
1770 =item check
1771
1772 Checks all fields to make sure this is a valid customer record.  If there is
1773 an error, returns the error, otherwise returns false.  Called by the insert
1774 and replace methods.
1775
1776 =cut
1777
1778 sub check {
1779   my $self = shift;
1780
1781   warn "$me check BEFORE: \n". $self->_dump
1782     if $DEBUG > 2;
1783
1784   my $error =
1785     $self->ut_numbern('custnum')
1786     || $self->ut_number('agentnum')
1787     || $self->ut_textn('agent_custid')
1788     || $self->ut_number('refnum')
1789     || $self->ut_foreign_key('bill_locationnum', 'cust_location','locationnum')
1790     || $self->ut_foreign_key('ship_locationnum', 'cust_location','locationnum')
1791     || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1792     || $self->ut_foreign_keyn('salesnum', 'sales', 'salesnum')
1793     || $self->ut_textn('custbatch')
1794     || $self->ut_name('last')
1795     || $self->ut_name('first')
1796     || $self->ut_snumbern('signupdate')
1797     || $self->ut_snumbern('birthdate')
1798     || $self->ut_namen('spouse_last')
1799     || $self->ut_namen('spouse_first')
1800     || $self->ut_snumbern('spouse_birthdate')
1801     || $self->ut_snumbern('anniversary_date')
1802     || $self->ut_textn('company')
1803     || $self->ut_textn('ship_company')
1804     || $self->ut_anything('comments')
1805     || $self->ut_numbern('referral_custnum')
1806     || $self->ut_textn('stateid')
1807     || $self->ut_textn('stateid_state')
1808     || $self->ut_textn('invoice_terms')
1809     || $self->ut_floatn('cdr_termination_percentage')
1810     || $self->ut_floatn('credit_limit')
1811     || $self->ut_numbern('billday')
1812     || $self->ut_numbern('prorate_day')
1813     || $self->ut_flag('edit_subject')
1814     || $self->ut_flag('calling_list_exempt')
1815     || $self->ut_flag('invoice_noemail')
1816     || $self->ut_flag('message_noemail')
1817     || $self->ut_enum('locale', [ '', FS::Locales->locales ])
1818     || $self->ut_flag('invoice_ship_address')
1819   ;
1820
1821   foreach (qw(company ship_company)) {
1822     my $company = $self->get($_);
1823     $company =~ s/^\s+//; 
1824     $company =~ s/\s+$//; 
1825     $company =~ s/\s+/ /g;
1826     $self->set($_, $company);
1827   }
1828
1829   #barf.  need message catalogs.  i18n.  etc.
1830   $error .= "Please select an advertising source."
1831     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1832   return $error if $error;
1833
1834   return "Unknown agent"
1835     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1836
1837   return "Unknown refnum"
1838     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1839
1840   return "Unknown referring custnum: ". $self->referral_custnum
1841     unless ! $self->referral_custnum 
1842            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1843
1844   if ( $self->ss eq '' ) {
1845     $self->ss('');
1846   } else {
1847     my $ss = $self->ss;
1848     $ss =~ s/\D//g;
1849     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1850       or return "Illegal social security number: ". $self->ss;
1851     $self->ss("$1-$2-$3");
1852   }
1853
1854   #turn off invoice_ship_address if ship & bill are the same
1855   if ($self->bill_locationnum eq $self->ship_locationnum) {
1856     $self->invoice_ship_address('');
1857   }
1858
1859   # cust_main_county verification now handled by cust_location check
1860
1861   $error =
1862        $self->ut_phonen('daytime', $self->country)
1863     || $self->ut_phonen('night',   $self->country)
1864     || $self->ut_phonen('fax',     $self->country)
1865     || $self->ut_phonen('mobile',  $self->country)
1866   ;
1867   return $error if $error;
1868
1869   if ( $conf->exists('cust_main-require_phone', $self->agentnum)
1870        && ! $import
1871        && ! length($self->daytime) && ! length($self->night) && ! length($self->mobile)
1872      ) {
1873
1874     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1875                           ? 'Day Phone'
1876                           : FS::Msgcat::_gettext('daytime');
1877     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1878                         ? 'Night Phone'
1879                         : FS::Msgcat::_gettext('night');
1880
1881     my $mobile_label = FS::Msgcat::_gettext('mobile') =~ /^(mobile)?$/
1882                         ? 'Mobile Phone'
1883                         : FS::Msgcat::_gettext('mobile');
1884
1885     return "$daytime_label, $night_label or $mobile_label is required"
1886   
1887   }
1888
1889   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1890   #  or return "Illegal payby: ". $self->payby;
1891   #$self->payby($1);
1892   FS::payby->can_payby($self->table, $self->payby)
1893     or return "Illegal payby: ". $self->payby;
1894
1895   $error =    $self->ut_numbern('paystart_month')
1896            || $self->ut_numbern('paystart_year')
1897            || $self->ut_numbern('payissue')
1898            || $self->ut_textn('paytype')
1899   ;
1900   return $error if $error;
1901
1902   if ( $self->payip eq '' ) {
1903     $self->payip('');
1904   } else {
1905     $error = $self->ut_ip('payip');
1906     return $error if $error;
1907   }
1908
1909   # If it is encrypted and the private key is not availaible then we can't
1910   # check the credit card.
1911   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1912
1913   # Need some kind of global flag to accept invalid cards, for testing
1914   # on scrubbed data.
1915   if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1916
1917     my $payinfo = $self->payinfo;
1918     $payinfo =~ s/\D//g;
1919     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1920       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1921     $payinfo = $1;
1922     $self->payinfo($payinfo);
1923     validate($payinfo)
1924       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1925
1926     return gettext('unknown_card_type')
1927       if $self->payinfo !~ /^99\d{14}$/ #token
1928       && cardtype($self->payinfo) eq "Unknown";
1929
1930     unless ( $ignore_banned_card ) {
1931       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1932       if ( $ban ) {
1933         if ( $ban->bantype eq 'warn' ) {
1934           #or others depending on value of $ban->reason ?
1935           return '_duplicate_card'.
1936                  ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
1937                  ' until '.         time2str('%a %h %o at %r', $ban->_end_date).
1938                  ' (ban# '. $ban->bannum. ')'
1939             unless $self->override_ban_warn;
1940         } else {
1941           return 'Banned credit card: banned on '.
1942                  time2str('%a %h %o at %r', $ban->_date).
1943                  ' by '. $ban->otaker.
1944                  ' (ban# '. $ban->bannum. ')';
1945         }
1946       }
1947     }
1948
1949     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1950       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1951         $self->paycvv =~ /^(\d{4})$/
1952           or return "CVV2 (CID) for American Express cards is four digits.";
1953         $self->paycvv($1);
1954       } else {
1955         $self->paycvv =~ /^(\d{3})$/
1956           or return "CVV2 (CVC2/CID) is three digits.";
1957         $self->paycvv($1);
1958       }
1959     } else {
1960       $self->paycvv('');
1961     }
1962
1963     my $cardtype = cardtype($payinfo);
1964     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1965
1966       return "Start date or issue number is required for $cardtype cards"
1967         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1968
1969       return "Start month must be between 1 and 12"
1970         if $self->paystart_month
1971            and $self->paystart_month < 1 || $self->paystart_month > 12;
1972
1973       return "Start year must be 1990 or later"
1974         if $self->paystart_year
1975            and $self->paystart_year < 1990;
1976
1977       return "Issue number must be beween 1 and 99"
1978         if $self->payissue
1979           and $self->payissue < 1 || $self->payissue > 99;
1980
1981     } else {
1982       $self->paystart_month('');
1983       $self->paystart_year('');
1984       $self->payissue('');
1985     }
1986
1987   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1988
1989     my $payinfo = $self->payinfo;
1990     $payinfo =~ s/[^\d\@\.]//g;
1991     if ( $conf->config('echeck-country') eq 'CA' ) {
1992       $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
1993         or return 'invalid echeck account@branch.bank';
1994       $payinfo = "$1\@$2.$3";
1995     } elsif ( $conf->config('echeck-country') eq 'US' ) {
1996       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1997       $payinfo = "$1\@$2";
1998     } else {
1999       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
2000       $payinfo = "$1\@$2";
2001     }
2002     $self->payinfo($payinfo);
2003     $self->paycvv('');
2004
2005     unless ( $ignore_banned_card ) {
2006       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
2007       if ( $ban ) {
2008         if ( $ban->bantype eq 'warn' ) {
2009           #or others depending on value of $ban->reason ?
2010           return '_duplicate_ach' unless $self->override_ban_warn;
2011         } else {
2012           return 'Banned ACH account: banned on '.
2013                  time2str('%a %h %o at %r', $ban->_date).
2014                  ' by '. $ban->otaker.
2015                  ' (ban# '. $ban->bannum. ')';
2016         }
2017       }
2018     }
2019
2020   } elsif ( $self->payby eq 'LECB' ) {
2021
2022     my $payinfo = $self->payinfo;
2023     $payinfo =~ s/\D//g;
2024     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
2025     $payinfo = $1;
2026     $self->payinfo($payinfo);
2027     $self->paycvv('');
2028
2029   } elsif ( $self->payby eq 'BILL' ) {
2030
2031     $error = $self->ut_textn('payinfo');
2032     return "Illegal P.O. number: ". $self->payinfo if $error;
2033     $self->paycvv('');
2034
2035   } elsif ( $self->payby eq 'COMP' ) {
2036
2037     my $curuser = $FS::CurrentUser::CurrentUser;
2038     if (    ! $self->custnum
2039          && ! $curuser->access_right('Complimentary customer')
2040        )
2041     {
2042       return "You are not permitted to create complimentary accounts."
2043     }
2044
2045     $error = $self->ut_textn('payinfo');
2046     return "Illegal comp account issuer: ". $self->payinfo if $error;
2047     $self->paycvv('');
2048
2049   } elsif ( $self->payby eq 'PREPAY' ) {
2050
2051     my $payinfo = $self->payinfo;
2052     $payinfo =~ s/\W//g; #anything else would just confuse things
2053     $self->payinfo($payinfo);
2054     $error = $self->ut_alpha('payinfo');
2055     return "Illegal prepayment identifier: ". $self->payinfo if $error;
2056     return "Unknown prepayment identifier"
2057       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
2058     $self->paycvv('');
2059
2060   }
2061
2062   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
2063     return "Expiration date required"
2064       # shouldn't payinfo_check do this?
2065       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD|PPAL)$/;
2066     $self->paydate('');
2067   } else {
2068     my( $m, $y );
2069     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
2070       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
2071     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2072       ( $m, $y ) = ( $2, "19$1" );
2073     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
2074       ( $m, $y ) = ( $3, "20$2" );
2075     } else {
2076       return "Illegal expiration date: ". $self->paydate;
2077     }
2078     $m = sprintf('%02d',$m);
2079     $self->paydate("$y-$m-01");
2080     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
2081     return gettext('expired_card')
2082       if !$import
2083       && !$ignore_expired_card 
2084       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
2085   }
2086
2087   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
2088        ( ! $conf->exists('require_cardname')
2089          || $self->payby !~ /^(CARD|DCRD)$/  ) 
2090   ) {
2091     $self->payname( $self->first. " ". $self->getfield('last') );
2092   } else {
2093
2094     if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2095       $self->payname =~ /^([\w \,\.\-\']*)$/
2096         or return gettext('illegal_name'). " payname: ". $self->payname;
2097       $self->payname($1);
2098     } else {
2099       $self->payname =~ /^([\w \,\.\-\'\&]*)$/
2100         or return gettext('illegal_name'). " payname: ". $self->payname;
2101       $self->payname($1);
2102     }
2103
2104   }
2105
2106   return "Please select an invoicing locale"
2107     if ! $self->locale
2108     && ! $self->custnum
2109     && $conf->exists('cust_main-require_locale');
2110
2111   foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
2112     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
2113     $self->$flag($1);
2114   }
2115
2116   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2117
2118   warn "$me check AFTER: \n". $self->_dump
2119     if $DEBUG > 2;
2120
2121   $self->SUPER::check;
2122 }
2123
2124 =item replace_check
2125
2126 Additional checks for replace only.
2127
2128 =cut
2129
2130 sub replace_check {
2131   my ($new,$old) = @_;
2132   #preserve old value if global config is set
2133   if ($old && $conf->exists('invoice-ship_address')) {
2134     $new->invoice_ship_address($old->invoice_ship_address);
2135   }
2136   return '';
2137 }
2138
2139 =item addr_fields 
2140
2141 Returns a list of fields which have ship_ duplicates.
2142
2143 =cut
2144
2145 sub addr_fields {
2146   qw( last first company
2147       locationname
2148       address1 address2 city county state zip country
2149       latitude longitude
2150       daytime night fax mobile
2151     );
2152 }
2153
2154 =item has_ship_address
2155
2156 Returns true if this customer record has a separate shipping address.
2157
2158 =cut
2159
2160 sub has_ship_address {
2161   my $self = shift;
2162   $self->bill_locationnum != $self->ship_locationnum;
2163 }
2164
2165 =item location_hash
2166
2167 Returns a list of key/value pairs, with the following keys: address1, 
2168 adddress2, city, county, state, zip, country, district, and geocode.  The 
2169 shipping address is used if present.
2170
2171 =cut
2172
2173 sub location_hash {
2174   my $self = shift;
2175   $self->ship_location->location_hash;
2176 }
2177
2178 =item cust_location
2179
2180 Returns all locations (see L<FS::cust_location>) for this customer.
2181
2182 =cut
2183
2184 sub cust_location {
2185   my $self = shift;
2186   qsearch('cust_location', { 'custnum' => $self->custnum,
2187                              'prospectnum' => '' } );
2188 }
2189
2190 =item cust_contact
2191
2192 Returns all contacts (see L<FS::contact>) for this customer.
2193
2194 =cut
2195
2196 #already used :/ sub contact {
2197 sub cust_contact {
2198   my $self = shift;
2199   qsearch('contact', { 'custnum' => $self->custnum } );
2200 }
2201
2202 =item unsuspend
2203
2204 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2205 and L<FS::cust_pkg>) for this customer, except those on hold.
2206
2207 Returns a list: an empty list on success or a list of errors.
2208
2209 =cut
2210
2211 sub unsuspend {
2212   my $self = shift;
2213   grep { ($_->get('setup')) && $_->unsuspend } $self->suspended_pkgs;
2214 }
2215
2216 =item release_hold
2217
2218 Unsuspends all suspended packages in the on-hold state (those without setup 
2219 dates) for this customer. 
2220
2221 =cut
2222
2223 sub release_hold {
2224   my $self = shift;
2225   grep { (!$_->setup) && $_->unsuspend } $self->suspended_pkgs;
2226 }
2227
2228 =item suspend
2229
2230 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2231
2232 Returns a list: an empty list on success or a list of errors.
2233
2234 =cut
2235
2236 sub suspend {
2237   my $self = shift;
2238   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2239 }
2240
2241 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2242
2243 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2244 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
2245 of a list of pkgparts; the hashref has the following keys:
2246
2247 =over 4
2248
2249 =item pkgparts - listref of pkgparts
2250
2251 =item (other options are passed to the suspend method)
2252
2253 =back
2254
2255
2256 Returns a list: an empty list on success or a list of errors.
2257
2258 =cut
2259
2260 sub suspend_if_pkgpart {
2261   my $self = shift;
2262   my (@pkgparts, %opt);
2263   if (ref($_[0]) eq 'HASH'){
2264     @pkgparts = @{$_[0]{pkgparts}};
2265     %opt      = %{$_[0]};
2266   }else{
2267     @pkgparts = @_;
2268   }
2269   grep { $_->suspend(%opt) }
2270     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2271       $self->unsuspended_pkgs;
2272 }
2273
2274 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2275
2276 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2277 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
2278 instead of a list of pkgparts; the hashref has the following keys:
2279
2280 =over 4
2281
2282 =item pkgparts - listref of pkgparts
2283
2284 =item (other options are passed to the suspend method)
2285
2286 =back
2287
2288 Returns a list: an empty list on success or a list of errors.
2289
2290 =cut
2291
2292 sub suspend_unless_pkgpart {
2293   my $self = shift;
2294   my (@pkgparts, %opt);
2295   if (ref($_[0]) eq 'HASH'){
2296     @pkgparts = @{$_[0]{pkgparts}};
2297     %opt      = %{$_[0]};
2298   }else{
2299     @pkgparts = @_;
2300   }
2301   grep { $_->suspend(%opt) }
2302     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2303       $self->unsuspended_pkgs;
2304 }
2305
2306 =item cancel [ OPTION => VALUE ... ]
2307
2308 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2309
2310 Available options are:
2311
2312 =over 4
2313
2314 =item quiet - can be set true to supress email cancellation notices.
2315
2316 =item reason - can be set to a cancellation reason (see L<FS:reason>), either a reasonnum of an existing reason, or passing a hashref will create a new reason.  The hashref should have the following keys: typenum - Reason type (see L<FS::reason_type>, reason - Text of the new reason.
2317
2318 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2319
2320 =item nobill - can be set true to skip billing if it might otherwise be done.
2321
2322 =back
2323
2324 Always returns a list: an empty list on success or a list of errors.
2325
2326 =cut
2327
2328 # nb that dates are not specified as valid options to this method
2329
2330 sub cancel {
2331   my( $self, %opt ) = @_;
2332
2333   warn "$me cancel called on customer ". $self->custnum. " with options ".
2334        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2335     if $DEBUG;
2336
2337   return ( 'access denied' )
2338     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2339
2340   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2341
2342     #should try decryption (we might have the private key)
2343     # and if not maybe queue a job for the server that does?
2344     return ( "Can't (yet) ban encrypted credit cards" )
2345       if $self->is_encrypted($self->payinfo);
2346
2347     my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2348     my $error = $ban->insert;
2349     return ( $error ) if $error;
2350
2351   }
2352
2353   my @pkgs = $self->ncancelled_pkgs;
2354
2355   if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2356     $opt{nobill} = 1;
2357     my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2358     warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2359       if $error;
2360   }
2361
2362   warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2363        scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2364     if $DEBUG;
2365
2366   grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2367 }
2368
2369 sub _banned_pay_hashref {
2370   my $self = shift;
2371
2372   my %payby2ban = (
2373     'CARD' => 'CARD',
2374     'DCRD' => 'CARD',
2375     'CHEK' => 'CHEK',
2376     'DCHK' => 'CHEK'
2377   );
2378
2379   {
2380     'payby'   => $payby2ban{$self->payby},
2381     'payinfo' => $self->payinfo,
2382     #don't ever *search* on reason! #'reason'  =>
2383   };
2384 }
2385
2386 sub _new_banned_pay_hashref {
2387   my $self = shift;
2388   my $hr = $self->_banned_pay_hashref;
2389   $hr->{payinfo} = md5_base64($hr->{payinfo});
2390   $hr;
2391 }
2392
2393 =item notes
2394
2395 Returns all notes (see L<FS::cust_main_note>) for this customer.
2396
2397 =cut
2398
2399 sub notes {
2400   my($self,$orderby_classnum) = (shift,shift);
2401   my $orderby = "sticky DESC, _date DESC";
2402   $orderby = "classnum ASC, $orderby" if $orderby_classnum;
2403   qsearch( 'cust_main_note',
2404            { 'custnum' => $self->custnum },
2405            '',
2406            "ORDER BY $orderby",
2407          );
2408 }
2409
2410 =item agent
2411
2412 Returns the agent (see L<FS::agent>) for this customer.
2413
2414 =cut
2415
2416 sub agent {
2417   my $self = shift;
2418   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2419 }
2420
2421 =item agent_name
2422
2423 Returns the agent name (see L<FS::agent>) for this customer.
2424
2425 =cut
2426
2427 sub agent_name {
2428   my $self = shift;
2429   $self->agent->agent;
2430 }
2431
2432 =item cust_tag
2433
2434 Returns any tags associated with this customer, as FS::cust_tag objects,
2435 or an empty list if there are no tags.
2436
2437 =cut
2438
2439 sub cust_tag {
2440   my $self = shift;
2441   qsearch('cust_tag', { 'custnum' => $self->custnum } );
2442 }
2443
2444 =item part_tag
2445
2446 Returns any tags associated with this customer, as FS::part_tag objects,
2447 or an empty list if there are no tags.
2448
2449 =cut
2450
2451 sub part_tag {
2452   my $self = shift;
2453   map $_->part_tag, $self->cust_tag; 
2454 }
2455
2456
2457 =item cust_class
2458
2459 Returns the customer class, as an FS::cust_class object, or the empty string
2460 if there is no customer class.
2461
2462 =cut
2463
2464 sub cust_class {
2465   my $self = shift;
2466   if ( $self->classnum ) {
2467     qsearchs('cust_class', { 'classnum' => $self->classnum } );
2468   } else {
2469     return '';
2470   } 
2471 }
2472
2473 =item categoryname 
2474
2475 Returns the customer category name, or the empty string if there is no customer
2476 category.
2477
2478 =cut
2479
2480 sub categoryname {
2481   my $self = shift;
2482   my $cust_class = $self->cust_class;
2483   $cust_class
2484     ? $cust_class->categoryname
2485     : '';
2486 }
2487
2488 =item classname 
2489
2490 Returns the customer class name, or the empty string if there is no customer
2491 class.
2492
2493 =cut
2494
2495 sub classname {
2496   my $self = shift;
2497   my $cust_class = $self->cust_class;
2498   $cust_class
2499     ? $cust_class->classname
2500     : '';
2501 }
2502
2503 =item BILLING METHODS
2504
2505 Documentation on billing methods has been moved to
2506 L<FS::cust_main::Billing>.
2507
2508 =item REALTIME BILLING METHODS
2509
2510 Documentation on realtime billing methods has been moved to
2511 L<FS::cust_main::Billing_Realtime>.
2512
2513 =item remove_cvv
2514
2515 Removes the I<paycvv> field from the database directly.
2516
2517 If there is an error, returns the error, otherwise returns false.
2518
2519 =cut
2520
2521 sub remove_cvv {
2522   my $self = shift;
2523   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2524     or return dbh->errstr;
2525   $sth->execute($self->custnum)
2526     or return $sth->errstr;
2527   $self->paycvv('');
2528   '';
2529 }
2530
2531 =item batch_card OPTION => VALUE...
2532
2533 Adds a payment for this invoice to the pending credit card batch (see
2534 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2535 runs the payment using a realtime gateway.
2536
2537 Options may include:
2538
2539 B<amount>: the amount to be paid; defaults to the customer's balance minus
2540 any payments in transit.
2541
2542 B<payby>: the payment method; defaults to cust_main.payby
2543
2544 B<realtime>: runs this as a realtime payment instead of adding it to a 
2545 batch.  Deprecated.
2546
2547 B<invnum>: sets cust_pay_batch.invnum.
2548
2549 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets 
2550 the billing address for the payment; defaults to the customer's billing
2551 location.
2552
2553 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
2554 date, and name; defaults to those fields in cust_main.
2555
2556 =cut
2557
2558 sub batch_card {
2559   my ($self, %options) = @_;
2560
2561   my $amount;
2562   if (exists($options{amount})) {
2563     $amount = $options{amount};
2564   }else{
2565     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2566   }
2567   if ($amount <= 0) {
2568     warn(sprintf("Customer balance %.2f - in transit amount %.2f is <= 0.\n",
2569         $self->balance,
2570         $self->in_transit_payments
2571     ));
2572     return;
2573   }
2574   
2575   my $invnum = delete $options{invnum};
2576   my $payby = $options{payby} || $self->payby;  #still dubious
2577
2578   if ($options{'realtime'}) {
2579     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2580                                 $amount,
2581                                 %options,
2582                               );
2583   }
2584
2585   my $oldAutoCommit = $FS::UID::AutoCommit;
2586   local $FS::UID::AutoCommit = 0;
2587   my $dbh = dbh;
2588
2589   #this needs to handle mysql as well as Pg, like svc_acct.pm
2590   #(make it into a common function if folks need to do batching with mysql)
2591   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2592     or return "Cannot lock pay_batch: " . $dbh->errstr;
2593
2594   my %pay_batch = (
2595     'status' => 'O',
2596     'payby'  => FS::payby->payby2payment($payby),
2597   );
2598   $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
2599
2600   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2601
2602   unless ( $pay_batch ) {
2603     $pay_batch = new FS::pay_batch \%pay_batch;
2604     my $error = $pay_batch->insert;
2605     if ( $error ) {
2606       $dbh->rollback if $oldAutoCommit;
2607       die "error creating new batch: $error\n";
2608     }
2609   }
2610
2611   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2612       'batchnum' => $pay_batch->batchnum,
2613       'custnum'  => $self->custnum,
2614   } );
2615
2616   foreach (qw( address1 address2 city state zip country latitude longitude
2617                payby payinfo paydate payname ))
2618   {
2619     $options{$_} = '' unless exists($options{$_});
2620   }
2621
2622   my $loc = $self->bill_location;
2623
2624   my $cust_pay_batch = new FS::cust_pay_batch ( {
2625     'batchnum' => $pay_batch->batchnum,
2626     'invnum'   => $invnum || 0,                    # is there a better value?
2627                                                    # this field should be
2628                                                    # removed...
2629                                                    # cust_bill_pay_batch now
2630     'custnum'  => $self->custnum,
2631     'last'     => $self->getfield('last'),
2632     'first'    => $self->getfield('first'),
2633     'address1' => $options{address1} || $loc->address1,
2634     'address2' => $options{address2} || $loc->address2,
2635     'city'     => $options{city}     || $loc->city,
2636     'state'    => $options{state}    || $loc->state,
2637     'zip'      => $options{zip}      || $loc->zip,
2638     'country'  => $options{country}  || $loc->country,
2639     'payby'    => $options{payby}    || $self->payby,
2640     'payinfo'  => $options{payinfo}  || $self->payinfo,
2641     'exp'      => $options{paydate}  || $self->paydate,
2642     'payname'  => $options{payname}  || $self->payname,
2643     'amount'   => $amount,                         # consolidating
2644   } );
2645   
2646   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2647     if $old_cust_pay_batch;
2648
2649   my $error;
2650   if ($old_cust_pay_batch) {
2651     $error = $cust_pay_batch->replace($old_cust_pay_batch)
2652   } else {
2653     $error = $cust_pay_batch->insert;
2654   }
2655
2656   if ( $error ) {
2657     $dbh->rollback if $oldAutoCommit;
2658     die $error;
2659   }
2660
2661   my $unapplied =   $self->total_unapplied_credits
2662                   + $self->total_unapplied_payments
2663                   + $self->in_transit_payments;
2664   foreach my $cust_bill ($self->open_cust_bill) {
2665     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2666     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2667       'invnum' => $cust_bill->invnum,
2668       'paybatchnum' => $cust_pay_batch->paybatchnum,
2669       'amount' => $cust_bill->owed,
2670       '_date' => time,
2671     };
2672     if ($unapplied >= $cust_bill_pay_batch->amount){
2673       $unapplied -= $cust_bill_pay_batch->amount;
2674       next;
2675     }else{
2676       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
2677                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
2678     }
2679     $error = $cust_bill_pay_batch->insert;
2680     if ( $error ) {
2681       $dbh->rollback if $oldAutoCommit;
2682       die $error;
2683     }
2684   }
2685
2686   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2687   '';
2688 }
2689
2690 =item total_owed
2691
2692 Returns the total owed for this customer on all invoices
2693 (see L<FS::cust_bill/owed>).
2694
2695 =cut
2696
2697 sub total_owed {
2698   my $self = shift;
2699   $self->total_owed_date(2145859200); #12/31/2037
2700 }
2701
2702 =item total_owed_date TIME
2703
2704 Returns the total owed for this customer on all invoices with date earlier than
2705 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2706 see L<Time::Local> and L<Date::Parse> for conversion functions.
2707
2708 =cut
2709
2710 sub total_owed_date {
2711   my $self = shift;
2712   my $time = shift;
2713
2714   my $custnum = $self->custnum;
2715
2716   my $owed_sql = FS::cust_bill->owed_sql;
2717
2718   my $sql = "
2719     SELECT SUM($owed_sql) FROM cust_bill
2720       WHERE custnum = $custnum
2721         AND _date <= $time
2722   ";
2723
2724   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2725
2726 }
2727
2728 =item total_owed_pkgnum PKGNUM
2729
2730 Returns the total owed on all invoices for this customer's specific package
2731 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2732
2733 =cut
2734
2735 sub total_owed_pkgnum {
2736   my( $self, $pkgnum ) = @_;
2737   $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2738 }
2739
2740 =item total_owed_date_pkgnum TIME PKGNUM
2741
2742 Returns the total owed for this customer's specific package when using
2743 experimental package balances on all invoices with date earlier than
2744 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2745 see L<Time::Local> and L<Date::Parse> for conversion functions.
2746
2747 =cut
2748
2749 sub total_owed_date_pkgnum {
2750   my( $self, $time, $pkgnum ) = @_;
2751
2752   my $total_bill = 0;
2753   foreach my $cust_bill (
2754     grep { $_->_date <= $time }
2755       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2756   ) {
2757     $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2758   }
2759   sprintf( "%.2f", $total_bill );
2760
2761 }
2762
2763 =item total_paid
2764
2765 Returns the total amount of all payments.
2766
2767 =cut
2768
2769 sub total_paid {
2770   my $self = shift;
2771   my $total = 0;
2772   $total += $_->paid foreach $self->cust_pay;
2773   sprintf( "%.2f", $total );
2774 }
2775
2776 =item total_unapplied_credits
2777
2778 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2779 customer.  See L<FS::cust_credit/credited>.
2780
2781 =item total_credited
2782
2783 Old name for total_unapplied_credits.  Don't use.
2784
2785 =cut
2786
2787 sub total_credited {
2788   #carp "total_credited deprecated, use total_unapplied_credits";
2789   shift->total_unapplied_credits(@_);
2790 }
2791
2792 sub total_unapplied_credits {
2793   my $self = shift;
2794
2795   my $custnum = $self->custnum;
2796
2797   my $unapplied_sql = FS::cust_credit->unapplied_sql;
2798
2799   my $sql = "
2800     SELECT SUM($unapplied_sql) FROM cust_credit
2801       WHERE custnum = $custnum
2802   ";
2803
2804   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2805
2806 }
2807
2808 =item total_unapplied_credits_pkgnum PKGNUM
2809
2810 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2811 customer.  See L<FS::cust_credit/credited>.
2812
2813 =cut
2814
2815 sub total_unapplied_credits_pkgnum {
2816   my( $self, $pkgnum ) = @_;
2817   my $total_credit = 0;
2818   $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2819   sprintf( "%.2f", $total_credit );
2820 }
2821
2822
2823 =item total_unapplied_payments
2824
2825 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2826 See L<FS::cust_pay/unapplied>.
2827
2828 =cut
2829
2830 sub total_unapplied_payments {
2831   my $self = shift;
2832
2833   my $custnum = $self->custnum;
2834
2835   my $unapplied_sql = FS::cust_pay->unapplied_sql;
2836
2837   my $sql = "
2838     SELECT SUM($unapplied_sql) FROM cust_pay
2839       WHERE custnum = $custnum
2840   ";
2841
2842   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2843
2844 }
2845
2846 =item total_unapplied_payments_pkgnum PKGNUM
2847
2848 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2849 specific package when using experimental package balances.  See
2850 L<FS::cust_pay/unapplied>.
2851
2852 =cut
2853
2854 sub total_unapplied_payments_pkgnum {
2855   my( $self, $pkgnum ) = @_;
2856   my $total_unapplied = 0;
2857   $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2858   sprintf( "%.2f", $total_unapplied );
2859 }
2860
2861
2862 =item total_unapplied_refunds
2863
2864 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2865 customer.  See L<FS::cust_refund/unapplied>.
2866
2867 =cut
2868
2869 sub total_unapplied_refunds {
2870   my $self = shift;
2871   my $custnum = $self->custnum;
2872
2873   my $unapplied_sql = FS::cust_refund->unapplied_sql;
2874
2875   my $sql = "
2876     SELECT SUM($unapplied_sql) FROM cust_refund
2877       WHERE custnum = $custnum
2878   ";
2879
2880   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2881
2882 }
2883
2884 =item balance
2885
2886 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2887 total_unapplied_credits minus total_unapplied_payments).
2888
2889 =cut
2890
2891 sub balance {
2892   my $self = shift;
2893   $self->balance_date_range;
2894 }
2895
2896 =item balance_date TIME
2897
2898 Returns the balance for this customer, only considering invoices with date
2899 earlier than TIME (total_owed_date minus total_credited minus
2900 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
2901 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
2902 functions.
2903
2904 =cut
2905
2906 sub balance_date {
2907   my $self = shift;
2908   $self->balance_date_range(shift);
2909 }
2910
2911 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2912
2913 Returns the balance for this customer, optionally considering invoices with
2914 date earlier than START_TIME, and not later than END_TIME
2915 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2916
2917 Times are specified as SQL fragments or numeric
2918 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
2919 L<Date::Parse> for conversion functions.  The empty string can be passed
2920 to disable that time constraint completely.
2921
2922 Accepts the same options as L<balance_date_sql>:
2923
2924 =over 4
2925
2926 =item unapplied_date
2927
2928 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
2929
2930 =item cutoff
2931
2932 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
2933 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
2934 range for invoices and I<unapplied> payments, credits, and refunds.
2935
2936 =back
2937
2938 =cut
2939
2940 sub balance_date_range {
2941   my $self = shift;
2942   my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2943             ') FROM cust_main WHERE custnum='. $self->custnum;
2944   sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2945 }
2946
2947 =item balance_pkgnum PKGNUM
2948
2949 Returns the balance for this customer's specific package when using
2950 experimental package balances (total_owed plus total_unrefunded, minus
2951 total_unapplied_credits minus total_unapplied_payments)
2952
2953 =cut
2954
2955 sub balance_pkgnum {
2956   my( $self, $pkgnum ) = @_;
2957
2958   sprintf( "%.2f",
2959       $self->total_owed_pkgnum($pkgnum)
2960 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2961 #    + $self->total_unapplied_refunds_pkgnum($pkgnum)
2962     - $self->total_unapplied_credits_pkgnum($pkgnum)
2963     - $self->total_unapplied_payments_pkgnum($pkgnum)
2964   );
2965 }
2966
2967 =item in_transit_payments
2968
2969 Returns the total of requests for payments for this customer pending in 
2970 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
2971
2972 =cut
2973
2974 sub in_transit_payments {
2975   my $self = shift;
2976   my $in_transit_payments = 0;
2977   foreach my $pay_batch ( qsearch('pay_batch', {
2978     'status' => 'I',
2979   } ) ) {
2980     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2981       'batchnum' => $pay_batch->batchnum,
2982       'custnum' => $self->custnum,
2983       'status'  => '',
2984     } ) ) {
2985       $in_transit_payments += $cust_pay_batch->amount;
2986     }
2987   }
2988   sprintf( "%.2f", $in_transit_payments );
2989 }
2990
2991 =item payment_info
2992
2993 Returns a hash of useful information for making a payment.
2994
2995 =over 4
2996
2997 =item balance
2998
2999 Current balance.
3000
3001 =item payby
3002
3003 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
3004 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
3005 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
3006
3007 =back
3008
3009 For credit card transactions:
3010
3011 =over 4
3012
3013 =item card_type 1
3014
3015 =item payname
3016
3017 Exact name on card
3018
3019 =back
3020
3021 For electronic check transactions:
3022
3023 =over 4
3024
3025 =item stateid_state
3026
3027 =back
3028
3029 =cut
3030
3031 sub payment_info {
3032   my $self = shift;
3033
3034   my %return = ();
3035
3036   $return{balance} = $self->balance;
3037
3038   $return{payname} = $self->payname
3039                      || ( $self->first. ' '. $self->get('last') );
3040
3041   $return{$_} = $self->bill_location->$_
3042     for qw(address1 address2 city state zip);
3043
3044   $return{payby} = $self->payby;
3045   $return{stateid_state} = $self->stateid_state;
3046
3047   if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
3048     $return{card_type} = cardtype($self->payinfo);
3049     $return{payinfo} = $self->paymask;
3050
3051     @return{'month', 'year'} = $self->paydate_monthyear;
3052
3053   }
3054
3055   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
3056     my ($payinfo1, $payinfo2) = split '@', $self->paymask;
3057     $return{payinfo1} = $payinfo1;
3058     $return{payinfo2} = $payinfo2;
3059     $return{paytype}  = $self->paytype;
3060     $return{paystate} = $self->paystate;
3061
3062   }
3063
3064   #doubleclick protection
3065   my $_date = time;
3066   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
3067
3068   %return;
3069
3070 }
3071
3072 =item paydate_monthyear
3073
3074 Returns a two-element list consisting of the month and year of this customer's
3075 paydate (credit card expiration date for CARD customers)
3076
3077 =cut
3078
3079 sub paydate_monthyear {
3080   my $self = shift;
3081   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3082     ( $2, $1 );
3083   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3084     ( $1, $3 );
3085   } else {
3086     ('', '');
3087   }
3088 }
3089
3090 =item paydate_epoch
3091
3092 Returns the exact time in seconds corresponding to the payment method 
3093 expiration date.  For CARD/DCRD customers this is the end of the month;
3094 for others (COMP is the only other payby that uses paydate) it's the start.
3095 Returns 0 if the paydate is empty or set to the far future.
3096
3097 =cut
3098
3099 sub paydate_epoch {
3100   my $self = shift;
3101   my ($month, $year) = $self->paydate_monthyear;
3102   return 0 if !$year or $year >= 2037;
3103   if ( $self->payby eq 'CARD' or $self->payby eq 'DCRD' ) {
3104     $month++;
3105     if ( $month == 13 ) {
3106       $month = 1;
3107       $year++;
3108     }
3109     return timelocal(0,0,0,1,$month-1,$year) - 1;
3110   }
3111   else {
3112     return timelocal(0,0,0,1,$month-1,$year);
3113   }
3114 }
3115
3116 =item paydate_epoch_sql
3117
3118 Class method.  Returns an SQL expression to obtain the payment expiration date
3119 as a number of seconds.
3120
3121 =cut
3122
3123 # Special expiration date behavior for non-CARD/DCRD customers has been 
3124 # carefully preserved.  Do we really use that?
3125 sub paydate_epoch_sql {
3126   my $class = shift;
3127   my $table = shift || 'cust_main';
3128   my ($case1, $case2);
3129   if ( driver_name eq 'Pg' ) {
3130     $case1 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) + INTERVAL '1 month') - 1";
3131     $case2 = "EXTRACT( EPOCH FROM CAST( $table.paydate AS TIMESTAMP ) )";
3132   }
3133   elsif ( lc(driver_name) eq 'mysql' ) {
3134     $case1 = "UNIX_TIMESTAMP( DATE_ADD( CAST( $table.paydate AS DATETIME ), INTERVAL 1 month ) ) - 1";
3135     $case2 = "UNIX_TIMESTAMP( CAST( $table.paydate AS DATETIME ) )";
3136   }
3137   else { return '' }
3138   return "CASE WHEN $table.payby IN('CARD','DCRD') 
3139   THEN ($case1)
3140   ELSE ($case2)
3141   END"
3142 }
3143
3144 =item tax_exemption TAXNAME
3145
3146 =cut
3147
3148 sub tax_exemption {
3149   my( $self, $taxname ) = @_;
3150
3151   qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
3152                                      'taxname' => $taxname,
3153                                    },
3154           );
3155 }
3156
3157 =item cust_main_exemption
3158
3159 =cut
3160
3161 sub cust_main_exemption {
3162   my $self = shift;
3163   qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
3164 }
3165
3166 =item invoicing_list [ ARRAYREF ]
3167
3168 If an arguement is given, sets these email addresses as invoice recipients
3169 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
3170 (except as warnings), so use check_invoicing_list first.
3171
3172 Returns a list of email addresses (with svcnum entries expanded).
3173
3174 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
3175 check it without disturbing anything by passing nothing.
3176
3177 This interface may change in the future.
3178
3179 =cut
3180
3181 sub invoicing_list {
3182   my( $self, $arrayref ) = @_;
3183
3184   if ( $arrayref ) {
3185     my @cust_main_invoice;
3186     if ( $self->custnum ) {
3187       @cust_main_invoice = 
3188         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3189     } else {
3190       @cust_main_invoice = ();
3191     }
3192     foreach my $cust_main_invoice ( @cust_main_invoice ) {
3193       #warn $cust_main_invoice->destnum;
3194       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3195         #warn $cust_main_invoice->destnum;
3196         my $error = $cust_main_invoice->delete;
3197         warn $error if $error;
3198       }
3199     }
3200     if ( $self->custnum ) {
3201       @cust_main_invoice = 
3202         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3203     } else {
3204       @cust_main_invoice = ();
3205     }
3206     my %seen = map { $_->address => 1 } @cust_main_invoice;
3207     foreach my $address ( @{$arrayref} ) {
3208       next if exists $seen{$address} && $seen{$address};
3209       $seen{$address} = 1;
3210       my $cust_main_invoice = new FS::cust_main_invoice ( {
3211         'custnum' => $self->custnum,
3212         'dest'    => $address,
3213       } );
3214       my $error = $cust_main_invoice->insert;
3215       warn $error if $error;
3216     }
3217   }
3218   
3219   if ( $self->custnum ) {
3220     map { $_->address }
3221       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3222   } else {
3223     ();
3224   }
3225
3226 }
3227
3228 =item check_invoicing_list ARRAYREF
3229
3230 Checks these arguements as valid input for the invoicing_list method.  If there
3231 is an error, returns the error, otherwise returns false.
3232
3233 =cut
3234
3235 sub check_invoicing_list {
3236   my( $self, $arrayref ) = @_;
3237
3238   foreach my $address ( @$arrayref ) {
3239
3240     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3241       return 'Can\'t add FAX invoice destination with a blank FAX number.';
3242     }
3243
3244     my $cust_main_invoice = new FS::cust_main_invoice ( {
3245       'custnum' => $self->custnum,
3246       'dest'    => $address,
3247     } );
3248     my $error = $self->custnum
3249                 ? $cust_main_invoice->check
3250                 : $cust_main_invoice->checkdest
3251     ;
3252     return $error if $error;
3253
3254   }
3255
3256   return "Email address required"
3257     if $conf->exists('cust_main-require_invoicing_list_email', $self->agentnum)
3258     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3259
3260   '';
3261 }
3262
3263 =item set_default_invoicing_list
3264
3265 Sets the invoicing list to all accounts associated with this customer,
3266 overwriting any previous invoicing list.
3267
3268 =cut
3269
3270 sub set_default_invoicing_list {
3271   my $self = shift;
3272   $self->invoicing_list($self->all_emails);
3273 }
3274
3275 =item all_emails
3276
3277 Returns the email addresses of all accounts provisioned for this customer.
3278
3279 =cut
3280
3281 sub all_emails {
3282   my $self = shift;
3283   my %list;
3284   foreach my $cust_pkg ( $self->all_pkgs ) {
3285     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3286     my @svc_acct =
3287       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3288         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3289           @cust_svc;
3290     $list{$_}=1 foreach map { $_->email } @svc_acct;
3291   }
3292   keys %list;
3293 }
3294
3295 =item invoicing_list_addpost
3296
3297 Adds postal invoicing to this customer.  If this customer is already configured
3298 to receive postal invoices, does nothing.
3299
3300 =cut
3301
3302 sub invoicing_list_addpost {
3303   my $self = shift;
3304   return if grep { $_ eq 'POST' } $self->invoicing_list;
3305   my @invoicing_list = $self->invoicing_list;
3306   push @invoicing_list, 'POST';
3307   $self->invoicing_list(\@invoicing_list);
3308 }
3309
3310 =item invoicing_list_emailonly
3311
3312 Returns the list of email invoice recipients (invoicing_list without non-email
3313 destinations such as POST and FAX).
3314
3315 =cut
3316
3317 sub invoicing_list_emailonly {
3318   my $self = shift;
3319   warn "$me invoicing_list_emailonly called"
3320     if $DEBUG;
3321   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3322 }
3323
3324 =item invoicing_list_emailonly_scalar
3325
3326 Returns the list of email invoice recipients (invoicing_list without non-email
3327 destinations such as POST and FAX) as a comma-separated scalar.
3328
3329 =cut
3330
3331 sub invoicing_list_emailonly_scalar {
3332   my $self = shift;
3333   warn "$me invoicing_list_emailonly_scalar called"
3334     if $DEBUG;
3335   join(', ', $self->invoicing_list_emailonly);
3336 }
3337
3338 =item referral_custnum_cust_main
3339
3340 Returns the customer who referred this customer (or the empty string, if
3341 this customer was not referred).
3342
3343 Note the difference with referral_cust_main method: This method,
3344 referral_custnum_cust_main returns the single customer (if any) who referred
3345 this customer, while referral_cust_main returns an array of customers referred
3346 BY this customer.
3347
3348 =cut
3349
3350 sub referral_custnum_cust_main {
3351   my $self = shift;
3352   return '' unless $self->referral_custnum;
3353   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3354 }
3355
3356 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3357
3358 Returns an array of customers referred by this customer (referral_custnum set
3359 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
3360 customers referred by customers referred by this customer and so on, inclusive.
3361 The default behavior is DEPTH 1 (no recursion).
3362
3363 Note the difference with referral_custnum_cust_main method: This method,
3364 referral_cust_main, returns an array of customers referred BY this customer,
3365 while referral_custnum_cust_main returns the single customer (if any) who
3366 referred this customer.
3367
3368 =cut
3369
3370 sub referral_cust_main {
3371   my $self = shift;
3372   my $depth = @_ ? shift : 1;
3373   my $exclude = @_ ? shift : {};
3374
3375   my @cust_main =
3376     map { $exclude->{$_->custnum}++; $_; }
3377       grep { ! $exclude->{ $_->custnum } }
3378         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3379
3380   if ( $depth > 1 ) {
3381     push @cust_main,
3382       map { $_->referral_cust_main($depth-1, $exclude) }
3383         @cust_main;
3384   }
3385
3386   @cust_main;
3387 }
3388
3389 =item referral_cust_main_ncancelled
3390
3391 Same as referral_cust_main, except only returns customers with uncancelled
3392 packages.
3393
3394 =cut
3395
3396 sub referral_cust_main_ncancelled {
3397   my $self = shift;
3398   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3399 }
3400
3401 =item referral_cust_pkg [ DEPTH ]
3402
3403 Like referral_cust_main, except returns a flat list of all unsuspended (and
3404 uncancelled) packages for each customer.  The number of items in this list may
3405 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3406
3407 =cut
3408
3409 sub referral_cust_pkg {
3410   my $self = shift;
3411   my $depth = @_ ? shift : 1;
3412
3413   map { $_->unsuspended_pkgs }
3414     grep { $_->unsuspended_pkgs }
3415       $self->referral_cust_main($depth);
3416 }
3417
3418 =item referring_cust_main
3419
3420 Returns the single cust_main record for the customer who referred this customer
3421 (referral_custnum), or false.
3422
3423 =cut
3424
3425 sub referring_cust_main {
3426   my $self = shift;
3427   return '' unless $self->referral_custnum;
3428   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3429 }
3430
3431 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3432
3433 Applies a credit to this customer.  If there is an error, returns the error,
3434 otherwise returns false.
3435
3436 REASON can be a text string, an FS::reason object, or a scalar reference to
3437 a reasonnum.  If a text string, it will be automatically inserted as a new
3438 reason, and a 'reason_type' option must be passed to indicate the
3439 FS::reason_type for the new reason.
3440
3441 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3442 Likewise for I<eventnum>, I<commission_agentnum>, I<commission_salesnum> and
3443 I<commission_pkgnum>.
3444
3445 Any other options are passed to FS::cust_credit::insert.
3446
3447 =cut
3448
3449 sub credit {
3450   my( $self, $amount, $reason, %options ) = @_;
3451
3452   my $cust_credit = new FS::cust_credit {
3453     'custnum' => $self->custnum,
3454     'amount'  => $amount,
3455   };
3456
3457   if ( ref($reason) ) {
3458
3459     if ( ref($reason) eq 'SCALAR' ) {
3460       $cust_credit->reasonnum( $$reason );
3461     } else {
3462       $cust_credit->reasonnum( $reason->reasonnum );
3463     }
3464
3465   } else {
3466     $cust_credit->set('reason', $reason)
3467   }
3468
3469   $cust_credit->$_( delete $options{$_} )
3470     foreach grep exists($options{$_}),
3471               qw( addlinfo eventnum ),
3472               map "commission_$_", qw( agentnum salesnum pkgnum );
3473
3474   $cust_credit->insert(%options);
3475
3476 }
3477
3478 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3479
3480 Creates a one-time charge for this customer.  If there is an error, returns
3481 the error, otherwise returns false.
3482
3483 New-style, with a hashref of options:
3484
3485   my $error = $cust_main->charge(
3486                                   {
3487                                     'amount'     => 54.32,
3488                                     'quantity'   => 1,
3489                                     'start_date' => str2time('7/4/2009'),
3490                                     'pkg'        => 'Description',
3491                                     'comment'    => 'Comment',
3492                                     'additional' => [], #extra invoice detail
3493                                     'classnum'   => 1,  #pkg_class
3494
3495                                     'setuptax'   => '', # or 'Y' for tax exempt
3496
3497                                     'locationnum'=> 1234, # optional
3498
3499                                     #internal taxation
3500                                     'taxclass'   => 'Tax class',
3501
3502                                     #vendor taxation
3503                                     'taxproduct' => 2,  #part_pkg_taxproduct
3504                                     'override'   => {}, #XXX describe
3505
3506                                     #will be filled in with the new object
3507                                     'cust_pkg_ref' => \$cust_pkg,
3508
3509                                     #generate an invoice immediately
3510                                     'bill_now' => 0,
3511                                     'invoice_terms' => '', #with these terms
3512                                   }
3513                                 );
3514
3515 Old-style:
3516
3517   my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3518
3519 =cut
3520
3521 #super false laziness w/quotation::charge
3522 sub charge {
3523   my $self = shift;
3524   my ( $amount, $setup_cost, $quantity, $start_date, $classnum );
3525   my ( $pkg, $comment, $additional );
3526   my ( $setuptax, $taxclass );   #internal taxes
3527   my ( $taxproduct, $override ); #vendor (CCH) taxes
3528   my $no_auto = '';
3529   my $separate_bill = '';
3530   my $cust_pkg_ref = '';
3531   my ( $bill_now, $invoice_terms ) = ( 0, '' );
3532   my $locationnum;
3533   if ( ref( $_[0] ) ) {
3534     $amount     = $_[0]->{amount};
3535     $setup_cost = $_[0]->{setup_cost};
3536     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3537     $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3538     $no_auto    = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3539     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3540     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
3541                                            : '$'. sprintf("%.2f",$amount);
3542     $setuptax   = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3543     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3544     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3545     $additional = $_[0]->{additional} || [];
3546     $taxproduct = $_[0]->{taxproductnum};
3547     $override   = { '' => $_[0]->{tax_override} };
3548     $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3549     $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3550     $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3551     $locationnum = $_[0]->{locationnum} || $self->ship_locationnum;
3552     $separate_bill = $_[0]->{separate_bill} || '';
3553   } else { # yuck
3554     $amount     = shift;
3555     $setup_cost = '';
3556     $quantity   = 1;
3557     $start_date = '';
3558     $pkg        = @_ ? shift : 'One-time charge';
3559     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
3560     $setuptax   = '';
3561     $taxclass   = @_ ? shift : '';
3562     $additional = [];
3563   }
3564
3565   local $SIG{HUP} = 'IGNORE';
3566   local $SIG{INT} = 'IGNORE';
3567   local $SIG{QUIT} = 'IGNORE';
3568   local $SIG{TERM} = 'IGNORE';
3569   local $SIG{TSTP} = 'IGNORE';
3570   local $SIG{PIPE} = 'IGNORE';
3571
3572   my $oldAutoCommit = $FS::UID::AutoCommit;
3573   local $FS::UID::AutoCommit = 0;
3574   my $dbh = dbh;
3575
3576   my $part_pkg = new FS::part_pkg ( {
3577     'pkg'           => $pkg,
3578     'comment'       => $comment,
3579     'plan'          => 'flat',
3580     'freq'          => 0,
3581     'disabled'      => 'Y',
3582     'classnum'      => ( $classnum ? $classnum : '' ),
3583     'setuptax'      => $setuptax,
3584     'taxclass'      => $taxclass,
3585     'taxproductnum' => $taxproduct,
3586     'setup_cost'    => $setup_cost,
3587   } );
3588
3589   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3590                         ( 0 .. @$additional - 1 )
3591                   ),
3592                   'additional_count' => scalar(@$additional),
3593                   'setup_fee' => $amount,
3594                 );
3595
3596   my $error = $part_pkg->insert( options       => \%options,
3597                                  tax_overrides => $override,
3598                                );
3599   if ( $error ) {
3600     $dbh->rollback if $oldAutoCommit;
3601     return $error;
3602   }
3603
3604   my $pkgpart = $part_pkg->pkgpart;
3605   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3606   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3607     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3608     $error = $type_pkgs->insert;
3609     if ( $error ) {
3610       $dbh->rollback if $oldAutoCommit;
3611       return $error;
3612     }
3613   }
3614
3615   my $cust_pkg = new FS::cust_pkg ( {
3616     'custnum'    => $self->custnum,
3617     'pkgpart'    => $pkgpart,
3618     'quantity'   => $quantity,
3619     'start_date' => $start_date,
3620     'no_auto'    => $no_auto,
3621     'separate_bill' => $separate_bill,
3622     'locationnum'=> $locationnum,
3623   } );
3624
3625   $error = $cust_pkg->insert;
3626   if ( $error ) {
3627     $dbh->rollback if $oldAutoCommit;
3628     return $error;
3629   } elsif ( $cust_pkg_ref ) {
3630     ${$cust_pkg_ref} = $cust_pkg;
3631   }
3632
3633   if ( $bill_now ) {
3634     my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3635                              'pkg_list'      => [ $cust_pkg ],
3636                            );
3637     if ( $error ) {
3638       $dbh->rollback if $oldAutoCommit;
3639       return $error;
3640     }   
3641   }
3642
3643   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3644   return '';
3645
3646 }
3647
3648 #=item charge_postal_fee
3649 #
3650 #Applies a one time charge this customer.  If there is an error,
3651 #returns the error, returns the cust_pkg charge object or false
3652 #if there was no charge.
3653 #
3654 #=cut
3655 #
3656 # This should be a customer event.  For that to work requires that bill
3657 # also be a customer event.
3658
3659 sub charge_postal_fee {
3660   my $self = shift;
3661
3662   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3663   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3664
3665   my $cust_pkg = new FS::cust_pkg ( {
3666     'custnum'  => $self->custnum,
3667     'pkgpart'  => $pkgpart,
3668     'quantity' => 1,
3669   } );
3670
3671   my $error = $cust_pkg->insert;
3672   $error ? $error : $cust_pkg;
3673 }
3674
3675 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3676
3677 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3678
3679 Optionally, a list or hashref of additional arguments to the qsearch call can
3680 be passed.
3681
3682 =cut
3683
3684 sub cust_bill {
3685   my $self = shift;
3686   my $opt = ref($_[0]) ? shift : { @_ };
3687
3688   #return $self->num_cust_bill unless wantarray || keys %$opt;
3689
3690   $opt->{'table'} = 'cust_bill';
3691   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3692   $opt->{'hashref'}{'custnum'} = $self->custnum;
3693   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3694
3695   map { $_ } #behavior of sort undefined in scalar context
3696     sort { $a->_date <=> $b->_date }
3697       qsearch($opt);
3698 }
3699
3700 =item open_cust_bill
3701
3702 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3703 customer.
3704
3705 =cut
3706
3707 sub open_cust_bill {
3708   my $self = shift;
3709
3710   $self->cust_bill(
3711     'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3712     #@_
3713   );
3714
3715 }
3716
3717 =item legacy_cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3718
3719 Returns all the legacy invoices (see L<FS::legacy_cust_bill>) for this customer.
3720
3721 =cut
3722
3723 sub legacy_cust_bill {
3724   my $self = shift;
3725
3726   #return $self->num_legacy_cust_bill unless wantarray;
3727
3728   map { $_ } #behavior of sort undefined in scalar context
3729     sort { $a->_date <=> $b->_date }
3730       qsearch({ 'table'    => 'legacy_cust_bill',
3731                 'hashref'  => { 'custnum' => $self->custnum, },
3732                 'order_by' => 'ORDER BY _date ASC',
3733              });
3734 }
3735
3736 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3737
3738 Returns all the statements (see L<FS::cust_statement>) for this customer.
3739
3740 Optionally, a list or hashref of additional arguments to the qsearch call can
3741 be passed.
3742
3743 =cut
3744
3745 =item cust_bill_void
3746
3747 Returns all the voided invoices (see L<FS::cust_bill_void>) for this customer.
3748
3749 =cut
3750
3751 sub cust_bill_void {
3752   my $self = shift;
3753
3754   map { $_ } #return $self->num_cust_bill_void unless wantarray;
3755   sort { $a->_date <=> $b->_date }
3756     qsearch( 'cust_bill_void', { 'custnum' => $self->custnum } )
3757 }
3758
3759 sub cust_statement {
3760   my $self = shift;
3761   my $opt = ref($_[0]) ? shift : { @_ };
3762
3763   #return $self->num_cust_statement unless wantarray || keys %$opt;
3764
3765   $opt->{'table'} = 'cust_statement';
3766   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3767   $opt->{'hashref'}{'custnum'} = $self->custnum;
3768   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3769
3770   map { $_ } #behavior of sort undefined in scalar context
3771     sort { $a->_date <=> $b->_date }
3772       qsearch($opt);
3773 }
3774
3775 =item svc_x SVCDB [ OPTION => VALUE | EXTRA_QSEARCH_PARAMS_HASHREF ]
3776
3777 Returns all services of type SVCDB (such as 'svc_acct') for this customer.  
3778
3779 Optionally, a list or hashref of additional arguments to the qsearch call can 
3780 be passed following the SVCDB.
3781
3782 =cut
3783
3784 sub svc_x {
3785   my $self = shift;
3786   my $svcdb = shift;
3787   if ( ! $svcdb =~ /^svc_\w+$/ ) {
3788     warn "$me svc_x requires a svcdb";
3789     return;
3790   }
3791   my $opt = ref($_[0]) ? shift : { @_ };
3792
3793   $opt->{'table'} = $svcdb;
3794   $opt->{'addl_from'} = 
3795     'LEFT JOIN cust_svc USING (svcnum) LEFT JOIN cust_pkg USING (pkgnum) '.
3796     ($opt->{'addl_from'} || '');
3797
3798   my $custnum = $self->custnum;
3799   $custnum =~ /^\d+$/ or die "bad custnum '$custnum'";
3800   my $where = "cust_pkg.custnum = $custnum";
3801
3802   my $extra_sql = $opt->{'extra_sql'} || '';
3803   if ( keys %{ $opt->{'hashref'} } ) {
3804     $extra_sql = " AND $where $extra_sql";
3805   }
3806   else {
3807     if ( $opt->{'extra_sql'} =~ /^\s*where\s(.*)/si ) {
3808       $extra_sql = "WHERE $where AND $1";
3809     }
3810     else {
3811       $extra_sql = "WHERE $where $extra_sql";
3812     }
3813   }
3814   $opt->{'extra_sql'} = $extra_sql;
3815
3816   qsearch($opt);
3817 }
3818
3819 # required for use as an eventtable; 
3820 sub svc_acct {
3821   my $self = shift;
3822   $self->svc_x('svc_acct', @_);
3823 }
3824
3825 =item cust_credit
3826
3827 Returns all the credits (see L<FS::cust_credit>) for this customer.
3828
3829 =cut
3830
3831 sub cust_credit {
3832   my $self = shift;
3833   map { $_ } #return $self->num_cust_credit unless wantarray;
3834   sort { $a->_date <=> $b->_date }
3835     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3836 }
3837
3838 =item cust_credit_pkgnum
3839
3840 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3841 package when using experimental package balances.
3842
3843 =cut
3844
3845 sub cust_credit_pkgnum {
3846   my( $self, $pkgnum ) = @_;
3847   map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3848   sort { $a->_date <=> $b->_date }
3849     qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3850                               'pkgnum'  => $pkgnum,
3851                             }
3852     );
3853 }
3854
3855 =item cust_credit_void
3856
3857 Returns all voided credits (see L<FS::cust_credit_void>) for this customer.
3858
3859 =cut
3860
3861 sub cust_credit_void {
3862   my $self = shift;
3863   map { $_ }
3864   sort { $a->_date <=> $b->_date }
3865     qsearch( 'cust_credit_void', { 'custnum' => $self->custnum } )
3866 }
3867
3868 =item cust_pay
3869
3870 Returns all the payments (see L<FS::cust_pay>) for this customer.
3871
3872 =cut
3873
3874 sub cust_pay {
3875   my $self = shift;
3876   my $opt = ref($_[0]) ? shift : { @_ };
3877
3878   return $self->num_cust_pay unless wantarray || keys %$opt;
3879
3880   $opt->{'table'} = 'cust_pay';
3881   $opt->{'hashref'}{'custnum'} = $self->custnum;
3882
3883   map { $_ } #behavior of sort undefined in scalar context
3884     sort { $a->_date <=> $b->_date }
3885       qsearch($opt);
3886
3887 }
3888
3889 =item num_cust_pay
3890
3891 Returns the number of payments (see L<FS::cust_pay>) for this customer.  Also
3892 called automatically when the cust_pay method is used in a scalar context.
3893
3894 =cut
3895
3896 sub num_cust_pay {
3897   my $self = shift;
3898   my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3899   my $sth = dbh->prepare($sql) or die dbh->errstr;
3900   $sth->execute($self->custnum) or die $sth->errstr;
3901   $sth->fetchrow_arrayref->[0];
3902 }
3903
3904 =item unapplied_cust_pay
3905
3906 Returns all the unapplied payments (see L<FS::cust_pay>) for this customer.
3907
3908 =cut
3909
3910 sub unapplied_cust_pay {
3911   my $self = shift;
3912
3913   $self->cust_pay(
3914     'extra_sql' => ' AND '. FS::cust_pay->unapplied_sql. ' > 0',
3915     #@_
3916   );
3917
3918 }
3919
3920 =item cust_pay_pkgnum
3921
3922 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3923 package when using experimental package balances.
3924
3925 =cut
3926
3927 sub cust_pay_pkgnum {
3928   my( $self, $pkgnum ) = @_;
3929   map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3930   sort { $a->_date <=> $b->_date }
3931     qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3932                            'pkgnum'  => $pkgnum,
3933                          }
3934     );
3935 }
3936
3937 =item cust_pay_void
3938
3939 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3940
3941 =cut
3942
3943 sub cust_pay_void {
3944   my $self = shift;
3945   map { $_ } #return $self->num_cust_pay_void unless wantarray;
3946   sort { $a->_date <=> $b->_date }
3947     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3948 }
3949
3950 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3951
3952 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
3953
3954 Optionally, a list or hashref of additional arguments to the qsearch call can
3955 be passed.
3956
3957 =cut
3958
3959 sub cust_pay_batch {
3960   my $self = shift;
3961   my $opt = ref($_[0]) ? shift : { @_ };
3962
3963   #return $self->num_cust_statement unless wantarray || keys %$opt;
3964
3965   $opt->{'table'} = 'cust_pay_batch';
3966   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3967   $opt->{'hashref'}{'custnum'} = $self->custnum;
3968   $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3969
3970   map { $_ } #behavior of sort undefined in scalar context
3971     sort { $a->paybatchnum <=> $b->paybatchnum }
3972       qsearch($opt);
3973 }
3974
3975 =item cust_pay_pending
3976
3977 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3978 (without status "done").
3979
3980 =cut
3981
3982 sub cust_pay_pending {
3983   my $self = shift;
3984   return $self->num_cust_pay_pending unless wantarray;
3985   sort { $a->_date <=> $b->_date }
3986     qsearch( 'cust_pay_pending', {
3987                                    'custnum' => $self->custnum,
3988                                    'status'  => { op=>'!=', value=>'done' },
3989                                  },
3990            );
3991 }
3992
3993 =item cust_pay_pending_attempt
3994
3995 Returns all payment attempts / declined payments for this customer, as pending
3996 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3997 a corresponding payment (see L<FS::cust_pay>).
3998
3999 =cut
4000
4001 sub cust_pay_pending_attempt {
4002   my $self = shift;
4003   return $self->num_cust_pay_pending_attempt unless wantarray;
4004   sort { $a->_date <=> $b->_date }
4005     qsearch( 'cust_pay_pending', {
4006                                    'custnum' => $self->custnum,
4007                                    'status'  => 'done',
4008                                    'paynum'  => '',
4009                                  },
4010            );
4011 }
4012
4013 =item num_cust_pay_pending
4014
4015 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4016 customer (without status "done").  Also called automatically when the
4017 cust_pay_pending method is used in a scalar context.
4018
4019 =cut
4020
4021 sub num_cust_pay_pending {
4022   my $self = shift;
4023   $self->scalar_sql(
4024     " SELECT COUNT(*) FROM cust_pay_pending ".
4025       " WHERE custnum = ? AND status != 'done' ",
4026     $self->custnum
4027   );
4028 }
4029
4030 =item num_cust_pay_pending_attempt
4031
4032 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
4033 customer, with status "done" but without a corresp.  Also called automatically when the
4034 cust_pay_pending method is used in a scalar context.
4035
4036 =cut
4037
4038 sub num_cust_pay_pending_attempt {
4039   my $self = shift;
4040   $self->scalar_sql(
4041     " SELECT COUNT(*) FROM cust_pay_pending ".
4042       " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
4043     $self->custnum
4044   );
4045 }
4046
4047 =item cust_refund
4048
4049 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4050
4051 =cut
4052
4053 sub cust_refund {
4054   my $self = shift;
4055   map { $_ } #return $self->num_cust_refund unless wantarray;
4056   sort { $a->_date <=> $b->_date }
4057     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4058 }
4059
4060 =item display_custnum
4061
4062 Returns the displayed customer number for this customer: agent_custid if
4063 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
4064
4065 =cut
4066
4067 sub display_custnum {
4068   my $self = shift;
4069
4070   my $prefix = $conf->config('cust_main-custnum-display_prefix', $self->agentnum) || '';
4071   if ( my $special = $conf->config('cust_main-custnum-display_special') ) {
4072     if ( $special eq 'CoStAg' ) {
4073       $prefix = uc( join('',
4074         $self->country,
4075         ($self->state =~ /^(..)/),
4076         $prefix || ($self->agent->agent =~ /^(..)/)
4077       ) );
4078     }
4079     elsif ( $special eq 'CoStCl' ) {
4080       $prefix = uc( join('',
4081         $self->country,
4082         ($self->state =~ /^(..)/),
4083         ($self->classnum ? $self->cust_class->classname =~ /^(..)/ : '__')
4084       ) );
4085     }
4086     # add any others here if needed
4087   }
4088
4089   my $length = $conf->config('cust_main-custnum-display_length');
4090   if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
4091     return $self->agent_custid;
4092   } elsif ( $prefix ) {
4093     $length = 8 if !defined($length);
4094     return $prefix . 
4095            sprintf('%0'.$length.'d', $self->custnum)
4096   } elsif ( $length ) {
4097     return sprintf('%0'.$length.'d', $self->custnum);
4098   } else {
4099     return $self->custnum;
4100   }
4101 }
4102
4103 =item name
4104
4105 Returns a name string for this customer, either "Company (Last, First)" or
4106 "Last, First".
4107
4108 =cut
4109
4110 sub name {
4111   my $self = shift;
4112   my $name = $self->contact;
4113   $name = $self->company. " ($name)" if $self->company;
4114   $name;
4115 }
4116
4117 =item service_contact
4118
4119 Returns the L<FS::contact> object for this customer that has the 'Service'
4120 contact class, or undef if there is no such contact.  Deprecated; don't use
4121 this in new code.
4122
4123 =cut
4124
4125 sub service_contact {
4126   my $self = shift;
4127   if ( !exists($self->{service_contact}) ) {
4128     my $classnum = $self->scalar_sql(
4129       'SELECT classnum FROM contact_class WHERE classname = \'Service\''
4130     ) || 0; #if it's zero, qsearchs will return nothing
4131     $self->{service_contact} = qsearchs('contact', { 
4132         'classnum' => $classnum, 'custnum' => $self->custnum
4133       }) || undef;
4134   }
4135   $self->{service_contact};
4136 }
4137
4138 =item ship_name
4139
4140 Returns a name string for this (service/shipping) contact, either
4141 "Company (Last, First)" or "Last, First".
4142
4143 =cut
4144
4145 sub ship_name {
4146   my $self = shift;
4147
4148   my $name = $self->ship_contact;
4149   $name = $self->company. " ($name)" if $self->company;
4150   $name;
4151 }
4152
4153 =item name_short
4154
4155 Returns a name string for this customer, either "Company" or "First Last".
4156
4157 =cut
4158
4159 sub name_short {
4160   my $self = shift;
4161   $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
4162 }
4163
4164 =item ship_name_short
4165
4166 Returns a name string for this (service/shipping) contact, either "Company"
4167 or "First Last".
4168
4169 =cut
4170
4171 sub ship_name_short {
4172   my $self = shift;
4173   $self->service_contact 
4174     ? $self->ship_contact_firstlast 
4175     : $self->name_short
4176 }
4177
4178 =item contact
4179
4180 Returns this customer's full (billing) contact name only, "Last, First"
4181
4182 =cut
4183
4184 sub contact {
4185   my $self = shift;
4186   $self->get('last'). ', '. $self->first;
4187 }
4188
4189 =item ship_contact
4190
4191 Returns this customer's full (shipping) contact name only, "Last, First"
4192
4193 =cut
4194
4195 sub ship_contact {
4196   my $self = shift;
4197   my $contact = $self->service_contact || $self;
4198   $contact->get('last') . ', ' . $contact->get('first');
4199 }
4200
4201 =item contact_firstlast
4202
4203 Returns this customers full (billing) contact name only, "First Last".
4204
4205 =cut
4206
4207 sub contact_firstlast {
4208   my $self = shift;
4209   $self->first. ' '. $self->get('last');
4210 }
4211
4212 =item ship_contact_firstlast
4213
4214 Returns this customer's full (shipping) contact name only, "First Last".
4215
4216 =cut
4217
4218 sub ship_contact_firstlast {
4219   my $self = shift;
4220   my $contact = $self->service_contact || $self;
4221   $contact->get('first') . ' '. $contact->get('last');
4222 }
4223
4224 #XXX this doesn't work in 3.x+
4225 #=item country_full
4226 #
4227 #Returns this customer's full country name
4228 #
4229 #=cut
4230 #
4231 #sub country_full {
4232 #  my $self = shift;
4233 #  code2country($self->country);
4234 #}
4235
4236 sub bill_country_full {
4237   my $self = shift;
4238   code2country($self->bill_location->country);
4239 }
4240
4241 sub ship_country_full {
4242   my $self = shift;
4243   code2country($self->ship_location->country);
4244 }
4245
4246 =item county_state_county [ PREFIX ]
4247
4248 Returns a string consisting of just the county, state and country.
4249
4250 =cut
4251
4252 sub county_state_country {
4253   my $self = shift;
4254   my $locationnum;
4255   if ( @_ && $_[0] && $self->has_ship_address ) {
4256     $locationnum = $self->ship_locationnum;
4257   } else {
4258     $locationnum = $self->bill_locationnum;
4259   }
4260   my $cust_location = qsearchs('cust_location', { locationnum=>$locationnum });
4261   $cust_location->county_state_country;
4262 }
4263
4264 =item geocode DATA_VENDOR
4265
4266 Returns a value for the customer location as encoded by DATA_VENDOR.
4267 Currently this only makes sense for "CCH" as DATA_VENDOR.
4268
4269 =cut
4270
4271 =item cust_status
4272
4273 =item status
4274
4275 Returns a status string for this customer, currently:
4276
4277 =over 4
4278
4279 =item prospect - No packages have ever been ordered
4280
4281 =item ordered - Recurring packages all are new (not yet billed).
4282
4283 =item active - One or more recurring packages is active
4284
4285 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4286
4287 =item suspended - All non-cancelled recurring packages are suspended
4288
4289 =item cancelled - All recurring packages are cancelled
4290
4291 =back
4292
4293 Behavior of inactive vs. cancelled edge cases can be adjusted with the
4294 cust_main-status_module configuration option.
4295
4296 =cut
4297
4298 sub status { shift->cust_status(@_); }
4299
4300 sub cust_status {
4301   my $self = shift;
4302   for my $status ( FS::cust_main->statuses() ) {
4303     my $method = $status.'_sql';
4304     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4305     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4306     $sth->execute( ($self->custnum) x $numnum )
4307       or die "Error executing 'SELECT $sql': ". $sth->errstr;
4308     return $status if $sth->fetchrow_arrayref->[0];
4309   }
4310 }
4311
4312 =item is_status_delay_cancel
4313
4314 Returns true if customer status is 'suspended'
4315 and all suspended cust_pkg return true for
4316 cust_pkg->is_status_delay_cancel.
4317
4318 This is not a real status, this only meant for hacking display 
4319 values, because otherwise treating the customer as suspended is 
4320 really the whole point of the delay_cancel option.
4321
4322 =cut
4323
4324 sub is_status_delay_cancel {
4325   my ($self) = @_;
4326   return 0 unless $self->status eq 'suspended';
4327   foreach my $cust_pkg ($self->ncancelled_pkgs) {
4328     return 0 unless $cust_pkg->is_status_delay_cancel;
4329   }
4330   return 1;
4331 }
4332
4333 =item ucfirst_cust_status
4334
4335 =item ucfirst_status
4336
4337 Returns the status with the first character capitalized.
4338
4339 =cut
4340
4341 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4342
4343 sub ucfirst_cust_status {
4344   my $self = shift;
4345   ucfirst($self->cust_status);
4346 }
4347
4348 =item statuscolor
4349
4350 Returns a hex triplet color string for this customer's status.
4351
4352 =cut
4353
4354 sub statuscolor { shift->cust_statuscolor(@_); }
4355
4356 sub cust_statuscolor {
4357   my $self = shift;
4358   __PACKAGE__->statuscolors->{$self->cust_status};
4359 }
4360
4361 =item tickets [ STATUS ]
4362
4363 Returns an array of hashes representing the customer's RT tickets.
4364
4365 An optional status (or arrayref or hashref of statuses) may be specified.
4366
4367 =cut
4368
4369 sub tickets {
4370   my $self = shift;
4371   my $status = ( @_ && $_[0] ) ? shift : '';
4372
4373   my $num = $conf->config('cust_main-max_tickets') || 10;
4374   my @tickets = ();
4375
4376   if ( $conf->config('ticket_system') ) {
4377     unless ( $conf->config('ticket_system-custom_priority_field') ) {
4378
4379       @tickets = @{ FS::TicketSystem->customer_tickets( $self->custnum,
4380                                                         $num,
4381                                                         undef,
4382                                                         $status,
4383                                                       )
4384                   };
4385
4386     } else {
4387
4388       foreach my $priority (
4389         $conf->config('ticket_system-custom_priority_field-values'), ''
4390       ) {
4391         last if scalar(@tickets) >= $num;
4392         push @tickets, 
4393           @{ FS::TicketSystem->customer_tickets( $self->custnum,
4394                                                  $num - scalar(@tickets),
4395                                                  $priority,
4396                                                  $status,
4397                                                )
4398            };
4399       }
4400     }
4401   }
4402   (@tickets);
4403 }
4404
4405 # Return services representing svc_accts in customer support packages
4406 sub support_services {
4407   my $self = shift;
4408   my %packages = map { $_ => 1 } $conf->config('support_packages');
4409
4410   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
4411     grep { $_->part_svc->svcdb eq 'svc_acct' }
4412     map { $_->cust_svc }
4413     grep { exists $packages{ $_->pkgpart } }
4414     $self->ncancelled_pkgs;
4415
4416 }
4417
4418 # Return a list of latitude/longitude for one of the services (if any)
4419 sub service_coordinates {
4420   my $self = shift;
4421
4422   my @svc_X = 
4423     grep { $_->latitude && $_->longitude }
4424     map { $_->svc_x }
4425     map { $_->cust_svc }
4426     $self->ncancelled_pkgs;
4427
4428   scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
4429 }
4430
4431 =item masked FIELD
4432
4433 Returns a masked version of the named field
4434
4435 =cut
4436
4437 sub masked {
4438 my ($self,$field) = @_;
4439
4440 # Show last four
4441
4442 'x'x(length($self->getfield($field))-4).
4443   substr($self->getfield($field), (length($self->getfield($field))-4));
4444
4445 }
4446
4447 =item payment_history
4448
4449 Returns an array of hashrefs standardizing information from cust_bill, cust_pay,
4450 cust_credit and cust_refund objects.  Each hashref has the following fields:
4451
4452 I<type> - one of 'Line item', 'Invoice', 'Payment', 'Credit', 'Refund' or 'Previous'
4453
4454 I<date> - value of _date field, unix timestamp
4455
4456 I<date_pretty> - user-friendly date
4457
4458 I<description> - user-friendly description of item
4459
4460 I<amount> - impact of item on user's balance 
4461 (positive for Invoice/Refund/Line item, negative for Payment/Credit.)
4462 Not to be confused with the native 'amount' field in cust_credit, see below.
4463
4464 I<amount_pretty> - includes money char
4465
4466 I<balance> - customer balance, chronologically as of this item
4467
4468 I<balance_pretty> - includes money char
4469
4470 I<charged> - amount charged for cust_bill (Invoice or Line item) records, undef for other types
4471
4472 I<paid> - amount paid for cust_pay records, undef for other types
4473
4474 I<credit> - amount credited for cust_credit records, undef for other types.
4475 Literally the 'amount' field from cust_credit, renamed here to avoid confusion.
4476
4477 I<refund> - amount refunded for cust_refund records, undef for other types
4478
4479 The four table-specific keys always have positive values, whether they reflect charges or payments.
4480
4481 The following options may be passed to this method:
4482
4483 I<line_items> - if true, returns charges ('Line item') rather than invoices
4484
4485 I<start_date> - unix timestamp, only include records on or after.
4486 If specified, an item of type 'Previous' will also be included.
4487 It does not have table-specific fields.
4488
4489 I<end_date> - unix timestamp, only include records before
4490
4491 I<reverse_sort> - order from newest to oldest (default is oldest to newest)
4492
4493 I<conf> - optional already-loaded FS::Conf object.
4494
4495 =cut
4496
4497 # Caution: this gets used by FS::ClientAPI::MyAccount::billing_history,
4498 # and also for sending customer statements, which should both be kept customer-friendly.
4499 # If you add anything that shouldn't be passed on through the API or exposed 
4500 # to customers, add a new option to include it, don't include it by default
4501 sub payment_history {
4502   my $self = shift;
4503   my $opt = ref($_[0]) ? $_[0] : { @_ };
4504
4505   my $conf = $$opt{'conf'} || new FS::Conf;
4506   my $money_char = $conf->config("money_char") || '$',
4507
4508   #first load entire history, 
4509   #need previous to calculate previous balance
4510   #loading after end_date shouldn't hurt too much?
4511   my @history = ();
4512   if ( $$opt{'line_items'} ) {
4513
4514     foreach my $cust_bill ( $self->cust_bill ) {
4515
4516       push @history, {
4517         'type'        => 'Line item',
4518         'description' => $_->desc( $self->locale ).
4519                            ( $_->sdate && $_->edate
4520                                ? ' '. time2str('%d-%b-%Y', $_->sdate).
4521                                  ' To '. time2str('%d-%b-%Y', $_->edate)
4522                                : ''
4523                            ),
4524         'amount'      => sprintf('%.2f', $_->setup + $_->recur ),
4525         'charged'     => sprintf('%.2f', $_->setup + $_->recur ),
4526         'date'        => $cust_bill->_date,
4527         'date_pretty' => $self->time2str_local('short', $cust_bill->_date ),
4528       }
4529         foreach $cust_bill->cust_bill_pkg;
4530
4531     }
4532
4533   } else {
4534
4535     push @history, {
4536                      'type'        => 'Invoice',
4537                      'description' => 'Invoice #'. $_->display_invnum,
4538                      'amount'      => sprintf('%.2f', $_->charged ),
4539                      'charged'     => sprintf('%.2f', $_->charged ),
4540                      'date'        => $_->_date,
4541                      'date_pretty' => $self->time2str_local('short', $_->_date ),
4542                    }
4543       foreach $self->cust_bill;
4544
4545   }
4546
4547   push @history, {
4548                    'type'        => 'Payment',
4549                    'description' => 'Payment', #XXX type
4550                    'amount'      => sprintf('%.2f', 0 - $_->paid ),
4551                    'paid'        => sprintf('%.2f', $_->paid ),
4552                    'date'        => $_->_date,
4553                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4554                  }
4555     foreach $self->cust_pay;
4556
4557   push @history, {
4558                    'type'        => 'Credit',
4559                    'description' => 'Credit', #more info?
4560                    'amount'      => sprintf('%.2f', 0 -$_->amount ),
4561                    'credit'      => sprintf('%.2f', $_->amount ),
4562                    'date'        => $_->_date,
4563                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4564                  }
4565     foreach $self->cust_credit;
4566
4567   push @history, {
4568                    'type'        => 'Refund',
4569                    'description' => 'Refund', #more info?  type, like payment?
4570                    'amount'      => $_->refund,
4571                    'refund'      => $_->refund,
4572                    'date'        => $_->_date,
4573                    'date_pretty' => $self->time2str_local('short', $_->_date ),
4574                  }
4575     foreach $self->cust_refund;
4576
4577   #put it all in chronological order
4578   @history = sort { $a->{'date'} <=> $b->{'date'} } @history;
4579
4580   #calculate balance, filter items outside date range
4581   my $previous = 0;
4582   my $balance = 0;
4583   my @out = ();
4584   foreach my $item (@history) {
4585     last if $$opt{'end_date'} && ($$item{'date'} >= $$opt{'end_date'});
4586     $balance += $$item{'amount'};
4587     if ($$opt{'start_date'} && ($$item{'date'} < $$opt{'start_date'})) {
4588       $previous += $$item{'amount'};
4589       next;
4590     }
4591     $$item{'balance'} = sprintf("%.2f",$balance);
4592     foreach my $key ( qw(amount balance) ) {
4593       $$item{$key.'_pretty'} = money_pretty($$item{$key});
4594     }
4595     push(@out,$item);
4596   }
4597
4598   # start with previous balance, if there was one
4599   if ($previous) {
4600     my $item = {
4601       'type'        => 'Previous',
4602       'description' => 'Previous balance',
4603       'amount'      => sprintf("%.2f",$previous),
4604       'balance'     => sprintf("%.2f",$previous),
4605       'date'        => $$opt{'start_date'},
4606       'date_pretty' => $self->time2str_local('short', $$opt{'start_date'} ),
4607     };
4608     #false laziness with above
4609     foreach my $key ( qw(amount balance) ) {
4610       $$item{$key.'_pretty'} = $$item{$key};
4611       $$item{$key.'_pretty'} =~ s/^(-?)/$1$money_char/;
4612     }
4613     unshift(@out,$item);
4614   }
4615
4616   @out = reverse @history if $$opt{'reverse_sort'};
4617
4618   return @out;
4619 }
4620
4621 =back
4622
4623 =head1 CLASS METHODS
4624
4625 =over 4
4626
4627 =item statuses
4628
4629 Class method that returns the list of possible status strings for customers
4630 (see L<the status method|/status>).  For example:
4631
4632   @statuses = FS::cust_main->statuses();
4633
4634 =cut
4635
4636 sub statuses {
4637   my $self = shift;
4638   keys %{ $self->statuscolors };
4639 }
4640
4641 =item cust_status_sql
4642
4643 Returns an SQL fragment to determine the status of a cust_main record, as a 
4644 string.
4645
4646 =cut
4647
4648 sub cust_status_sql {
4649   my $sql = 'CASE';
4650   for my $status ( FS::cust_main->statuses() ) {
4651     my $method = $status.'_sql';
4652     $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
4653   }
4654   $sql .= ' END';
4655   return $sql;
4656 }
4657
4658
4659 =item prospect_sql
4660
4661 Returns an SQL expression identifying prospective cust_main records (customers
4662 with no packages ever ordered)
4663
4664 =cut
4665
4666 use vars qw($select_count_pkgs);
4667 $select_count_pkgs =
4668   "SELECT COUNT(*) FROM cust_pkg
4669     WHERE cust_pkg.custnum = cust_main.custnum";
4670
4671 sub select_count_pkgs_sql {
4672   $select_count_pkgs;
4673 }
4674
4675 sub prospect_sql {
4676   " 0 = ( $select_count_pkgs ) ";
4677 }
4678
4679 =item ordered_sql
4680
4681 Returns an SQL expression identifying ordered cust_main records (customers with
4682 no active packages, but recurring packages not yet setup or one time charges
4683 not yet billed).
4684
4685 =cut
4686
4687 sub ordered_sql {
4688   FS::cust_main->none_active_sql.
4689   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4690 }
4691
4692 =item active_sql
4693
4694 Returns an SQL expression identifying active cust_main records (customers with
4695 active recurring packages).
4696
4697 =cut
4698
4699 sub active_sql {
4700   " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4701 }
4702
4703 =item none_active_sql
4704
4705 Returns an SQL expression identifying cust_main records with no active
4706 recurring packages.  This includes customers of status prospect, ordered,
4707 inactive, and suspended.
4708
4709 =cut
4710
4711 sub none_active_sql {
4712   " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4713 }
4714
4715 =item inactive_sql
4716
4717 Returns an SQL expression identifying inactive cust_main records (customers with
4718 no active recurring packages, but otherwise unsuspended/uncancelled).
4719
4720 =cut
4721
4722 sub inactive_sql {
4723   FS::cust_main->none_active_sql.
4724   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4725 }
4726
4727 =item susp_sql
4728 =item suspended_sql
4729
4730 Returns an SQL expression identifying suspended cust_main records.
4731
4732 =cut
4733
4734
4735 sub suspended_sql { susp_sql(@_); }
4736 sub susp_sql {
4737   FS::cust_main->none_active_sql.
4738   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4739 }
4740
4741 =item cancel_sql
4742 =item cancelled_sql
4743
4744 Returns an SQL expression identifying cancelled cust_main records.
4745
4746 =cut
4747
4748 sub cancel_sql { shift->cancelled_sql(@_); }
4749
4750 =item uncancel_sql
4751 =item uncancelled_sql
4752
4753 Returns an SQL expression identifying un-cancelled cust_main records.
4754
4755 =cut
4756
4757 sub uncancelled_sql { uncancel_sql(@_); }
4758 sub uncancel_sql { "
4759   ( 0 < ( $select_count_pkgs
4760                    AND ( cust_pkg.cancel IS NULL
4761                          OR cust_pkg.cancel = 0
4762                        )
4763         )
4764     OR 0 = ( $select_count_pkgs )
4765   )
4766 "; }
4767
4768 =item balance_sql
4769
4770 Returns an SQL fragment to retreive the balance.
4771
4772 =cut
4773
4774 sub balance_sql { "
4775     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4776         WHERE cust_bill.custnum   = cust_main.custnum     )
4777   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
4778         WHERE cust_pay.custnum    = cust_main.custnum     )
4779   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
4780         WHERE cust_credit.custnum = cust_main.custnum     )
4781   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
4782         WHERE cust_refund.custnum = cust_main.custnum     )
4783 "; }
4784
4785 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4786
4787 Returns an SQL fragment to retreive the balance for this customer, optionally
4788 considering invoices with date earlier than START_TIME, and not
4789 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4790 total_unapplied_payments).
4791
4792 Times are specified as SQL fragments or numeric
4793 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
4794 L<Date::Parse> for conversion functions.  The empty string can be passed
4795 to disable that time constraint completely.
4796
4797 Available options are:
4798
4799 =over 4
4800
4801 =item unapplied_date
4802
4803 set to true to disregard unapplied credits, payments and refunds outside the specified time period - by default the time period restriction only applies to invoices (useful for reporting, probably a bad idea for event triggering)
4804
4805 =item total
4806
4807 (unused.  obsolete?)
4808 set to true to remove all customer comparison clauses, for totals
4809
4810 =item where
4811
4812 (unused.  obsolete?)
4813 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4814
4815 =item join
4816
4817 (unused.  obsolete?)
4818 JOIN clause (typically used with the total option)
4819
4820 =item cutoff
4821
4822 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
4823 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
4824 range for invoices and I<unapplied> payments, credits, and refunds.
4825
4826 =back
4827
4828 =cut
4829
4830 sub balance_date_sql {
4831   my( $class, $start, $end, %opt ) = @_;
4832
4833   my $cutoff = $opt{'cutoff'};
4834
4835   my $owed         = FS::cust_bill->owed_sql($cutoff);
4836   my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4837   my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4838   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
4839
4840   my $j = $opt{'join'} || '';
4841
4842   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
4843   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4844   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4845   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
4846
4847   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
4848     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4849     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4850     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
4851   ";
4852
4853 }
4854
4855 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4856
4857 Returns an SQL fragment to retreive the total unapplied payments for this
4858 customer, only considering payments with date earlier than START_TIME, and
4859 optionally not later than END_TIME.
4860
4861 Times are specified as SQL fragments or numeric
4862 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
4863 L<Date::Parse> for conversion functions.  The empty string can be passed
4864 to disable that time constraint completely.
4865
4866 Available options are:
4867
4868 =cut
4869
4870 sub unapplied_payments_date_sql {
4871   my( $class, $start, $end, %opt ) = @_;
4872
4873   my $cutoff = $opt{'cutoff'};
4874
4875   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
4876
4877   my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4878                                                           'unapplied_date'=>1 );
4879
4880   " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4881 }
4882
4883 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4884
4885 Helper method for balance_date_sql; name (and usage) subject to change
4886 (suggestions welcome).
4887
4888 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4889 cust_refund, cust_credit or cust_pay).
4890
4891 If TABLE is "cust_bill" or the unapplied_date option is true, only
4892 considers records with date earlier than START_TIME, and optionally not
4893 later than END_TIME .
4894
4895 =cut
4896
4897 sub _money_table_where {
4898   my( $class, $table, $start, $end, %opt ) = @_;
4899
4900   my @where = ();
4901   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4902   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4903     push @where, "$table._date <= $start" if defined($start) && length($start);
4904     push @where, "$table._date >  $end"   if defined($end)   && length($end);
4905   }
4906   push @where, @{$opt{'where'}} if $opt{'where'};
4907   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4908
4909   $where;
4910
4911 }
4912
4913 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4914 use FS::cust_main::Search;
4915 sub search {
4916   my $class = shift;
4917   FS::cust_main::Search->search(@_);
4918 }
4919
4920 =back
4921
4922 =head1 SUBROUTINES
4923
4924 =over 4
4925
4926 =item batch_charge
4927
4928 =cut
4929
4930 sub batch_charge {
4931   my $param = shift;
4932   #warn join('-',keys %$param);
4933   my $fh = $param->{filehandle};
4934   my $agentnum = $param->{agentnum};
4935   my $format = $param->{format};
4936
4937   my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4938
4939   my @fields;
4940   if ( $format eq 'simple' ) {
4941     @fields = qw( custnum agent_custid amount pkg );
4942   } else {
4943     die "unknown format $format";
4944   }
4945
4946   eval "use Text::CSV_XS;";
4947   die $@ if $@;
4948
4949   my $csv = new Text::CSV_XS;
4950   #warn $csv;
4951   #warn $fh;
4952
4953   my $imported = 0;
4954   #my $columns;
4955
4956   local $SIG{HUP} = 'IGNORE';
4957   local $SIG{INT} = 'IGNORE';
4958   local $SIG{QUIT} = 'IGNORE';
4959   local $SIG{TERM} = 'IGNORE';
4960   local $SIG{TSTP} = 'IGNORE';
4961   local $SIG{PIPE} = 'IGNORE';
4962
4963   my $oldAutoCommit = $FS::UID::AutoCommit;
4964   local $FS::UID::AutoCommit = 0;
4965   my $dbh = dbh;
4966   
4967   #while ( $columns = $csv->getline($fh) ) {
4968   my $line;
4969   while ( defined($line=<$fh>) ) {
4970
4971     $csv->parse($line) or do {
4972       $dbh->rollback if $oldAutoCommit;
4973       return "can't parse: ". $csv->error_input();
4974     };
4975
4976     my @columns = $csv->fields();
4977     #warn join('-',@columns);
4978
4979     my %row = ();
4980     foreach my $field ( @fields ) {
4981       $row{$field} = shift @columns;
4982     }
4983
4984     if ( $row{custnum} && $row{agent_custid} ) {
4985       dbh->rollback if $oldAutoCommit;
4986       return "can't specify custnum with agent_custid $row{agent_custid}";
4987     }
4988
4989     my %hash = ();
4990     if ( $row{agent_custid} && $agentnum ) {
4991       %hash = ( 'agent_custid' => $row{agent_custid},
4992                 'agentnum'     => $agentnum,
4993               );
4994     }
4995
4996     if ( $row{custnum} ) {
4997       %hash = ( 'custnum' => $row{custnum} );
4998     }
4999
5000     unless ( scalar(keys %hash) ) {
5001       $dbh->rollback if $oldAutoCommit;
5002       return "can't find customer without custnum or agent_custid and agentnum";
5003     }
5004
5005     my $cust_main = qsearchs('cust_main', { %hash } );
5006     unless ( $cust_main ) {
5007       $dbh->rollback if $oldAutoCommit;
5008       my $custnum = $row{custnum} || $row{agent_custid};
5009       return "unknown custnum $custnum";
5010     }
5011
5012     if ( $row{'amount'} > 0 ) {
5013       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5014       if ( $error ) {
5015         $dbh->rollback if $oldAutoCommit;
5016         return $error;
5017       }
5018       $imported++;
5019     } elsif ( $row{'amount'} < 0 ) {
5020       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5021                                       $row{'pkg'}                         );
5022       if ( $error ) {
5023         $dbh->rollback if $oldAutoCommit;
5024         return $error;
5025       }
5026       $imported++;
5027     } else {
5028       #hmm?
5029     }
5030
5031   }
5032
5033   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5034
5035   return "Empty file!" unless $imported;
5036
5037   ''; #no error
5038
5039 }
5040
5041 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5042
5043 Deprecated.  Use event notification and message templates 
5044 (L<FS::msg_template>) instead.
5045
5046 Sends a templated email notification to the customer (see L<Text::Template>).
5047
5048 OPTIONS is a hash and may include
5049
5050 I<from> - the email sender (default is invoice_from)
5051
5052 I<to> - comma-separated scalar or arrayref of recipients 
5053    (default is invoicing_list)
5054
5055 I<subject> - The subject line of the sent email notification
5056    (default is "Notice from company_name")
5057
5058 I<extra_fields> - a hashref of name/value pairs which will be substituted
5059    into the template
5060
5061 The following variables are vavailable in the template.
5062
5063 I<$first> - the customer first name
5064 I<$last> - the customer last name
5065 I<$company> - the customer company
5066 I<$payby> - a description of the method of payment for the customer
5067             # would be nice to use FS::payby::shortname
5068 I<$payinfo> - the account information used to collect for this customer
5069 I<$expdate> - the expiration of the customer payment in seconds from epoch
5070
5071 =cut
5072
5073 sub notify {
5074   my ($self, $template, %options) = @_;
5075
5076   return unless $conf->exists($template);
5077
5078   my $from = $conf->invoice_from_full($self->agentnum)
5079     if $conf->exists('invoice_from', $self->agentnum);
5080   $from = $options{from} if exists($options{from});
5081
5082   my $to = join(',', $self->invoicing_list_emailonly);
5083   $to = $options{to} if exists($options{to});
5084   
5085   my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
5086     if $conf->exists('company_name', $self->agentnum);
5087   $subject = $options{subject} if exists($options{subject});
5088
5089   my $notify_template = new Text::Template (TYPE => 'ARRAY',
5090                                             SOURCE => [ map "$_\n",
5091                                               $conf->config($template)]
5092                                            )
5093     or die "can't create new Text::Template object: Text::Template::ERROR";
5094   $notify_template->compile()
5095     or die "can't compile template: Text::Template::ERROR";
5096
5097   $FS::notify_template::_template::company_name =
5098     $conf->config('company_name', $self->agentnum);
5099   $FS::notify_template::_template::company_address =
5100     join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
5101
5102   my $paydate = $self->paydate || '2037-12-31';
5103   $FS::notify_template::_template::first = $self->first;
5104   $FS::notify_template::_template::last = $self->last;
5105   $FS::notify_template::_template::company = $self->company;
5106   $FS::notify_template::_template::payinfo = $self->mask_payinfo;
5107   my $payby = $self->payby;
5108   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5109   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5110
5111   #credit cards expire at the end of the month/year of their exp date
5112   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5113     $FS::notify_template::_template::payby = 'credit card';
5114     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5115     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5116     $expire_time--;
5117   }elsif ($payby eq 'COMP') {
5118     $FS::notify_template::_template::payby = 'complimentary account';
5119   }else{
5120     $FS::notify_template::_template::payby = 'current method';
5121   }
5122   $FS::notify_template::_template::expdate = $expire_time;
5123
5124   for (keys %{$options{extra_fields}}){
5125     no strict "refs";
5126     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5127   }
5128
5129   send_email(from => $from,
5130              to => $to,
5131              subject => $subject,
5132              body => $notify_template->fill_in( PACKAGE =>
5133                                                 'FS::notify_template::_template'                                              ),
5134             );
5135
5136 }
5137
5138 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5139
5140 Generates a templated notification to the customer (see L<Text::Template>).
5141
5142 OPTIONS is a hash and may include
5143
5144 I<extra_fields> - a hashref of name/value pairs which will be substituted
5145    into the template.  These values may override values mentioned below
5146    and those from the customer record.
5147
5148 I<template_text> - if present, ignores TEMPLATE_NAME and uses the provided text
5149
5150 The following variables are available in the template instead of or in addition
5151 to the fields of the customer record.
5152
5153 I<$payby> - a description of the method of payment for the customer
5154             # would be nice to use FS::payby::shortname
5155 I<$payinfo> - the masked account information used to collect for this customer
5156 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5157 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
5158
5159 =cut
5160
5161 # a lot like cust_bill::print_latex
5162 sub generate_letter {
5163   my ($self, $template, %options) = @_;
5164
5165   warn "Template $template does not exist" && return
5166     unless $conf->exists($template) || $options{'template_text'};
5167
5168   my $template_source = $options{'template_text'} 
5169                         ? [ $options{'template_text'} ] 
5170                         : [ map "$_\n", $conf->config($template) ];
5171
5172   my $letter_template = new Text::Template
5173                         ( TYPE       => 'ARRAY',
5174                           SOURCE     => $template_source,
5175                           DELIMITERS => [ '[@--', '--@]' ],
5176                         )
5177     or die "can't create new Text::Template object: Text::Template::ERROR";
5178
5179   $letter_template->compile()
5180     or die "can't compile template: Text::Template::ERROR";
5181
5182   my %letter_data = map { $_ => $self->$_ } $self->fields;
5183   $letter_data{payinfo} = $self->mask_payinfo;
5184
5185   #my $paydate = $self->paydate || '2037-12-31';
5186   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
5187
5188   my $payby = $self->payby;
5189   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5190   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5191
5192   #credit cards expire at the end of the month/year of their exp date
5193   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5194     $letter_data{payby} = 'credit card';
5195     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5196     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5197     $expire_time--;
5198   }elsif ($payby eq 'COMP') {
5199     $letter_data{payby} = 'complimentary account';
5200   }else{
5201     $letter_data{payby} = 'current method';
5202   }
5203   $letter_data{expdate} = $expire_time;
5204
5205   for (keys %{$options{extra_fields}}){
5206     $letter_data{$_} = $options{extra_fields}->{$_};
5207   }
5208
5209   unless(exists($letter_data{returnaddress})){
5210     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5211                                                   $self->agent_template)
5212                      );
5213     if ( length($retadd) ) {
5214       $letter_data{returnaddress} = $retadd;
5215     } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
5216       $letter_data{returnaddress} =
5217         join( "\n", map { s/( {2,})/'~' x length($1)/eg;
5218                           s/$/\\\\\*/;
5219                           $_;
5220                         }
5221                     ( $conf->config('company_name', $self->agentnum),
5222                       $conf->config('company_address', $self->agentnum),
5223                     )
5224         );
5225     } else {
5226       $letter_data{returnaddress} = '~';
5227     }
5228   }
5229
5230   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5231
5232   $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
5233
5234   my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
5235
5236   my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5237                            DIR      => $dir,
5238                            SUFFIX   => '.eps',
5239                            UNLINK   => 0,
5240                          ) or die "can't open temp file: $!\n";
5241   print $lh $conf->config_binary('logo.eps', $self->agentnum)
5242     or die "can't write temp file: $!\n";
5243   close $lh;
5244   $letter_data{'logo_file'} = $lh->filename;
5245
5246   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5247                            DIR      => $dir,
5248                            SUFFIX   => '.tex',
5249                            UNLINK   => 0,
5250                          ) or die "can't open temp file: $!\n";
5251
5252   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5253   close $fh;
5254   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5255   return ($1, $letter_data{'logo_file'});
5256
5257 }
5258
5259 =item print_ps TEMPLATE 
5260
5261 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5262
5263 =cut
5264
5265 sub print_ps {
5266   my $self = shift;
5267   my($file, $lfile) = $self->generate_letter(@_);
5268   my $ps = FS::Misc::generate_ps($file);
5269   unlink($file.'.tex');
5270   unlink($lfile);
5271
5272   $ps;
5273 }
5274
5275 =item print TEMPLATE
5276
5277 Prints the filled in template.
5278
5279 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5280
5281 =cut
5282
5283 sub queueable_print {
5284   my %opt = @_;
5285
5286   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5287     or die "invalid customer number: " . $opt{custnum};
5288
5289   my $error = $self->print( { 'template' => $opt{template} } );
5290   die $error if $error;
5291 }
5292
5293 sub print {
5294   my ($self, $template) = (shift, shift);
5295   do_print(
5296     [ $self->print_ps($template) ],
5297     'agentnum' => $self->agentnum,
5298   );
5299 }
5300
5301 #these three subs should just go away once agent stuff is all config overrides
5302
5303 sub agent_template {
5304   my $self = shift;
5305   $self->_agent_plandata('agent_templatename');
5306 }
5307
5308 sub agent_invoice_from {
5309   my $self = shift;
5310   $self->_agent_plandata('agent_invoice_from');
5311 }
5312
5313 sub _agent_plandata {
5314   my( $self, $option ) = @_;
5315
5316   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
5317   #agent-specific Conf
5318
5319   use FS::part_event::Condition;
5320   
5321   my $agentnum = $self->agentnum;
5322
5323   my $regexp = regexp_sql();
5324
5325   my $part_event_option =
5326     qsearchs({
5327       'select'    => 'part_event_option.*',
5328       'table'     => 'part_event_option',
5329       'addl_from' => q{
5330         LEFT JOIN part_event USING ( eventpart )
5331         LEFT JOIN part_event_option AS peo_agentnum
5332           ON ( part_event.eventpart = peo_agentnum.eventpart
5333                AND peo_agentnum.optionname = 'agentnum'
5334                AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
5335              )
5336         LEFT JOIN part_event_condition
5337           ON ( part_event.eventpart = part_event_condition.eventpart
5338                AND part_event_condition.conditionname = 'cust_bill_age'
5339              )
5340         LEFT JOIN part_event_condition_option
5341           ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
5342                AND part_event_condition_option.optionname = 'age'
5343              )
5344       },
5345       #'hashref'   => { 'optionname' => $option },
5346       #'hashref'   => { 'part_event_option.optionname' => $option },
5347       'extra_sql' =>
5348         " WHERE part_event_option.optionname = ". dbh->quote($option).
5349         " AND action = 'cust_bill_send_agent' ".
5350         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
5351         " AND peo_agentnum.optionname = 'agentnum' ".
5352         " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
5353         " ORDER BY
5354            CASE WHEN part_event_condition_option.optionname IS NULL
5355            THEN -1
5356            ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
5357         " END
5358           , part_event.weight".
5359         " LIMIT 1"
5360     });
5361     
5362   unless ( $part_event_option ) {
5363     return $self->agent->invoice_template || ''
5364       if $option eq 'agent_templatename';
5365     return '';
5366   }
5367
5368   $part_event_option->optionvalue;
5369
5370 }
5371
5372 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
5373
5374 Subroutine (not a method), designed to be called from the queue.
5375
5376 Takes a list of options and values.
5377
5378 Pulls up the customer record via the custnum option and calls bill_and_collect.
5379
5380 =cut
5381
5382 sub queued_bill {
5383   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
5384
5385   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
5386   warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
5387
5388   #without this errors don't get rolled back
5389   $args{'fatal'} = 1; # runs from job queue, will be caught
5390
5391   $cust_main->bill_and_collect( %args );
5392 }
5393
5394 sub process_bill_and_collect {
5395   my $job = shift;
5396   my $param = thaw(decode_base64(shift));
5397   my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
5398       or die "custnum '$param->{custnum}' not found!\n";
5399   $param->{'job'}   = $job;
5400   $param->{'fatal'} = 1; # runs from job queue, will be caught
5401   $param->{'retry'} = 1;
5402
5403   $cust_main->bill_and_collect( %$param );
5404 }
5405
5406 #starting to take quite a while for big dbs
5407 #   (JRNL: journaled so it only happens once per database)
5408 # - seq scan of h_cust_main (yuck), but not going to index paycvv, so
5409 # JRNL seq scan of cust_main on signupdate... index signupdate?  will that help?
5410 # JRNL seq scan of cust_main on paydate... index on substrings?  maybe set an
5411 # JRNL seq scan of cust_main on payinfo.. certainly not going toi ndex that...
5412 # JRNL leading/trailing spaces in first, last, company
5413 # - otaker upgrade?  journal and call it good?  (double check to make sure
5414 #    we're not still setting otaker here)
5415 #
5416 #only going to get worse with new location stuff...
5417
5418 sub _upgrade_data { #class method
5419   my ($class, %opts) = @_;
5420
5421   my @statements = (
5422     'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
5423   );
5424
5425   #this seems to be the only expensive one.. why does it take so long?
5426   unless ( FS::upgrade_journal->is_done('cust_main__signupdate') ) {
5427     push @statements,
5428       'UPDATE cust_main SET signupdate = (SELECT signupdate FROM h_cust_main WHERE signupdate IS NOT NULL AND h_cust_main.custnum = cust_main.custnum ORDER BY historynum DESC LIMIT 1) WHERE signupdate IS NULL';
5429     FS::upgrade_journal->set_done('cust_main__signupdate');
5430   }
5431
5432   unless ( FS::upgrade_journal->is_done('cust_main__paydate') ) {
5433
5434     # fix yyyy-m-dd formatted paydates
5435     if ( driver_name =~ /^mysql/i ) {
5436       push @statements,
5437       "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5438     } else { # the SQL standard
5439       push @statements, 
5440       "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
5441     }
5442     FS::upgrade_journal->set_done('cust_main__paydate');
5443   }
5444
5445   unless ( FS::upgrade_journal->is_done('cust_main__payinfo') ) {
5446
5447     push @statements, #fix the weird BILL with a cc# in payinfo problem
5448       #DCRD to be safe
5449       "UPDATE cust_main SET payby = 'DCRD' WHERE payby = 'BILL' and length(payinfo) = 16 and payinfo ". regexp_sql. q( '^[0-9]*$' );
5450
5451     FS::upgrade_journal->set_done('cust_main__payinfo');
5452     
5453   }
5454
5455   my $t = time;
5456   foreach my $sql ( @statements ) {
5457     my $sth = dbh->prepare($sql) or die dbh->errstr;
5458     $sth->execute or die $sth->errstr;
5459     #warn ( (time - $t). " seconds\n" );
5460     #$t = time;
5461   }
5462
5463   local($ignore_expired_card) = 1;
5464   local($ignore_banned_card) = 1;
5465   local($skip_fuzzyfiles) = 1;
5466   local($import) = 1; #prevent automatic geocoding (need its own variable?)
5467
5468   FS::cust_main::Location->_upgrade_data(%opts);
5469
5470   unless ( FS::upgrade_journal->is_done('cust_main__trimspaces') ) {
5471
5472     foreach my $cust_main ( qsearch({
5473       'table'     => 'cust_main', 
5474       'hashref'   => {},
5475       'extra_sql' => 'WHERE '.
5476                        join(' OR ',
5477                          map "$_ LIKE ' %' OR $_ LIKE '% ' OR $_ LIKE '%  %'",
5478                            qw( first last company )
5479                        ),
5480     }) ) {
5481       my $error = $cust_main->replace;
5482       die $error if $error;
5483     }
5484
5485     FS::upgrade_journal->set_done('cust_main__trimspaces');
5486
5487   }
5488
5489   $class->_upgrade_otaker(%opts);
5490
5491 }
5492
5493 =back
5494
5495 =head1 BUGS
5496
5497 The delete method.
5498
5499 The delete method should possibly take an FS::cust_main object reference
5500 instead of a scalar customer number.
5501
5502 Bill and collect options should probably be passed as references instead of a
5503 list.
5504
5505 There should probably be a configuration file with a list of allowed credit
5506 card types.
5507
5508 No multiple currency support (probably a larger project than just this module).
5509
5510 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
5511
5512 Birthdates rely on negative epoch values.
5513
5514 The payby for card/check batches is broken.  With mixed batching, bad
5515 things will happen.
5516
5517 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
5518
5519 =head1 SEE ALSO
5520
5521 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
5522 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
5523 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
5524
5525 =cut
5526
5527 1;
5528