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