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