add signup-duplicate_cc-warn_hours to warn about duplicate signups in a time span...
[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 $SIG{HUP} = 'IGNORE';
1444   local $SIG{INT} = 'IGNORE';
1445   local $SIG{QUIT} = 'IGNORE';
1446   local $SIG{TERM} = 'IGNORE';
1447   local $SIG{TSTP} = 'IGNORE';
1448   local $SIG{PIPE} = 'IGNORE';
1449
1450   my $oldAutoCommit = $FS::UID::AutoCommit;
1451   local $FS::UID::AutoCommit = 0;
1452   my $dbh = dbh;
1453
1454   my $error = $self->SUPER::replace($old);
1455
1456   if ( $error ) {
1457     $dbh->rollback if $oldAutoCommit;
1458     return $error;
1459   }
1460
1461   if ( @param && ref($param[0]) eq 'ARRAY' ) { # INVOICING_LIST_ARYREF
1462     my $invoicing_list = shift @param;
1463     $error = $self->check_invoicing_list( $invoicing_list );
1464     if ( $error ) {
1465       $dbh->rollback if $oldAutoCommit;
1466       return $error;
1467     }
1468     $self->invoicing_list( $invoicing_list );
1469   }
1470
1471   if ( $self->exists('tagnum') ) { #so we don't delete these on edit by accident
1472
1473     #this could be more efficient than deleting and re-inserting, if it matters
1474     foreach my $cust_tag (qsearch('cust_tag', {'custnum'=>$self->custnum} )) {
1475       my $error = $cust_tag->delete;
1476       if ( $error ) {
1477         $dbh->rollback if $oldAutoCommit;
1478         return $error;
1479       }
1480     }
1481     foreach my $tagnum ( @{ $self->tagnum || [] } ) {
1482       my $cust_tag = new FS::cust_tag { 'tagnum'  => $tagnum,
1483                                         'custnum' => $self->custnum };
1484       my $error = $cust_tag->insert;
1485       if ( $error ) {
1486         $dbh->rollback if $oldAutoCommit;
1487         return $error;
1488       }
1489     }
1490
1491   }
1492
1493   my %options = @param;
1494
1495   my $tax_exemption = delete $options{'tax_exemption'};
1496   if ( $tax_exemption ) {
1497
1498     my %cust_main_exemption =
1499       map { $_->taxname => $_ }
1500           qsearch('cust_main_exemption', { 'custnum' => $old->custnum } );
1501
1502     foreach my $taxname ( @$tax_exemption ) {
1503
1504       next if delete $cust_main_exemption{$taxname};
1505
1506       my $cust_main_exemption = new FS::cust_main_exemption {
1507         'custnum' => $self->custnum,
1508         'taxname' => $taxname,
1509       };
1510       my $error = $cust_main_exemption->insert;
1511       if ( $error ) {
1512         $dbh->rollback if $oldAutoCommit;
1513         return "inserting cust_main_exemption (transaction rolled back): $error";
1514       }
1515     }
1516
1517     foreach my $cust_main_exemption ( values %cust_main_exemption ) {
1518       my $error = $cust_main_exemption->delete;
1519       if ( $error ) {
1520         $dbh->rollback if $oldAutoCommit;
1521         return "deleting cust_main_exemption (transaction rolled back): $error";
1522       }
1523     }
1524
1525   }
1526
1527   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/
1528        && ( ( $self->get('payinfo') ne $old->get('payinfo')
1529               && $self->get('payinfo') !~ /^99\d{14}$/ 
1530             )
1531             || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
1532           )
1533      )
1534   {
1535
1536     # card/check/lec info has changed, want to retry realtime_ invoice events
1537     my $error = $self->retry_realtime;
1538     if ( $error ) {
1539       $dbh->rollback if $oldAutoCommit;
1540       return $error;
1541     }
1542   }
1543
1544   unless ( $import || $skip_fuzzyfiles ) {
1545     $error = $self->queue_fuzzyfiles_update;
1546     if ( $error ) {
1547       $dbh->rollback if $oldAutoCommit;
1548       return "updating fuzzy search cache: $error";
1549     }
1550   }
1551
1552   # cust_main exports!
1553
1554   my $export_args = $options{'export_args'} || [];
1555
1556   my @part_export =
1557     map qsearch( 'part_export', {exportnum=>$_} ),
1558       $conf->config('cust_main-exports'); #, $agentnum
1559
1560   foreach my $part_export ( @part_export ) {
1561     my $error = $part_export->export_replace( $self, $old, @$export_args);
1562     if ( $error ) {
1563       $dbh->rollback if $oldAutoCommit;
1564       return "exporting to ". $part_export->exporttype.
1565              " (transaction rolled back): $error";
1566     }
1567   }
1568
1569   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1570   '';
1571
1572 }
1573
1574 =item queue_fuzzyfiles_update
1575
1576 Used by insert & replace to update the fuzzy search cache
1577
1578 =cut
1579
1580 sub queue_fuzzyfiles_update {
1581   my $self = shift;
1582
1583   local $SIG{HUP} = 'IGNORE';
1584   local $SIG{INT} = 'IGNORE';
1585   local $SIG{QUIT} = 'IGNORE';
1586   local $SIG{TERM} = 'IGNORE';
1587   local $SIG{TSTP} = 'IGNORE';
1588   local $SIG{PIPE} = 'IGNORE';
1589
1590   my $oldAutoCommit = $FS::UID::AutoCommit;
1591   local $FS::UID::AutoCommit = 0;
1592   my $dbh = dbh;
1593
1594   my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1595   my $error = $queue->insert( map $self->getfield($_), @fuzzyfields );
1596   if ( $error ) {
1597     $dbh->rollback if $oldAutoCommit;
1598     return "queueing job (transaction rolled back): $error";
1599   }
1600
1601   if ( $self->ship_last ) {
1602     $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1603     $error = $queue->insert( map $self->getfield("ship_$_"), @fuzzyfields );
1604     if ( $error ) {
1605       $dbh->rollback if $oldAutoCommit;
1606       return "queueing job (transaction rolled back): $error";
1607     }
1608   }
1609
1610   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1611   '';
1612
1613 }
1614
1615 =item check
1616
1617 Checks all fields to make sure this is a valid customer record.  If there is
1618 an error, returns the error, otherwise returns false.  Called by the insert
1619 and replace methods.
1620
1621 =cut
1622
1623 sub check {
1624   my $self = shift;
1625
1626   warn "$me check BEFORE: \n". $self->_dump
1627     if $DEBUG > 2;
1628
1629   my $error =
1630     $self->ut_numbern('custnum')
1631     || $self->ut_number('agentnum')
1632     || $self->ut_textn('agent_custid')
1633     || $self->ut_number('refnum')
1634     || $self->ut_foreign_keyn('classnum', 'cust_class', 'classnum')
1635     || $self->ut_textn('custbatch')
1636     || $self->ut_name('last')
1637     || $self->ut_name('first')
1638     || $self->ut_snumbern('birthdate')
1639     || $self->ut_snumbern('signupdate')
1640     || $self->ut_textn('company')
1641     || $self->ut_text('address1')
1642     || $self->ut_textn('address2')
1643     || $self->ut_text('city')
1644     || $self->ut_textn('county')
1645     || $self->ut_textn('state')
1646     || $self->ut_country('country')
1647     || $self->ut_anything('comments')
1648     || $self->ut_numbern('referral_custnum')
1649     || $self->ut_textn('stateid')
1650     || $self->ut_textn('stateid_state')
1651     || $self->ut_textn('invoice_terms')
1652     || $self->ut_alphan('geocode')
1653     || $self->ut_floatn('cdr_termination_percentage')
1654     || $self->ut_floatn('credit_limit')
1655     || $self->ut_numbern('billday')
1656   ;
1657
1658   #barf.  need message catalogs.  i18n.  etc.
1659   $error .= "Please select an advertising source."
1660     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1661   return $error if $error;
1662
1663   return "Unknown agent"
1664     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1665
1666   return "Unknown refnum"
1667     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1668
1669   return "Unknown referring custnum: ". $self->referral_custnum
1670     unless ! $self->referral_custnum 
1671            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1672
1673   if ( $self->censustract ne '' ) {
1674     $self->censustract =~ /^\s*(\d{9})\.?(\d{2})\s*$/
1675       or return "Illegal census tract: ". $self->censustract;
1676     
1677     $self->censustract("$1.$2");
1678   }
1679
1680   if ( $self->ss eq '' ) {
1681     $self->ss('');
1682   } else {
1683     my $ss = $self->ss;
1684     $ss =~ s/\D//g;
1685     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1686       or return "Illegal social security number: ". $self->ss;
1687     $self->ss("$1-$2-$3");
1688   }
1689
1690
1691 # bad idea to disable, causes billing to fail because of no tax rates later
1692 # except we don't fail any more
1693   unless ( $import ) {
1694     unless ( qsearch('cust_main_county', {
1695       'country' => $self->country,
1696       'state'   => '',
1697      } ) ) {
1698       return "Unknown state/county/country: ".
1699         $self->state. "/". $self->county. "/". $self->country
1700         unless qsearch('cust_main_county',{
1701           'state'   => $self->state,
1702           'county'  => $self->county,
1703           'country' => $self->country,
1704         } );
1705     }
1706   }
1707
1708   $error =
1709     $self->ut_phonen('daytime', $self->country)
1710     || $self->ut_phonen('night', $self->country)
1711     || $self->ut_phonen('fax', $self->country)
1712   ;
1713   return $error if $error;
1714
1715   unless ( $ignore_illegal_zip ) {
1716     $error = $self->ut_zip('zip', $self->country);
1717     return $error if $error;
1718   }
1719
1720   if ( $conf->exists('cust_main-require_phone')
1721        && ! length($self->daytime) && ! length($self->night)
1722      ) {
1723
1724     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1725                           ? 'Day Phone'
1726                           : FS::Msgcat::_gettext('daytime');
1727     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1728                         ? 'Night Phone'
1729                         : FS::Msgcat::_gettext('night');
1730   
1731     return "$daytime_label or $night_label is required"
1732   
1733   }
1734
1735   if ( $self->has_ship_address
1736        && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1737                         $self->addr_fields )
1738      )
1739   {
1740     my $error =
1741       $self->ut_name('ship_last')
1742       || $self->ut_name('ship_first')
1743       || $self->ut_textn('ship_company')
1744       || $self->ut_text('ship_address1')
1745       || $self->ut_textn('ship_address2')
1746       || $self->ut_text('ship_city')
1747       || $self->ut_textn('ship_county')
1748       || $self->ut_textn('ship_state')
1749       || $self->ut_country('ship_country')
1750     ;
1751     return $error if $error;
1752
1753     #false laziness with above
1754     unless ( qsearchs('cust_main_county', {
1755       'country' => $self->ship_country,
1756       'state'   => '',
1757      } ) ) {
1758       return "Unknown ship_state/ship_county/ship_country: ".
1759         $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1760         unless qsearch('cust_main_county',{
1761           'state'   => $self->ship_state,
1762           'county'  => $self->ship_county,
1763           'country' => $self->ship_country,
1764         } );
1765     }
1766     #eofalse
1767
1768     $error =
1769       $self->ut_phonen('ship_daytime', $self->ship_country)
1770       || $self->ut_phonen('ship_night', $self->ship_country)
1771       || $self->ut_phonen('ship_fax', $self->ship_country)
1772     ;
1773     return $error if $error;
1774
1775     unless ( $ignore_illegal_zip ) {
1776       $error = $self->ut_zip('ship_zip', $self->ship_country);
1777       return $error if $error;
1778     }
1779     return "Unit # is required."
1780       if $self->ship_address2 =~ /^\s*$/
1781       && $conf->exists('cust_main-require_address2');
1782
1783   } else { # ship_ info eq billing info, so don't store dup info in database
1784
1785     $self->setfield("ship_$_", '')
1786       foreach $self->addr_fields;
1787
1788     return "Unit # is required."
1789       if $self->address2 =~ /^\s*$/
1790       && $conf->exists('cust_main-require_address2');
1791
1792   }
1793
1794   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1795   #  or return "Illegal payby: ". $self->payby;
1796   #$self->payby($1);
1797   FS::payby->can_payby($self->table, $self->payby)
1798     or return "Illegal payby: ". $self->payby;
1799
1800   $error =    $self->ut_numbern('paystart_month')
1801            || $self->ut_numbern('paystart_year')
1802            || $self->ut_numbern('payissue')
1803            || $self->ut_textn('paytype')
1804   ;
1805   return $error if $error;
1806
1807   if ( $self->payip eq '' ) {
1808     $self->payip('');
1809   } else {
1810     $error = $self->ut_ip('payip');
1811     return $error if $error;
1812   }
1813
1814   # If it is encrypted and the private key is not availaible then we can't
1815   # check the credit card.
1816   my $check_payinfo = ! $self->is_encrypted($self->payinfo);
1817
1818   if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1819
1820     my $payinfo = $self->payinfo;
1821     $payinfo =~ s/\D//g;
1822     $payinfo =~ /^(\d{13,16})$/
1823       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1824     $payinfo = $1;
1825     $self->payinfo($payinfo);
1826     validate($payinfo)
1827       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1828
1829     return gettext('unknown_card_type')
1830       if $self->payinfo !~ /^99\d{14}$/ #token
1831       && cardtype($self->payinfo) eq "Unknown";
1832
1833     unless ( $ignore_banned_card ) {
1834       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1835       if ( $ban ) {
1836         if ( $ban->bantype eq 'warn' ) {
1837           #or others depending on value of $ban->reason ?
1838           return '_duplicate_card' unless $self->override_ban_warn;
1839         } else {
1840           return 'Banned credit card: banned on '.
1841                  time2str('%a %h %o at %r', $ban->_date).
1842                  ' by '. $ban->otaker.
1843                  ' (ban# '. $ban->bannum. ')';
1844         }
1845       }
1846     }
1847
1848     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1849       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1850         $self->paycvv =~ /^(\d{4})$/
1851           or return "CVV2 (CID) for American Express cards is four digits.";
1852         $self->paycvv($1);
1853       } else {
1854         $self->paycvv =~ /^(\d{3})$/
1855           or return "CVV2 (CVC2/CID) is three digits.";
1856         $self->paycvv($1);
1857       }
1858     } else {
1859       $self->paycvv('');
1860     }
1861
1862     my $cardtype = cardtype($payinfo);
1863     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1864
1865       return "Start date or issue number is required for $cardtype cards"
1866         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1867
1868       return "Start month must be between 1 and 12"
1869         if $self->paystart_month
1870            and $self->paystart_month < 1 || $self->paystart_month > 12;
1871
1872       return "Start year must be 1990 or later"
1873         if $self->paystart_year
1874            and $self->paystart_year < 1990;
1875
1876       return "Issue number must be beween 1 and 99"
1877         if $self->payissue
1878           and $self->payissue < 1 || $self->payissue > 99;
1879
1880     } else {
1881       $self->paystart_month('');
1882       $self->paystart_year('');
1883       $self->payissue('');
1884     }
1885
1886   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1887
1888     my $payinfo = $self->payinfo;
1889     $payinfo =~ s/[^\d\@\.]//g;
1890     if ( $conf->exists('cust_main-require-bank-branch') ) {
1891       $payinfo =~ /^(\d+)\@(\d+)\.(\d+)$/ or return 'invalid echeck account@branch.bank';
1892       $payinfo = "$1\@$2.$3";
1893     }
1894     elsif ( $conf->exists('echeck-nonus') ) {
1895       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1896       $payinfo = "$1\@$2";
1897     } else {
1898       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1899       $payinfo = "$1\@$2";
1900     }
1901     $self->payinfo($payinfo);
1902     $self->paycvv('');
1903
1904     unless ( $ignore_banned_card ) {
1905       my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
1906       if ( $ban ) {
1907         if ( $ban->bantype eq 'warn' ) {
1908           #or others depending on value of $ban->reason ?
1909           return '_duplicate_ach' unless $self->override_ban_warn;
1910         } else {
1911           return 'Banned ACH account: banned on '.
1912                  time2str('%a %h %o at %r', $ban->_date).
1913                  ' by '. $ban->otaker.
1914                  ' (ban# '. $ban->bannum. ')';
1915         }
1916       }
1917     }
1918
1919   } elsif ( $self->payby eq 'LECB' ) {
1920
1921     my $payinfo = $self->payinfo;
1922     $payinfo =~ s/\D//g;
1923     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1924     $payinfo = $1;
1925     $self->payinfo($payinfo);
1926     $self->paycvv('');
1927
1928   } elsif ( $self->payby eq 'BILL' ) {
1929
1930     $error = $self->ut_textn('payinfo');
1931     return "Illegal P.O. number: ". $self->payinfo if $error;
1932     $self->paycvv('');
1933
1934   } elsif ( $self->payby eq 'COMP' ) {
1935
1936     my $curuser = $FS::CurrentUser::CurrentUser;
1937     if (    ! $self->custnum
1938          && ! $curuser->access_right('Complimentary customer')
1939        )
1940     {
1941       return "You are not permitted to create complimentary accounts."
1942     }
1943
1944     $error = $self->ut_textn('payinfo');
1945     return "Illegal comp account issuer: ". $self->payinfo if $error;
1946     $self->paycvv('');
1947
1948   } elsif ( $self->payby eq 'PREPAY' ) {
1949
1950     my $payinfo = $self->payinfo;
1951     $payinfo =~ s/\W//g; #anything else would just confuse things
1952     $self->payinfo($payinfo);
1953     $error = $self->ut_alpha('payinfo');
1954     return "Illegal prepayment identifier: ". $self->payinfo if $error;
1955     return "Unknown prepayment identifier"
1956       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1957     $self->paycvv('');
1958
1959   }
1960
1961   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1962     return "Expiration date required"
1963       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1964     $self->paydate('');
1965   } else {
1966     my( $m, $y );
1967     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1968       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1969     } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1970       ( $m, $y ) = ( $2, "19$1" );
1971     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1972       ( $m, $y ) = ( $3, "20$2" );
1973     } else {
1974       return "Illegal expiration date: ". $self->paydate;
1975     }
1976     $m = sprintf('%02d',$m);
1977     $self->paydate("$y-$m-01");
1978     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1979     return gettext('expired_card')
1980       if !$import
1981       && !$ignore_expired_card 
1982       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1983   }
1984
1985   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1986        ( ! $conf->exists('require_cardname')
1987          || $self->payby !~ /^(CARD|DCRD)$/  ) 
1988   ) {
1989     $self->payname( $self->first. " ". $self->getfield('last') );
1990   } else {
1991     $self->payname =~ /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \,\.\-\'\&]+)$/
1992       or return gettext('illegal_name'). " payname: ". $self->payname;
1993     $self->payname($1);
1994   }
1995
1996   foreach my $flag (qw( tax spool_cdr squelch_cdr archived email_csv_cdr )) {
1997     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1998     $self->$flag($1);
1999   }
2000
2001   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
2002
2003   warn "$me check AFTER: \n". $self->_dump
2004     if $DEBUG > 2;
2005
2006   $self->SUPER::check;
2007 }
2008
2009 =item addr_fields 
2010
2011 Returns a list of fields which have ship_ duplicates.
2012
2013 =cut
2014
2015 sub addr_fields {
2016   qw( last first company
2017       address1 address2 city county state zip country
2018       daytime night fax
2019     );
2020 }
2021
2022 =item has_ship_address
2023
2024 Returns true if this customer record has a separate shipping address.
2025
2026 =cut
2027
2028 sub has_ship_address {
2029   my $self = shift;
2030   scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
2031 }
2032
2033 =item location_hash
2034
2035 Returns a list of key/value pairs, with the following keys: address1, adddress2,
2036 city, county, state, zip, country, and geocode.  The shipping address is used if present.
2037
2038 =cut
2039
2040 =item cust_location
2041
2042 Returns all locations (see L<FS::cust_location>) for this customer.
2043
2044 =cut
2045
2046 sub cust_location {
2047   my $self = shift;
2048   qsearch('cust_location', { 'custnum' => $self->custnum } );
2049 }
2050
2051 =item unsuspend
2052
2053 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
2054 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
2055 on success or a list of errors.
2056
2057 =cut
2058
2059 sub unsuspend {
2060   my $self = shift;
2061   grep { $_->unsuspend } $self->suspended_pkgs;
2062 }
2063
2064 =item suspend
2065
2066 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
2067
2068 Returns a list: an empty list on success or a list of errors.
2069
2070 =cut
2071
2072 sub suspend {
2073   my $self = shift;
2074   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
2075 }
2076
2077 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2078
2079 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
2080 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
2081 of a list of pkgparts; the hashref has the following keys:
2082
2083 =over 4
2084
2085 =item pkgparts - listref of pkgparts
2086
2087 =item (other options are passed to the suspend method)
2088
2089 =back
2090
2091
2092 Returns a list: an empty list on success or a list of errors.
2093
2094 =cut
2095
2096 sub suspend_if_pkgpart {
2097   my $self = shift;
2098   my (@pkgparts, %opt);
2099   if (ref($_[0]) eq 'HASH'){
2100     @pkgparts = @{$_[0]{pkgparts}};
2101     %opt      = %{$_[0]};
2102   }else{
2103     @pkgparts = @_;
2104   }
2105   grep { $_->suspend(%opt) }
2106     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
2107       $self->unsuspended_pkgs;
2108 }
2109
2110 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
2111
2112 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
2113 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
2114 instead of a list of pkgparts; the hashref has the following keys:
2115
2116 =over 4
2117
2118 =item pkgparts - listref of pkgparts
2119
2120 =item (other options are passed to the suspend method)
2121
2122 =back
2123
2124 Returns a list: an empty list on success or a list of errors.
2125
2126 =cut
2127
2128 sub suspend_unless_pkgpart {
2129   my $self = shift;
2130   my (@pkgparts, %opt);
2131   if (ref($_[0]) eq 'HASH'){
2132     @pkgparts = @{$_[0]{pkgparts}};
2133     %opt      = %{$_[0]};
2134   }else{
2135     @pkgparts = @_;
2136   }
2137   grep { $_->suspend(%opt) }
2138     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
2139       $self->unsuspended_pkgs;
2140 }
2141
2142 =item cancel [ OPTION => VALUE ... ]
2143
2144 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
2145
2146 Available options are:
2147
2148 =over 4
2149
2150 =item quiet - can be set true to supress email cancellation notices.
2151
2152 =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.
2153
2154 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
2155
2156 =item nobill - can be set true to skip billing if it might otherwise be done.
2157
2158 =back
2159
2160 Always returns a list: an empty list on success or a list of errors.
2161
2162 =cut
2163
2164 # nb that dates are not specified as valid options to this method
2165
2166 sub cancel {
2167   my( $self, %opt ) = @_;
2168
2169   warn "$me cancel called on customer ". $self->custnum. " with options ".
2170        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
2171     if $DEBUG;
2172
2173   return ( 'access denied' )
2174     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
2175
2176   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
2177
2178     #should try decryption (we might have the private key)
2179     # and if not maybe queue a job for the server that does?
2180     return ( "Can't (yet) ban encrypted credit cards" )
2181       if $self->is_encrypted($self->payinfo);
2182
2183     my $ban = new FS::banned_pay $self->_new_banned_pay_hashref;
2184     my $error = $ban->insert;
2185     return ( $error ) if $error;
2186
2187   }
2188
2189   my @pkgs = $self->ncancelled_pkgs;
2190
2191   if ( !$opt{nobill} && $conf->exists('bill_usage_on_cancel') ) {
2192     $opt{nobill} = 1;
2193     my $error = $self->bill( pkg_list => [ @pkgs ], cancel => 1 );
2194     warn "Error billing during cancel, custnum ". $self->custnum. ": $error"
2195       if $error;
2196   }
2197
2198   warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
2199        scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
2200     if $DEBUG;
2201
2202   grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
2203 }
2204
2205 sub _banned_pay_hashref {
2206   my $self = shift;
2207
2208   my %payby2ban = (
2209     'CARD' => 'CARD',
2210     'DCRD' => 'CARD',
2211     'CHEK' => 'CHEK',
2212     'DCHK' => 'CHEK'
2213   );
2214
2215   {
2216     'payby'   => $payby2ban{$self->payby},
2217     'payinfo' => $self->payinfo,
2218     #don't ever *search* on reason! #'reason'  =>
2219   };
2220 }
2221
2222 sub _new_banned_pay_hashref {
2223   my $self = shift;
2224   my $hr = $self->_banned_pay_hashref;
2225   $hr->{payinfo} = md5_base64($hr->{payinfo});
2226   $hr;
2227 }
2228
2229 =item notes
2230
2231 Returns all notes (see L<FS::cust_main_note>) for this customer.
2232
2233 =cut
2234
2235 sub notes {
2236    my($self,$orderby_classnum) = (shift,shift);
2237    my $orderby = "_DATE DESC";
2238    $orderby = "CLASSNUM ASC, $orderby" if $orderby_classnum;
2239   qsearch( 'cust_main_note',
2240            { 'custnum' => $self->custnum },
2241            '',
2242            "ORDER BY $orderby",
2243          );
2244 }
2245
2246 =item agent
2247
2248 Returns the agent (see L<FS::agent>) for this customer.
2249
2250 =cut
2251
2252 sub agent {
2253   my $self = shift;
2254   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
2255 }
2256
2257 =item agent_name
2258
2259 Returns the agent name (see L<FS::agent>) for this customer.
2260
2261 =cut
2262
2263 sub agent_name {
2264   my $self = shift;
2265   $self->agent->agent;
2266 }
2267
2268 =item cust_tag
2269
2270 Returns any tags associated with this customer, as FS::cust_tag objects,
2271 or an empty list if there are no tags.
2272
2273 =cut
2274
2275 sub cust_tag {
2276   my $self = shift;
2277   qsearch('cust_tag', { 'custnum' => $self->custnum } );
2278 }
2279
2280 =item part_tag
2281
2282 Returns any tags associated with this customer, as FS::part_tag objects,
2283 or an empty list if there are no tags.
2284
2285 =cut
2286
2287 sub part_tag {
2288   my $self = shift;
2289   map $_->part_tag, $self->cust_tag; 
2290 }
2291
2292
2293 =item cust_class
2294
2295 Returns the customer class, as an FS::cust_class object, or the empty string
2296 if there is no customer class.
2297
2298 =cut
2299
2300 sub cust_class {
2301   my $self = shift;
2302   if ( $self->classnum ) {
2303     qsearchs('cust_class', { 'classnum' => $self->classnum } );
2304   } else {
2305     return '';
2306   } 
2307 }
2308
2309 =item categoryname 
2310
2311 Returns the customer category name, or the empty string if there is no customer
2312 category.
2313
2314 =cut
2315
2316 sub categoryname {
2317   my $self = shift;
2318   my $cust_class = $self->cust_class;
2319   $cust_class
2320     ? $cust_class->categoryname
2321     : '';
2322 }
2323
2324 =item classname 
2325
2326 Returns the customer class name, or the empty string if there is no customer
2327 class.
2328
2329 =cut
2330
2331 sub classname {
2332   my $self = shift;
2333   my $cust_class = $self->cust_class;
2334   $cust_class
2335     ? $cust_class->classname
2336     : '';
2337 }
2338
2339 =item BILLING METHODS
2340
2341 Documentation on billing methods has been moved to
2342 L<FS::cust_main::Billing>.
2343
2344 =item REALTIME BILLING METHODS
2345
2346 Documentation on realtime billing methods has been moved to
2347 L<FS::cust_main::Billing_Realtime>.
2348
2349 =item remove_cvv
2350
2351 Removes the I<paycvv> field from the database directly.
2352
2353 If there is an error, returns the error, otherwise returns false.
2354
2355 =cut
2356
2357 sub remove_cvv {
2358   my $self = shift;
2359   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2360     or return dbh->errstr;
2361   $sth->execute($self->custnum)
2362     or return $sth->errstr;
2363   $self->paycvv('');
2364   '';
2365 }
2366
2367 =item batch_card OPTION => VALUE...
2368
2369 Adds a payment for this invoice to the pending credit card batch (see
2370 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2371 runs the payment using a realtime gateway.
2372
2373 =cut
2374
2375 sub batch_card {
2376   my ($self, %options) = @_;
2377
2378   my $amount;
2379   if (exists($options{amount})) {
2380     $amount = $options{amount};
2381   }else{
2382     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
2383   }
2384   return '' unless $amount > 0;
2385   
2386   my $invnum = delete $options{invnum};
2387   my $payby = $options{payby} || $self->payby;  #still dubious
2388
2389   if ($options{'realtime'}) {
2390     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
2391                                 $amount,
2392                                 %options,
2393                               );
2394   }
2395
2396   my $oldAutoCommit = $FS::UID::AutoCommit;
2397   local $FS::UID::AutoCommit = 0;
2398   my $dbh = dbh;
2399
2400   #this needs to handle mysql as well as Pg, like svc_acct.pm
2401   #(make it into a common function if folks need to do batching with mysql)
2402   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
2403     or return "Cannot lock pay_batch: " . $dbh->errstr;
2404
2405   my %pay_batch = (
2406     'status' => 'O',
2407     'payby'  => FS::payby->payby2payment($payby),
2408   );
2409
2410   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
2411
2412   unless ( $pay_batch ) {
2413     $pay_batch = new FS::pay_batch \%pay_batch;
2414     my $error = $pay_batch->insert;
2415     if ( $error ) {
2416       $dbh->rollback if $oldAutoCommit;
2417       die "error creating new batch: $error\n";
2418     }
2419   }
2420
2421   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
2422       'batchnum' => $pay_batch->batchnum,
2423       'custnum'  => $self->custnum,
2424   } );
2425
2426   foreach (qw( address1 address2 city state zip country payby payinfo paydate
2427                payname )) {
2428     $options{$_} = '' unless exists($options{$_});
2429   }
2430
2431   my $cust_pay_batch = new FS::cust_pay_batch ( {
2432     'batchnum' => $pay_batch->batchnum,
2433     'invnum'   => $invnum || 0,                    # is there a better value?
2434                                                    # this field should be
2435                                                    # removed...
2436                                                    # cust_bill_pay_batch now
2437     'custnum'  => $self->custnum,
2438     'last'     => $self->getfield('last'),
2439     'first'    => $self->getfield('first'),
2440     'address1' => $options{address1} || $self->address1,
2441     'address2' => $options{address2} || $self->address2,
2442     'city'     => $options{city}     || $self->city,
2443     'state'    => $options{state}    || $self->state,
2444     'zip'      => $options{zip}      || $self->zip,
2445     'country'  => $options{country}  || $self->country,
2446     'payby'    => $options{payby}    || $self->payby,
2447     'payinfo'  => $options{payinfo}  || $self->payinfo,
2448     'exp'      => $options{paydate}  || $self->paydate,
2449     'payname'  => $options{payname}  || $self->payname,
2450     'amount'   => $amount,                         # consolidating
2451   } );
2452   
2453   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
2454     if $old_cust_pay_batch;
2455
2456   my $error;
2457   if ($old_cust_pay_batch) {
2458     $error = $cust_pay_batch->replace($old_cust_pay_batch)
2459   } else {
2460     $error = $cust_pay_batch->insert;
2461   }
2462
2463   if ( $error ) {
2464     $dbh->rollback if $oldAutoCommit;
2465     die $error;
2466   }
2467
2468   my $unapplied =   $self->total_unapplied_credits
2469                   + $self->total_unapplied_payments
2470                   + $self->in_transit_payments;
2471   foreach my $cust_bill ($self->open_cust_bill) {
2472     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
2473     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
2474       'invnum' => $cust_bill->invnum,
2475       'paybatchnum' => $cust_pay_batch->paybatchnum,
2476       'amount' => $cust_bill->owed,
2477       '_date' => time,
2478     };
2479     if ($unapplied >= $cust_bill_pay_batch->amount){
2480       $unapplied -= $cust_bill_pay_batch->amount;
2481       next;
2482     }else{
2483       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
2484                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
2485     }
2486     $error = $cust_bill_pay_batch->insert;
2487     if ( $error ) {
2488       $dbh->rollback if $oldAutoCommit;
2489       die $error;
2490     }
2491   }
2492
2493   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2494   '';
2495 }
2496
2497 =item total_owed
2498
2499 Returns the total owed for this customer on all invoices
2500 (see L<FS::cust_bill/owed>).
2501
2502 =cut
2503
2504 sub total_owed {
2505   my $self = shift;
2506   $self->total_owed_date(2145859200); #12/31/2037
2507 }
2508
2509 =item total_owed_date TIME
2510
2511 Returns the total owed for this customer on all invoices with date earlier than
2512 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2513 see L<Time::Local> and L<Date::Parse> for conversion functions.
2514
2515 =cut
2516
2517 sub total_owed_date {
2518   my $self = shift;
2519   my $time = shift;
2520
2521   my $custnum = $self->custnum;
2522
2523   my $owed_sql = FS::cust_bill->owed_sql;
2524
2525   my $sql = "
2526     SELECT SUM($owed_sql) FROM cust_bill
2527       WHERE custnum = $custnum
2528         AND _date <= $time
2529   ";
2530
2531   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2532
2533 }
2534
2535 =item total_owed_pkgnum PKGNUM
2536
2537 Returns the total owed on all invoices for this customer's specific package
2538 when using experimental package balances (see L<FS::cust_bill/owed_pkgnum>).
2539
2540 =cut
2541
2542 sub total_owed_pkgnum {
2543   my( $self, $pkgnum ) = @_;
2544   $self->total_owed_date_pkgnum(2145859200, $pkgnum); #12/31/2037
2545 }
2546
2547 =item total_owed_date_pkgnum TIME PKGNUM
2548
2549 Returns the total owed for this customer's specific package when using
2550 experimental package balances on all invoices with date earlier than
2551 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
2552 see L<Time::Local> and L<Date::Parse> for conversion functions.
2553
2554 =cut
2555
2556 sub total_owed_date_pkgnum {
2557   my( $self, $time, $pkgnum ) = @_;
2558
2559   my $total_bill = 0;
2560   foreach my $cust_bill (
2561     grep { $_->_date <= $time }
2562       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2563   ) {
2564     $total_bill += $cust_bill->owed_pkgnum($pkgnum);
2565   }
2566   sprintf( "%.2f", $total_bill );
2567
2568 }
2569
2570 =item total_paid
2571
2572 Returns the total amount of all payments.
2573
2574 =cut
2575
2576 sub total_paid {
2577   my $self = shift;
2578   my $total = 0;
2579   $total += $_->paid foreach $self->cust_pay;
2580   sprintf( "%.2f", $total );
2581 }
2582
2583 =item total_unapplied_credits
2584
2585 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2586 customer.  See L<FS::cust_credit/credited>.
2587
2588 =item total_credited
2589
2590 Old name for total_unapplied_credits.  Don't use.
2591
2592 =cut
2593
2594 sub total_credited {
2595   #carp "total_credited deprecated, use total_unapplied_credits";
2596   shift->total_unapplied_credits(@_);
2597 }
2598
2599 sub total_unapplied_credits {
2600   my $self = shift;
2601
2602   my $custnum = $self->custnum;
2603
2604   my $unapplied_sql = FS::cust_credit->unapplied_sql;
2605
2606   my $sql = "
2607     SELECT SUM($unapplied_sql) FROM cust_credit
2608       WHERE custnum = $custnum
2609   ";
2610
2611   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2612
2613 }
2614
2615 =item total_unapplied_credits_pkgnum PKGNUM
2616
2617 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2618 customer.  See L<FS::cust_credit/credited>.
2619
2620 =cut
2621
2622 sub total_unapplied_credits_pkgnum {
2623   my( $self, $pkgnum ) = @_;
2624   my $total_credit = 0;
2625   $total_credit += $_->credited foreach $self->cust_credit_pkgnum($pkgnum);
2626   sprintf( "%.2f", $total_credit );
2627 }
2628
2629
2630 =item total_unapplied_payments
2631
2632 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2633 See L<FS::cust_pay/unapplied>.
2634
2635 =cut
2636
2637 sub total_unapplied_payments {
2638   my $self = shift;
2639
2640   my $custnum = $self->custnum;
2641
2642   my $unapplied_sql = FS::cust_pay->unapplied_sql;
2643
2644   my $sql = "
2645     SELECT SUM($unapplied_sql) FROM cust_pay
2646       WHERE custnum = $custnum
2647   ";
2648
2649   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2650
2651 }
2652
2653 =item total_unapplied_payments_pkgnum PKGNUM
2654
2655 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer's
2656 specific package when using experimental package balances.  See
2657 L<FS::cust_pay/unapplied>.
2658
2659 =cut
2660
2661 sub total_unapplied_payments_pkgnum {
2662   my( $self, $pkgnum ) = @_;
2663   my $total_unapplied = 0;
2664   $total_unapplied += $_->unapplied foreach $self->cust_pay_pkgnum($pkgnum);
2665   sprintf( "%.2f", $total_unapplied );
2666 }
2667
2668
2669 =item total_unapplied_refunds
2670
2671 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
2672 customer.  See L<FS::cust_refund/unapplied>.
2673
2674 =cut
2675
2676 sub total_unapplied_refunds {
2677   my $self = shift;
2678   my $custnum = $self->custnum;
2679
2680   my $unapplied_sql = FS::cust_refund->unapplied_sql;
2681
2682   my $sql = "
2683     SELECT SUM($unapplied_sql) FROM cust_refund
2684       WHERE custnum = $custnum
2685   ";
2686
2687   sprintf( "%.2f", $self->scalar_sql($sql) || 0 );
2688
2689 }
2690
2691 =item balance
2692
2693 Returns the balance for this customer (total_owed plus total_unrefunded, minus
2694 total_unapplied_credits minus total_unapplied_payments).
2695
2696 =cut
2697
2698 sub balance {
2699   my $self = shift;
2700   $self->balance_date_range;
2701 }
2702
2703 =item balance_date TIME
2704
2705 Returns the balance for this customer, only considering invoices with date
2706 earlier than TIME (total_owed_date minus total_credited minus
2707 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
2708 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
2709 functions.
2710
2711 =cut
2712
2713 sub balance_date {
2714   my $self = shift;
2715   $self->balance_date_range(shift);
2716 }
2717
2718 =item balance_date_range [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
2719
2720 Returns the balance for this customer, optionally considering invoices with
2721 date earlier than START_TIME, and not later than END_TIME
2722 (total_owed_date minus total_unapplied_credits minus total_unapplied_payments).
2723
2724 Times are specified as SQL fragments or numeric
2725 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
2726 L<Date::Parse> for conversion functions.  The empty string can be passed
2727 to disable that time constraint completely.
2728
2729 Available options are:
2730
2731 =over 4
2732
2733 =item unapplied_date
2734
2735 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)
2736
2737 =back
2738
2739 =cut
2740
2741 sub balance_date_range {
2742   my $self = shift;
2743   my $sql = 'SELECT SUM('. $self->balance_date_sql(@_).
2744             ') FROM cust_main WHERE custnum='. $self->custnum;
2745   sprintf( '%.2f', $self->scalar_sql($sql) || 0 );
2746 }
2747
2748 =item balance_pkgnum PKGNUM
2749
2750 Returns the balance for this customer's specific package when using
2751 experimental package balances (total_owed plus total_unrefunded, minus
2752 total_unapplied_credits minus total_unapplied_payments)
2753
2754 =cut
2755
2756 sub balance_pkgnum {
2757   my( $self, $pkgnum ) = @_;
2758
2759   sprintf( "%.2f",
2760       $self->total_owed_pkgnum($pkgnum)
2761 # n/a - refunds aren't part of pkg-balances since they don't apply to invoices
2762 #    + $self->total_unapplied_refunds_pkgnum($pkgnum)
2763     - $self->total_unapplied_credits_pkgnum($pkgnum)
2764     - $self->total_unapplied_payments_pkgnum($pkgnum)
2765   );
2766 }
2767
2768 =item in_transit_payments
2769
2770 Returns the total of requests for payments for this customer pending in 
2771 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
2772
2773 =cut
2774
2775 sub in_transit_payments {
2776   my $self = shift;
2777   my $in_transit_payments = 0;
2778   foreach my $pay_batch ( qsearch('pay_batch', {
2779     'status' => 'I',
2780   } ) ) {
2781     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
2782       'batchnum' => $pay_batch->batchnum,
2783       'custnum' => $self->custnum,
2784     } ) ) {
2785       $in_transit_payments += $cust_pay_batch->amount;
2786     }
2787   }
2788   sprintf( "%.2f", $in_transit_payments );
2789 }
2790
2791 =item payment_info
2792
2793 Returns a hash of useful information for making a payment.
2794
2795 =over 4
2796
2797 =item balance
2798
2799 Current balance.
2800
2801 =item payby
2802
2803 'CARD' (credit card - automatic), 'DCRD' (credit card - on-demand),
2804 'CHEK' (electronic check - automatic), 'DCHK' (electronic check - on-demand),
2805 'LECB' (Phone bill billing), 'BILL' (billing), or 'COMP' (free).
2806
2807 =back
2808
2809 For credit card transactions:
2810
2811 =over 4
2812
2813 =item card_type 1
2814
2815 =item payname
2816
2817 Exact name on card
2818
2819 =back
2820
2821 For electronic check transactions:
2822
2823 =over 4
2824
2825 =item stateid_state
2826
2827 =back
2828
2829 =cut
2830
2831 sub payment_info {
2832   my $self = shift;
2833
2834   my %return = ();
2835
2836   $return{balance} = $self->balance;
2837
2838   $return{payname} = $self->payname
2839                      || ( $self->first. ' '. $self->get('last') );
2840
2841   $return{$_} = $self->get($_) for qw(address1 address2 city state zip);
2842
2843   $return{payby} = $self->payby;
2844   $return{stateid_state} = $self->stateid_state;
2845
2846   if ( $self->payby =~ /^(CARD|DCRD)$/ ) {
2847     $return{card_type} = cardtype($self->payinfo);
2848     $return{payinfo} = $self->paymask;
2849
2850     @return{'month', 'year'} = $self->paydate_monthyear;
2851
2852   }
2853
2854   if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
2855     my ($payinfo1, $payinfo2) = split '@', $self->paymask;
2856     $return{payinfo1} = $payinfo1;
2857     $return{payinfo2} = $payinfo2;
2858     $return{paytype}  = $self->paytype;
2859     $return{paystate} = $self->paystate;
2860
2861   }
2862
2863   #doubleclick protection
2864   my $_date = time;
2865   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
2866
2867   %return;
2868
2869 }
2870
2871 =item paydate_monthyear
2872
2873 Returns a two-element list consisting of the month and year of this customer's
2874 paydate (credit card expiration date for CARD customers)
2875
2876 =cut
2877
2878 sub paydate_monthyear {
2879   my $self = shift;
2880   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2881     ( $2, $1 );
2882   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2883     ( $1, $3 );
2884   } else {
2885     ('', '');
2886   }
2887 }
2888
2889 =item tax_exemption TAXNAME
2890
2891 =cut
2892
2893 sub tax_exemption {
2894   my( $self, $taxname ) = @_;
2895
2896   qsearchs( 'cust_main_exemption', { 'custnum' => $self->custnum,
2897                                      'taxname' => $taxname,
2898                                    },
2899           );
2900 }
2901
2902 =item cust_main_exemption
2903
2904 =cut
2905
2906 sub cust_main_exemption {
2907   my $self = shift;
2908   qsearch( 'cust_main_exemption', { 'custnum' => $self->custnum } );
2909 }
2910
2911 =item invoicing_list [ ARRAYREF ]
2912
2913 If an arguement is given, sets these email addresses as invoice recipients
2914 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
2915 (except as warnings), so use check_invoicing_list first.
2916
2917 Returns a list of email addresses (with svcnum entries expanded).
2918
2919 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
2920 check it without disturbing anything by passing nothing.
2921
2922 This interface may change in the future.
2923
2924 =cut
2925
2926 sub invoicing_list {
2927   my( $self, $arrayref ) = @_;
2928
2929   if ( $arrayref ) {
2930     my @cust_main_invoice;
2931     if ( $self->custnum ) {
2932       @cust_main_invoice = 
2933         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2934     } else {
2935       @cust_main_invoice = ();
2936     }
2937     foreach my $cust_main_invoice ( @cust_main_invoice ) {
2938       #warn $cust_main_invoice->destnum;
2939       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2940         #warn $cust_main_invoice->destnum;
2941         my $error = $cust_main_invoice->delete;
2942         warn $error if $error;
2943       }
2944     }
2945     if ( $self->custnum ) {
2946       @cust_main_invoice = 
2947         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2948     } else {
2949       @cust_main_invoice = ();
2950     }
2951     my %seen = map { $_->address => 1 } @cust_main_invoice;
2952     foreach my $address ( @{$arrayref} ) {
2953       next if exists $seen{$address} && $seen{$address};
2954       $seen{$address} = 1;
2955       my $cust_main_invoice = new FS::cust_main_invoice ( {
2956         'custnum' => $self->custnum,
2957         'dest'    => $address,
2958       } );
2959       my $error = $cust_main_invoice->insert;
2960       warn $error if $error;
2961     }
2962   }
2963   
2964   if ( $self->custnum ) {
2965     map { $_->address }
2966       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2967   } else {
2968     ();
2969   }
2970
2971 }
2972
2973 =item check_invoicing_list ARRAYREF
2974
2975 Checks these arguements as valid input for the invoicing_list method.  If there
2976 is an error, returns the error, otherwise returns false.
2977
2978 =cut
2979
2980 sub check_invoicing_list {
2981   my( $self, $arrayref ) = @_;
2982
2983   foreach my $address ( @$arrayref ) {
2984
2985     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2986       return 'Can\'t add FAX invoice destination with a blank FAX number.';
2987     }
2988
2989     my $cust_main_invoice = new FS::cust_main_invoice ( {
2990       'custnum' => $self->custnum,
2991       'dest'    => $address,
2992     } );
2993     my $error = $self->custnum
2994                 ? $cust_main_invoice->check
2995                 : $cust_main_invoice->checkdest
2996     ;
2997     return $error if $error;
2998
2999   }
3000
3001   return "Email address required"
3002     if $conf->exists('cust_main-require_invoicing_list_email')
3003     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3004
3005   '';
3006 }
3007
3008 =item set_default_invoicing_list
3009
3010 Sets the invoicing list to all accounts associated with this customer,
3011 overwriting any previous invoicing list.
3012
3013 =cut
3014
3015 sub set_default_invoicing_list {
3016   my $self = shift;
3017   $self->invoicing_list($self->all_emails);
3018 }
3019
3020 =item all_emails
3021
3022 Returns the email addresses of all accounts provisioned for this customer.
3023
3024 =cut
3025
3026 sub all_emails {
3027   my $self = shift;
3028   my %list;
3029   foreach my $cust_pkg ( $self->all_pkgs ) {
3030     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
3031     my @svc_acct =
3032       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3033         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
3034           @cust_svc;
3035     $list{$_}=1 foreach map { $_->email } @svc_acct;
3036   }
3037   keys %list;
3038 }
3039
3040 =item invoicing_list_addpost
3041
3042 Adds postal invoicing to this customer.  If this customer is already configured
3043 to receive postal invoices, does nothing.
3044
3045 =cut
3046
3047 sub invoicing_list_addpost {
3048   my $self = shift;
3049   return if grep { $_ eq 'POST' } $self->invoicing_list;
3050   my @invoicing_list = $self->invoicing_list;
3051   push @invoicing_list, 'POST';
3052   $self->invoicing_list(\@invoicing_list);
3053 }
3054
3055 =item invoicing_list_emailonly
3056
3057 Returns the list of email invoice recipients (invoicing_list without non-email
3058 destinations such as POST and FAX).
3059
3060 =cut
3061
3062 sub invoicing_list_emailonly {
3063   my $self = shift;
3064   warn "$me invoicing_list_emailonly called"
3065     if $DEBUG;
3066   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
3067 }
3068
3069 =item invoicing_list_emailonly_scalar
3070
3071 Returns the list of email invoice recipients (invoicing_list without non-email
3072 destinations such as POST and FAX) as a comma-separated scalar.
3073
3074 =cut
3075
3076 sub invoicing_list_emailonly_scalar {
3077   my $self = shift;
3078   warn "$me invoicing_list_emailonly_scalar called"
3079     if $DEBUG;
3080   join(', ', $self->invoicing_list_emailonly);
3081 }
3082
3083 =item referral_custnum_cust_main
3084
3085 Returns the customer who referred this customer (or the empty string, if
3086 this customer was not referred).
3087
3088 Note the difference with referral_cust_main method: This method,
3089 referral_custnum_cust_main returns the single customer (if any) who referred
3090 this customer, while referral_cust_main returns an array of customers referred
3091 BY this customer.
3092
3093 =cut
3094
3095 sub referral_custnum_cust_main {
3096   my $self = shift;
3097   return '' unless $self->referral_custnum;
3098   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3099 }
3100
3101 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
3102
3103 Returns an array of customers referred by this customer (referral_custnum set
3104 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
3105 customers referred by customers referred by this customer and so on, inclusive.
3106 The default behavior is DEPTH 1 (no recursion).
3107
3108 Note the difference with referral_custnum_cust_main method: This method,
3109 referral_cust_main, returns an array of customers referred BY this customer,
3110 while referral_custnum_cust_main returns the single customer (if any) who
3111 referred this customer.
3112
3113 =cut
3114
3115 sub referral_cust_main {
3116   my $self = shift;
3117   my $depth = @_ ? shift : 1;
3118   my $exclude = @_ ? shift : {};
3119
3120   my @cust_main =
3121     map { $exclude->{$_->custnum}++; $_; }
3122       grep { ! $exclude->{ $_->custnum } }
3123         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
3124
3125   if ( $depth > 1 ) {
3126     push @cust_main,
3127       map { $_->referral_cust_main($depth-1, $exclude) }
3128         @cust_main;
3129   }
3130
3131   @cust_main;
3132 }
3133
3134 =item referral_cust_main_ncancelled
3135
3136 Same as referral_cust_main, except only returns customers with uncancelled
3137 packages.
3138
3139 =cut
3140
3141 sub referral_cust_main_ncancelled {
3142   my $self = shift;
3143   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
3144 }
3145
3146 =item referral_cust_pkg [ DEPTH ]
3147
3148 Like referral_cust_main, except returns a flat list of all unsuspended (and
3149 uncancelled) packages for each customer.  The number of items in this list may
3150 be useful for commission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
3151
3152 =cut
3153
3154 sub referral_cust_pkg {
3155   my $self = shift;
3156   my $depth = @_ ? shift : 1;
3157
3158   map { $_->unsuspended_pkgs }
3159     grep { $_->unsuspended_pkgs }
3160       $self->referral_cust_main($depth);
3161 }
3162
3163 =item referring_cust_main
3164
3165 Returns the single cust_main record for the customer who referred this customer
3166 (referral_custnum), or false.
3167
3168 =cut
3169
3170 sub referring_cust_main {
3171   my $self = shift;
3172   return '' unless $self->referral_custnum;
3173   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
3174 }
3175
3176 =item credit AMOUNT, REASON [ , OPTION => VALUE ... ]
3177
3178 Applies a credit to this customer.  If there is an error, returns the error,
3179 otherwise returns false.
3180
3181 REASON can be a text string, an FS::reason object, or a scalar reference to
3182 a reasonnum.  If a text string, it will be automatically inserted as a new
3183 reason, and a 'reason_type' option must be passed to indicate the
3184 FS::reason_type for the new reason.
3185
3186 An I<addlinfo> option may be passed to set the credit's I<addlinfo> field.
3187
3188 Any other options are passed to FS::cust_credit::insert.
3189
3190 =cut
3191
3192 sub credit {
3193   my( $self, $amount, $reason, %options ) = @_;
3194
3195   my $cust_credit = new FS::cust_credit {
3196     'custnum' => $self->custnum,
3197     'amount'  => $amount,
3198   };
3199
3200   if ( ref($reason) ) {
3201
3202     if ( ref($reason) eq 'SCALAR' ) {
3203       $cust_credit->reasonnum( $$reason );
3204     } else {
3205       $cust_credit->reasonnum( $reason->reasonnum );
3206     }
3207
3208   } else {
3209     $cust_credit->set('reason', $reason)
3210   }
3211
3212   for (qw( addlinfo eventnum )) {
3213     $cust_credit->$_( delete $options{$_} )
3214       if exists($options{$_});
3215   }
3216
3217   $cust_credit->insert(%options);
3218
3219 }
3220
3221 =item charge HASHREF || AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
3222
3223 Creates a one-time charge for this customer.  If there is an error, returns
3224 the error, otherwise returns false.
3225
3226 New-style, with a hashref of options:
3227
3228   my $error = $cust_main->charge(
3229                                   {
3230                                     'amount'     => 54.32,
3231                                     'quantity'   => 1,
3232                                     'start_date' => str2time('7/4/2009'),
3233                                     'pkg'        => 'Description',
3234                                     'comment'    => 'Comment',
3235                                     'additional' => [], #extra invoice detail
3236                                     'classnum'   => 1,  #pkg_class
3237
3238                                     'setuptax'   => '', # or 'Y' for tax exempt
3239
3240                                     #internal taxation
3241                                     'taxclass'   => 'Tax class',
3242
3243                                     #vendor taxation
3244                                     'taxproduct' => 2,  #part_pkg_taxproduct
3245                                     'override'   => {}, #XXX describe
3246
3247                                     #will be filled in with the new object
3248                                     'cust_pkg_ref' => \$cust_pkg,
3249
3250                                     #generate an invoice immediately
3251                                     'bill_now' => 0,
3252                                     'invoice_terms' => '', #with these terms
3253                                   }
3254                                 );
3255
3256 Old-style:
3257
3258   my $error = $cust_main->charge( 54.32, 'Description', 'Comment', 'Tax class' );
3259
3260 =cut
3261
3262 sub charge {
3263   my $self = shift;
3264   my ( $amount, $quantity, $start_date, $classnum );
3265   my ( $pkg, $comment, $additional );
3266   my ( $setuptax, $taxclass );   #internal taxes
3267   my ( $taxproduct, $override ); #vendor (CCH) taxes
3268   my $no_auto = '';
3269   my $cust_pkg_ref = '';
3270   my ( $bill_now, $invoice_terms ) = ( 0, '' );
3271   if ( ref( $_[0] ) ) {
3272     $amount     = $_[0]->{amount};
3273     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
3274     $start_date = exists($_[0]->{start_date}) ? $_[0]->{start_date} : '';
3275     $no_auto    = exists($_[0]->{no_auto}) ? $_[0]->{no_auto} : '';
3276     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
3277     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
3278                                            : '$'. sprintf("%.2f",$amount);
3279     $setuptax   = exists($_[0]->{setuptax}) ? $_[0]->{setuptax} : '';
3280     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
3281     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
3282     $additional = $_[0]->{additional} || [];
3283     $taxproduct = $_[0]->{taxproductnum};
3284     $override   = { '' => $_[0]->{tax_override} };
3285     $cust_pkg_ref = exists($_[0]->{cust_pkg_ref}) ? $_[0]->{cust_pkg_ref} : '';
3286     $bill_now = exists($_[0]->{bill_now}) ? $_[0]->{bill_now} : '';
3287     $invoice_terms = exists($_[0]->{invoice_terms}) ? $_[0]->{invoice_terms} : '';
3288   } else {
3289     $amount     = shift;
3290     $quantity   = 1;
3291     $start_date = '';
3292     $pkg        = @_ ? shift : 'One-time charge';
3293     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
3294     $setuptax   = '';
3295     $taxclass   = @_ ? shift : '';
3296     $additional = [];
3297   }
3298
3299   local $SIG{HUP} = 'IGNORE';
3300   local $SIG{INT} = 'IGNORE';
3301   local $SIG{QUIT} = 'IGNORE';
3302   local $SIG{TERM} = 'IGNORE';
3303   local $SIG{TSTP} = 'IGNORE';
3304   local $SIG{PIPE} = 'IGNORE';
3305
3306   my $oldAutoCommit = $FS::UID::AutoCommit;
3307   local $FS::UID::AutoCommit = 0;
3308   my $dbh = dbh;
3309
3310   my $part_pkg = new FS::part_pkg ( {
3311     'pkg'           => $pkg,
3312     'comment'       => $comment,
3313     'plan'          => 'flat',
3314     'freq'          => 0,
3315     'disabled'      => 'Y',
3316     'classnum'      => ( $classnum ? $classnum : '' ),
3317     'setuptax'      => $setuptax,
3318     'taxclass'      => $taxclass,
3319     'taxproductnum' => $taxproduct,
3320   } );
3321
3322   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
3323                         ( 0 .. @$additional - 1 )
3324                   ),
3325                   'additional_count' => scalar(@$additional),
3326                   'setup_fee' => $amount,
3327                 );
3328
3329   my $error = $part_pkg->insert( options       => \%options,
3330                                  tax_overrides => $override,
3331                                );
3332   if ( $error ) {
3333     $dbh->rollback if $oldAutoCommit;
3334     return $error;
3335   }
3336
3337   my $pkgpart = $part_pkg->pkgpart;
3338   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
3339   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
3340     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
3341     $error = $type_pkgs->insert;
3342     if ( $error ) {
3343       $dbh->rollback if $oldAutoCommit;
3344       return $error;
3345     }
3346   }
3347
3348   my $cust_pkg = new FS::cust_pkg ( {
3349     'custnum'    => $self->custnum,
3350     'pkgpart'    => $pkgpart,
3351     'quantity'   => $quantity,
3352     'start_date' => $start_date,
3353     'no_auto'    => $no_auto,
3354   } );
3355
3356   $error = $cust_pkg->insert;
3357   if ( $error ) {
3358     $dbh->rollback if $oldAutoCommit;
3359     return $error;
3360   } elsif ( $cust_pkg_ref ) {
3361     ${$cust_pkg_ref} = $cust_pkg;
3362   }
3363
3364   if ( $bill_now ) {
3365     my $error = $self->bill( 'invoice_terms' => $invoice_terms,
3366                              'pkg_list'      => [ $cust_pkg ],
3367                            );
3368     if ( $error ) {
3369       $dbh->rollback if $oldAutoCommit;
3370       return $error;
3371     }   
3372   }
3373
3374   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3375   return '';
3376
3377 }
3378
3379 #=item charge_postal_fee
3380 #
3381 #Applies a one time charge this customer.  If there is an error,
3382 #returns the error, returns the cust_pkg charge object or false
3383 #if there was no charge.
3384 #
3385 #=cut
3386 #
3387 # This should be a customer event.  For that to work requires that bill
3388 # also be a customer event.
3389
3390 sub charge_postal_fee {
3391   my $self = shift;
3392
3393   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart', $self->agentnum);
3394   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
3395
3396   my $cust_pkg = new FS::cust_pkg ( {
3397     'custnum'  => $self->custnum,
3398     'pkgpart'  => $pkgpart,
3399     'quantity' => 1,
3400   } );
3401
3402   my $error = $cust_pkg->insert;
3403   $error ? $error : $cust_pkg;
3404 }
3405
3406 =item cust_bill [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3407
3408 Returns all the invoices (see L<FS::cust_bill>) for this customer.
3409
3410 Optionally, a list or hashref of additional arguments to the qsearch call can
3411 be passed.
3412
3413 =cut
3414
3415 sub cust_bill {
3416   my $self = shift;
3417   my $opt = ref($_[0]) ? shift : { @_ };
3418
3419   #return $self->num_cust_bill unless wantarray || keys %$opt;
3420
3421   $opt->{'table'} = 'cust_bill';
3422   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3423   $opt->{'hashref'}{'custnum'} = $self->custnum;
3424   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3425
3426   map { $_ } #behavior of sort undefined in scalar context
3427     sort { $a->_date <=> $b->_date }
3428       qsearch($opt);
3429 }
3430
3431 =item open_cust_bill
3432
3433 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
3434 customer.
3435
3436 =cut
3437
3438 sub open_cust_bill {
3439   my $self = shift;
3440
3441   $self->cust_bill(
3442     'extra_sql' => ' AND '. FS::cust_bill->owed_sql. ' > 0',
3443     #@_
3444   );
3445
3446 }
3447
3448 =item cust_statement [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3449
3450 Returns all the statements (see L<FS::cust_statement>) for this customer.
3451
3452 Optionally, a list or hashref of additional arguments to the qsearch call can
3453 be passed.
3454
3455 =cut
3456
3457 sub cust_statement {
3458   my $self = shift;
3459   my $opt = ref($_[0]) ? shift : { @_ };
3460
3461   #return $self->num_cust_statement unless wantarray || keys %$opt;
3462
3463   $opt->{'table'} = 'cust_statement';
3464   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3465   $opt->{'hashref'}{'custnum'} = $self->custnum;
3466   $opt->{'order_by'} ||= 'ORDER BY _date ASC';
3467
3468   map { $_ } #behavior of sort undefined in scalar context
3469     sort { $a->_date <=> $b->_date }
3470       qsearch($opt);
3471 }
3472
3473 =item cust_credit
3474
3475 Returns all the credits (see L<FS::cust_credit>) for this customer.
3476
3477 =cut
3478
3479 sub cust_credit {
3480   my $self = shift;
3481   map { $_ } #return $self->num_cust_credit unless wantarray;
3482   sort { $a->_date <=> $b->_date }
3483     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
3484 }
3485
3486 =item cust_credit_pkgnum
3487
3488 Returns all the credits (see L<FS::cust_credit>) for this customer's specific
3489 package when using experimental package balances.
3490
3491 =cut
3492
3493 sub cust_credit_pkgnum {
3494   my( $self, $pkgnum ) = @_;
3495   map { $_ } #return $self->num_cust_credit_pkgnum($pkgnum) unless wantarray;
3496   sort { $a->_date <=> $b->_date }
3497     qsearch( 'cust_credit', { 'custnum' => $self->custnum,
3498                               'pkgnum'  => $pkgnum,
3499                             }
3500     );
3501 }
3502
3503 =item cust_pay
3504
3505 Returns all the payments (see L<FS::cust_pay>) for this customer.
3506
3507 =cut
3508
3509 sub cust_pay {
3510   my $self = shift;
3511   return $self->num_cust_pay unless wantarray;
3512   sort { $a->_date <=> $b->_date }
3513     qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
3514 }
3515
3516 =item num_cust_pay
3517
3518 Returns the number of payments (see L<FS::cust_pay>) for this customer.  Also
3519 called automatically when the cust_pay method is used in a scalar context.
3520
3521 =cut
3522
3523 sub num_cust_pay {
3524   my $self = shift;
3525   my $sql = "SELECT COUNT(*) FROM cust_pay WHERE custnum = ?";
3526   my $sth = dbh->prepare($sql) or die dbh->errstr;
3527   $sth->execute($self->custnum) or die $sth->errstr;
3528   $sth->fetchrow_arrayref->[0];
3529 }
3530
3531 =item cust_pay_pkgnum
3532
3533 Returns all the payments (see L<FS::cust_pay>) for this customer's specific
3534 package when using experimental package balances.
3535
3536 =cut
3537
3538 sub cust_pay_pkgnum {
3539   my( $self, $pkgnum ) = @_;
3540   map { $_ } #return $self->num_cust_pay_pkgnum($pkgnum) unless wantarray;
3541   sort { $a->_date <=> $b->_date }
3542     qsearch( 'cust_pay', { 'custnum' => $self->custnum,
3543                            'pkgnum'  => $pkgnum,
3544                          }
3545     );
3546 }
3547
3548 =item cust_pay_void
3549
3550 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
3551
3552 =cut
3553
3554 sub cust_pay_void {
3555   my $self = shift;
3556   map { $_ } #return $self->num_cust_pay_void unless wantarray;
3557   sort { $a->_date <=> $b->_date }
3558     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
3559 }
3560
3561 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
3562
3563 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
3564
3565 Optionally, a list or hashref of additional arguments to the qsearch call can
3566 be passed.
3567
3568 =cut
3569
3570 sub cust_pay_batch {
3571   my $self = shift;
3572   my $opt = ref($_[0]) ? shift : { @_ };
3573
3574   #return $self->num_cust_statement unless wantarray || keys %$opt;
3575
3576   $opt->{'table'} = 'cust_pay_batch';
3577   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
3578   $opt->{'hashref'}{'custnum'} = $self->custnum;
3579   $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
3580
3581   map { $_ } #behavior of sort undefined in scalar context
3582     sort { $a->paybatchnum <=> $b->paybatchnum }
3583       qsearch($opt);
3584 }
3585
3586 =item cust_pay_pending
3587
3588 Returns all pending payments (see L<FS::cust_pay_pending>) for this customer
3589 (without status "done").
3590
3591 =cut
3592
3593 sub cust_pay_pending {
3594   my $self = shift;
3595   return $self->num_cust_pay_pending unless wantarray;
3596   sort { $a->_date <=> $b->_date }
3597     qsearch( 'cust_pay_pending', {
3598                                    'custnum' => $self->custnum,
3599                                    'status'  => { op=>'!=', value=>'done' },
3600                                  },
3601            );
3602 }
3603
3604 =item cust_pay_pending_attempt
3605
3606 Returns all payment attempts / declined payments for this customer, as pending
3607 payments objects (see L<FS::cust_pay_pending>), with status "done" but without
3608 a corresponding payment (see L<FS::cust_pay>).
3609
3610 =cut
3611
3612 sub cust_pay_pending_attempt {
3613   my $self = shift;
3614   return $self->num_cust_pay_pending_attempt unless wantarray;
3615   sort { $a->_date <=> $b->_date }
3616     qsearch( 'cust_pay_pending', {
3617                                    'custnum' => $self->custnum,
3618                                    'status'  => 'done',
3619                                    'paynum'  => '',
3620                                  },
3621            );
3622 }
3623
3624 =item num_cust_pay_pending
3625
3626 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3627 customer (without status "done").  Also called automatically when the
3628 cust_pay_pending method is used in a scalar context.
3629
3630 =cut
3631
3632 sub num_cust_pay_pending {
3633   my $self = shift;
3634   $self->scalar_sql(
3635     " SELECT COUNT(*) FROM cust_pay_pending ".
3636       " WHERE custnum = ? AND status != 'done' ",
3637     $self->custnum
3638   );
3639 }
3640
3641 =item num_cust_pay_pending_attempt
3642
3643 Returns the number of pending payments (see L<FS::cust_pay_pending>) for this
3644 customer, with status "done" but without a corresp.  Also called automatically when the
3645 cust_pay_pending method is used in a scalar context.
3646
3647 =cut
3648
3649 sub num_cust_pay_pending_attempt {
3650   my $self = shift;
3651   $self->scalar_sql(
3652     " SELECT COUNT(*) FROM cust_pay_pending ".
3653       " WHERE custnum = ? AND status = 'done' AND paynum IS NULL",
3654     $self->custnum
3655   );
3656 }
3657
3658 =item cust_refund
3659
3660 Returns all the refunds (see L<FS::cust_refund>) for this customer.
3661
3662 =cut
3663
3664 sub cust_refund {
3665   my $self = shift;
3666   map { $_ } #return $self->num_cust_refund unless wantarray;
3667   sort { $a->_date <=> $b->_date }
3668     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
3669 }
3670
3671 =item display_custnum
3672
3673 Returns the displayed customer number for this customer: agent_custid if
3674 cust_main-default_agent_custid is set and it has a value, custnum otherwise.
3675
3676 =cut
3677
3678 sub display_custnum {
3679   my $self = shift;
3680   if ( $conf->exists('cust_main-default_agent_custid') && $self->agent_custid ){
3681     return $self->agent_custid;
3682   } else {
3683     return $self->custnum;
3684   }
3685 }
3686
3687 =item name
3688
3689 Returns a name string for this customer, either "Company (Last, First)" or
3690 "Last, First".
3691
3692 =cut
3693
3694 sub name {
3695   my $self = shift;
3696   my $name = $self->contact;
3697   $name = $self->company. " ($name)" if $self->company;
3698   $name;
3699 }
3700
3701 =item ship_name
3702
3703 Returns a name string for this (service/shipping) contact, either
3704 "Company (Last, First)" or "Last, First".
3705
3706 =cut
3707
3708 sub ship_name {
3709   my $self = shift;
3710   if ( $self->get('ship_last') ) { 
3711     my $name = $self->ship_contact;
3712     $name = $self->ship_company. " ($name)" if $self->ship_company;
3713     $name;
3714   } else {
3715     $self->name;
3716   }
3717 }
3718
3719 =item name_short
3720
3721 Returns a name string for this customer, either "Company" or "First Last".
3722
3723 =cut
3724
3725 sub name_short {
3726   my $self = shift;
3727   $self->company !~ /^\s*$/ ? $self->company : $self->contact_firstlast;
3728 }
3729
3730 =item ship_name_short
3731
3732 Returns a name string for this (service/shipping) contact, either "Company"
3733 or "First Last".
3734
3735 =cut
3736
3737 sub ship_name_short {
3738   my $self = shift;
3739   if ( $self->get('ship_last') ) { 
3740     $self->ship_company !~ /^\s*$/
3741       ? $self->ship_company
3742       : $self->ship_contact_firstlast;
3743   } else {
3744     $self->name_company_or_firstlast;
3745   }
3746 }
3747
3748 =item contact
3749
3750 Returns this customer's full (billing) contact name only, "Last, First"
3751
3752 =cut
3753
3754 sub contact {
3755   my $self = shift;
3756   $self->get('last'). ', '. $self->first;
3757 }
3758
3759 =item ship_contact
3760
3761 Returns this customer's full (shipping) contact name only, "Last, First"
3762
3763 =cut
3764
3765 sub ship_contact {
3766   my $self = shift;
3767   $self->get('ship_last')
3768     ? $self->get('ship_last'). ', '. $self->ship_first
3769     : $self->contact;
3770 }
3771
3772 =item contact_firstlast
3773
3774 Returns this customers full (billing) contact name only, "First Last".
3775
3776 =cut
3777
3778 sub contact_firstlast {
3779   my $self = shift;
3780   $self->first. ' '. $self->get('last');
3781 }
3782
3783 =item ship_contact_firstlast
3784
3785 Returns this customer's full (shipping) contact name only, "First Last".
3786
3787 =cut
3788
3789 sub ship_contact_firstlast {
3790   my $self = shift;
3791   $self->get('ship_last')
3792     ? $self->first. ' '. $self->get('ship_last')
3793     : $self->contact_firstlast;
3794 }
3795
3796 =item country_full
3797
3798 Returns this customer's full country name
3799
3800 =cut
3801
3802 sub country_full {
3803   my $self = shift;
3804   code2country($self->country);
3805 }
3806
3807 =item geocode DATA_VENDOR
3808
3809 Returns a value for the customer location as encoded by DATA_VENDOR.
3810 Currently this only makes sense for "CCH" as DATA_VENDOR.
3811
3812 =cut
3813
3814 =item cust_status
3815
3816 =item status
3817
3818 Returns a status string for this customer, currently:
3819
3820 =over 4
3821
3822 =item prospect - No packages have ever been ordered
3823
3824 =item ordered - Recurring packages all are new (not yet billed).
3825
3826 =item active - One or more recurring packages is active
3827
3828 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
3829
3830 =item suspended - All non-cancelled recurring packages are suspended
3831
3832 =item cancelled - All recurring packages are cancelled
3833
3834 =back
3835
3836 Behavior of inactive vs. cancelled edge cases can be adjusted with the
3837 cust_main-status_module configuration option.
3838
3839 =cut
3840
3841 sub status { shift->cust_status(@_); }
3842
3843 sub cust_status {
3844   my $self = shift;
3845   for my $status ( FS::cust_main->statuses() ) {
3846     my $method = $status.'_sql';
3847     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3848     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3849     $sth->execute( ($self->custnum) x $numnum )
3850       or die "Error executing 'SELECT $sql': ". $sth->errstr;
3851     return $status if $sth->fetchrow_arrayref->[0];
3852   }
3853 }
3854
3855 =item ucfirst_cust_status
3856
3857 =item ucfirst_status
3858
3859 Returns the status with the first character capitalized.
3860
3861 =cut
3862
3863 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
3864
3865 sub ucfirst_cust_status {
3866   my $self = shift;
3867   ucfirst($self->cust_status);
3868 }
3869
3870 =item statuscolor
3871
3872 Returns a hex triplet color string for this customer's status.
3873
3874 =cut
3875
3876 sub statuscolor { shift->cust_statuscolor(@_); }
3877
3878 sub cust_statuscolor {
3879   my $self = shift;
3880   __PACKAGE__->statuscolors->{$self->cust_status};
3881 }
3882
3883 =item tickets
3884
3885 Returns an array of hashes representing the customer's RT tickets.
3886
3887 =cut
3888
3889 sub tickets {
3890   my $self = shift;
3891
3892   my $num = $conf->config('cust_main-max_tickets') || 10;
3893   my @tickets = ();
3894
3895   if ( $conf->config('ticket_system') ) {
3896     unless ( $conf->config('ticket_system-custom_priority_field') ) {
3897
3898       @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
3899
3900     } else {
3901
3902       foreach my $priority (
3903         $conf->config('ticket_system-custom_priority_field-values'), ''
3904       ) {
3905         last if scalar(@tickets) >= $num;
3906         push @tickets, 
3907           @{ FS::TicketSystem->customer_tickets( $self->custnum,
3908                                                  $num - scalar(@tickets),
3909                                                  $priority,
3910                                                )
3911            };
3912       }
3913     }
3914   }
3915   (@tickets);
3916 }
3917
3918 # Return services representing svc_accts in customer support packages
3919 sub support_services {
3920   my $self = shift;
3921   my %packages = map { $_ => 1 } $conf->config('support_packages');
3922
3923   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
3924     grep { $_->part_svc->svcdb eq 'svc_acct' }
3925     map { $_->cust_svc }
3926     grep { exists $packages{ $_->pkgpart } }
3927     $self->ncancelled_pkgs;
3928
3929 }
3930
3931 # Return a list of latitude/longitude for one of the services (if any)
3932 sub service_coordinates {
3933   my $self = shift;
3934
3935   my @svc_X = 
3936     grep { $_->latitude && $_->longitude }
3937     map { $_->svc_x }
3938     map { $_->cust_svc }
3939     $self->ncancelled_pkgs;
3940
3941   scalar(@svc_X) ? ( $svc_X[0]->latitude, $svc_X[0]->longitude ) : ()
3942 }
3943
3944 =item masked FIELD
3945
3946 Returns a masked version of the named field
3947
3948 =cut
3949
3950 sub masked {
3951 my ($self,$field) = @_;
3952
3953 # Show last four
3954
3955 'x'x(length($self->getfield($field))-4).
3956   substr($self->getfield($field), (length($self->getfield($field))-4));
3957
3958 }
3959
3960 =back
3961
3962 =head1 CLASS METHODS
3963
3964 =over 4
3965
3966 =item statuses
3967
3968 Class method that returns the list of possible status strings for customers
3969 (see L<the status method|/status>).  For example:
3970
3971   @statuses = FS::cust_main->statuses();
3972
3973 =cut
3974
3975 sub statuses {
3976   my $self = shift;
3977   keys %{ $self->statuscolors };
3978 }
3979
3980 =item cust_status_sql
3981
3982 Returns an SQL fragment to determine the status of a cust_main record, as a 
3983 string.
3984
3985 =cut
3986
3987 sub cust_status_sql {
3988   my $sql = 'CASE';
3989   for my $status ( FS::cust_main->statuses() ) {
3990     my $method = $status.'_sql';
3991     $sql .= ' WHEN ('.FS::cust_main->$method.") THEN '$status'";
3992   }
3993   $sql .= ' END';
3994   return $sql;
3995 }
3996
3997
3998 =item prospect_sql
3999
4000 Returns an SQL expression identifying prospective cust_main records (customers
4001 with no packages ever ordered)
4002
4003 =cut
4004
4005 use vars qw($select_count_pkgs);
4006 $select_count_pkgs =
4007   "SELECT COUNT(*) FROM cust_pkg
4008     WHERE cust_pkg.custnum = cust_main.custnum";
4009
4010 sub select_count_pkgs_sql {
4011   $select_count_pkgs;
4012 }
4013
4014 sub prospect_sql {
4015   " 0 = ( $select_count_pkgs ) ";
4016 }
4017
4018 =item ordered_sql
4019
4020 Returns an SQL expression identifying ordered cust_main records (customers with
4021 no active packages, but recurring packages not yet setup or one time charges
4022 not yet billed).
4023
4024 =cut
4025
4026 sub ordered_sql {
4027   FS::cust_main->none_active_sql.
4028   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->not_yet_billed_sql. " ) ";
4029 }
4030
4031 =item active_sql
4032
4033 Returns an SQL expression identifying active cust_main records (customers with
4034 active recurring packages).
4035
4036 =cut
4037
4038 sub active_sql {
4039   " 0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4040 }
4041
4042 =item none_active_sql
4043
4044 Returns an SQL expression identifying cust_main records with no active
4045 recurring packages.  This includes customers of status prospect, ordered,
4046 inactive, and suspended.
4047
4048 =cut
4049
4050 sub none_active_sql {
4051   " 0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " ) ";
4052 }
4053
4054 =item inactive_sql
4055
4056 Returns an SQL expression identifying inactive cust_main records (customers with
4057 no active recurring packages, but otherwise unsuspended/uncancelled).
4058
4059 =cut
4060
4061 sub inactive_sql {
4062   FS::cust_main->none_active_sql.
4063   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " ) ";
4064 }
4065
4066 =item susp_sql
4067 =item suspended_sql
4068
4069 Returns an SQL expression identifying suspended cust_main records.
4070
4071 =cut
4072
4073
4074 sub suspended_sql { susp_sql(@_); }
4075 sub susp_sql {
4076   FS::cust_main->none_active_sql.
4077   " AND 0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " ) ";
4078 }
4079
4080 =item cancel_sql
4081 =item cancelled_sql
4082
4083 Returns an SQL expression identifying cancelled cust_main records.
4084
4085 =cut
4086
4087 sub cancel_sql { shift->cancelled_sql(@_); }
4088
4089 =item uncancel_sql
4090 =item uncancelled_sql
4091
4092 Returns an SQL expression identifying un-cancelled cust_main records.
4093
4094 =cut
4095
4096 sub uncancelled_sql { uncancel_sql(@_); }
4097 sub uncancel_sql { "
4098   ( 0 < ( $select_count_pkgs
4099                    AND ( cust_pkg.cancel IS NULL
4100                          OR cust_pkg.cancel = 0
4101                        )
4102         )
4103     OR 0 = ( $select_count_pkgs )
4104   )
4105 "; }
4106
4107 =item balance_sql
4108
4109 Returns an SQL fragment to retreive the balance.
4110
4111 =cut
4112
4113 sub balance_sql { "
4114     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4115         WHERE cust_bill.custnum   = cust_main.custnum     )
4116   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
4117         WHERE cust_pay.custnum    = cust_main.custnum     )
4118   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
4119         WHERE cust_credit.custnum = cust_main.custnum     )
4120   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
4121         WHERE cust_refund.custnum = cust_main.custnum     )
4122 "; }
4123
4124 =item balance_date_sql [ START_TIME [ END_TIME [ OPTION => VALUE ... ] ] ]
4125
4126 Returns an SQL fragment to retreive the balance for this customer, optionally
4127 considering invoices with date earlier than START_TIME, and not
4128 later than END_TIME (total_owed_date minus total_unapplied_credits minus
4129 total_unapplied_payments).
4130
4131 Times are specified as SQL fragments or numeric
4132 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
4133 L<Date::Parse> for conversion functions.  The empty string can be passed
4134 to disable that time constraint completely.
4135
4136 Available options are:
4137
4138 =over 4
4139
4140 =item unapplied_date
4141
4142 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)
4143
4144 =item total
4145
4146 (unused.  obsolete?)
4147 set to true to remove all customer comparison clauses, for totals
4148
4149 =item where
4150
4151 (unused.  obsolete?)
4152 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4153
4154 =item join
4155
4156 (unused.  obsolete?)
4157 JOIN clause (typically used with the total option)
4158
4159 =item cutoff
4160
4161 An absolute cutoff time.  Payments, credits, and refunds I<applied> after this 
4162 time will be ignored.  Note that START_TIME and END_TIME only limit the date 
4163 range for invoices and I<unapplied> payments, credits, and refunds.
4164
4165 =back
4166
4167 =cut
4168
4169 sub balance_date_sql {
4170   my( $class, $start, $end, %opt ) = @_;
4171
4172   my $cutoff = $opt{'cutoff'};
4173
4174   my $owed         = FS::cust_bill->owed_sql($cutoff);
4175   my $unapp_refund = FS::cust_refund->unapplied_sql($cutoff);
4176   my $unapp_credit = FS::cust_credit->unapplied_sql($cutoff);
4177   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
4178
4179   my $j = $opt{'join'} || '';
4180
4181   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
4182   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4183   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4184   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
4185
4186   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
4187     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4188     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4189     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
4190   ";
4191
4192 }
4193
4194 =item unapplied_payments_date_sql START_TIME [ END_TIME ]
4195
4196 Returns an SQL fragment to retreive the total unapplied payments for this
4197 customer, only considering invoices with date earlier than START_TIME, and
4198 optionally not later than END_TIME.
4199
4200 Times are specified as SQL fragments or numeric
4201 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
4202 L<Date::Parse> for conversion functions.  The empty string can be passed
4203 to disable that time constraint completely.
4204
4205 Available options are:
4206
4207 =cut
4208
4209 sub unapplied_payments_date_sql {
4210   my( $class, $start, $end, %opt ) = @_;
4211
4212   my $cutoff = $opt{'cutoff'};
4213
4214   my $unapp_pay    = FS::cust_pay->unapplied_sql($cutoff);
4215
4216   my $pay_where = $class->_money_table_where( 'cust_pay', $start, $end,
4217                                                           'unapplied_date'=>1 );
4218
4219   " ( SELECT COALESCE(SUM($unapp_pay), 0) FROM cust_pay $pay_where ) ";
4220 }
4221
4222 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4223
4224 Helper method for balance_date_sql; name (and usage) subject to change
4225 (suggestions welcome).
4226
4227 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4228 cust_refund, cust_credit or cust_pay).
4229
4230 If TABLE is "cust_bill" or the unapplied_date option is true, only
4231 considers records with date earlier than START_TIME, and optionally not
4232 later than END_TIME .
4233
4234 =cut
4235
4236 sub _money_table_where {
4237   my( $class, $table, $start, $end, %opt ) = @_;
4238
4239   my @where = ();
4240   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4241   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4242     push @where, "$table._date <= $start" if defined($start) && length($start);
4243     push @where, "$table._date >  $end"   if defined($end)   && length($end);
4244   }
4245   push @where, @{$opt{'where'}} if $opt{'where'};
4246   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4247
4248   $where;
4249
4250 }
4251
4252 #for dyanmic FS::$table->search in httemplate/misc/email_customers.html
4253 use FS::cust_main::Search;
4254 sub search {
4255   my $class = shift;
4256   FS::cust_main::Search->search(@_);
4257 }
4258
4259 =back
4260
4261 =head1 SUBROUTINES
4262
4263 =over 4
4264
4265 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
4266
4267 =cut
4268
4269 use FS::cust_main::Search;
4270 sub append_fuzzyfiles {
4271   #my( $first, $last, $company ) = @_;
4272
4273   FS::cust_main::Search::check_and_rebuild_fuzzyfiles();
4274
4275   use Fcntl qw(:flock);
4276
4277   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
4278
4279   foreach my $field (@fuzzyfields) {
4280     my $value = shift;
4281
4282     if ( $value ) {
4283
4284       open(CACHE,">>$dir/cust_main.$field")
4285         or die "can't open $dir/cust_main.$field: $!";
4286       flock(CACHE,LOCK_EX)
4287         or die "can't lock $dir/cust_main.$field: $!";
4288
4289       print CACHE "$value\n";
4290
4291       flock(CACHE,LOCK_UN)
4292         or die "can't unlock $dir/cust_main.$field: $!";
4293       close CACHE;
4294     }
4295
4296   }
4297
4298   1;
4299 }
4300
4301 =item batch_charge
4302
4303 =cut
4304
4305 sub batch_charge {
4306   my $param = shift;
4307   #warn join('-',keys %$param);
4308   my $fh = $param->{filehandle};
4309   my $agentnum = $param->{agentnum};
4310   my $format = $param->{format};
4311
4312   my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
4313
4314   my @fields;
4315   if ( $format eq 'simple' ) {
4316     @fields = qw( custnum agent_custid amount pkg );
4317   } else {
4318     die "unknown format $format";
4319   }
4320
4321   eval "use Text::CSV_XS;";
4322   die $@ if $@;
4323
4324   my $csv = new Text::CSV_XS;
4325   #warn $csv;
4326   #warn $fh;
4327
4328   my $imported = 0;
4329   #my $columns;
4330
4331   local $SIG{HUP} = 'IGNORE';
4332   local $SIG{INT} = 'IGNORE';
4333   local $SIG{QUIT} = 'IGNORE';
4334   local $SIG{TERM} = 'IGNORE';
4335   local $SIG{TSTP} = 'IGNORE';
4336   local $SIG{PIPE} = 'IGNORE';
4337
4338   my $oldAutoCommit = $FS::UID::AutoCommit;
4339   local $FS::UID::AutoCommit = 0;
4340   my $dbh = dbh;
4341   
4342   #while ( $columns = $csv->getline($fh) ) {
4343   my $line;
4344   while ( defined($line=<$fh>) ) {
4345
4346     $csv->parse($line) or do {
4347       $dbh->rollback if $oldAutoCommit;
4348       return "can't parse: ". $csv->error_input();
4349     };
4350
4351     my @columns = $csv->fields();
4352     #warn join('-',@columns);
4353
4354     my %row = ();
4355     foreach my $field ( @fields ) {
4356       $row{$field} = shift @columns;
4357     }
4358
4359     if ( $row{custnum} && $row{agent_custid} ) {
4360       dbh->rollback if $oldAutoCommit;
4361       return "can't specify custnum with agent_custid $row{agent_custid}";
4362     }
4363
4364     my %hash = ();
4365     if ( $row{agent_custid} && $agentnum ) {
4366       %hash = ( 'agent_custid' => $row{agent_custid},
4367                 'agentnum'     => $agentnum,
4368               );
4369     }
4370
4371     if ( $row{custnum} ) {
4372       %hash = ( 'custnum' => $row{custnum} );
4373     }
4374
4375     unless ( scalar(keys %hash) ) {
4376       $dbh->rollback if $oldAutoCommit;
4377       return "can't find customer without custnum or agent_custid and agentnum";
4378     }
4379
4380     my $cust_main = qsearchs('cust_main', { %hash } );
4381     unless ( $cust_main ) {
4382       $dbh->rollback if $oldAutoCommit;
4383       my $custnum = $row{custnum} || $row{agent_custid};
4384       return "unknown custnum $custnum";
4385     }
4386
4387     if ( $row{'amount'} > 0 ) {
4388       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
4389       if ( $error ) {
4390         $dbh->rollback if $oldAutoCommit;
4391         return $error;
4392       }
4393       $imported++;
4394     } elsif ( $row{'amount'} < 0 ) {
4395       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
4396                                       $row{'pkg'}                         );
4397       if ( $error ) {
4398         $dbh->rollback if $oldAutoCommit;
4399         return $error;
4400       }
4401       $imported++;
4402     } else {
4403       #hmm?
4404     }
4405
4406   }
4407
4408   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4409
4410   return "Empty file!" unless $imported;
4411
4412   ''; #no error
4413
4414 }
4415
4416 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4417
4418 Deprecated.  Use event notification and message templates 
4419 (L<FS::msg_template>) instead.
4420
4421 Sends a templated email notification to the customer (see L<Text::Template>).
4422
4423 OPTIONS is a hash and may include
4424
4425 I<from> - the email sender (default is invoice_from)
4426
4427 I<to> - comma-separated scalar or arrayref of recipients 
4428    (default is invoicing_list)
4429
4430 I<subject> - The subject line of the sent email notification
4431    (default is "Notice from company_name")
4432
4433 I<extra_fields> - a hashref of name/value pairs which will be substituted
4434    into the template
4435
4436 The following variables are vavailable in the template.
4437
4438 I<$first> - the customer first name
4439 I<$last> - the customer last name
4440 I<$company> - the customer company
4441 I<$payby> - a description of the method of payment for the customer
4442             # would be nice to use FS::payby::shortname
4443 I<$payinfo> - the account information used to collect for this customer
4444 I<$expdate> - the expiration of the customer payment in seconds from epoch
4445
4446 =cut
4447
4448 sub notify {
4449   my ($self, $template, %options) = @_;
4450
4451   return unless $conf->exists($template);
4452
4453   my $from = $conf->config('invoice_from', $self->agentnum)
4454     if $conf->exists('invoice_from', $self->agentnum);
4455   $from = $options{from} if exists($options{from});
4456
4457   my $to = join(',', $self->invoicing_list_emailonly);
4458   $to = $options{to} if exists($options{to});
4459   
4460   my $subject = "Notice from " . $conf->config('company_name', $self->agentnum)
4461     if $conf->exists('company_name', $self->agentnum);
4462   $subject = $options{subject} if exists($options{subject});
4463
4464   my $notify_template = new Text::Template (TYPE => 'ARRAY',
4465                                             SOURCE => [ map "$_\n",
4466                                               $conf->config($template)]
4467                                            )
4468     or die "can't create new Text::Template object: Text::Template::ERROR";
4469   $notify_template->compile()
4470     or die "can't compile template: Text::Template::ERROR";
4471
4472   $FS::notify_template::_template::company_name =
4473     $conf->config('company_name', $self->agentnum);
4474   $FS::notify_template::_template::company_address =
4475     join("\n", $conf->config('company_address', $self->agentnum) ). "\n";
4476
4477   my $paydate = $self->paydate || '2037-12-31';
4478   $FS::notify_template::_template::first = $self->first;
4479   $FS::notify_template::_template::last = $self->last;
4480   $FS::notify_template::_template::company = $self->company;
4481   $FS::notify_template::_template::payinfo = $self->mask_payinfo;
4482   my $payby = $self->payby;
4483   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4484   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4485
4486   #credit cards expire at the end of the month/year of their exp date
4487   if ($payby eq 'CARD' || $payby eq 'DCRD') {
4488     $FS::notify_template::_template::payby = 'credit card';
4489     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4490     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4491     $expire_time--;
4492   }elsif ($payby eq 'COMP') {
4493     $FS::notify_template::_template::payby = 'complimentary account';
4494   }else{
4495     $FS::notify_template::_template::payby = 'current method';
4496   }
4497   $FS::notify_template::_template::expdate = $expire_time;
4498
4499   for (keys %{$options{extra_fields}}){
4500     no strict "refs";
4501     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
4502   }
4503
4504   send_email(from => $from,
4505              to => $to,
4506              subject => $subject,
4507              body => $notify_template->fill_in( PACKAGE =>
4508                                                 'FS::notify_template::_template'                                              ),
4509             );
4510
4511 }
4512
4513 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
4514
4515 Generates a templated notification to the customer (see L<Text::Template>).
4516
4517 OPTIONS is a hash and may include
4518
4519 I<extra_fields> - a hashref of name/value pairs which will be substituted
4520    into the template.  These values may override values mentioned below
4521    and those from the customer record.
4522
4523 The following variables are available in the template instead of or in addition
4524 to the fields of the customer record.
4525
4526 I<$payby> - a description of the method of payment for the customer
4527             # would be nice to use FS::payby::shortname
4528 I<$payinfo> - the masked account information used to collect for this customer
4529 I<$expdate> - the expiration of the customer payment method in seconds from epoch
4530 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
4531
4532 =cut
4533
4534 # a lot like cust_bill::print_latex
4535 sub generate_letter {
4536   my ($self, $template, %options) = @_;
4537
4538   return unless $conf->exists($template);
4539
4540   my $letter_template = new Text::Template
4541                         ( TYPE       => 'ARRAY',
4542                           SOURCE     => [ map "$_\n", $conf->config($template)],
4543                           DELIMITERS => [ '[@--', '--@]' ],
4544                         )
4545     or die "can't create new Text::Template object: Text::Template::ERROR";
4546
4547   $letter_template->compile()
4548     or die "can't compile template: Text::Template::ERROR";
4549
4550   my %letter_data = map { $_ => $self->$_ } $self->fields;
4551   $letter_data{payinfo} = $self->mask_payinfo;
4552
4553   #my $paydate = $self->paydate || '2037-12-31';
4554   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
4555
4556   my $payby = $self->payby;
4557   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
4558   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
4559
4560   #credit cards expire at the end of the month/year of their exp date
4561   if ($payby eq 'CARD' || $payby eq 'DCRD') {
4562     $letter_data{payby} = 'credit card';
4563     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
4564     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
4565     $expire_time--;
4566   }elsif ($payby eq 'COMP') {
4567     $letter_data{payby} = 'complimentary account';
4568   }else{
4569     $letter_data{payby} = 'current method';
4570   }
4571   $letter_data{expdate} = $expire_time;
4572
4573   for (keys %{$options{extra_fields}}){
4574     $letter_data{$_} = $options{extra_fields}->{$_};
4575   }
4576
4577   unless(exists($letter_data{returnaddress})){
4578     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
4579                                                   $self->agent_template)
4580                      );
4581     if ( length($retadd) ) {
4582       $letter_data{returnaddress} = $retadd;
4583     } elsif ( grep /\S/, $conf->config('company_address', $self->agentnum) ) {
4584       $letter_data{returnaddress} =
4585         join( "\n", map { s/( {2,})/'~' x length($1)/eg;
4586                           s/$/\\\\\*/;
4587                           $_;
4588                         }
4589                     ( $conf->config('company_name', $self->agentnum),
4590                       $conf->config('company_address', $self->agentnum),
4591                     )
4592         );
4593     } else {
4594       $letter_data{returnaddress} = '~';
4595     }
4596   }
4597
4598   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
4599
4600   $letter_data{company_name} = $conf->config('company_name', $self->agentnum);
4601
4602   my $dir = $FS::UID::conf_dir."/cache.". $FS::UID::datasrc;
4603
4604   my $lh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4605                            DIR      => $dir,
4606                            SUFFIX   => '.eps',
4607                            UNLINK   => 0,
4608                          ) or die "can't open temp file: $!\n";
4609   print $lh $conf->config_binary('logo.eps', $self->agentnum)
4610     or die "can't write temp file: $!\n";
4611   close $lh;
4612   $letter_data{'logo_file'} = $lh->filename;
4613
4614   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
4615                            DIR      => $dir,
4616                            SUFFIX   => '.tex',
4617                            UNLINK   => 0,
4618                          ) or die "can't open temp file: $!\n";
4619
4620   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
4621   close $fh;
4622   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
4623   return ($1, $letter_data{'logo_file'});
4624
4625 }
4626
4627 =item print_ps TEMPLATE 
4628
4629 Returns an postscript letter filled in from TEMPLATE, as a scalar.
4630
4631 =cut
4632
4633 sub print_ps {
4634   my $self = shift;
4635   my($file, $lfile) = $self->generate_letter(@_);
4636   my $ps = FS::Misc::generate_ps($file);
4637   unlink($file.'.tex');
4638   unlink($lfile);
4639
4640   $ps;
4641 }
4642
4643 =item print TEMPLATE
4644
4645 Prints the filled in template.
4646
4647 TEMPLATE is the name of a L<Text::Template> to fill in and print.
4648
4649 =cut
4650
4651 sub queueable_print {
4652   my %opt = @_;
4653
4654   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
4655     or die "invalid customer number: " . $opt{custvnum};
4656
4657   my $error = $self->print( $opt{template} );
4658   die $error if $error;
4659 }
4660
4661 sub print {
4662   my ($self, $template) = (shift, shift);
4663   do_print [ $self->print_ps($template) ];
4664 }
4665
4666 #these three subs should just go away once agent stuff is all config overrides
4667
4668 sub agent_template {
4669   my $self = shift;
4670   $self->_agent_plandata('agent_templatename');
4671 }
4672
4673 sub agent_invoice_from {
4674   my $self = shift;
4675   $self->_agent_plandata('agent_invoice_from');
4676 }
4677
4678 sub _agent_plandata {
4679   my( $self, $option ) = @_;
4680
4681   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
4682   #agent-specific Conf
4683
4684   use FS::part_event::Condition;
4685   
4686   my $agentnum = $self->agentnum;
4687
4688   my $regexp = regexp_sql();
4689
4690   my $part_event_option =
4691     qsearchs({
4692       'select'    => 'part_event_option.*',
4693       'table'     => 'part_event_option',
4694       'addl_from' => q{
4695         LEFT JOIN part_event USING ( eventpart )
4696         LEFT JOIN part_event_option AS peo_agentnum
4697           ON ( part_event.eventpart = peo_agentnum.eventpart
4698                AND peo_agentnum.optionname = 'agentnum'
4699                AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
4700              )
4701         LEFT JOIN part_event_condition
4702           ON ( part_event.eventpart = part_event_condition.eventpart
4703                AND part_event_condition.conditionname = 'cust_bill_age'
4704              )
4705         LEFT JOIN part_event_condition_option
4706           ON ( part_event_condition.eventconditionnum = part_event_condition_option.eventconditionnum
4707                AND part_event_condition_option.optionname = 'age'
4708              )
4709       },
4710       #'hashref'   => { 'optionname' => $option },
4711       #'hashref'   => { 'part_event_option.optionname' => $option },
4712       'extra_sql' =>
4713         " WHERE part_event_option.optionname = ". dbh->quote($option).
4714         " AND action = 'cust_bill_send_agent' ".
4715         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
4716         " AND peo_agentnum.optionname = 'agentnum' ".
4717         " AND ( agentnum IS NULL OR agentnum = $agentnum ) ".
4718         " ORDER BY
4719            CASE WHEN part_event_condition_option.optionname IS NULL
4720            THEN -1
4721            ELSE ". FS::part_event::Condition->age2seconds_sql('part_event_condition_option.optionvalue').
4722         " END
4723           , part_event.weight".
4724         " LIMIT 1"
4725     });
4726     
4727   unless ( $part_event_option ) {
4728     return $self->agent->invoice_template || ''
4729       if $option eq 'agent_templatename';
4730     return '';
4731   }
4732
4733   $part_event_option->optionvalue;
4734
4735 }
4736
4737 =item queued_bill 'custnum' => CUSTNUM [ , OPTION => VALUE ... ]
4738
4739 Subroutine (not a method), designed to be called from the queue.
4740
4741 Takes a list of options and values.
4742
4743 Pulls up the customer record via the custnum option and calls bill_and_collect.
4744
4745 =cut
4746
4747 sub queued_bill {
4748   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
4749
4750   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
4751   warn 'bill_and_collect custnum#'. $cust_main->custnum. "\n";#log custnum w/pid
4752
4753   $cust_main->bill_and_collect( %args );
4754 }
4755
4756 sub process_bill_and_collect {
4757   my $job = shift;
4758   my $param = thaw(decode_base64(shift));
4759   my $cust_main = qsearchs( 'cust_main', { custnum => $param->{'custnum'} } )
4760       or die "custnum '$param->{custnum}' not found!\n";
4761   $param->{'job'}   = $job;
4762   $param->{'fatal'} = 1; # runs from job queue, will be caught
4763   $param->{'retry'} = 1;
4764
4765   $cust_main->bill_and_collect( %$param );
4766 }
4767
4768 sub _upgrade_data { #class method
4769   my ($class, %opts) = @_;
4770
4771   my @statements = (
4772     'UPDATE h_cust_main SET paycvv = NULL WHERE paycvv IS NOT NULL',
4773     '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',
4774   );
4775   # fix yyyy-m-dd formatted paydates
4776   if ( driver_name =~ /^mysql$/i ) {
4777     push @statements,
4778     "UPDATE cust_main SET paydate = CONCAT( SUBSTRING(paydate FROM 1 FOR 5), '0', SUBSTRING(paydate FROM 6) ) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4779   }
4780   else { # the SQL standard
4781     push @statements, 
4782     "UPDATE cust_main SET paydate = SUBSTRING(paydate FROM 1 FOR 5) || '0' || SUBSTRING(paydate FROM 6) WHERE SUBSTRING(paydate FROM 7 FOR 1) = '-'";
4783   }
4784
4785   foreach my $sql ( @statements ) {
4786     my $sth = dbh->prepare($sql) or die dbh->errstr;
4787     $sth->execute or die $sth->errstr;
4788   }
4789
4790   local($ignore_expired_card) = 1;
4791   local($ignore_illegal_zip) = 1;
4792   local($ignore_banned_card) = 1;
4793   local($skip_fuzzyfiles) = 1;
4794   $class->_upgrade_otaker(%opts);
4795
4796 }
4797
4798 =back
4799
4800 =head1 BUGS
4801
4802 The delete method.
4803
4804 The delete method should possibly take an FS::cust_main object reference
4805 instead of a scalar customer number.
4806
4807 Bill and collect options should probably be passed as references instead of a
4808 list.
4809
4810 There should probably be a configuration file with a list of allowed credit
4811 card types.
4812
4813 No multiple currency support (probably a larger project than just this module).
4814
4815 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
4816
4817 Birthdates rely on negative epoch values.
4818
4819 The payby for card/check batches is broken.  With mixed batching, bad
4820 things will happen.
4821
4822 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
4823
4824 =head1 SEE ALSO
4825
4826 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
4827 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
4828 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
4829
4830 =cut
4831
4832 1;
4833