51270d6dde524b41a84e7db9541907a03ea2c5a9
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 require 5.006;
4 use strict;
5 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
6              $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
7 use vars qw( $realtime_bop_decline_quiet ); #ugh
8 use Safe;
9 use Carp;
10 use Exporter;
11 use Scalar::Util qw( blessed );
12 use Time::Local qw(timelocal_nocheck);
13 use Data::Dumper;
14 use Tie::IxHash;
15 use Digest::MD5 qw(md5_base64);
16 use Date::Format;
17 use Date::Parse;
18 #use Date::Manip;
19 use String::Approx qw(amatch);
20 use Business::CreditCard 0.28;
21 use Locale::Country;
22 use FS::UID qw( getotaker dbh driver_name );
23 use FS::Record qw( qsearchs qsearch dbdef );
24 use FS::Misc qw( generate_email send_email generate_ps do_print );
25 use FS::Msgcat qw(gettext);
26 use FS::cust_pkg;
27 use FS::cust_svc;
28 use FS::cust_bill;
29 use FS::cust_bill_pkg;
30 use FS::cust_pay;
31 use FS::cust_pay_pending;
32 use FS::cust_pay_void;
33 use FS::cust_pay_batch;
34 use FS::cust_credit;
35 use FS::cust_refund;
36 use FS::part_referral;
37 use FS::cust_main_county;
38 use FS::agent;
39 use FS::cust_main_invoice;
40 use FS::cust_credit_bill;
41 use FS::cust_bill_pay;
42 use FS::prepay_credit;
43 use FS::queue;
44 use FS::part_pkg;
45 use FS::part_event;
46 use FS::part_event_condition;
47 #use FS::cust_event;
48 use FS::type_pkgs;
49 use FS::payment_gateway;
50 use FS::agent_payment_gateway;
51 use FS::banned_pay;
52 use FS::payinfo_Mixin;
53 use FS::TicketSystem;
54
55 @ISA = qw( FS::payinfo_Mixin FS::Record );
56
57 @EXPORT_OK = qw( smart_search );
58
59 $realtime_bop_decline_quiet = 0;
60
61 # 1 is mostly method/subroutine entry and options
62 # 2 traces progress of some operations
63 # 3 is even more information including possibly sensitive data
64 $DEBUG = 0;
65 $me = '[FS::cust_main]';
66
67 $import = 0;
68 $skip_fuzzyfiles = 0;
69 $ignore_expired_card = 0;
70
71 @encrypted_fields = ('payinfo', 'paycvv');
72 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
73
74 #ask FS::UID to run this stuff for us later
75 #$FS::UID::callback{'FS::cust_main'} = sub { 
76 install_callback FS::UID sub { 
77   $conf = new FS::Conf;
78   #yes, need it for stuff below (prolly should be cached)
79 };
80
81 sub _cache {
82   my $self = shift;
83   my ( $hashref, $cache ) = @_;
84   if ( exists $hashref->{'pkgnum'} ) {
85     #@{ $self->{'_pkgnum'} } = ();
86     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
87     $self->{'_pkgnum'} = $subcache;
88     #push @{ $self->{'_pkgnum'} },
89     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
90   }
91 }
92
93 =head1 NAME
94
95 FS::cust_main - Object methods for cust_main records
96
97 =head1 SYNOPSIS
98
99   use FS::cust_main;
100
101   $record = new FS::cust_main \%hash;
102   $record = new FS::cust_main { 'column' => 'value' };
103
104   $error = $record->insert;
105
106   $error = $new_record->replace($old_record);
107
108   $error = $record->delete;
109
110   $error = $record->check;
111
112   @cust_pkg = $record->all_pkgs;
113
114   @cust_pkg = $record->ncancelled_pkgs;
115
116   @cust_pkg = $record->suspended_pkgs;
117
118   $error = $record->bill;
119   $error = $record->bill %options;
120   $error = $record->bill 'time' => $time;
121
122   $error = $record->collect;
123   $error = $record->collect %options;
124   $error = $record->collect 'invoice_time'   => $time,
125                           ;
126
127 =head1 DESCRIPTION
128
129 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
130 FS::Record.  The following fields are currently supported:
131
132 =over 4
133
134 =item custnum - primary key (assigned automatically for new customers)
135
136 =item agentnum - agent (see L<FS::agent>)
137
138 =item refnum - Advertising source (see L<FS::part_referral>)
139
140 =item first - name
141
142 =item last - name
143
144 =item ss - social security number (optional)
145
146 =item company - (optional)
147
148 =item address1
149
150 =item address2 - (optional)
151
152 =item city
153
154 =item county - (optional, see L<FS::cust_main_county>)
155
156 =item state - (see L<FS::cust_main_county>)
157
158 =item zip
159
160 =item country - (see L<FS::cust_main_county>)
161
162 =item daytime - phone (optional)
163
164 =item night - phone (optional)
165
166 =item fax - phone (optional)
167
168 =item ship_first - name
169
170 =item ship_last - name
171
172 =item ship_company - (optional)
173
174 =item ship_address1
175
176 =item ship_address2 - (optional)
177
178 =item ship_city
179
180 =item ship_county - (optional, see L<FS::cust_main_county>)
181
182 =item ship_state - (see L<FS::cust_main_county>)
183
184 =item ship_zip
185
186 =item ship_country - (see L<FS::cust_main_county>)
187
188 =item ship_daytime - phone (optional)
189
190 =item ship_night - phone (optional)
191
192 =item ship_fax - phone (optional)
193
194 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
195
196 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
197
198 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
199
200 =item paycvv
201
202 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
203
204 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
205
206 =item paystart_month - start date month (maestro/solo cards only)
207
208 =item paystart_year - start date year (maestro/solo cards only)
209
210 =item payissue - issue number (maestro/solo cards only)
211
212 =item payname - name on card or billing name
213
214 =item payip - IP address from which payment information was received
215
216 =item tax - tax exempt, empty or `Y'
217
218 =item otaker - order taker (assigned automatically, see L<FS::UID>)
219
220 =item comments - comments (optional)
221
222 =item referral_custnum - referring customer number
223
224 =item spool_cdr - Enable individual CDR spooling, empty or `Y'
225
226 =item squelch_cdr - Discourage individual CDR printing, empty or `Y'
227
228 =back
229
230 =head1 METHODS
231
232 =over 4
233
234 =item new HASHREF
235
236 Creates a new customer.  To add the customer to the database, see L<"insert">.
237
238 Note that this stores the hash reference, not a distinct copy of the hash it
239 points to.  You can ask the object for a copy with the I<hash> method.
240
241 =cut
242
243 sub table { 'cust_main'; }
244
245 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
246
247 Adds this customer to the database.  If there is an error, returns the error,
248 otherwise returns false.
249
250 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
251 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
252 are inserted atomicly, or the transaction is rolled back.  Passing an empty
253 hash reference is equivalent to not supplying this parameter.  There should be
254 a better explanation of this, but until then, here's an example:
255
256   use Tie::RefHash;
257   tie %hash, 'Tie::RefHash'; #this part is important
258   %hash = (
259     $cust_pkg => [ $svc_acct ],
260     ...
261   );
262   $cust_main->insert( \%hash );
263
264 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
265 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
266 expected and rollback the entire transaction; it is not necessary to call 
267 check_invoicing_list first.  The invoicing_list is set after the records in the
268 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
269 invoicing_list destination to the newly-created svc_acct.  Here's an example:
270
271   $cust_main->insert( {}, [ $email, 'POST' ] );
272
273 Currently available options are: I<depend_jobnum> and I<noexport>.
274
275 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
276 on the supplied jobnum (they will not run until the specific job completes).
277 This can be used to defer provisioning until some action completes (such
278 as running the customer's credit card successfully).
279
280 The I<noexport> option is deprecated.  If I<noexport> is set true, no
281 provisioning jobs (exports) are scheduled.  (You can schedule them later with
282 the B<reexport> method.)
283
284 =cut
285
286 sub insert {
287   my $self = shift;
288   my $cust_pkgs = @_ ? shift : {};
289   my $invoicing_list = @_ ? shift : '';
290   my %options = @_;
291   warn "$me insert called with options ".
292        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
293     if $DEBUG;
294
295   local $SIG{HUP} = 'IGNORE';
296   local $SIG{INT} = 'IGNORE';
297   local $SIG{QUIT} = 'IGNORE';
298   local $SIG{TERM} = 'IGNORE';
299   local $SIG{TSTP} = 'IGNORE';
300   local $SIG{PIPE} = 'IGNORE';
301
302   my $oldAutoCommit = $FS::UID::AutoCommit;
303   local $FS::UID::AutoCommit = 0;
304   my $dbh = dbh;
305
306   my $prepay_identifier = '';
307   my( $amount, $seconds ) = ( 0, 0 );
308   my $payby = '';
309   if ( $self->payby eq 'PREPAY' ) {
310
311     $self->payby('BILL');
312     $prepay_identifier = $self->payinfo;
313     $self->payinfo('');
314
315     warn "  looking up prepaid card $prepay_identifier\n"
316       if $DEBUG > 1;
317
318     my $error = $self->get_prepay($prepay_identifier, \$amount, \$seconds);
319     if ( $error ) {
320       $dbh->rollback if $oldAutoCommit;
321       #return "error applying prepaid card (transaction rolled back): $error";
322       return $error;
323     }
324
325     $payby = 'PREP' if $amount;
326
327   } elsif ( $self->payby =~ /^(CASH|WEST|MCRD)$/ ) {
328
329     $payby = $1;
330     $self->payby('BILL');
331     $amount = $self->paid;
332
333   }
334
335   warn "  inserting $self\n"
336     if $DEBUG > 1;
337
338   $self->signupdate(time) unless $self->signupdate;
339
340   my $error = $self->SUPER::insert;
341   if ( $error ) {
342     $dbh->rollback if $oldAutoCommit;
343     #return "inserting cust_main record (transaction rolled back): $error";
344     return $error;
345   }
346
347   warn "  setting invoicing list\n"
348     if $DEBUG > 1;
349
350   if ( $invoicing_list ) {
351     $error = $self->check_invoicing_list( $invoicing_list );
352     if ( $error ) {
353       $dbh->rollback if $oldAutoCommit;
354       #return "checking invoicing_list (transaction rolled back): $error";
355       return $error;
356     }
357     $self->invoicing_list( $invoicing_list );
358   }
359
360   if (    $conf->config('cust_main-skeleton_tables')
361        && $conf->config('cust_main-skeleton_custnum') ) {
362
363     warn "  inserting skeleton records\n"
364       if $DEBUG > 1;
365
366     my $error = $self->start_copy_skel;
367     if ( $error ) {
368       $dbh->rollback if $oldAutoCommit;
369       return $error;
370     }
371
372   }
373
374   warn "  ordering packages\n"
375     if $DEBUG > 1;
376
377   $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
378   if ( $error ) {
379     $dbh->rollback if $oldAutoCommit;
380     return $error;
381   }
382
383   if ( $seconds ) {
384     $dbh->rollback if $oldAutoCommit;
385     return "No svc_acct record to apply pre-paid time";
386   }
387
388   if ( $amount ) {
389     warn "  inserting initial $payby payment of $amount\n"
390       if $DEBUG > 1;
391     $error = $self->insert_cust_pay($payby, $amount, $prepay_identifier);
392     if ( $error ) {
393       $dbh->rollback if $oldAutoCommit;
394       return "inserting payment (transaction rolled back): $error";
395     }
396   }
397
398   unless ( $import || $skip_fuzzyfiles ) {
399     warn "  queueing fuzzyfiles update\n"
400       if $DEBUG > 1;
401     $error = $self->queue_fuzzyfiles_update;
402     if ( $error ) {
403       $dbh->rollback if $oldAutoCommit;
404       return "updating fuzzy search cache: $error";
405     }
406   }
407
408   warn "  insert complete; committing transaction\n"
409     if $DEBUG > 1;
410
411   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
412   '';
413
414 }
415
416 sub start_copy_skel {
417   my $self = shift;
418
419   #'mg_user_preference' => {},
420   #'mg_user_indicator_profile.user_indicator_profile_id' => { 'mg_profile_indicator.profile_indicator_id' => { 'mg_profile_details.profile_detail_id' }, },
421   #'mg_watchlist_header.watchlist_header_id' => { 'mg_watchlist_details.watchlist_details_id' },
422   #'mg_user_grid_header.grid_header_id' => { 'mg_user_grid_details.user_grid_details_id' },
423   #'mg_portfolio_header.portfolio_header_id' => { 'mg_portfolio_trades.portfolio_trades_id' => { 'mg_portfolio_trades_positions.portfolio_trades_positions_id' } },
424   my @tables = eval(join('\n',$conf->config('cust_main-skeleton_tables')));
425   die $@ if $@;
426
427   _copy_skel( 'cust_main',                                 #tablename
428               $conf->config('cust_main-skeleton_custnum'), #sourceid
429               $self->custnum,                              #destid
430               @tables,                                     #child tables
431             );
432 }
433
434 #recursive subroutine, not a method
435 sub _copy_skel {
436   my( $table, $sourceid, $destid, %child_tables ) = @_;
437
438   my $primary_key;
439   if ( $table =~ /^(\w+)\.(\w+)$/ ) {
440     ( $table, $primary_key ) = ( $1, $2 );
441   } else {
442     my $dbdef_table = dbdef->table($table);
443     $primary_key = $dbdef_table->primary_key
444       or return "$table has no primary key".
445                 " (or do you need to run dbdef-create?)";
446   }
447
448   warn "  _copy_skel: $table.$primary_key $sourceid to $destid for ".
449        join (', ', keys %child_tables). "\n"
450     if $DEBUG > 2;
451
452   foreach my $child_table_def ( keys %child_tables ) {
453
454     my $child_table;
455     my $child_pkey = '';
456     if ( $child_table_def =~ /^(\w+)\.(\w+)$/ ) {
457       ( $child_table, $child_pkey ) = ( $1, $2 );
458     } else {
459       $child_table = $child_table_def;
460
461       $child_pkey = dbdef->table($child_table)->primary_key;
462       #  or return "$table has no primary key".
463       #            " (or do you need to run dbdef-create?)\n";
464     }
465
466     my $sequence = '';
467     if ( keys %{ $child_tables{$child_table_def} } ) {
468
469       return "$child_table has no primary key".
470              " (run dbdef-create or try specifying it?)\n"
471         unless $child_pkey;
472
473       #false laziness w/Record::insert and only works on Pg
474       #refactor the proper last-inserted-id stuff out of Record::insert if this
475       # ever gets use for anything besides a quick kludge for one customer
476       my $default = dbdef->table($child_table)->column($child_pkey)->default;
477       $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i
478         or return "can't parse $child_table.$child_pkey default value ".
479                   " for sequence name: $default";
480       $sequence = $1;
481
482     }
483   
484     my @sel_columns = grep { $_ ne $primary_key }
485                            dbdef->table($child_table)->columns;
486     my $sel_columns = join(', ', @sel_columns );
487
488     my @ins_columns = grep { $_ ne $child_pkey } @sel_columns;
489     my $ins_columns = ' ( '. join(', ', $primary_key, @ins_columns ). ' ) ';
490     my $placeholders = ' ( ?, '. join(', ', map '?', @ins_columns ). ' ) ';
491
492     my $sel_st = "SELECT $sel_columns FROM $child_table".
493                  " WHERE $primary_key = $sourceid";
494     warn "    $sel_st\n"
495       if $DEBUG > 2;
496     my $sel_sth = dbh->prepare( $sel_st )
497       or return dbh->errstr;
498   
499     $sel_sth->execute or return $sel_sth->errstr;
500
501     while ( my $row = $sel_sth->fetchrow_hashref ) {
502
503       warn "    selected row: ".
504            join(', ', map { "$_=".$row->{$_} } keys %$row ). "\n"
505         if $DEBUG > 2;
506
507       my $statement =
508         "INSERT INTO $child_table $ins_columns VALUES $placeholders";
509       my $ins_sth =dbh->prepare($statement)
510           or return dbh->errstr;
511       my @param = ( $destid, map $row->{$_}, @ins_columns );
512       warn "    $statement: [ ". join(', ', @param). " ]\n"
513         if $DEBUG > 2;
514       $ins_sth->execute( @param )
515         or return $ins_sth->errstr;
516
517       #next unless keys %{ $child_tables{$child_table} };
518       next unless $sequence;
519       
520       #another section of that laziness
521       my $seq_sql = "SELECT currval('$sequence')";
522       my $seq_sth = dbh->prepare($seq_sql) or return dbh->errstr;
523       $seq_sth->execute or return $seq_sth->errstr;
524       my $insertid = $seq_sth->fetchrow_arrayref->[0];
525   
526       # don't drink soap!  recurse!  recurse!  okay!
527       my $error =
528         _copy_skel( $child_table_def,
529                     $row->{$child_pkey}, #sourceid
530                     $insertid, #destid
531                     %{ $child_tables{$child_table_def} },
532                   );
533       return $error if $error;
534
535     }
536
537   }
538
539   return '';
540
541 }
542
543 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
544
545 Like the insert method on an existing record, this method orders a package
546 and included services atomicaly.  Pass a Tie::RefHash data structure to this
547 method containing FS::cust_pkg and FS::svc_I<tablename> objects.  There should
548 be a better explanation of this, but until then, here's an example:
549
550   use Tie::RefHash;
551   tie %hash, 'Tie::RefHash'; #this part is important
552   %hash = (
553     $cust_pkg => [ $svc_acct ],
554     ...
555   );
556   $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
557
558 Services can be new, in which case they are inserted, or existing unaudited
559 services, in which case they are linked to the newly-created package.
560
561 Currently available options are: I<depend_jobnum> and I<noexport>.
562
563 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
564 on the supplied jobnum (they will not run until the specific job completes).
565 This can be used to defer provisioning until some action completes (such
566 as running the customer's credit card successfully).
567
568 The I<noexport> option is deprecated.  If I<noexport> is set true, no
569 provisioning jobs (exports) are scheduled.  (You can schedule them later with
570 the B<reexport> method for each cust_pkg object.  Using the B<reexport> method
571 on the cust_main object is not recommended, as existing services will also be
572 reexported.)
573
574 =cut
575
576 sub order_pkgs {
577   my $self = shift;
578   my $cust_pkgs = shift;
579   my $seconds = shift;
580   my %options = @_;
581   my %svc_options = ();
582   $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
583     if exists $options{'depend_jobnum'};
584   warn "$me order_pkgs called with options ".
585        join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
586     if $DEBUG;
587
588   local $SIG{HUP} = 'IGNORE';
589   local $SIG{INT} = 'IGNORE';
590   local $SIG{QUIT} = 'IGNORE';
591   local $SIG{TERM} = 'IGNORE';
592   local $SIG{TSTP} = 'IGNORE';
593   local $SIG{PIPE} = 'IGNORE';
594
595   my $oldAutoCommit = $FS::UID::AutoCommit;
596   local $FS::UID::AutoCommit = 0;
597   my $dbh = dbh;
598
599   local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
600
601   foreach my $cust_pkg ( keys %$cust_pkgs ) {
602     $cust_pkg->custnum( $self->custnum );
603     my $error = $cust_pkg->insert;
604     if ( $error ) {
605       $dbh->rollback if $oldAutoCommit;
606       return "inserting cust_pkg (transaction rolled back): $error";
607     }
608     foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
609       if ( $svc_something->svcnum ) {
610         my $old_cust_svc = $svc_something->cust_svc;
611         my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
612         $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
613         $error = $new_cust_svc->replace($old_cust_svc);
614       } else {
615         $svc_something->pkgnum( $cust_pkg->pkgnum );
616         if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
617           $svc_something->seconds( $svc_something->seconds + $$seconds );
618           $$seconds = 0;
619         }
620         $error = $svc_something->insert(%svc_options);
621       }
622       if ( $error ) {
623         $dbh->rollback if $oldAutoCommit;
624         #return "inserting svc_ (transaction rolled back): $error";
625         return $error;
626       }
627     }
628   }
629
630   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
631   ''; #no error
632 }
633
634 =item recharge_prepay IDENTIFIER | PREPAY_CREDIT_OBJ [ , AMOUNTREF, SECONDSREF, UPBYTEREF, DOWNBYTEREF ]
635
636 Recharges this (existing) customer with the specified prepaid card (see
637 L<FS::prepay_credit>), specified either by I<identifier> or as an
638 FS::prepay_credit object.  If there is an error, returns the error, otherwise
639 returns false.
640
641 Optionally, four scalar references can be passed as well.  They will have their
642 values filled in with the amount, number of seconds, and number of upload and
643 download bytes applied by this prepaid
644 card.
645
646 =cut
647
648 sub recharge_prepay { 
649   my( $self, $prepay_credit, $amountref, $secondsref, 
650       $upbytesref, $downbytesref, $totalbytesref ) = @_;
651
652   local $SIG{HUP} = 'IGNORE';
653   local $SIG{INT} = 'IGNORE';
654   local $SIG{QUIT} = 'IGNORE';
655   local $SIG{TERM} = 'IGNORE';
656   local $SIG{TSTP} = 'IGNORE';
657   local $SIG{PIPE} = 'IGNORE';
658
659   my $oldAutoCommit = $FS::UID::AutoCommit;
660   local $FS::UID::AutoCommit = 0;
661   my $dbh = dbh;
662
663   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes) = ( 0, 0, 0, 0, 0 );
664
665   my $error = $self->get_prepay($prepay_credit, \$amount,
666                                 \$seconds, \$upbytes, \$downbytes, \$totalbytes)
667            || $self->increment_seconds($seconds)
668            || $self->increment_upbytes($upbytes)
669            || $self->increment_downbytes($downbytes)
670            || $self->increment_totalbytes($totalbytes)
671            || $self->insert_cust_pay_prepay( $amount,
672                                              ref($prepay_credit)
673                                                ? $prepay_credit->identifier
674                                                : $prepay_credit
675                                            );
676
677   if ( $error ) {
678     $dbh->rollback if $oldAutoCommit;
679     return $error;
680   }
681
682   if ( defined($amountref)  ) { $$amountref  = $amount;  }
683   if ( defined($secondsref) ) { $$secondsref = $seconds; }
684   if ( defined($upbytesref) ) { $$upbytesref = $upbytes; }
685   if ( defined($downbytesref) ) { $$downbytesref = $downbytes; }
686   if ( defined($totalbytesref) ) { $$totalbytesref = $totalbytes; }
687
688   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
689   '';
690
691 }
692
693 =item get_prepay IDENTIFIER | PREPAY_CREDIT_OBJ , AMOUNTREF, SECONDSREF
694
695 Looks up and deletes a prepaid card (see L<FS::prepay_credit>),
696 specified either by I<identifier> or as an FS::prepay_credit object.
697
698 References to I<amount> and I<seconds> scalars should be passed as arguments
699 and will be incremented by the values of the prepaid card.
700
701 If the prepaid card specifies an I<agentnum> (see L<FS::agent>), it is used to
702 check or set this customer's I<agentnum>.
703
704 If there is an error, returns the error, otherwise returns false.
705
706 =cut
707
708
709 sub get_prepay {
710   my( $self, $prepay_credit, $amountref, $secondsref,
711       $upref, $downref, $totalref) = @_;
712
713   local $SIG{HUP} = 'IGNORE';
714   local $SIG{INT} = 'IGNORE';
715   local $SIG{QUIT} = 'IGNORE';
716   local $SIG{TERM} = 'IGNORE';
717   local $SIG{TSTP} = 'IGNORE';
718   local $SIG{PIPE} = 'IGNORE';
719
720   my $oldAutoCommit = $FS::UID::AutoCommit;
721   local $FS::UID::AutoCommit = 0;
722   my $dbh = dbh;
723
724   unless ( ref($prepay_credit) ) {
725
726     my $identifier = $prepay_credit;
727
728     $prepay_credit = qsearchs(
729       'prepay_credit',
730       { 'identifier' => $prepay_credit },
731       '',
732       'FOR UPDATE'
733     );
734
735     unless ( $prepay_credit ) {
736       $dbh->rollback if $oldAutoCommit;
737       return "Invalid prepaid card: ". $identifier;
738     }
739
740   }
741
742   if ( $prepay_credit->agentnum ) {
743     if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
744       $dbh->rollback if $oldAutoCommit;
745       return "prepaid card not valid for agent ". $self->agentnum;
746     }
747     $self->agentnum($prepay_credit->agentnum);
748   }
749
750   my $error = $prepay_credit->delete;
751   if ( $error ) {
752     $dbh->rollback if $oldAutoCommit;
753     return "removing prepay_credit (transaction rolled back): $error";
754   }
755
756   $$amountref  += $prepay_credit->amount;
757   $$secondsref += $prepay_credit->seconds;
758   $$upref      += $prepay_credit->upbytes;
759   $$downref    += $prepay_credit->downbytes;
760   $$totalref   += $prepay_credit->totalbytes;
761
762   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
763   '';
764
765 }
766
767 =item increment_upbytes SECONDS
768
769 Updates this customer's single or primary account (see L<FS::svc_acct>) by
770 the specified number of upbytes.  If there is an error, returns the error,
771 otherwise returns false.
772
773 =cut
774
775 sub increment_upbytes {
776   _increment_column( shift, 'upbytes', @_);
777 }
778
779 =item increment_downbytes SECONDS
780
781 Updates this customer's single or primary account (see L<FS::svc_acct>) by
782 the specified number of downbytes.  If there is an error, returns the error,
783 otherwise returns false.
784
785 =cut
786
787 sub increment_downbytes {
788   _increment_column( shift, 'downbytes', @_);
789 }
790
791 =item increment_totalbytes SECONDS
792
793 Updates this customer's single or primary account (see L<FS::svc_acct>) by
794 the specified number of totalbytes.  If there is an error, returns the error,
795 otherwise returns false.
796
797 =cut
798
799 sub increment_totalbytes {
800   _increment_column( shift, 'totalbytes', @_);
801 }
802
803 =item increment_seconds SECONDS
804
805 Updates this customer's single or primary account (see L<FS::svc_acct>) by
806 the specified number of seconds.  If there is an error, returns the error,
807 otherwise returns false.
808
809 =cut
810
811 sub increment_seconds {
812   _increment_column( shift, 'seconds', @_);
813 }
814
815 =item _increment_column AMOUNT
816
817 Updates this customer's single or primary account (see L<FS::svc_acct>) by
818 the specified number of seconds or bytes.  If there is an error, returns
819 the error, otherwise returns false.
820
821 =cut
822
823 sub _increment_column {
824   my( $self, $column, $amount ) = @_;
825   warn "$me increment_column called: $column, $amount\n"
826     if $DEBUG;
827
828   return '' unless $amount;
829
830   my @cust_pkg = grep { $_->part_pkg->svcpart('svc_acct') }
831                       $self->ncancelled_pkgs;
832
833   if ( ! @cust_pkg ) {
834     return 'No packages with primary or single services found'.
835            ' to apply pre-paid time';
836   } elsif ( scalar(@cust_pkg) > 1 ) {
837     #maybe have a way to specify the package/account?
838     return 'Multiple packages found to apply pre-paid time';
839   }
840
841   my $cust_pkg = $cust_pkg[0];
842   warn "  found package pkgnum ". $cust_pkg->pkgnum. "\n"
843     if $DEBUG > 1;
844
845   my @cust_svc =
846     $cust_pkg->cust_svc( $cust_pkg->part_pkg->svcpart('svc_acct') );
847
848   if ( ! @cust_svc ) {
849     return 'No account found to apply pre-paid time';
850   } elsif ( scalar(@cust_svc) > 1 ) {
851     return 'Multiple accounts found to apply pre-paid time';
852   }
853   
854   my $svc_acct = $cust_svc[0]->svc_x;
855   warn "  found service svcnum ". $svc_acct->pkgnum.
856        ' ('. $svc_acct->email. ")\n"
857     if $DEBUG > 1;
858
859   $column = "increment_$column";
860   $svc_acct->$column($amount);
861
862 }
863
864 =item insert_cust_pay_prepay AMOUNT [ PAYINFO ]
865
866 Inserts a prepayment in the specified amount for this customer.  An optional
867 second argument can specify the prepayment identifier for tracking purposes.
868 If there is an error, returns the error, otherwise returns false.
869
870 =cut
871
872 sub insert_cust_pay_prepay {
873   shift->insert_cust_pay('PREP', @_);
874 }
875
876 =item insert_cust_pay_cash AMOUNT [ PAYINFO ]
877
878 Inserts a cash payment in the specified amount for this customer.  An optional
879 second argument can specify the payment identifier for tracking purposes.
880 If there is an error, returns the error, otherwise returns false.
881
882 =cut
883
884 sub insert_cust_pay_cash {
885   shift->insert_cust_pay('CASH', @_);
886 }
887
888 =item insert_cust_pay_west AMOUNT [ PAYINFO ]
889
890 Inserts a Western Union payment in the specified amount for this customer.  An
891 optional second argument can specify the prepayment identifier for tracking
892 purposes.  If there is an error, returns the error, otherwise returns false.
893
894 =cut
895
896 sub insert_cust_pay_west {
897   shift->insert_cust_pay('WEST', @_);
898 }
899
900 sub insert_cust_pay {
901   my( $self, $payby, $amount ) = splice(@_, 0, 3);
902   my $payinfo = scalar(@_) ? shift : '';
903
904   my $cust_pay = new FS::cust_pay {
905     'custnum' => $self->custnum,
906     'paid'    => sprintf('%.2f', $amount),
907     #'_date'   => #date the prepaid card was purchased???
908     'payby'   => $payby,
909     'payinfo' => $payinfo,
910   };
911   $cust_pay->insert;
912
913 }
914
915 =item reexport
916
917 This method is deprecated.  See the I<depend_jobnum> option to the insert and
918 order_pkgs methods for a better way to defer provisioning.
919
920 Re-schedules all exports by calling the B<reexport> method of all associated
921 packages (see L<FS::cust_pkg>).  If there is an error, returns the error;
922 otherwise returns false.
923
924 =cut
925
926 sub reexport {
927   my $self = shift;
928
929   carp "WARNING: FS::cust_main::reexport is deprectated; ".
930        "use the depend_jobnum option to insert or order_pkgs to delay export";
931
932   local $SIG{HUP} = 'IGNORE';
933   local $SIG{INT} = 'IGNORE';
934   local $SIG{QUIT} = 'IGNORE';
935   local $SIG{TERM} = 'IGNORE';
936   local $SIG{TSTP} = 'IGNORE';
937   local $SIG{PIPE} = 'IGNORE';
938
939   my $oldAutoCommit = $FS::UID::AutoCommit;
940   local $FS::UID::AutoCommit = 0;
941   my $dbh = dbh;
942
943   foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
944     my $error = $cust_pkg->reexport;
945     if ( $error ) {
946       $dbh->rollback if $oldAutoCommit;
947       return $error;
948     }
949   }
950
951   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
952   '';
953
954 }
955
956 =item delete NEW_CUSTNUM
957
958 This deletes the customer.  If there is an error, returns the error, otherwise
959 returns false.
960
961 This will completely remove all traces of the customer record.  This is not
962 what you want when a customer cancels service; for that, cancel all of the
963 customer's packages (see L</cancel>).
964
965 If the customer has any uncancelled packages, you need to pass a new (valid)
966 customer number for those packages to be transferred to.  Cancelled packages
967 will be deleted.  Did I mention that this is NOT what you want when a customer
968 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
969
970 You can't delete a customer with invoices (see L<FS::cust_bill>),
971 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
972 refunds (see L<FS::cust_refund>).
973
974 =cut
975
976 sub delete {
977   my $self = shift;
978
979   local $SIG{HUP} = 'IGNORE';
980   local $SIG{INT} = 'IGNORE';
981   local $SIG{QUIT} = 'IGNORE';
982   local $SIG{TERM} = 'IGNORE';
983   local $SIG{TSTP} = 'IGNORE';
984   local $SIG{PIPE} = 'IGNORE';
985
986   my $oldAutoCommit = $FS::UID::AutoCommit;
987   local $FS::UID::AutoCommit = 0;
988   my $dbh = dbh;
989
990   if ( $self->cust_bill ) {
991     $dbh->rollback if $oldAutoCommit;
992     return "Can't delete a customer with invoices";
993   }
994   if ( $self->cust_credit ) {
995     $dbh->rollback if $oldAutoCommit;
996     return "Can't delete a customer with credits";
997   }
998   if ( $self->cust_pay ) {
999     $dbh->rollback if $oldAutoCommit;
1000     return "Can't delete a customer with payments";
1001   }
1002   if ( $self->cust_refund ) {
1003     $dbh->rollback if $oldAutoCommit;
1004     return "Can't delete a customer with refunds";
1005   }
1006
1007   my @cust_pkg = $self->ncancelled_pkgs;
1008   if ( @cust_pkg ) {
1009     my $new_custnum = shift;
1010     unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
1011       $dbh->rollback if $oldAutoCommit;
1012       return "Invalid new customer number: $new_custnum";
1013     }
1014     foreach my $cust_pkg ( @cust_pkg ) {
1015       my %hash = $cust_pkg->hash;
1016       $hash{'custnum'} = $new_custnum;
1017       my $new_cust_pkg = new FS::cust_pkg ( \%hash );
1018       my $error = $new_cust_pkg->replace($cust_pkg,
1019                                          options => { $cust_pkg->options },
1020                                         );
1021       if ( $error ) {
1022         $dbh->rollback if $oldAutoCommit;
1023         return $error;
1024       }
1025     }
1026   }
1027   my @cancelled_cust_pkg = $self->all_pkgs;
1028   foreach my $cust_pkg ( @cancelled_cust_pkg ) {
1029     my $error = $cust_pkg->delete;
1030     if ( $error ) {
1031       $dbh->rollback if $oldAutoCommit;
1032       return $error;
1033     }
1034   }
1035
1036   foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
1037     qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
1038   ) {
1039     my $error = $cust_main_invoice->delete;
1040     if ( $error ) {
1041       $dbh->rollback if $oldAutoCommit;
1042       return $error;
1043     }
1044   }
1045
1046   my $error = $self->SUPER::delete;
1047   if ( $error ) {
1048     $dbh->rollback if $oldAutoCommit;
1049     return $error;
1050   }
1051
1052   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1053   '';
1054
1055 }
1056
1057 =item replace [ OLD_RECORD ] [ INVOICING_LIST_ARYREF ]
1058
1059 Replaces the OLD_RECORD with this one in the database.  If there is an error,
1060 returns the error, otherwise returns false.
1061
1062 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
1063 be set as the invoicing list (see L<"invoicing_list">).  Errors return as
1064 expected and rollback the entire transaction; it is not necessary to call 
1065 check_invoicing_list first.  Here's an example:
1066
1067   $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
1068
1069 =cut
1070
1071 sub replace {
1072   my $self = shift;
1073
1074   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
1075               ? shift
1076               : $self->replace_old;
1077
1078   my @param = @_;
1079
1080   warn "$me replace called\n"
1081     if $DEBUG;
1082
1083   my $curuser = $FS::CurrentUser::CurrentUser;
1084   if (    $self->payby eq 'COMP'
1085        && $self->payby ne $old->payby
1086        && ! $curuser->access_right('Complimentary customer')
1087      )
1088   {
1089     return "You are not permitted to create complimentary accounts.";
1090   }
1091
1092   local($ignore_expired_card) = 1
1093     if $old->payby  =~ /^(CARD|DCRD)$/
1094     && $self->payby =~ /^(CARD|DCRD)$/
1095     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
1096
1097   local $SIG{HUP} = 'IGNORE';
1098   local $SIG{INT} = 'IGNORE';
1099   local $SIG{QUIT} = 'IGNORE';
1100   local $SIG{TERM} = 'IGNORE';
1101   local $SIG{TSTP} = 'IGNORE';
1102   local $SIG{PIPE} = 'IGNORE';
1103
1104   my $oldAutoCommit = $FS::UID::AutoCommit;
1105   local $FS::UID::AutoCommit = 0;
1106   my $dbh = dbh;
1107
1108   my $error = $self->SUPER::replace($old);
1109
1110   if ( $error ) {
1111     $dbh->rollback if $oldAutoCommit;
1112     return $error;
1113   }
1114
1115   if ( @param ) { # INVOICING_LIST_ARYREF
1116     my $invoicing_list = shift @param;
1117     $error = $self->check_invoicing_list( $invoicing_list );
1118     if ( $error ) {
1119       $dbh->rollback if $oldAutoCommit;
1120       return $error;
1121     }
1122     $self->invoicing_list( $invoicing_list );
1123   }
1124
1125   if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
1126        grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
1127     # card/check/lec info has changed, want to retry realtime_ invoice events
1128     my $error = $self->retry_realtime;
1129     if ( $error ) {
1130       $dbh->rollback if $oldAutoCommit;
1131       return $error;
1132     }
1133   }
1134
1135   unless ( $import || $skip_fuzzyfiles ) {
1136     $error = $self->queue_fuzzyfiles_update;
1137     if ( $error ) {
1138       $dbh->rollback if $oldAutoCommit;
1139       return "updating fuzzy search cache: $error";
1140     }
1141   }
1142
1143   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1144   '';
1145
1146 }
1147
1148 =item queue_fuzzyfiles_update
1149
1150 Used by insert & replace to update the fuzzy search cache
1151
1152 =cut
1153
1154 sub queue_fuzzyfiles_update {
1155   my $self = shift;
1156
1157   local $SIG{HUP} = 'IGNORE';
1158   local $SIG{INT} = 'IGNORE';
1159   local $SIG{QUIT} = 'IGNORE';
1160   local $SIG{TERM} = 'IGNORE';
1161   local $SIG{TSTP} = 'IGNORE';
1162   local $SIG{PIPE} = 'IGNORE';
1163
1164   my $oldAutoCommit = $FS::UID::AutoCommit;
1165   local $FS::UID::AutoCommit = 0;
1166   my $dbh = dbh;
1167
1168   my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1169   my $error = $queue->insert( map $self->getfield($_),
1170                                   qw(first last company)
1171                             );
1172   if ( $error ) {
1173     $dbh->rollback if $oldAutoCommit;
1174     return "queueing job (transaction rolled back): $error";
1175   }
1176
1177   if ( $self->ship_last ) {
1178     $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
1179     $error = $queue->insert( map $self->getfield("ship_$_"),
1180                                  qw(first last company)
1181                            );
1182     if ( $error ) {
1183       $dbh->rollback if $oldAutoCommit;
1184       return "queueing job (transaction rolled back): $error";
1185     }
1186   }
1187
1188   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1189   '';
1190
1191 }
1192
1193 =item check
1194
1195 Checks all fields to make sure this is a valid customer record.  If there is
1196 an error, returns the error, otherwise returns false.  Called by the insert
1197 and replace methods.
1198
1199 =cut
1200
1201 sub check {
1202   my $self = shift;
1203
1204   warn "$me check BEFORE: \n". $self->_dump
1205     if $DEBUG > 2;
1206
1207   my $error =
1208     $self->ut_numbern('custnum')
1209     || $self->ut_number('agentnum')
1210     || $self->ut_textn('agent_custid')
1211     || $self->ut_number('refnum')
1212     || $self->ut_name('last')
1213     || $self->ut_name('first')
1214     || $self->ut_snumbern('birthdate')
1215     || $self->ut_snumbern('signupdate')
1216     || $self->ut_textn('company')
1217     || $self->ut_text('address1')
1218     || $self->ut_textn('address2')
1219     || $self->ut_text('city')
1220     || $self->ut_textn('county')
1221     || $self->ut_textn('state')
1222     || $self->ut_country('country')
1223     || $self->ut_anything('comments')
1224     || $self->ut_numbern('referral_custnum')
1225     || $self->ut_textn('stateid')
1226     || $self->ut_textn('stateid_state')
1227     || $self->ut_textn('invoice_terms')
1228   ;
1229   #barf.  need message catalogs.  i18n.  etc.
1230   $error .= "Please select an advertising source."
1231     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1232   return $error if $error;
1233
1234   return "Unknown agent"
1235     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1236
1237   return "Unknown refnum"
1238     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1239
1240   return "Unknown referring custnum: ". $self->referral_custnum
1241     unless ! $self->referral_custnum 
1242            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1243
1244   if ( $self->ss eq '' ) {
1245     $self->ss('');
1246   } else {
1247     my $ss = $self->ss;
1248     $ss =~ s/\D//g;
1249     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1250       or return "Illegal social security number: ". $self->ss;
1251     $self->ss("$1-$2-$3");
1252   }
1253
1254
1255 # bad idea to disable, causes billing to fail because of no tax rates later
1256 #  unless ( $import ) {
1257     unless ( qsearch('cust_main_county', {
1258       'country' => $self->country,
1259       'state'   => '',
1260      } ) ) {
1261       return "Unknown state/county/country: ".
1262         $self->state. "/". $self->county. "/". $self->country
1263         unless qsearch('cust_main_county',{
1264           'state'   => $self->state,
1265           'county'  => $self->county,
1266           'country' => $self->country,
1267         } );
1268     }
1269 #  }
1270
1271   $error =
1272     $self->ut_phonen('daytime', $self->country)
1273     || $self->ut_phonen('night', $self->country)
1274     || $self->ut_phonen('fax', $self->country)
1275     || $self->ut_zip('zip', $self->country)
1276   ;
1277   return $error if $error;
1278
1279   if ( $conf->exists('cust_main-require_phone')
1280        && ! length($self->daytime) && ! length($self->night)
1281      ) {
1282
1283     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1284                           ? 'Day Phone'
1285                           : FS::Msgcat::_gettext('daytime');
1286     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1287                         ? 'Night Phone'
1288                         : FS::Msgcat::_gettext('night');
1289   
1290     return "$daytime_label or $night_label is required"
1291   
1292   }
1293
1294   if ( $self->has_ship_address
1295        && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1296                         $self->addr_fields )
1297      )
1298   {
1299     my $error =
1300       $self->ut_name('ship_last')
1301       || $self->ut_name('ship_first')
1302       || $self->ut_textn('ship_company')
1303       || $self->ut_text('ship_address1')
1304       || $self->ut_textn('ship_address2')
1305       || $self->ut_text('ship_city')
1306       || $self->ut_textn('ship_county')
1307       || $self->ut_textn('ship_state')
1308       || $self->ut_country('ship_country')
1309     ;
1310     return $error if $error;
1311
1312     #false laziness with above
1313     unless ( qsearchs('cust_main_county', {
1314       'country' => $self->ship_country,
1315       'state'   => '',
1316      } ) ) {
1317       return "Unknown ship_state/ship_county/ship_country: ".
1318         $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1319         unless qsearch('cust_main_county',{
1320           'state'   => $self->ship_state,
1321           'county'  => $self->ship_county,
1322           'country' => $self->ship_country,
1323         } );
1324     }
1325     #eofalse
1326
1327     $error =
1328       $self->ut_phonen('ship_daytime', $self->ship_country)
1329       || $self->ut_phonen('ship_night', $self->ship_country)
1330       || $self->ut_phonen('ship_fax', $self->ship_country)
1331       || $self->ut_zip('ship_zip', $self->ship_country)
1332     ;
1333     return $error if $error;
1334
1335     return "Unit # is required."
1336       if $self->ship_address2 =~ /^\s*$/
1337       && $conf->exists('cust_main-require_address2');
1338
1339   } else { # ship_ info eq billing info, so don't store dup info in database
1340
1341     $self->setfield("ship_$_", '')
1342       foreach $self->addr_fields;
1343
1344     return "Unit # is required."
1345       if $self->address2 =~ /^\s*$/
1346       && $conf->exists('cust_main-require_address2');
1347
1348   }
1349
1350   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1351   #  or return "Illegal payby: ". $self->payby;
1352   #$self->payby($1);
1353   FS::payby->can_payby($self->table, $self->payby)
1354     or return "Illegal payby: ". $self->payby;
1355
1356   $error =    $self->ut_numbern('paystart_month')
1357            || $self->ut_numbern('paystart_year')
1358            || $self->ut_numbern('payissue')
1359            || $self->ut_textn('paytype')
1360   ;
1361   return $error if $error;
1362
1363   if ( $self->payip eq '' ) {
1364     $self->payip('');
1365   } else {
1366     $error = $self->ut_ip('payip');
1367     return $error if $error;
1368   }
1369
1370   # If it is encrypted and the private key is not availaible then we can't
1371   # check the credit card.
1372
1373   my $check_payinfo = 1;
1374
1375   if ($self->is_encrypted($self->payinfo)) {
1376     $check_payinfo = 0;
1377   }
1378
1379   if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1380
1381     my $payinfo = $self->payinfo;
1382     $payinfo =~ s/\D//g;
1383     $payinfo =~ /^(\d{13,16})$/
1384       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1385     $payinfo = $1;
1386     $self->payinfo($payinfo);
1387     validate($payinfo)
1388       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1389
1390     return gettext('unknown_card_type')
1391       if cardtype($self->payinfo) eq "Unknown";
1392
1393     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1394     if ( $ban ) {
1395       return 'Banned credit card: banned on '.
1396              time2str('%a %h %o at %r', $ban->_date).
1397              ' by '. $ban->otaker.
1398              ' (ban# '. $ban->bannum. ')';
1399     }
1400
1401     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1402       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1403         $self->paycvv =~ /^(\d{4})$/
1404           or return "CVV2 (CID) for American Express cards is four digits.";
1405         $self->paycvv($1);
1406       } else {
1407         $self->paycvv =~ /^(\d{3})$/
1408           or return "CVV2 (CVC2/CID) is three digits.";
1409         $self->paycvv($1);
1410       }
1411     } else {
1412       $self->paycvv('');
1413     }
1414
1415     my $cardtype = cardtype($payinfo);
1416     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1417
1418       return "Start date or issue number is required for $cardtype cards"
1419         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1420
1421       return "Start month must be between 1 and 12"
1422         if $self->paystart_month
1423            and $self->paystart_month < 1 || $self->paystart_month > 12;
1424
1425       return "Start year must be 1990 or later"
1426         if $self->paystart_year
1427            and $self->paystart_year < 1990;
1428
1429       return "Issue number must be beween 1 and 99"
1430         if $self->payissue
1431           and $self->payissue < 1 || $self->payissue > 99;
1432
1433     } else {
1434       $self->paystart_month('');
1435       $self->paystart_year('');
1436       $self->payissue('');
1437     }
1438
1439   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1440
1441     my $payinfo = $self->payinfo;
1442     $payinfo =~ s/[^\d\@]//g;
1443     if ( $conf->exists('echeck-nonus') ) {
1444       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1445       $payinfo = "$1\@$2";
1446     } else {
1447       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1448       $payinfo = "$1\@$2";
1449     }
1450     $self->payinfo($payinfo);
1451     $self->paycvv('');
1452
1453     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1454     if ( $ban ) {
1455       return 'Banned ACH account: banned on '.
1456              time2str('%a %h %o at %r', $ban->_date).
1457              ' by '. $ban->otaker.
1458              ' (ban# '. $ban->bannum. ')';
1459     }
1460
1461   } elsif ( $self->payby eq 'LECB' ) {
1462
1463     my $payinfo = $self->payinfo;
1464     $payinfo =~ s/\D//g;
1465     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1466     $payinfo = $1;
1467     $self->payinfo($payinfo);
1468     $self->paycvv('');
1469
1470   } elsif ( $self->payby eq 'BILL' ) {
1471
1472     $error = $self->ut_textn('payinfo');
1473     return "Illegal P.O. number: ". $self->payinfo if $error;
1474     $self->paycvv('');
1475
1476   } elsif ( $self->payby eq 'COMP' ) {
1477
1478     my $curuser = $FS::CurrentUser::CurrentUser;
1479     if (    ! $self->custnum
1480          && ! $curuser->access_right('Complimentary customer')
1481        )
1482     {
1483       return "You are not permitted to create complimentary accounts."
1484     }
1485
1486     $error = $self->ut_textn('payinfo');
1487     return "Illegal comp account issuer: ". $self->payinfo if $error;
1488     $self->paycvv('');
1489
1490   } elsif ( $self->payby eq 'PREPAY' ) {
1491
1492     my $payinfo = $self->payinfo;
1493     $payinfo =~ s/\W//g; #anything else would just confuse things
1494     $self->payinfo($payinfo);
1495     $error = $self->ut_alpha('payinfo');
1496     return "Illegal prepayment identifier: ". $self->payinfo if $error;
1497     return "Unknown prepayment identifier"
1498       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1499     $self->paycvv('');
1500
1501   }
1502
1503   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1504     return "Expiration date required"
1505       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1506     $self->paydate('');
1507   } else {
1508     my( $m, $y );
1509     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1510       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1511     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1512       ( $m, $y ) = ( $3, "20$2" );
1513     } else {
1514       return "Illegal expiration date: ". $self->paydate;
1515     }
1516     $self->paydate("$y-$m-01");
1517     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1518     return gettext('expired_card')
1519       if !$import
1520       && !$ignore_expired_card 
1521       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1522   }
1523
1524   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1525        ( ! $conf->exists('require_cardname')
1526          || $self->payby !~ /^(CARD|DCRD)$/  ) 
1527   ) {
1528     $self->payname( $self->first. " ". $self->getfield('last') );
1529   } else {
1530     $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1531       or return gettext('illegal_name'). " payname: ". $self->payname;
1532     $self->payname($1);
1533   }
1534
1535   foreach my $flag (qw( tax spool_cdr squelch_cdr )) {
1536     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1537     $self->$flag($1);
1538   }
1539
1540   $self->otaker(getotaker) unless $self->otaker;
1541
1542   warn "$me check AFTER: \n". $self->_dump
1543     if $DEBUG > 2;
1544
1545   $self->SUPER::check;
1546 }
1547
1548 =item addr_fields 
1549
1550 Returns a list of fields which have ship_ duplicates.
1551
1552 =cut
1553
1554 sub addr_fields {
1555   qw( last first company
1556       address1 address2 city county state zip country
1557       daytime night fax
1558     );
1559 }
1560
1561 =item has_ship_address
1562
1563 Returns true if this customer record has a separate shipping address.
1564
1565 =cut
1566
1567 sub has_ship_address {
1568   my $self = shift;
1569   scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1570 }
1571
1572 =item all_pkgs
1573
1574 Returns all packages (see L<FS::cust_pkg>) for this customer.
1575
1576 =cut
1577
1578 sub all_pkgs {
1579   my $self = shift;
1580
1581   return $self->num_pkgs unless wantarray;
1582
1583   my @cust_pkg = ();
1584   if ( $self->{'_pkgnum'} ) {
1585     @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1586   } else {
1587     @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1588   }
1589
1590   sort sort_packages @cust_pkg;
1591 }
1592
1593 =item cust_pkg
1594
1595 Synonym for B<all_pkgs>.
1596
1597 =cut
1598
1599 sub cust_pkg {
1600   shift->all_pkgs(@_);
1601 }
1602
1603 =item ncancelled_pkgs
1604
1605 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1606
1607 =cut
1608
1609 sub ncancelled_pkgs {
1610   my $self = shift;
1611
1612   return $self->num_ncancelled_pkgs unless wantarray;
1613
1614   my @cust_pkg = ();
1615   if ( $self->{'_pkgnum'} ) {
1616
1617     warn "$me ncancelled_pkgs: returning cached objects"
1618       if $DEBUG > 1;
1619
1620     @cust_pkg = grep { ! $_->getfield('cancel') }
1621                 values %{ $self->{'_pkgnum'}->cache };
1622
1623   } else {
1624
1625     warn "$me ncancelled_pkgs: searching for packages with custnum ".
1626          $self->custnum. "\n"
1627       if $DEBUG > 1;
1628
1629     @cust_pkg =
1630       qsearch( 'cust_pkg', {
1631                              'custnum' => $self->custnum,
1632                              'cancel'  => '',
1633                            });
1634     push @cust_pkg,
1635       qsearch( 'cust_pkg', {
1636                              'custnum' => $self->custnum,
1637                              'cancel'  => 0,
1638                            });
1639   }
1640
1641   sort sort_packages @cust_pkg;
1642
1643 }
1644
1645 # This should be generalized to use config options to determine order.
1646 sub sort_packages {
1647   if ( $a->get('cancel') and $b->get('cancel') ) {
1648     $a->pkgnum <=> $b->pkgnum;
1649   } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1650     return -1 if $b->get('cancel');
1651     return  1 if $a->get('cancel');
1652     return 0;
1653   } else {
1654     $a->pkgnum <=> $b->pkgnum;
1655   }
1656 }
1657
1658 =item suspended_pkgs
1659
1660 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1661
1662 =cut
1663
1664 sub suspended_pkgs {
1665   my $self = shift;
1666   grep { $_->susp } $self->ncancelled_pkgs;
1667 }
1668
1669 =item unflagged_suspended_pkgs
1670
1671 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1672 customer (thouse packages without the `manual_flag' set).
1673
1674 =cut
1675
1676 sub unflagged_suspended_pkgs {
1677   my $self = shift;
1678   return $self->suspended_pkgs
1679     unless dbdef->table('cust_pkg')->column('manual_flag');
1680   grep { ! $_->manual_flag } $self->suspended_pkgs;
1681 }
1682
1683 =item unsuspended_pkgs
1684
1685 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1686 this customer.
1687
1688 =cut
1689
1690 sub unsuspended_pkgs {
1691   my $self = shift;
1692   grep { ! $_->susp } $self->ncancelled_pkgs;
1693 }
1694
1695 =item num_cancelled_pkgs
1696
1697 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1698 customer.
1699
1700 =cut
1701
1702 sub num_cancelled_pkgs {
1703   shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1704 }
1705
1706 sub num_ncancelled_pkgs {
1707   shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1708 }
1709
1710 sub num_pkgs {
1711   my( $self ) = shift;
1712   my $sql = scalar(@_) ? shift : '';
1713   $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1714   my $sth = dbh->prepare(
1715     "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1716   ) or die dbh->errstr;
1717   $sth->execute($self->custnum) or die $sth->errstr;
1718   $sth->fetchrow_arrayref->[0];
1719 }
1720
1721 =item unsuspend
1722
1723 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1724 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
1725 on success or a list of errors.
1726
1727 =cut
1728
1729 sub unsuspend {
1730   my $self = shift;
1731   grep { $_->unsuspend } $self->suspended_pkgs;
1732 }
1733
1734 =item suspend
1735
1736 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1737
1738 Returns a list: an empty list on success or a list of errors.
1739
1740 =cut
1741
1742 sub suspend {
1743   my $self = shift;
1744   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1745 }
1746
1747 =item suspend_if_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1748
1749 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1750 PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref instead
1751 of a list of pkgparts; the hashref has the following keys:
1752
1753 =over 4
1754
1755 =item pkgparts - listref of pkgparts
1756
1757 =item (other options are passed to the suspend method)
1758
1759 =back
1760
1761
1762 Returns a list: an empty list on success or a list of errors.
1763
1764 =cut
1765
1766 sub suspend_if_pkgpart {
1767   my $self = shift;
1768   my (@pkgparts, %opt);
1769   if (ref($_[0]) eq 'HASH'){
1770     @pkgparts = @{$_[0]{pkgparts}};
1771     %opt      = %{$_[0]};
1772   }else{
1773     @pkgparts = @_;
1774   }
1775   grep { $_->suspend(%opt) }
1776     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1777       $self->unsuspended_pkgs;
1778 }
1779
1780 =item suspend_unless_pkgpart HASHREF | PKGPART [ , PKGPART ... ]
1781
1782 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1783 given PKGPARTs (see L<FS::part_pkg>).  Preferred usage is to pass a hashref
1784 instead of a list of pkgparts; the hashref has the following keys:
1785
1786 =over 4
1787
1788 =item pkgparts - listref of pkgparts
1789
1790 =item (other options are passed to the suspend method)
1791
1792 =back
1793
1794 Returns a list: an empty list on success or a list of errors.
1795
1796 =cut
1797
1798 sub suspend_unless_pkgpart {
1799   my $self = shift;
1800   my (@pkgparts, %opt);
1801   if (ref($_[0]) eq 'HASH'){
1802     @pkgparts = @{$_[0]{pkgparts}};
1803     %opt      = %{$_[0]};
1804   }else{
1805     @pkgparts = @_;
1806   }
1807   grep { $_->suspend(%opt) }
1808     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1809       $self->unsuspended_pkgs;
1810 }
1811
1812 =item cancel [ OPTION => VALUE ... ]
1813
1814 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1815
1816 Available options are:
1817
1818 =over 4
1819
1820 =item quiet - can be set true to supress email cancellation notices.
1821
1822 =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.
1823
1824 =item ban - can be set true to ban this customer's credit card or ACH information, if present.
1825
1826 =back
1827
1828 Always returns a list: an empty list on success or a list of errors.
1829
1830 =cut
1831
1832 sub cancel {
1833   my( $self, %opt ) = @_;
1834
1835   warn "$me cancel called on customer ". $self->custnum. " with options ".
1836        join(', ', map { "$_: $opt{$_}" } keys %opt ). "\n"
1837     if $DEBUG;
1838
1839   return ( 'access denied' )
1840     unless $FS::CurrentUser::CurrentUser->access_right('Cancel customer');
1841
1842   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1843
1844     #should try decryption (we might have the private key)
1845     # and if not maybe queue a job for the server that does?
1846     return ( "Can't (yet) ban encrypted credit cards" )
1847       if $self->is_encrypted($self->payinfo);
1848
1849     my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1850     my $error = $ban->insert;
1851     return ( $error ) if $error;
1852
1853   }
1854
1855   my @pkgs = $self->ncancelled_pkgs;
1856
1857   warn "$me cancelling ". scalar($self->ncancelled_pkgs). "/".
1858        scalar(@pkgs). " packages for customer ". $self->custnum. "\n"
1859     if $DEBUG;
1860
1861   grep { $_ } map { $_->cancel(%opt) } $self->ncancelled_pkgs;
1862 }
1863
1864 sub _banned_pay_hashref {
1865   my $self = shift;
1866
1867   my %payby2ban = (
1868     'CARD' => 'CARD',
1869     'DCRD' => 'CARD',
1870     'CHEK' => 'CHEK',
1871     'DCHK' => 'CHEK'
1872   );
1873
1874   {
1875     'payby'   => $payby2ban{$self->payby},
1876     'payinfo' => md5_base64($self->payinfo),
1877     #don't ever *search* on reason! #'reason'  =>
1878   };
1879 }
1880
1881 =item notes
1882
1883 Returns all notes (see L<FS::cust_main_note>) for this customer.
1884
1885 =cut
1886
1887 sub notes {
1888   my $self = shift;
1889   #order by?
1890   qsearch( 'cust_main_note',
1891            { 'custnum' => $self->custnum },
1892            '',
1893            'ORDER BY _DATE DESC'
1894          );
1895 }
1896
1897 =item agent
1898
1899 Returns the agent (see L<FS::agent>) for this customer.
1900
1901 =cut
1902
1903 sub agent {
1904   my $self = shift;
1905   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1906 }
1907
1908 =item bill_and_collect 
1909
1910 Cancels and suspends any packages due, generates bills, applies payments and
1911 cred
1912
1913 Warns on errors (Does not currently: If there is an error, returns the error, otherwise returns false.)
1914
1915 Options are passed as name-value pairs.  Currently available options are:
1916
1917 =over 4
1918
1919 =item time
1920
1921 Bills the customer as if it were that time.  Specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.  For example:
1922
1923  use Date::Parse;
1924  ...
1925  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1926
1927 =item invoice_time
1928
1929 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices.  Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
1930
1931 =item check_freq
1932
1933 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
1934
1935 =item resetup
1936
1937 If set true, re-charges setup fees.
1938
1939 =item debug
1940
1941 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
1942
1943 =back
1944
1945 =cut
1946
1947 sub bill_and_collect {
1948   my( $self, %options ) = @_;
1949
1950   ###
1951   # cancel packages
1952   ###
1953
1954   #$options{actual_time} not $options{time} because freeside-daily -d is for
1955   #pre-printing invoices
1956   my @cancel_pkgs = grep { $_->expire && $_->expire <= $options{actual_time} }
1957                          $self->ncancelled_pkgs;
1958
1959   foreach my $cust_pkg ( @cancel_pkgs ) {
1960     my $error = $cust_pkg->cancel;
1961     warn "Error cancelling expired pkg ". $cust_pkg->pkgnum.
1962          " for custnum ". $self->custnum. ": $error"
1963       if $error;
1964   }
1965
1966   ###
1967   # suspend packages
1968   ###
1969
1970   #$options{actual_time} not $options{time} because freeside-daily -d is for
1971   #pre-printing invoices
1972   my @susp_pkgs = 
1973     grep { ! $_->susp
1974            && (    (    $_->part_pkg->is_prepaid
1975                      && $_->bill
1976                      && $_->bill < $options{actual_time}
1977                    )
1978                 || (    $_->adjourn
1979                     && $_->adjourn <= $options{actual_time}
1980                   )
1981               )
1982          }
1983          $self->ncancelled_pkgs;
1984
1985   foreach my $cust_pkg ( @susp_pkgs ) {
1986     my $error = $cust_pkg->suspend;
1987     warn "Error suspending package ". $cust_pkg->pkgnum.
1988          " for custnum ". $self->custnum. ": $error"
1989       if $error;
1990   }
1991
1992   ###
1993   # bill and collect
1994   ###
1995
1996   my $error = $self->bill( %options );
1997   warn "Error billing, custnum ". $self->custnum. ": $error" if $error;
1998
1999   $self->apply_payments_and_credits;
2000
2001   $error = $self->collect( %options );
2002   warn "Error collecting, custnum". $self->custnum. ": $error" if $error;
2003
2004 }
2005
2006 =item bill OPTIONS
2007
2008 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
2009 conjunction with the collect method by calling B<bill_and_collect>.
2010
2011 If there is an error, returns the error, otherwise returns false.
2012
2013 Options are passed as name-value pairs.  Currently available options are:
2014
2015 =over 4
2016
2017 =item resetup
2018
2019 If set true, re-charges setup fees.
2020
2021 =item time
2022
2023 Bills the customer as if it were that time.  Specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.  For example:
2024
2025  use Date::Parse;
2026  ...
2027  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
2028
2029 =item pkg_list
2030
2031 An array ref of specific packages (objects) to attempt billing, instead trying all of them.
2032
2033  $cust_main->bill( pkg_list => [$pkg1, $pkg2] );
2034
2035 =item invoice_time
2036
2037 Used in conjunction with the I<time> option, this option specifies the date of for the generated invoices.  Other calculations, such as whether or not to generate the invoice in the first place, are not affected.
2038
2039 =back
2040
2041 =cut
2042
2043 sub bill {
2044   my( $self, %options ) = @_;
2045   return '' if $self->payby eq 'COMP';
2046   warn "$me bill customer ". $self->custnum. "\n"
2047     if $DEBUG;
2048
2049   my $time = $options{'time'} || time;
2050
2051   #put below somehow?
2052   local $SIG{HUP} = 'IGNORE';
2053   local $SIG{INT} = 'IGNORE';
2054   local $SIG{QUIT} = 'IGNORE';
2055   local $SIG{TERM} = 'IGNORE';
2056   local $SIG{TSTP} = 'IGNORE';
2057   local $SIG{PIPE} = 'IGNORE';
2058
2059   my $oldAutoCommit = $FS::UID::AutoCommit;
2060   local $FS::UID::AutoCommit = 0;
2061   my $dbh = dbh;
2062
2063   $self->select_for_update; #mutex
2064
2065   my @cust_bill_pkg = ();
2066   my @appended_cust_bill_pkg = ();
2067
2068   ###
2069   # find the packages which are due for billing, find out how much they are
2070   # & generate invoice database.
2071   ###
2072
2073   my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
2074   my %tax;
2075   my %taxlisthash;
2076   my %taxname;
2077   my @precommit_hooks = ();
2078
2079   my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
2080   foreach my $cust_pkg (@cust_pkgs) {
2081
2082     #NO!! next if $cust_pkg->cancel;  
2083     next if $cust_pkg->getfield('cancel');  
2084
2085     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
2086
2087     #? to avoid use of uninitialized value errors... ?
2088     $cust_pkg->setfield('bill', '')
2089       unless defined($cust_pkg->bill);
2090  
2091     #my $part_pkg = $cust_pkg->part_pkg;
2092
2093     my $real_pkgpart = $cust_pkg->pkgpart;
2094     my %hash = $cust_pkg->hash;
2095
2096     foreach my $part_pkg ( $cust_pkg->part_pkg->self_and_bill_linked ) {
2097
2098       $cust_pkg->set($_, $hash{$_}) foreach qw ( setup last_bill bill );
2099
2100       my $error =
2101         $self->_make_lines( 'part_pkg'            => $part_pkg,
2102                             'cust_pkg'            => $cust_pkg,
2103                             'precommit_hooks'     => \@precommit_hooks,
2104                             'line_items'          => \@cust_bill_pkg,
2105                             'appended_line_items' => \@appended_cust_bill_pkg,
2106                             'setup'               => \$total_setup,
2107                             'recur'               => \$total_recur,
2108                             'tax_matrix'          => \%taxlisthash,
2109                             'time'                => $time,
2110                             'options'             => \%options,
2111                           );
2112       if ($error) {
2113         $dbh->rollback if $oldAutoCommit;
2114         return $error;
2115       }
2116
2117     } #foreach my $part_pkg
2118
2119   } #foreach my $cust_pkg
2120
2121   push @cust_bill_pkg, @appended_cust_bill_pkg;
2122
2123   unless ( @cust_bill_pkg ) { #don't create an invoice w/o line items
2124     #but do commit any package date cycling that happened
2125     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2126     return '';
2127   }
2128
2129   my $postal_pkg = $self->charge_postal_fee();
2130   if ( $postal_pkg && !ref( $postal_pkg ) ) {
2131     $dbh->rollback if $oldAutoCommit;
2132     return "can't charge postal invoice fee for customer ".
2133       $self->custnum. ": $postal_pkg";
2134   }
2135   if ( $postal_pkg ) {
2136     foreach my $part_pkg ( $postal_pkg->part_pkg->self_and_bill_linked ) {
2137       my $error =
2138         $self->_make_lines( 'part_pkg'            => $part_pkg,
2139                             'cust_pkg'            => $postal_pkg,
2140                             'precommit_hooks'     => \@precommit_hooks,
2141                             'line_items'          => \@cust_bill_pkg,
2142                             'appended_line_items' => \@appended_cust_bill_pkg,
2143                             'setup'               => \$total_setup,
2144                             'recur'               => \$total_recur,
2145                             'tax_matrix'          => \%taxlisthash,
2146                             'time'                => $time,
2147                             'options'             => \%options,
2148                           );
2149       if ($error) {
2150         $dbh->rollback if $oldAutoCommit;
2151         return $error;
2152       }
2153     }
2154   }
2155
2156   warn "having a look at the taxes we found...\n" if $DEBUG > 2;
2157   foreach my $tax ( keys %taxlisthash ) {
2158     my $tax_object = shift @{ $taxlisthash{$tax} };
2159     warn "found ". $tax_object->taxname. " as $tax\n" if $DEBUG > 2;
2160     my $listref_or_error = $tax_object->taxline( @{ $taxlisthash{$tax} } );
2161     unless (ref($listref_or_error)) {
2162       $dbh->rollback if $oldAutoCommit;
2163       return $listref_or_error;
2164     }
2165     unshift @{ $taxlisthash{$tax} }, $tax_object;
2166
2167     warn "adding ". $listref_or_error->[1].
2168          " as ". $listref_or_error->[0]. "\n"
2169       if $DEBUG > 2;
2170     $tax{ $tax_object->taxname } += $listref_or_error->[1];
2171     if ( $taxname{ $listref_or_error->[0] } ) {
2172       push @{ $taxname{ $listref_or_error->[0] } }, $tax_object->taxname;
2173     }else{
2174       $taxname{ $listref_or_error->[0] } = [ $tax_object->taxname ];
2175     }
2176   
2177   }
2178
2179   #some taxes are taxed
2180   my %totlisthash;
2181   
2182   warn "finding taxed taxes...\n" if $DEBUG > 2;
2183   foreach my $tax ( keys %taxlisthash ) {
2184     my $tax_object = shift @{ $taxlisthash{$tax} };
2185     warn "found possible taxed tax ". $tax_object->taxname. " we call $tax\n"
2186       if $DEBUG > 2;
2187     next unless $tax_object->can('tax_on_tax');
2188
2189     foreach my $tot ( $tax_object->tax_on_tax( $self ) ) {
2190       my $totname = ref( $tot ). ' '. $tot->taxnum;
2191
2192       warn "checking $totname which we call ". $tot->taxname. " as applicable\n"
2193         if $DEBUG > 2;
2194       next unless exists( $taxlisthash{ $totname } ); # only increase
2195                                                       # existing taxes
2196       warn "adding $totname to taxed taxes\n" if $DEBUG > 2;
2197       if ( exists( $totlisthash{ $totname } ) ) {
2198         push @{ $totlisthash{ $totname  } }, $tax{ $tax_object->taxname };
2199       }else{
2200         $totlisthash{ $totname } = [ $tot, $tax{ $tax_object->taxname } ];
2201       }
2202     }
2203   }
2204
2205   warn "having a look at taxed taxes...\n" if $DEBUG > 2;
2206   foreach my $tax ( keys %totlisthash ) {
2207     my $tax_object = shift @{ $totlisthash{$tax} };
2208     warn "found previously found taxed tax ". $tax_object->taxname. "\n"
2209       if $DEBUG > 2;
2210     my $listref_or_error = $tax_object->taxline( @{ $totlisthash{$tax} } );
2211     unless (ref($listref_or_error)) {
2212       $dbh->rollback if $oldAutoCommit;
2213       return $listref_or_error;
2214     }
2215
2216     warn "adding taxed tax amount ". $listref_or_error->[1].
2217          " as ". $tax_object->taxname. "\n"
2218       if $DEBUG;
2219     $tax{ $tax_object->taxname } += $listref_or_error->[1];
2220   }
2221   
2222   #consolidate and create tax line items
2223   warn "consolidating and generating...\n" if $DEBUG > 2;
2224   foreach my $taxname ( keys %taxname ) {
2225     my $tax = 0;
2226     my %seen = ();
2227     warn "adding $taxname\n" if $DEBUG > 1;
2228     foreach my $taxitem ( @{ $taxname{$taxname} } ) {
2229       $tax += $tax{$taxitem} unless $seen{$taxitem};
2230       warn "adding $tax{$taxitem}\n" if $DEBUG > 1;
2231     }
2232     next unless $tax;
2233
2234     $tax = sprintf('%.2f', $tax );
2235     $total_setup = sprintf('%.2f', $total_setup+$tax );
2236   
2237     push @cust_bill_pkg, new FS::cust_bill_pkg {
2238       'pkgnum'   => 0,
2239       'setup'    => $tax,
2240       'recur'    => 0,
2241       'sdate'    => '',
2242       'edate'    => '',
2243       'itemdesc' => $taxname,
2244     };
2245
2246   }
2247
2248   my $charged = sprintf('%.2f', $total_setup + $total_recur );
2249
2250   #create the new invoice
2251   my $cust_bill = new FS::cust_bill ( {
2252     'custnum' => $self->custnum,
2253     '_date'   => ( $options{'invoice_time'} || $time ),
2254     'charged' => $charged,
2255   } );
2256   my $error = $cust_bill->insert;
2257   if ( $error ) {
2258     $dbh->rollback if $oldAutoCommit;
2259     return "can't create invoice for customer #". $self->custnum. ": $error";
2260   }
2261
2262   foreach my $cust_bill_pkg ( @cust_bill_pkg ) {
2263     $cust_bill_pkg->invnum($cust_bill->invnum); 
2264     my $error = $cust_bill_pkg->insert;
2265     if ( $error ) {
2266       $dbh->rollback if $oldAutoCommit;
2267       return "can't create invoice line item: $error";
2268     }
2269   }
2270     
2271
2272   foreach my $hook ( @precommit_hooks ) { 
2273     eval {
2274       &{$hook}; #($self) ?
2275     };
2276     if ( $@ ) {
2277       $dbh->rollback if $oldAutoCommit;
2278       return "$@ running precommit hook $hook\n";
2279     }
2280   }
2281   
2282   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2283   ''; #no error
2284 }
2285
2286
2287 sub _make_lines {
2288   my ($self, %params) = @_;
2289
2290   my $part_pkg = $params{part_pkg} or die "no part_pkg specified";
2291   my $cust_pkg = $params{cust_pkg} or die "no cust_pkg specified";
2292   my $precommit_hooks = $params{precommit_hooks} or die "no package specified";
2293   my $cust_bill_pkgs = $params{line_items} or die "no line buffer specified";
2294   my $appended_cust_bill_pkg = $params{appended_line_items}
2295     or die "no appended line buffer specified";
2296   my $total_setup = $params{setup} or die "no setup accumulator specified";
2297   my $total_recur = $params{recur} or die "no recur accumulator specified";
2298   my $taxlisthash = $params{tax_matrix} or die "no tax accumulator specified";
2299   my $time = $params{'time'} or die "no time specified";
2300   my (%options) = %{$params{options}};  #hmmm  only for 'resetup'
2301
2302   my $dbh = dbh;
2303   my $real_pkgpart = $cust_pkg->pkgpart;
2304   my %hash = $cust_pkg->hash;
2305   my $old_cust_pkg = new FS::cust_pkg \%hash;
2306
2307   my @details = ();
2308
2309   my $lineitems = 0;
2310
2311   $cust_pkg->pkgpart($part_pkg->pkgpart);
2312
2313   ###
2314   # bill setup
2315   ###
2316
2317   my $setup = 0;
2318   my $unitsetup = 0;
2319   if ( ! $cust_pkg->setup &&
2320        (
2321          ( $conf->exists('disable_setup_suspended_pkgs') &&
2322           ! $cust_pkg->getfield('susp')
2323         ) || ! $conf->exists('disable_setup_suspended_pkgs')
2324        )
2325     || $options{'resetup'}
2326   ) {
2327     
2328     warn "    bill setup\n" if $DEBUG > 1;
2329     $lineitems++;
2330
2331     $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
2332     return "$@ running calc_setup for $cust_pkg\n"
2333       if $@;
2334
2335     $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
2336
2337     $cust_pkg->setfield('setup', $time)
2338       unless $cust_pkg->setup;
2339           #do need it, but it won't get written to the db
2340           #|| $cust_pkg->pkgpart != $real_pkgpart;
2341
2342   }
2343
2344   ###
2345   # bill recurring fee
2346   ### 
2347
2348   #XXX unit stuff here too
2349   my $recur = 0;
2350   my $unitrecur = 0;
2351   my $sdate;
2352   if ( $part_pkg->getfield('freq') ne '0' &&
2353        ! $cust_pkg->getfield('susp') &&
2354        ( $cust_pkg->getfield('bill') || 0 ) <= $time
2355   ) {
2356
2357     # XXX should this be a package event?  probably.  events are called
2358     # at collection time at the moment, though...
2359     $part_pkg->reset_usage($cust_pkg, 'debug'=>$DEBUG)
2360       if $part_pkg->can('reset_usage');
2361       #don't want to reset usage just cause we want a line item??
2362       #&& $part_pkg->pkgpart == $real_pkgpart;
2363
2364     warn "    bill recur\n" if $DEBUG > 1;
2365     $lineitems++;
2366
2367     # XXX shared with $recur_prog
2368     $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2369
2370     #over two params!  lets at least switch to a hashref for the rest...
2371     my %param = ( 'precommit_hooks' => $precommit_hooks, );
2372
2373     $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2374     return "$@ running calc_recur for $cust_pkg\n"
2375       if ( $@ );
2376
2377   
2378     #change this bit to use Date::Manip? CAREFUL with timezones (see
2379     # mailing list archive)
2380     my ($sec,$min,$hour,$mday,$mon,$year) =
2381       (localtime($sdate) )[0,1,2,3,4,5];
2382     
2383     #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2384     # only for figuring next bill date, nothing else, so, reset $sdate again
2385     # here
2386     $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2387     $cust_pkg->last_bill($sdate);
2388     
2389     if ( $part_pkg->freq =~ /^\d+$/ ) {
2390       $mon += $part_pkg->freq;
2391       until ( $mon < 12 ) { $mon -= 12; $year++; }
2392     } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2393       my $weeks = $1;
2394       $mday += $weeks * 7;
2395     } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2396       my $days = $1;
2397       $mday += $days;
2398     } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2399       my $hours = $1;
2400       $hour += $hours;
2401     } else {
2402       return "unparsable frequency: ". $part_pkg->freq;
2403     }
2404     $cust_pkg->setfield('bill',
2405       timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2406
2407   }
2408
2409   warn "\$setup is undefined" unless defined($setup);
2410   warn "\$recur is undefined" unless defined($recur);
2411   warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2412   
2413   ###
2414   # If there's line items, create em cust_bill_pkg records
2415   # If $cust_pkg has been modified, update it (if we're a real pkgpart)
2416   ###
2417
2418   if ( $lineitems ) {
2419
2420     if ( $cust_pkg->modified && $cust_pkg->pkgpart == $real_pkgpart ) {
2421       # hmm.. and if just the options are modified in some weird price plan?
2422   
2423       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
2424         if $DEBUG >1;
2425   
2426       my $error = $cust_pkg->replace( $old_cust_pkg,
2427                                       'options' => { $cust_pkg->options },
2428                                     );
2429       return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error"
2430         if $error; #just in case
2431     }
2432   
2433     $setup = sprintf( "%.2f", $setup );
2434     $recur = sprintf( "%.2f", $recur );
2435     if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2436       return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2437     }
2438     if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2439       return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2440     }
2441
2442     if ( $setup != 0 || $recur != 0 ) {
2443
2444       warn "    charges (setup=$setup, recur=$recur); adding line items\n"
2445         if $DEBUG > 1;
2446       my $cust_bill_pkg = new FS::cust_bill_pkg {
2447         'pkgnum'    => $cust_pkg->pkgnum,
2448         'setup'     => $setup,
2449         'unitsetup' => $unitsetup,
2450         'recur'     => $recur,
2451         'unitrecur' => $unitrecur,
2452         'quantity'  => $cust_pkg->quantity,
2453         'sdate'     => $sdate,
2454         'edate'     => $cust_pkg->bill,
2455         'details'   => \@details,
2456       };
2457       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2458         unless $part_pkg->pkgpart == $real_pkgpart;
2459       push @$cust_bill_pkgs, $cust_bill_pkg;
2460
2461       $$total_setup += $setup;
2462       $$total_recur += $recur;
2463
2464       ###
2465       # handle taxes
2466       ###
2467
2468       unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2469
2470         $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg);
2471
2472       } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2473
2474     } #if $setup != 0 || $recur != 0
2475       
2476   } #if $line_items
2477
2478   if ( $part_pkg->can('append_cust_bill_pkgs') ) {
2479     my %param = ( 'precommit_hooks' => $precommit_hooks, );
2480     my ($more_cust_bill_pkgs) =
2481       eval { $part_pkg->append_cust_bill_pkgs( $cust_pkg, \$sdate, \%param ) };
2482
2483     return "$@ running append_cust_bill_pkgs for $cust_pkg\n"
2484       if ( $@ );
2485     return "$more_cust_bill_pkgs"
2486       unless ( ref($more_cust_bill_pkgs) );
2487
2488     foreach my $cust_bill_pkg ( @{$more_cust_bill_pkgs} ) {
2489
2490       $cust_bill_pkg->pkgpart_override($part_pkg->pkgpart)
2491         unless $part_pkg->pkgpart == $real_pkgpart;
2492       push @$appended_cust_bill_pkg, $cust_bill_pkg;
2493
2494       unless ($cust_bill_pkg->duplicate) {
2495         $$total_setup += $cust_bill_pkg->setup;
2496         $$total_recur += $cust_bill_pkg->recur;
2497
2498         ###
2499         # handle taxes
2500         ###
2501
2502         unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2503
2504           $self->_handle_taxes($part_pkg, $taxlisthash, $cust_bill_pkg);
2505
2506         } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2507       }
2508     }
2509   }
2510
2511 }
2512
2513 sub _handle_taxes {
2514   my $self = shift;
2515   my $part_pkg = shift;
2516   my $taxlisthash = shift;
2517   my $cust_bill_pkg = shift;
2518
2519   my @taxes = ();
2520   my @taxoverrides = $part_pkg->part_pkg_taxoverride;
2521     
2522   my $prefix = 
2523     ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2524     ? 'ship_'
2525     : '';
2526
2527   if ( $conf->exists('enable_taxproducts')
2528        && (scalar(@taxoverrides) || $part_pkg->taxproductnum )
2529      )
2530   { 
2531
2532     my @taxclassnums = ();
2533     my $geocode = $self->geocode('cch');
2534
2535     if ( scalar( @taxoverrides ) ) {
2536       @taxclassnums = map { $_->taxclassnum } @taxoverrides;
2537     }elsif ( $part_pkg->taxproductnum ) {
2538       @taxclassnums = map { $_->taxclassnum }
2539                       $part_pkg->part_pkg_taxrate('cch', $geocode);
2540     }
2541
2542     my $extra_sql =
2543       "AND (".
2544       join(' OR ', map { "taxclassnum = $_" } @taxclassnums ). ")";
2545
2546     @taxes = qsearch({ 'table' => 'tax_rate',
2547                        'hashref' => { 'geocode' => $geocode, },
2548                        'extra_sql' => $extra_sql,
2549                     })
2550       if scalar(@taxclassnums);
2551
2552
2553   }else{
2554
2555     my %taxhash = map { $_ => $self->get("$prefix$_") }
2556                       qw( state county country );
2557
2558     $taxhash{'taxclass'} = $part_pkg->taxclass;
2559
2560     @taxes = qsearch( 'cust_main_county', \%taxhash );
2561
2562     unless ( @taxes ) {
2563       $taxhash{'taxclass'} = '';
2564       @taxes =  qsearch( 'cust_main_county', \%taxhash );
2565     }
2566
2567     #one more try at a whole-country tax rate
2568     unless ( @taxes ) {
2569       $taxhash{$_} = '' foreach qw( state county );
2570       @taxes =  qsearch( 'cust_main_county', \%taxhash );
2571     }
2572
2573   } #if $conf->exists('enable_taxproducts') 
2574
2575   # maybe eliminate this entirely, along with all the 0% records
2576   unless ( @taxes ) {
2577     my $error;
2578     if ( $conf->exists('enable_taxproducts') ) { 
2579       $error = 
2580         "fatal: can't find tax rate for zip/taxproduct/pkgpart ".
2581         join('/', ( map $self->get("$prefix$_"),
2582                         qw(zip)
2583                   ),
2584                   $part_pkg->taxproduct_description,
2585                   $part_pkg->pkgpart ). "\n";
2586     } else {
2587       $error = 
2588         "fatal: can't find tax rate for state/county/country/taxclass ".
2589         join('/', ( map $self->get("$prefix$_"),
2590                         qw(state county country)
2591                   ),
2592                   $part_pkg->taxclass ). "\n";
2593     }
2594     return $error;
2595   }
2596
2597   foreach my $tax ( @taxes ) {
2598     my $taxname = ref( $tax ). ' '. $tax->taxnum;
2599     if ( exists( $taxlisthash->{ $taxname } ) ) {
2600       push @{ $taxlisthash->{ $taxname  } }, $cust_bill_pkg;
2601     }else{
2602       $taxlisthash->{ $taxname } = [ $tax, $cust_bill_pkg ];
2603     }
2604   }
2605
2606 }
2607
2608 =item collect OPTIONS
2609
2610 (Attempt to) collect money for this customer's outstanding invoices (see
2611 L<FS::cust_bill>).  Usually used after the bill method.
2612
2613 Actions are now triggered by billing events; see L<FS::part_event> and the
2614 billing events web interface.  Old-style invoice events (see
2615 L<FS::part_bill_event>) have been deprecated.
2616
2617 If there is an error, returns the error, otherwise returns false.
2618
2619 Options are passed as name-value pairs.
2620
2621 Currently available options are:
2622
2623 =over 4
2624
2625 =item invoice_time
2626
2627 Use this time when deciding when to print invoices and late notices on those invoices.  The default is now.  It is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion functions.
2628
2629 =item retry
2630
2631 Retry card/echeck/LEC transactions even when not scheduled by invoice events.
2632
2633 =item quiet
2634
2635 set true to surpress email card/ACH decline notices.
2636
2637 =item check_freq
2638
2639 "1d" for the traditional, daily events (the default), or "1m" for the new monthly events (part_event.check_freq)
2640
2641 =item payby
2642
2643 allows for one time override of normal customer billing method
2644
2645 =item debug
2646
2647 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2648
2649
2650 =back
2651
2652 =cut
2653
2654 sub collect {
2655   my( $self, %options ) = @_;
2656   my $invoice_time = $options{'invoice_time'} || time;
2657
2658   #put below somehow?
2659   local $SIG{HUP} = 'IGNORE';
2660   local $SIG{INT} = 'IGNORE';
2661   local $SIG{QUIT} = 'IGNORE';
2662   local $SIG{TERM} = 'IGNORE';
2663   local $SIG{TSTP} = 'IGNORE';
2664   local $SIG{PIPE} = 'IGNORE';
2665
2666   my $oldAutoCommit = $FS::UID::AutoCommit;
2667   local $FS::UID::AutoCommit = 0;
2668   my $dbh = dbh;
2669
2670   $self->select_for_update; #mutex
2671
2672   if ( $DEBUG ) {
2673     my $balance = $self->balance;
2674     warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2675   }
2676
2677   if ( exists($options{'retry_card'}) ) {
2678     carp 'retry_card option passed to collect is deprecated; use retry';
2679     $options{'retry'} ||= $options{'retry_card'};
2680   }
2681   if ( exists($options{'retry'}) && $options{'retry'} ) {
2682     my $error = $self->retry_realtime;
2683     if ( $error ) {
2684       $dbh->rollback if $oldAutoCommit;
2685       return $error;
2686     }
2687   }
2688
2689   # false laziness w/pay_batch::import_results
2690
2691   my $due_cust_event = $self->due_cust_event(
2692     'debug'      => ( $options{'debug'} || 0 ),
2693     'time'       => $invoice_time,
2694     'check_freq' => $options{'check_freq'},
2695   );
2696   unless( ref($due_cust_event) ) {
2697     $dbh->rollback if $oldAutoCommit;
2698     return $due_cust_event;
2699   }
2700
2701   foreach my $cust_event ( @$due_cust_event ) {
2702
2703     #XXX lock event
2704     
2705     #re-eval event conditions (a previous event could have changed things)
2706     unless ( $cust_event->test_conditions( 'time' => $invoice_time ) ) {
2707       #don't leave stray "new/locked" records around
2708       my $error = $cust_event->delete;
2709       if ( $error ) {
2710         #gah, even with transactions
2711         $dbh->commit if $oldAutoCommit; #well.
2712         return $error;
2713       }
2714       next;
2715     }
2716
2717     {
2718       local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2719       warn "  running cust_event ". $cust_event->eventnum. "\n"
2720         if $DEBUG > 1;
2721
2722       
2723       #if ( my $error = $cust_event->do_event(%options) ) { #XXX %options?
2724       if ( my $error = $cust_event->do_event() ) {
2725         #XXX wtf is this?  figure out a proper dealio with return value
2726         #from do_event
2727           # gah, even with transactions.
2728           $dbh->commit if $oldAutoCommit; #well.
2729           return $error;
2730         }
2731     }
2732
2733   }
2734
2735   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2736   '';
2737
2738 }
2739
2740 =item due_cust_event [ HASHREF | OPTION => VALUE ... ]
2741
2742 Inserts database records for and returns an ordered listref of new events due
2743 for this customer, as FS::cust_event objects (see L<FS::cust_event>).  If no
2744 events are due, an empty listref is returned.  If there is an error, returns a
2745 scalar error message.
2746
2747 To actually run the events, call each event's test_condition method, and if
2748 still true, call the event's do_event method.
2749
2750 Options are passed as a hashref or as a list of name-value pairs.  Available
2751 options are:
2752
2753 =over 4
2754
2755 =item check_freq
2756
2757 Search only for events of this check frequency (how often events of this type are checked); currently "1d" (daily, the default) and "1m" (monthly) are recognized.
2758
2759 =item time
2760
2761 "Current time" for the events.
2762
2763 =item debug
2764
2765 Debugging level.  Default is 0 (no debugging), or can be set to 1 (passed-in options), 2 (traces progress), 3 (more information), or 4 (include full search queries)
2766
2767 =item eventtable
2768
2769 Only return events for the specified eventtable (by default, events of all eventtables are returned)
2770
2771 =item objects
2772
2773 Explicitly pass the objects to be tested (typically used with eventtable).
2774
2775 =back
2776
2777 =cut
2778
2779 sub due_cust_event {
2780   my $self = shift;
2781   my %opt = ref($_[0]) ? %{ $_[0] } : @_;
2782
2783   #???
2784   #my $DEBUG = $opt{'debug'}
2785   local($DEBUG) = $opt{'debug'}
2786     if defined($opt{'debug'}) && $opt{'debug'} > $DEBUG;
2787
2788   warn "$me due_cust_event called with options ".
2789        join(', ', map { "$_: $opt{$_}" } keys %opt). "\n"
2790     if $DEBUG;
2791
2792   $opt{'time'} ||= time;
2793
2794   local $SIG{HUP} = 'IGNORE';
2795   local $SIG{INT} = 'IGNORE';
2796   local $SIG{QUIT} = 'IGNORE';
2797   local $SIG{TERM} = 'IGNORE';
2798   local $SIG{TSTP} = 'IGNORE';
2799   local $SIG{PIPE} = 'IGNORE';
2800
2801   my $oldAutoCommit = $FS::UID::AutoCommit;
2802   local $FS::UID::AutoCommit = 0;
2803   my $dbh = dbh;
2804
2805   $self->select_for_update; #mutex
2806
2807   ###
2808   # 1: find possible events (initial search)
2809   ###
2810   
2811   my @cust_event = ();
2812
2813   my @eventtable = $opt{'eventtable'}
2814                      ? ( $opt{'eventtable'} )
2815                      : FS::part_event->eventtables_runorder;
2816
2817   foreach my $eventtable ( @eventtable ) {
2818
2819     my @objects;
2820     if ( $opt{'objects'} ) {
2821
2822       @objects = @{ $opt{'objects'} };
2823
2824     } else {
2825
2826       #my @objects = $self->eventtable(); # sub cust_main { @{ [ $self ] }; }
2827       @objects = ( $eventtable eq 'cust_main' )
2828                    ? ( $self )
2829                    : ( $self->$eventtable() );
2830
2831     }
2832
2833     my @e_cust_event = ();
2834
2835     my $cross = "CROSS JOIN $eventtable";
2836     $cross .= ' LEFT JOIN cust_main USING ( custnum )'
2837       unless $eventtable eq 'cust_main';
2838
2839     foreach my $object ( @objects ) {
2840
2841       #this first search uses the condition_sql magic for optimization.
2842       #the more possible events we can eliminate in this step the better
2843
2844       my $cross_where = '';
2845       my $pkey = $object->primary_key;
2846       $cross_where = "$eventtable.$pkey = ". $object->$pkey();
2847
2848       my $join = FS::part_event_condition->join_conditions_sql( $eventtable );
2849       my $extra_sql =
2850         FS::part_event_condition->where_conditions_sql( $eventtable,
2851                                                         'time'=>$opt{'time'}
2852                                                       );
2853       my $order = FS::part_event_condition->order_conditions_sql( $eventtable );
2854
2855       $extra_sql = "AND $extra_sql" if $extra_sql;
2856
2857       #here is the agent virtualization
2858       $extra_sql .= " AND (    part_event.agentnum IS NULL
2859                             OR part_event.agentnum = ". $self->agentnum. ' )';
2860
2861       $extra_sql .= " $order";
2862
2863       warn "searching for events for $eventtable ". $object->$pkey. "\n"
2864         if $opt{'debug'} > 2;
2865       my @part_event = qsearch( {
2866         'debug'     => ( $opt{'debug'} > 3 ? 1 : 0 ),
2867         'select'    => 'part_event.*',
2868         'table'     => 'part_event',
2869         'addl_from' => "$cross $join",
2870         'hashref'   => { 'check_freq' => ( $opt{'check_freq'} || '1d' ),
2871                          'eventtable' => $eventtable,
2872                          'disabled'   => '',
2873                        },
2874         'extra_sql' => "AND $cross_where $extra_sql",
2875       } );
2876
2877       if ( $DEBUG > 2 ) {
2878         my $pkey = $object->primary_key;
2879         warn "      ". scalar(@part_event).
2880              " possible events found for $eventtable ". $object->$pkey(). "\n";
2881       }
2882
2883       push @e_cust_event, map { $_->new_cust_event($object) } @part_event;
2884
2885     }
2886
2887     warn "    ". scalar(@e_cust_event).
2888          " subtotal possible cust events found for $eventtable\n"
2889       if $DEBUG > 1;
2890
2891     push @cust_event, @e_cust_event;
2892
2893   }
2894
2895   warn "  ". scalar(@cust_event).
2896        " total possible cust events found in initial search\n"
2897     if $DEBUG; # > 1;
2898
2899   ##
2900   # 2: test conditions
2901   ##
2902   
2903   my %unsat = ();
2904
2905   @cust_event = grep $_->test_conditions( 'time'          => $opt{'time'},
2906                                           'stats_hashref' => \%unsat ),
2907                      @cust_event;
2908
2909   warn "  ". scalar(@cust_event). " cust events left satisfying conditions\n"
2910     if $DEBUG; # > 1;
2911
2912   warn "    invalid conditions not eliminated with condition_sql:\n".
2913        join('', map "      $_: ".$unsat{$_}."\n", keys %unsat )
2914     if $DEBUG; # > 1;
2915
2916   ##
2917   # 3: insert
2918   ##
2919
2920   foreach my $cust_event ( @cust_event ) {
2921
2922     my $error = $cust_event->insert();
2923     if ( $error ) {
2924       $dbh->rollback if $oldAutoCommit;
2925       return $error;
2926     }
2927                                        
2928   }
2929
2930   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2931
2932   ##
2933   # 4: return
2934   ##
2935
2936   warn "  returning events: ". Dumper(@cust_event). "\n"
2937     if $DEBUG > 2;
2938
2939   \@cust_event;
2940
2941 }
2942
2943 =item retry_realtime
2944
2945 Schedules realtime / batch  credit card / electronic check / LEC billing
2946 events for for retry.  Useful if card information has changed or manual
2947 retry is desired.  The 'collect' method must be called to actually retry
2948 the transaction.
2949
2950 Implementation details: For either this customer, or for each of this
2951 customer's open invoices, changes the status of the first "done" (with
2952 statustext error) realtime processing event to "failed".
2953
2954 =cut
2955
2956 sub retry_realtime {
2957   my $self = shift;
2958
2959   local $SIG{HUP} = 'IGNORE';
2960   local $SIG{INT} = 'IGNORE';
2961   local $SIG{QUIT} = 'IGNORE';
2962   local $SIG{TERM} = 'IGNORE';
2963   local $SIG{TSTP} = 'IGNORE';
2964   local $SIG{PIPE} = 'IGNORE';
2965
2966   my $oldAutoCommit = $FS::UID::AutoCommit;
2967   local $FS::UID::AutoCommit = 0;
2968   my $dbh = dbh;
2969
2970   #a little false laziness w/due_cust_event (not too bad, really)
2971
2972   my $join = FS::part_event_condition->join_conditions_sql;
2973   my $order = FS::part_event_condition->order_conditions_sql;
2974   my $mine = 
2975   '( '
2976    . join ( ' OR ' , map { 
2977     "( part_event.eventtable = " . dbh->quote($_) 
2978     . " AND tablenum IN( SELECT " . dbdef->table($_)->primary_key . " from $_ where custnum = " . dbh->quote( $self->custnum ) . "))" ;
2979    } FS::part_event->eventtables)
2980    . ') ';
2981
2982   #here is the agent virtualization
2983   my $agent_virt = " (    part_event.agentnum IS NULL
2984                        OR part_event.agentnum = ". $self->agentnum. ' )';
2985
2986   #XXX this shouldn't be hardcoded, actions should declare it...
2987   my @realtime_events = qw(
2988     cust_bill_realtime_card
2989     cust_bill_realtime_check
2990     cust_bill_realtime_lec
2991     cust_bill_batch
2992   );
2993
2994   my $is_realtime_event = ' ( '. join(' OR ', map "part_event.action = '$_'",
2995                                                   @realtime_events
2996                                      ).
2997                           ' ) ';
2998
2999   my @cust_event = qsearchs({
3000     'table'     => 'cust_event',
3001     'select'    => 'cust_event.*',
3002     'addl_from' => "LEFT JOIN part_event USING ( eventpart ) $join",
3003     'hashref'   => { 'status' => 'done' },
3004     'extra_sql' => " AND statustext IS NOT NULL AND statustext != '' ".
3005                    " AND $mine AND $is_realtime_event AND $agent_virt $order" # LIMIT 1"
3006   });
3007
3008   my %seen_invnum = ();
3009   foreach my $cust_event (@cust_event) {
3010
3011     #max one for the customer, one for each open invoice
3012     my $cust_X = $cust_event->cust_X;
3013     next if $seen_invnum{ $cust_event->part_event->eventtable eq 'cust_bill'
3014                           ? $cust_X->invnum
3015                           : 0
3016                         }++
3017          or $cust_event->part_event->eventtable eq 'cust_bill'
3018             && ! $cust_X->owed;
3019
3020     my $error = $cust_event->retry;
3021     if ( $error ) {
3022       $dbh->rollback if $oldAutoCommit;
3023       return "error scheduling event for retry: $error";
3024     }
3025
3026   }
3027
3028   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3029   '';
3030
3031 }
3032
3033 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
3034
3035 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
3036 via a Business::OnlinePayment realtime gateway.  See
3037 L<http://420.am/business-onlinepayment> for supported gateways.
3038
3039 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3040
3041 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
3042
3043 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3044 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
3045 if set, will override the value from the customer record.
3046
3047 I<description> is a free-text field passed to the gateway.  It defaults to
3048 "Internet services".
3049
3050 If an I<invnum> is specified, this payment (if successful) is applied to the
3051 specified invoice.  If you don't specify an I<invnum> you might want to
3052 call the B<apply_payments> method.
3053
3054 I<quiet> can be set true to surpress email decline notices.
3055
3056 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
3057 resulting paynum, if any.
3058
3059 I<payunique> is a unique identifier for this payment.
3060
3061 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
3062
3063 =cut
3064
3065 sub realtime_bop {
3066   my( $self, $method, $amount, %options ) = @_;
3067   if ( $DEBUG ) {
3068     warn "$me realtime_bop: $method $amount\n";
3069     warn "  $_ => $options{$_}\n" foreach keys %options;
3070   }
3071
3072   $options{'description'} ||= 'Internet services';
3073
3074   return $self->fake_bop($method, $amount, %options) if $options{'fake'};
3075
3076   eval "use Business::OnlinePayment";  
3077   die $@ if $@;
3078
3079   my $payinfo = exists($options{'payinfo'})
3080                   ? $options{'payinfo'}
3081                   : $self->payinfo;
3082
3083   my %method2payby = (
3084     'CC'     => 'CARD',
3085     'ECHECK' => 'CHEK',
3086     'LEC'    => 'LECB',
3087   );
3088
3089   ###
3090   # check for banned credit card/ACH
3091   ###
3092
3093   my $ban = qsearchs('banned_pay', {
3094     'payby'   => $method2payby{$method},
3095     'payinfo' => md5_base64($payinfo),
3096   } );
3097   return "Banned credit card" if $ban;
3098
3099   ###
3100   # select a gateway
3101   ###
3102
3103   my $taxclass = '';
3104   if ( $options{'invnum'} ) {
3105     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
3106     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
3107     my @taxclasses =
3108       map  { $_->part_pkg->taxclass }
3109       grep { $_ }
3110       map  { $_->cust_pkg }
3111       $cust_bill->cust_bill_pkg;
3112     unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
3113                                                            #different taxclasses
3114       $taxclass = $taxclasses[0];
3115     }
3116   }
3117
3118   #look for an agent gateway override first
3119   my $cardtype;
3120   if ( $method eq 'CC' ) {
3121     $cardtype = cardtype($payinfo);
3122   } elsif ( $method eq 'ECHECK' ) {
3123     $cardtype = 'ACH';
3124   } else {
3125     $cardtype = $method;
3126   }
3127
3128   my $override =
3129        qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3130                                            cardtype => $cardtype,
3131                                            taxclass => $taxclass,       } )
3132     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3133                                            cardtype => '',
3134                                            taxclass => $taxclass,       } )
3135     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3136                                            cardtype => $cardtype,
3137                                            taxclass => '',              } )
3138     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3139                                            cardtype => '',
3140                                            taxclass => '',              } );
3141
3142   my $payment_gateway = '';
3143   my( $processor, $login, $password, $action, @bop_options );
3144   if ( $override ) { #use a payment gateway override
3145
3146     $payment_gateway = $override->payment_gateway;
3147
3148     $processor   = $payment_gateway->gateway_module;
3149     $login       = $payment_gateway->gateway_username;
3150     $password    = $payment_gateway->gateway_password;
3151     $action      = $payment_gateway->gateway_action;
3152     @bop_options = $payment_gateway->options;
3153
3154   } else { #use the standard settings from the config
3155
3156     ( $processor, $login, $password, $action, @bop_options ) =
3157       $self->default_payment_gateway($method);
3158
3159   }
3160
3161   ###
3162   # massage data
3163   ###
3164
3165   my $address = exists($options{'address1'})
3166                     ? $options{'address1'}
3167                     : $self->address1;
3168   my $address2 = exists($options{'address2'})
3169                     ? $options{'address2'}
3170                     : $self->address2;
3171   $address .= ", ". $address2 if length($address2);
3172
3173   my $o_payname = exists($options{'payname'})
3174                     ? $options{'payname'}
3175                     : $self->payname;
3176   my($payname, $payfirst, $paylast);
3177   if ( $o_payname && $method ne 'ECHECK' ) {
3178     ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3179       or return "Illegal payname $payname";
3180     ($payfirst, $paylast) = ($1, $2);
3181   } else {
3182     $payfirst = $self->getfield('first');
3183     $paylast = $self->getfield('last');
3184     $payname =  "$payfirst $paylast";
3185   }
3186
3187   my @invoicing_list = $self->invoicing_list_emailonly;
3188   if ( $conf->exists('emailinvoiceautoalways')
3189        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3190        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3191     push @invoicing_list, $self->all_emails;
3192   }
3193
3194   my $email = ($conf->exists('business-onlinepayment-email-override'))
3195               ? $conf->config('business-onlinepayment-email-override')
3196               : $invoicing_list[0];
3197
3198   my %content = ();
3199
3200   my $payip = exists($options{'payip'})
3201                 ? $options{'payip'}
3202                 : $self->payip;
3203   $content{customer_ip} = $payip
3204     if length($payip);
3205
3206   $content{invoice_number} = $options{'invnum'}
3207     if exists($options{'invnum'}) && length($options{'invnum'});
3208
3209   $content{email_customer} = 
3210     (    $conf->exists('business-onlinepayment-email_customer')
3211       || $conf->exists('business-onlinepayment-email-override') );
3212       
3213   my $paydate = '';
3214   if ( $method eq 'CC' ) { 
3215
3216     $content{card_number} = $payinfo;
3217     $paydate = exists($options{'paydate'})
3218                     ? $options{'paydate'}
3219                     : $self->paydate;
3220     $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3221     $content{expiration} = "$2/$1";
3222
3223     my $paycvv = exists($options{'paycvv'})
3224                    ? $options{'paycvv'}
3225                    : $self->paycvv;
3226     $content{cvv2} = $paycvv
3227       if length($paycvv);
3228
3229     my $paystart_month = exists($options{'paystart_month'})
3230                            ? $options{'paystart_month'}
3231                            : $self->paystart_month;
3232
3233     my $paystart_year  = exists($options{'paystart_year'})
3234                            ? $options{'paystart_year'}
3235                            : $self->paystart_year;
3236
3237     $content{card_start} = "$paystart_month/$paystart_year"
3238       if $paystart_month && $paystart_year;
3239
3240     my $payissue       = exists($options{'payissue'})
3241                            ? $options{'payissue'}
3242                            : $self->payissue;
3243     $content{issue_number} = $payissue if $payissue;
3244
3245     $content{recurring_billing} = 'YES'
3246       if qsearch('cust_pay', { 'custnum' => $self->custnum,
3247                                'payby'   => 'CARD',
3248                                'payinfo' => $payinfo,
3249                              } )
3250       || qsearch('cust_pay', { 'custnum' => $self->custnum,
3251                                'payby'   => 'CARD',
3252                                'paymask' => $self->mask_payinfo('CARD', $payinfo),
3253                              } );
3254
3255
3256   } elsif ( $method eq 'ECHECK' ) {
3257     ( $content{account_number}, $content{routing_code} ) =
3258       split('@', $payinfo);
3259     $content{bank_name} = $o_payname;
3260     $content{bank_state} = exists($options{'paystate'})
3261                              ? $options{'paystate'}
3262                              : $self->getfield('paystate');
3263     $content{account_type} = exists($options{'paytype'})
3264                                ? uc($options{'paytype'}) || 'CHECKING'
3265                                : uc($self->getfield('paytype')) || 'CHECKING';
3266     $content{account_name} = $payname;
3267     $content{customer_org} = $self->company ? 'B' : 'I';
3268     $content{state_id}       = exists($options{'stateid'})
3269                                  ? $options{'stateid'}
3270                                  : $self->getfield('stateid');
3271     $content{state_id_state} = exists($options{'stateid_state'})
3272                                  ? $options{'stateid_state'}
3273                                  : $self->getfield('stateid_state');
3274     $content{customer_ssn} = exists($options{'ss'})
3275                                ? $options{'ss'}
3276                                : $self->ss;
3277   } elsif ( $method eq 'LEC' ) {
3278     $content{phone} = $payinfo;
3279   }
3280
3281   ###
3282   # run transaction(s)
3283   ###
3284
3285   my $balance = exists( $options{'balance'} )
3286                   ? $options{'balance'}
3287                   : $self->balance;
3288
3289   $self->select_for_update; #mutex ... just until we get our pending record in
3290
3291   #the checks here are intended to catch concurrent payments
3292   #double-form-submission prevention is taken care of in cust_pay_pending::check
3293
3294   #check the balance
3295   return "The customer's balance has changed; $method transaction aborted."
3296     if $self->balance < $balance;
3297     #&& $self->balance < $amount; #might as well anyway?
3298
3299   #also check and make sure there aren't *other* pending payments for this cust
3300
3301   my @pending = qsearch('cust_pay_pending', {
3302     'custnum' => $self->custnum,
3303     'status'  => { op=>'!=', value=>'done' } 
3304   });
3305   return "A payment is already being processed for this customer (".
3306          join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
3307          "); $method transaction aborted."
3308     if scalar(@pending);
3309
3310   #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
3311
3312   my $cust_pay_pending = new FS::cust_pay_pending {
3313     'custnum'    => $self->custnum,
3314     #'invnum'     => $options{'invnum'},
3315     'paid'       => $amount,
3316     '_date'      => '',
3317     'payby'      => $method2payby{$method},
3318     'payinfo'    => $payinfo,
3319     'paydate'    => $paydate,
3320     'status'     => 'new',
3321     'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
3322   };
3323   $cust_pay_pending->payunique( $options{payunique} )
3324     if defined($options{payunique}) && length($options{payunique});
3325   my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
3326   return $cpp_new_err if $cpp_new_err;
3327
3328   my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
3329
3330   my $transaction = new Business::OnlinePayment( $processor, @bop_options );
3331   $transaction->content(
3332     'type'           => $method,
3333     'login'          => $login,
3334     'password'       => $password,
3335     'action'         => $action1,
3336     'description'    => $options{'description'},
3337     'amount'         => $amount,
3338     #'invoice_number' => $options{'invnum'},
3339     'customer_id'    => $self->custnum,
3340     'last_name'      => $paylast,
3341     'first_name'     => $payfirst,
3342     'name'           => $payname,
3343     'address'        => $address,
3344     'city'           => ( exists($options{'city'})
3345                             ? $options{'city'}
3346                             : $self->city          ),
3347     'state'          => ( exists($options{'state'})
3348                             ? $options{'state'}
3349                             : $self->state          ),
3350     'zip'            => ( exists($options{'zip'})
3351                             ? $options{'zip'}
3352                             : $self->zip          ),
3353     'country'        => ( exists($options{'country'})
3354                             ? $options{'country'}
3355                             : $self->country          ),
3356     'referer'        => 'http://cleanwhisker.420.am/',
3357     'email'          => $email,
3358     'phone'          => $self->daytime || $self->night,
3359     %content, #after
3360   );
3361
3362   $cust_pay_pending->status('pending');
3363   my $cpp_pending_err = $cust_pay_pending->replace;
3364   return $cpp_pending_err if $cpp_pending_err;
3365
3366   #config?
3367   my $BOP_TESTING = 0;
3368   my $BOP_TESTING_SUCCESS = 1;
3369
3370   unless ( $BOP_TESTING ) {
3371     $transaction->submit();
3372   } else {
3373     if ( $BOP_TESTING_SUCCESS ) {
3374       $transaction->is_success(1);
3375       $transaction->authorization('fake auth');
3376     } else {
3377       $transaction->is_success(0);
3378       $transaction->error_message('fake failure');
3379     }
3380   }
3381
3382   if ( $transaction->is_success() && $action2 ) {
3383
3384     $cust_pay_pending->status('authorized');
3385     my $cpp_authorized_err = $cust_pay_pending->replace;
3386     return $cpp_authorized_err if $cpp_authorized_err;
3387
3388     my $auth = $transaction->authorization;
3389     my $ordernum = $transaction->can('order_number')
3390                    ? $transaction->order_number
3391                    : '';
3392
3393     my $capture =
3394       new Business::OnlinePayment( $processor, @bop_options );
3395
3396     my %capture = (
3397       %content,
3398       type           => $method,
3399       action         => $action2,
3400       login          => $login,
3401       password       => $password,
3402       order_number   => $ordernum,
3403       amount         => $amount,
3404       authorization  => $auth,
3405       description    => $options{'description'},
3406     );
3407
3408     foreach my $field (qw( authorization_source_code returned_ACI
3409                            transaction_identifier validation_code           
3410                            transaction_sequence_num local_transaction_date    
3411                            local_transaction_time AVS_result_code          )) {
3412       $capture{$field} = $transaction->$field() if $transaction->can($field);
3413     }
3414
3415     $capture->content( %capture );
3416
3417     $capture->submit();
3418
3419     unless ( $capture->is_success ) {
3420       my $e = "Authorization successful but capture failed, custnum #".
3421               $self->custnum. ': '.  $capture->result_code.
3422               ": ". $capture->error_message;
3423       warn $e;
3424       return $e;
3425     }
3426
3427   }
3428
3429   $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
3430   my $cpp_captured_err = $cust_pay_pending->replace;
3431   return $cpp_captured_err if $cpp_captured_err;
3432
3433   ###
3434   # remove paycvv after initial transaction
3435   ###
3436
3437   #false laziness w/misc/process/payment.cgi - check both to make sure working
3438   # correctly
3439   if ( defined $self->dbdef_table->column('paycvv')
3440        && length($self->paycvv)
3441        && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
3442   ) {
3443     my $error = $self->remove_cvv;
3444     if ( $error ) {
3445       warn "WARNING: error removing cvv: $error\n";
3446     }
3447   }
3448
3449   ###
3450   # result handling
3451   ###
3452
3453   if ( $transaction->is_success() ) {
3454
3455     my $paybatch = '';
3456     if ( $payment_gateway ) { # agent override
3457       $paybatch = $payment_gateway->gatewaynum. '-';
3458     }
3459
3460     $paybatch .= "$processor:". $transaction->authorization;
3461
3462     $paybatch .= ':'. $transaction->order_number
3463       if $transaction->can('order_number')
3464       && length($transaction->order_number);
3465
3466     my $cust_pay = new FS::cust_pay ( {
3467        'custnum'  => $self->custnum,
3468        'invnum'   => $options{'invnum'},
3469        'paid'     => $amount,
3470        '_date'    => '',
3471        'payby'    => $method2payby{$method},
3472        'payinfo'  => $payinfo,
3473        'paybatch' => $paybatch,
3474        'paydate'  => $paydate,
3475     } );
3476     #doesn't hurt to know, even though the dup check is in cust_pay_pending now
3477     $cust_pay->payunique( $options{payunique} )
3478       if defined($options{payunique}) && length($options{payunique});
3479
3480     my $oldAutoCommit = $FS::UID::AutoCommit;
3481     local $FS::UID::AutoCommit = 0;
3482     my $dbh = dbh;
3483
3484     #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
3485
3486     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3487
3488     if ( $error ) {
3489       $cust_pay->invnum(''); #try again with no specific invnum
3490       my $error2 = $cust_pay->insert( $options{'manual'} ?
3491                                       ( 'manual' => 1 ) : ()
3492                                     );
3493       if ( $error2 ) {
3494         # gah.  but at least we have a record of the state we had to abort in
3495         # from cust_pay_pending now.
3496         my $e = "WARNING: $method captured but payment not recorded - ".
3497                 "error inserting payment ($processor): $error2".
3498                 " (previously tried insert with invnum #$options{'invnum'}" .
3499                 ": $error ) - pending payment saved as paypendingnum ".
3500                 $cust_pay_pending->paypendingnum. "\n";
3501         warn $e;
3502         return $e;
3503       }
3504     }
3505
3506     if ( $options{'paynum_ref'} ) {
3507       ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3508     }
3509
3510     $cust_pay_pending->status('done');
3511     $cust_pay_pending->statustext('captured');
3512     my $cpp_done_err = $cust_pay_pending->replace;
3513
3514     if ( $cpp_done_err ) {
3515
3516       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3517       my $e = "WARNING: $method captured but payment not recorded - ".
3518               "error updating status for paypendingnum ".
3519               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3520       warn $e;
3521       return $e;
3522
3523     } else {
3524
3525       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3526       return ''; #no error
3527
3528     }
3529
3530   } else {
3531
3532     my $perror = "$processor error: ". $transaction->error_message;
3533
3534     unless ( $transaction->error_message ) {
3535
3536       my $t_response;
3537       if ( $transaction->can('response_page') ) {
3538         $t_response = {
3539                         'page'    => ( $transaction->can('response_page')
3540                                          ? $transaction->response_page
3541                                          : ''
3542                                      ),
3543                         'code'    => ( $transaction->can('response_code')
3544                                          ? $transaction->response_code
3545                                          : ''
3546                                      ),
3547                         'headers' => ( $transaction->can('response_headers')
3548                                          ? $transaction->response_headers
3549                                          : ''
3550                                      ),
3551                       };
3552       } else {
3553         $t_response .=
3554           "No additional debugging information available for $processor";
3555       }
3556
3557       $perror .= "No error_message returned from $processor -- ".
3558                  ( ref($t_response) ? Dumper($t_response) : $t_response );
3559
3560     }
3561
3562     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
3563          && $conf->exists('emaildecline')
3564          && grep { $_ ne 'POST' } $self->invoicing_list
3565          && ! grep { $transaction->error_message =~ /$_/ }
3566                    $conf->config('emaildecline-exclude')
3567     ) {
3568       my @templ = $conf->config('declinetemplate');
3569       my $template = new Text::Template (
3570         TYPE   => 'ARRAY',
3571         SOURCE => [ map "$_\n", @templ ],
3572       ) or return "($perror) can't create template: $Text::Template::ERROR";
3573       $template->compile()
3574         or return "($perror) can't compile template: $Text::Template::ERROR";
3575
3576       my $templ_hash = { error => $transaction->error_message };
3577
3578       my $error = send_email(
3579         'from'    => $conf->config('invoice_from'),
3580         'to'      => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3581         'subject' => 'Your payment could not be processed',
3582         'body'    => [ $template->fill_in(HASH => $templ_hash) ],
3583       );
3584
3585       $perror .= " (also received error sending decline notification: $error)"
3586         if $error;
3587
3588     }
3589
3590     $cust_pay_pending->status('done');
3591     $cust_pay_pending->statustext("declined: $perror");
3592     my $cpp_done_err = $cust_pay_pending->replace;
3593     if ( $cpp_done_err ) {
3594       my $e = "WARNING: $method declined but pending payment not resolved - ".
3595               "error updating status for paypendingnum ".
3596               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3597       warn $e;
3598       $perror = "$e ($perror)";
3599     }
3600
3601     return $perror;
3602   }
3603
3604 }
3605
3606 =item fake_bop
3607
3608 =cut
3609
3610 sub fake_bop {
3611   my( $self, $method, $amount, %options ) = @_;
3612
3613   if ( $options{'fake_failure'} ) {
3614      return "Error: No error; test failure requested with fake_failure";
3615   }
3616
3617   my %method2payby = (
3618     'CC'     => 'CARD',
3619     'ECHECK' => 'CHEK',
3620     'LEC'    => 'LECB',
3621   );
3622
3623   #my $paybatch = '';
3624   #if ( $payment_gateway ) { # agent override
3625   #  $paybatch = $payment_gateway->gatewaynum. '-';
3626   #}
3627   #
3628   #$paybatch .= "$processor:". $transaction->authorization;
3629   #
3630   #$paybatch .= ':'. $transaction->order_number
3631   #  if $transaction->can('order_number')
3632   #  && length($transaction->order_number);
3633
3634   my $paybatch = 'FakeProcessor:54:32';
3635
3636   my $cust_pay = new FS::cust_pay ( {
3637      'custnum'  => $self->custnum,
3638      'invnum'   => $options{'invnum'},
3639      'paid'     => $amount,
3640      '_date'    => '',
3641      'payby'    => $method2payby{$method},
3642      #'payinfo'  => $payinfo,
3643      'payinfo'  => '4111111111111111',
3644      'paybatch' => $paybatch,
3645      #'paydate'  => $paydate,
3646      'paydate'  => '2012-05-01',
3647   } );
3648   $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
3649
3650   my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
3651
3652   if ( $error ) {
3653     $cust_pay->invnum(''); #try again with no specific invnum
3654     my $error2 = $cust_pay->insert( $options{'manual'} ?
3655                                     ( 'manual' => 1 ) : ()
3656                                   );
3657     if ( $error2 ) {
3658       # gah, even with transactions.
3659       my $e = 'WARNING: Card/ACH debited but database not updated - '.
3660               "error inserting (fake!) payment: $error2".
3661               " (previously tried insert with invnum #$options{'invnum'}" .
3662               ": $error )";
3663       warn $e;
3664       return $e;
3665     }
3666   }
3667
3668   if ( $options{'paynum_ref'} ) {
3669     ${ $options{'paynum_ref'} } = $cust_pay->paynum;
3670   }
3671
3672   return ''; #no error
3673
3674 }
3675
3676 =item default_payment_gateway
3677
3678 =cut
3679
3680 sub default_payment_gateway {
3681   my( $self, $method ) = @_;
3682
3683   die "Real-time processing not enabled\n"
3684     unless $conf->exists('business-onlinepayment');
3685
3686   #load up config
3687   my $bop_config = 'business-onlinepayment';
3688   $bop_config .= '-ach'
3689     if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3690   my ( $processor, $login, $password, $action, @bop_options ) =
3691     $conf->config($bop_config);
3692   $action ||= 'normal authorization';
3693   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3694   die "No real-time processor is enabled - ".
3695       "did you set the business-onlinepayment configuration value?\n"
3696     unless $processor;
3697
3698   ( $processor, $login, $password, $action, @bop_options )
3699 }
3700
3701 =item remove_cvv
3702
3703 Removes the I<paycvv> field from the database directly.
3704
3705 If there is an error, returns the error, otherwise returns false.
3706
3707 =cut
3708
3709 sub remove_cvv {
3710   my $self = shift;
3711   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3712     or return dbh->errstr;
3713   $sth->execute($self->custnum)
3714     or return $sth->errstr;
3715   $self->paycvv('');
3716   '';
3717 }
3718
3719 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3720
3721 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3722 via a Business::OnlinePayment realtime gateway.  See
3723 L<http://420.am/business-onlinepayment> for supported gateways.
3724
3725 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3726
3727 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3728
3729 Most gateways require a reference to an original payment transaction to refund,
3730 so you probably need to specify a I<paynum>.
3731
3732 I<amount> defaults to the original amount of the payment if not specified.
3733
3734 I<reason> specifies a reason for the refund.
3735
3736 I<paydate> specifies the expiration date for a credit card overriding the
3737 value from the customer record or the payment record. Specified as yyyy-mm-dd
3738
3739 Implementation note: If I<amount> is unspecified or equal to the amount of the
3740 orignal payment, first an attempt is made to "void" the transaction via
3741 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3742 the normal attempt is made to "refund" ("credit") the transaction via the
3743 gateway is attempted.
3744
3745 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3746 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
3747 #if set, will override the value from the customer record.
3748
3749 #If an I<invnum> is specified, this payment (if successful) is applied to the
3750 #specified invoice.  If you don't specify an I<invnum> you might want to
3751 #call the B<apply_payments> method.
3752
3753 =cut
3754
3755 #some false laziness w/realtime_bop, not enough to make it worth merging
3756 #but some useful small subs should be pulled out
3757 sub realtime_refund_bop {
3758   my( $self, $method, %options ) = @_;
3759   if ( $DEBUG ) {
3760     warn "$me realtime_refund_bop: $method refund\n";
3761     warn "  $_ => $options{$_}\n" foreach keys %options;
3762   }
3763
3764   eval "use Business::OnlinePayment";  
3765   die $@ if $@;
3766
3767   ###
3768   # look up the original payment and optionally a gateway for that payment
3769   ###
3770
3771   my $cust_pay = '';
3772   my $amount = $options{'amount'};
3773
3774   my( $processor, $login, $password, @bop_options ) ;
3775   my( $auth, $order_number ) = ( '', '', '' );
3776
3777   if ( $options{'paynum'} ) {
3778
3779     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
3780     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3781       or return "Unknown paynum $options{'paynum'}";
3782     $amount ||= $cust_pay->paid;
3783
3784     $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3785       or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3786                 $cust_pay->paybatch;
3787     my $gatewaynum = '';
3788     ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3789
3790     if ( $gatewaynum ) { #gateway for the payment to be refunded
3791
3792       my $payment_gateway =
3793         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3794       die "payment gateway $gatewaynum not found"
3795         unless $payment_gateway;
3796
3797       $processor   = $payment_gateway->gateway_module;
3798       $login       = $payment_gateway->gateway_username;
3799       $password    = $payment_gateway->gateway_password;
3800       @bop_options = $payment_gateway->options;
3801
3802     } else { #try the default gateway
3803
3804       my( $conf_processor, $unused_action );
3805       ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3806         $self->default_payment_gateway($method);
3807
3808       return "processor of payment $options{'paynum'} $processor does not".
3809              " match default processor $conf_processor"
3810         unless $processor eq $conf_processor;
3811
3812     }
3813
3814
3815   } else { # didn't specify a paynum, so look for agent gateway overrides
3816            # like a normal transaction 
3817
3818     my $cardtype;
3819     if ( $method eq 'CC' ) {
3820       $cardtype = cardtype($self->payinfo);
3821     } elsif ( $method eq 'ECHECK' ) {
3822       $cardtype = 'ACH';
3823     } else {
3824       $cardtype = $method;
3825     }
3826     my $override =
3827            qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3828                                                cardtype => $cardtype,
3829                                                taxclass => '',              } )
3830         || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3831                                                cardtype => '',
3832                                                taxclass => '',              } );
3833
3834     if ( $override ) { #use a payment gateway override
3835  
3836       my $payment_gateway = $override->payment_gateway;
3837
3838       $processor   = $payment_gateway->gateway_module;
3839       $login       = $payment_gateway->gateway_username;
3840       $password    = $payment_gateway->gateway_password;
3841       #$action      = $payment_gateway->gateway_action;
3842       @bop_options = $payment_gateway->options;
3843
3844     } else { #use the standard settings from the config
3845
3846       my $unused_action;
3847       ( $processor, $login, $password, $unused_action, @bop_options ) =
3848         $self->default_payment_gateway($method);
3849
3850     }
3851
3852   }
3853   return "neither amount nor paynum specified" unless $amount;
3854
3855   my %content = (
3856     'type'           => $method,
3857     'login'          => $login,
3858     'password'       => $password,
3859     'order_number'   => $order_number,
3860     'amount'         => $amount,
3861     'referer'        => 'http://cleanwhisker.420.am/',
3862   );
3863   $content{authorization} = $auth
3864     if length($auth); #echeck/ACH transactions have an order # but no auth
3865                       #(at least with authorize.net)
3866
3867   my $disable_void_after;
3868   if ($conf->exists('disable_void_after')
3869       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3870     $disable_void_after = $1;
3871   }
3872
3873   #first try void if applicable
3874   if ( $cust_pay && $cust_pay->paid == $amount
3875     && (
3876       ( not defined($disable_void_after) )
3877       || ( time < ($cust_pay->_date + $disable_void_after ) )
3878     )
3879   ) {
3880     warn "  attempting void\n" if $DEBUG > 1;
3881     my $void = new Business::OnlinePayment( $processor, @bop_options );
3882     $void->content( 'action' => 'void', %content );
3883     $void->submit();
3884     if ( $void->is_success ) {
3885       my $error = $cust_pay->void($options{'reason'});
3886       if ( $error ) {
3887         # gah, even with transactions.
3888         my $e = 'WARNING: Card/ACH voided but database not updated - '.
3889                 "error voiding payment: $error";
3890         warn $e;
3891         return $e;
3892       }
3893       warn "  void successful\n" if $DEBUG > 1;
3894       return '';
3895     }
3896   }
3897
3898   warn "  void unsuccessful, trying refund\n"
3899     if $DEBUG > 1;
3900
3901   #massage data
3902   my $address = $self->address1;
3903   $address .= ", ". $self->address2 if $self->address2;
3904
3905   my($payname, $payfirst, $paylast);
3906   if ( $self->payname && $method ne 'ECHECK' ) {
3907     $payname = $self->payname;
3908     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3909       or return "Illegal payname $payname";
3910     ($payfirst, $paylast) = ($1, $2);
3911   } else {
3912     $payfirst = $self->getfield('first');
3913     $paylast = $self->getfield('last');
3914     $payname =  "$payfirst $paylast";
3915   }
3916
3917   my @invoicing_list = $self->invoicing_list_emailonly;
3918   if ( $conf->exists('emailinvoiceautoalways')
3919        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3920        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3921     push @invoicing_list, $self->all_emails;
3922   }
3923
3924   my $email = ($conf->exists('business-onlinepayment-email-override'))
3925               ? $conf->config('business-onlinepayment-email-override')
3926               : $invoicing_list[0];
3927
3928   my $payip = exists($options{'payip'})
3929                 ? $options{'payip'}
3930                 : $self->payip;
3931   $content{customer_ip} = $payip
3932     if length($payip);
3933
3934   my $payinfo = '';
3935   if ( $method eq 'CC' ) {
3936
3937     if ( $cust_pay ) {
3938       $content{card_number} = $payinfo = $cust_pay->payinfo;
3939       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3940         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3941         ($content{expiration} = "$2/$1");  # where available
3942     } else {
3943       $content{card_number} = $payinfo = $self->payinfo;
3944       (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3945         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3946       $content{expiration} = "$2/$1";
3947     }
3948
3949   } elsif ( $method eq 'ECHECK' ) {
3950
3951     if ( $cust_pay ) {
3952       $payinfo = $cust_pay->payinfo;
3953     } else {
3954       $payinfo = $self->payinfo;
3955     } 
3956     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3957     $content{bank_name} = $self->payname;
3958     $content{account_type} = 'CHECKING';
3959     $content{account_name} = $payname;
3960     $content{customer_org} = $self->company ? 'B' : 'I';
3961     $content{customer_ssn} = $self->ss;
3962   } elsif ( $method eq 'LEC' ) {
3963     $content{phone} = $payinfo = $self->payinfo;
3964   }
3965
3966   #then try refund
3967   my $refund = new Business::OnlinePayment( $processor, @bop_options );
3968   my %sub_content = $refund->content(
3969     'action'         => 'credit',
3970     'customer_id'    => $self->custnum,
3971     'last_name'      => $paylast,
3972     'first_name'     => $payfirst,
3973     'name'           => $payname,
3974     'address'        => $address,
3975     'city'           => $self->city,
3976     'state'          => $self->state,
3977     'zip'            => $self->zip,
3978     'country'        => $self->country,
3979     'email'          => $email,
3980     'phone'          => $self->daytime || $self->night,
3981     %content, #after
3982   );
3983   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
3984     if $DEBUG > 1;
3985   $refund->submit();
3986
3987   return "$processor error: ". $refund->error_message
3988     unless $refund->is_success();
3989
3990   my %method2payby = (
3991     'CC'     => 'CARD',
3992     'ECHECK' => 'CHEK',
3993     'LEC'    => 'LECB',
3994   );
3995
3996   my $paybatch = "$processor:". $refund->authorization;
3997   $paybatch .= ':'. $refund->order_number
3998     if $refund->can('order_number') && $refund->order_number;
3999
4000   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
4001     my @cust_bill_pay = $cust_pay->cust_bill_pay;
4002     last unless @cust_bill_pay;
4003     my $cust_bill_pay = pop @cust_bill_pay;
4004     my $error = $cust_bill_pay->delete;
4005     last if $error;
4006   }
4007
4008   my $cust_refund = new FS::cust_refund ( {
4009     'custnum'  => $self->custnum,
4010     'paynum'   => $options{'paynum'},
4011     'refund'   => $amount,
4012     '_date'    => '',
4013     'payby'    => $method2payby{$method},
4014     'payinfo'  => $payinfo,
4015     'paybatch' => $paybatch,
4016     'reason'   => $options{'reason'} || 'card or ACH refund',
4017   } );
4018   my $error = $cust_refund->insert;
4019   if ( $error ) {
4020     $cust_refund->paynum(''); #try again with no specific paynum
4021     my $error2 = $cust_refund->insert;
4022     if ( $error2 ) {
4023       # gah, even with transactions.
4024       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
4025               "error inserting refund ($processor): $error2".
4026               " (previously tried insert with paynum #$options{'paynum'}" .
4027               ": $error )";
4028       warn $e;
4029       return $e;
4030     }
4031   }
4032
4033   ''; #no error
4034
4035 }
4036
4037 =item batch_card OPTION => VALUE...
4038
4039 Adds a payment for this invoice to the pending credit card batch (see
4040 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
4041 runs the payment using a realtime gateway.
4042
4043 =cut
4044
4045 sub batch_card {
4046   my ($self, %options) = @_;
4047
4048   my $amount;
4049   if (exists($options{amount})) {
4050     $amount = $options{amount};
4051   }else{
4052     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
4053   }
4054   return '' unless $amount > 0;
4055   
4056   my $invnum = delete $options{invnum};
4057   my $payby = $options{invnum} || $self->payby;  #dubious
4058
4059   if ($options{'realtime'}) {
4060     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
4061                                 $amount,
4062                                 %options,
4063                               );
4064   }
4065
4066   my $oldAutoCommit = $FS::UID::AutoCommit;
4067   local $FS::UID::AutoCommit = 0;
4068   my $dbh = dbh;
4069
4070   #this needs to handle mysql as well as Pg, like svc_acct.pm
4071   #(make it into a common function if folks need to do batching with mysql)
4072   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
4073     or return "Cannot lock pay_batch: " . $dbh->errstr;
4074
4075   my %pay_batch = (
4076     'status' => 'O',
4077     'payby'  => FS::payby->payby2payment($payby),
4078   );
4079
4080   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
4081
4082   unless ( $pay_batch ) {
4083     $pay_batch = new FS::pay_batch \%pay_batch;
4084     my $error = $pay_batch->insert;
4085     if ( $error ) {
4086       $dbh->rollback if $oldAutoCommit;
4087       die "error creating new batch: $error\n";
4088     }
4089   }
4090
4091   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
4092       'batchnum' => $pay_batch->batchnum,
4093       'custnum'  => $self->custnum,
4094   } );
4095
4096   foreach (qw( address1 address2 city state zip country payby payinfo paydate
4097                payname )) {
4098     $options{$_} = '' unless exists($options{$_});
4099   }
4100
4101   my $cust_pay_batch = new FS::cust_pay_batch ( {
4102     'batchnum' => $pay_batch->batchnum,
4103     'invnum'   => $invnum || 0,                    # is there a better value?
4104                                                    # this field should be
4105                                                    # removed...
4106                                                    # cust_bill_pay_batch now
4107     'custnum'  => $self->custnum,
4108     'last'     => $self->getfield('last'),
4109     'first'    => $self->getfield('first'),
4110     'address1' => $options{address1} || $self->address1,
4111     'address2' => $options{address2} || $self->address2,
4112     'city'     => $options{city}     || $self->city,
4113     'state'    => $options{state}    || $self->state,
4114     'zip'      => $options{zip}      || $self->zip,
4115     'country'  => $options{country}  || $self->country,
4116     'payby'    => $options{payby}    || $self->payby,
4117     'payinfo'  => $options{payinfo}  || $self->payinfo,
4118     'exp'      => $options{paydate}  || $self->paydate,
4119     'payname'  => $options{payname}  || $self->payname,
4120     'amount'   => $amount,                         # consolidating
4121   } );
4122   
4123   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
4124     if $old_cust_pay_batch;
4125
4126   my $error;
4127   if ($old_cust_pay_batch) {
4128     $error = $cust_pay_batch->replace($old_cust_pay_batch)
4129   } else {
4130     $error = $cust_pay_batch->insert;
4131   }
4132
4133   if ( $error ) {
4134     $dbh->rollback if $oldAutoCommit;
4135     die $error;
4136   }
4137
4138   my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
4139   foreach my $cust_bill ($self->open_cust_bill) {
4140     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
4141     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
4142       'invnum' => $cust_bill->invnum,
4143       'paybatchnum' => $cust_pay_batch->paybatchnum,
4144       'amount' => $cust_bill->owed,
4145       '_date' => time,
4146     };
4147     if ($unapplied >= $cust_bill_pay_batch->amount){
4148       $unapplied -= $cust_bill_pay_batch->amount;
4149       next;
4150     }else{
4151       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
4152                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
4153     }
4154     $error = $cust_bill_pay_batch->insert;
4155     if ( $error ) {
4156       $dbh->rollback if $oldAutoCommit;
4157       die $error;
4158     }
4159   }
4160
4161   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4162   '';
4163 }
4164
4165 =item total_owed
4166
4167 Returns the total owed for this customer on all invoices
4168 (see L<FS::cust_bill/owed>).
4169
4170 =cut
4171
4172 sub total_owed {
4173   my $self = shift;
4174   $self->total_owed_date(2145859200); #12/31/2037
4175 }
4176
4177 =item total_owed_date TIME
4178
4179 Returns the total owed for this customer on all invoices with date earlier than
4180 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
4181 see L<Time::Local> and L<Date::Parse> for conversion functions.
4182
4183 =cut
4184
4185 sub total_owed_date {
4186   my $self = shift;
4187   my $time = shift;
4188   my $total_bill = 0;
4189   foreach my $cust_bill (
4190     grep { $_->_date <= $time }
4191       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4192   ) {
4193     $total_bill += $cust_bill->owed;
4194   }
4195   sprintf( "%.2f", $total_bill );
4196 }
4197
4198 =item apply_payments_and_credits
4199
4200 Applies unapplied payments and credits.
4201
4202 In most cases, this new method should be used in place of sequential
4203 apply_payments and apply_credits methods.
4204
4205 If there is an error, returns the error, otherwise returns false.
4206
4207 =cut
4208
4209 sub apply_payments_and_credits {
4210   my $self = shift;
4211
4212   local $SIG{HUP} = 'IGNORE';
4213   local $SIG{INT} = 'IGNORE';
4214   local $SIG{QUIT} = 'IGNORE';
4215   local $SIG{TERM} = 'IGNORE';
4216   local $SIG{TSTP} = 'IGNORE';
4217   local $SIG{PIPE} = 'IGNORE';
4218
4219   my $oldAutoCommit = $FS::UID::AutoCommit;
4220   local $FS::UID::AutoCommit = 0;
4221   my $dbh = dbh;
4222
4223   $self->select_for_update; #mutex
4224
4225   foreach my $cust_bill ( $self->open_cust_bill ) {
4226     my $error = $cust_bill->apply_payments_and_credits;
4227     if ( $error ) {
4228       $dbh->rollback if $oldAutoCommit;
4229       return "Error applying: $error";
4230     }
4231   }
4232
4233   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4234   ''; #no error
4235
4236 }
4237
4238 =item apply_credits OPTION => VALUE ...
4239
4240 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
4241 to outstanding invoice balances in chronological order (or reverse
4242 chronological order if the I<order> option is set to B<newest>) and returns the
4243 value of any remaining unapplied credits available for refund (see
4244 L<FS::cust_refund>).
4245
4246 Dies if there is an error.
4247
4248 =cut
4249
4250 sub apply_credits {
4251   my $self = shift;
4252   my %opt = @_;
4253
4254   local $SIG{HUP} = 'IGNORE';
4255   local $SIG{INT} = 'IGNORE';
4256   local $SIG{QUIT} = 'IGNORE';
4257   local $SIG{TERM} = 'IGNORE';
4258   local $SIG{TSTP} = 'IGNORE';
4259   local $SIG{PIPE} = 'IGNORE';
4260
4261   my $oldAutoCommit = $FS::UID::AutoCommit;
4262   local $FS::UID::AutoCommit = 0;
4263   my $dbh = dbh;
4264
4265   $self->select_for_update; #mutex
4266
4267   unless ( $self->total_credited ) {
4268     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4269     return 0;
4270   }
4271
4272   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
4273       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
4274
4275   my @invoices = $self->open_cust_bill;
4276   @invoices = sort { $b->_date <=> $a->_date } @invoices
4277     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
4278
4279   my $credit;
4280   foreach my $cust_bill ( @invoices ) {
4281     my $amount;
4282
4283     if ( !defined($credit) || $credit->credited == 0) {
4284       $credit = pop @credits or last;
4285     }
4286
4287     if ($cust_bill->owed >= $credit->credited) {
4288       $amount=$credit->credited;
4289     }else{
4290       $amount=$cust_bill->owed;
4291     }
4292     
4293     my $cust_credit_bill = new FS::cust_credit_bill ( {
4294       'crednum' => $credit->crednum,
4295       'invnum'  => $cust_bill->invnum,
4296       'amount'  => $amount,
4297     } );
4298     my $error = $cust_credit_bill->insert;
4299     if ( $error ) {
4300       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4301       die $error;
4302     }
4303     
4304     redo if ($cust_bill->owed > 0);
4305
4306   }
4307
4308   my $total_credited = $self->total_credited;
4309
4310   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4311
4312   return $total_credited;
4313 }
4314
4315 =item apply_payments
4316
4317 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
4318 to outstanding invoice balances in chronological order.
4319
4320  #and returns the value of any remaining unapplied payments.
4321
4322 Dies if there is an error.
4323
4324 =cut
4325
4326 sub apply_payments {
4327   my $self = shift;
4328
4329   local $SIG{HUP} = 'IGNORE';
4330   local $SIG{INT} = 'IGNORE';
4331   local $SIG{QUIT} = 'IGNORE';
4332   local $SIG{TERM} = 'IGNORE';
4333   local $SIG{TSTP} = 'IGNORE';
4334   local $SIG{PIPE} = 'IGNORE';
4335
4336   my $oldAutoCommit = $FS::UID::AutoCommit;
4337   local $FS::UID::AutoCommit = 0;
4338   my $dbh = dbh;
4339
4340   $self->select_for_update; #mutex
4341
4342   #return 0 unless
4343
4344   my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
4345       qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
4346
4347   my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
4348       qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
4349
4350   my $payment;
4351
4352   foreach my $cust_bill ( @invoices ) {
4353     my $amount;
4354
4355     if ( !defined($payment) || $payment->unapplied == 0 ) {
4356       $payment = pop @payments or last;
4357     }
4358
4359     if ( $cust_bill->owed >= $payment->unapplied ) {
4360       $amount = $payment->unapplied;
4361     } else {
4362       $amount = $cust_bill->owed;
4363     }
4364
4365     my $cust_bill_pay = new FS::cust_bill_pay ( {
4366       'paynum' => $payment->paynum,
4367       'invnum' => $cust_bill->invnum,
4368       'amount' => $amount,
4369     } );
4370     my $error = $cust_bill_pay->insert;
4371     if ( $error ) {
4372       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
4373       die $error;
4374     }
4375
4376     redo if ( $cust_bill->owed > 0);
4377
4378   }
4379
4380   my $total_unapplied_payments = $self->total_unapplied_payments;
4381
4382   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4383
4384   return $total_unapplied_payments;
4385 }
4386
4387 =item total_credited
4388
4389 Returns the total outstanding credit (see L<FS::cust_credit>) for this
4390 customer.  See L<FS::cust_credit/credited>.
4391
4392 =cut
4393
4394 sub total_credited {
4395   my $self = shift;
4396   my $total_credit = 0;
4397   foreach my $cust_credit ( qsearch('cust_credit', {
4398     'custnum' => $self->custnum,
4399   } ) ) {
4400     $total_credit += $cust_credit->credited;
4401   }
4402   sprintf( "%.2f", $total_credit );
4403 }
4404
4405 =item total_unapplied_payments
4406
4407 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
4408 See L<FS::cust_pay/unapplied>.
4409
4410 =cut
4411
4412 sub total_unapplied_payments {
4413   my $self = shift;
4414   my $total_unapplied = 0;
4415   foreach my $cust_pay ( qsearch('cust_pay', {
4416     'custnum' => $self->custnum,
4417   } ) ) {
4418     $total_unapplied += $cust_pay->unapplied;
4419   }
4420   sprintf( "%.2f", $total_unapplied );
4421 }
4422
4423 =item total_unapplied_refunds
4424
4425 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
4426 customer.  See L<FS::cust_refund/unapplied>.
4427
4428 =cut
4429
4430 sub total_unapplied_refunds {
4431   my $self = shift;
4432   my $total_unapplied = 0;
4433   foreach my $cust_refund ( qsearch('cust_refund', {
4434     'custnum' => $self->custnum,
4435   } ) ) {
4436     $total_unapplied += $cust_refund->unapplied;
4437   }
4438   sprintf( "%.2f", $total_unapplied );
4439 }
4440
4441 =item balance
4442
4443 Returns the balance for this customer (total_owed plus total_unrefunded, minus
4444 total_credited minus total_unapplied_payments).
4445
4446 =cut
4447
4448 sub balance {
4449   my $self = shift;
4450   sprintf( "%.2f",
4451       $self->total_owed
4452     + $self->total_unapplied_refunds
4453     - $self->total_credited
4454     - $self->total_unapplied_payments
4455   );
4456 }
4457
4458 =item balance_date TIME
4459
4460 Returns the balance for this customer, only considering invoices with date
4461 earlier than TIME (total_owed_date minus total_credited minus
4462 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
4463 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
4464 functions.
4465
4466 =cut
4467
4468 sub balance_date {
4469   my $self = shift;
4470   my $time = shift;
4471   sprintf( "%.2f",
4472         $self->total_owed_date($time)
4473       + $self->total_unapplied_refunds
4474       - $self->total_credited
4475       - $self->total_unapplied_payments
4476   );
4477 }
4478
4479 =item in_transit_payments
4480
4481 Returns the total of requests for payments for this customer pending in 
4482 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
4483
4484 =cut
4485
4486 sub in_transit_payments {
4487   my $self = shift;
4488   my $in_transit_payments = 0;
4489   foreach my $pay_batch ( qsearch('pay_batch', {
4490     'status' => 'I',
4491   } ) ) {
4492     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
4493       'batchnum' => $pay_batch->batchnum,
4494       'custnum' => $self->custnum,
4495     } ) ) {
4496       $in_transit_payments += $cust_pay_batch->amount;
4497     }
4498   }
4499   sprintf( "%.2f", $in_transit_payments );
4500 }
4501
4502 =item paydate_monthyear
4503
4504 Returns a two-element list consisting of the month and year of this customer's
4505 paydate (credit card expiration date for CARD customers)
4506
4507 =cut
4508
4509 sub paydate_monthyear {
4510   my $self = shift;
4511   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
4512     ( $2, $1 );
4513   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
4514     ( $1, $3 );
4515   } else {
4516     ('', '');
4517   }
4518 }
4519
4520 =item invoicing_list [ ARRAYREF ]
4521
4522 If an arguement is given, sets these email addresses as invoice recipients
4523 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
4524 (except as warnings), so use check_invoicing_list first.
4525
4526 Returns a list of email addresses (with svcnum entries expanded).
4527
4528 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
4529 check it without disturbing anything by passing nothing.
4530
4531 This interface may change in the future.
4532
4533 =cut
4534
4535 sub invoicing_list {
4536   my( $self, $arrayref ) = @_;
4537
4538   if ( $arrayref ) {
4539     my @cust_main_invoice;
4540     if ( $self->custnum ) {
4541       @cust_main_invoice = 
4542         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4543     } else {
4544       @cust_main_invoice = ();
4545     }
4546     foreach my $cust_main_invoice ( @cust_main_invoice ) {
4547       #warn $cust_main_invoice->destnum;
4548       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
4549         #warn $cust_main_invoice->destnum;
4550         my $error = $cust_main_invoice->delete;
4551         warn $error if $error;
4552       }
4553     }
4554     if ( $self->custnum ) {
4555       @cust_main_invoice = 
4556         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4557     } else {
4558       @cust_main_invoice = ();
4559     }
4560     my %seen = map { $_->address => 1 } @cust_main_invoice;
4561     foreach my $address ( @{$arrayref} ) {
4562       next if exists $seen{$address} && $seen{$address};
4563       $seen{$address} = 1;
4564       my $cust_main_invoice = new FS::cust_main_invoice ( {
4565         'custnum' => $self->custnum,
4566         'dest'    => $address,
4567       } );
4568       my $error = $cust_main_invoice->insert;
4569       warn $error if $error;
4570     }
4571   }
4572   
4573   if ( $self->custnum ) {
4574     map { $_->address }
4575       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
4576   } else {
4577     ();
4578   }
4579
4580 }
4581
4582 =item check_invoicing_list ARRAYREF
4583
4584 Checks these arguements as valid input for the invoicing_list method.  If there
4585 is an error, returns the error, otherwise returns false.
4586
4587 =cut
4588
4589 sub check_invoicing_list {
4590   my( $self, $arrayref ) = @_;
4591
4592   foreach my $address ( @$arrayref ) {
4593
4594     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
4595       return 'Can\'t add FAX invoice destination with a blank FAX number.';
4596     }
4597
4598     my $cust_main_invoice = new FS::cust_main_invoice ( {
4599       'custnum' => $self->custnum,
4600       'dest'    => $address,
4601     } );
4602     my $error = $self->custnum
4603                 ? $cust_main_invoice->check
4604                 : $cust_main_invoice->checkdest
4605     ;
4606     return $error if $error;
4607
4608   }
4609
4610   return "Email address required"
4611     if $conf->exists('cust_main-require_invoicing_list_email')
4612     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
4613
4614   '';
4615 }
4616
4617 =item set_default_invoicing_list
4618
4619 Sets the invoicing list to all accounts associated with this customer,
4620 overwriting any previous invoicing list.
4621
4622 =cut
4623
4624 sub set_default_invoicing_list {
4625   my $self = shift;
4626   $self->invoicing_list($self->all_emails);
4627 }
4628
4629 =item all_emails
4630
4631 Returns the email addresses of all accounts provisioned for this customer.
4632
4633 =cut
4634
4635 sub all_emails {
4636   my $self = shift;
4637   my %list;
4638   foreach my $cust_pkg ( $self->all_pkgs ) {
4639     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4640     my @svc_acct =
4641       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4642         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4643           @cust_svc;
4644     $list{$_}=1 foreach map { $_->email } @svc_acct;
4645   }
4646   keys %list;
4647 }
4648
4649 =item invoicing_list_addpost
4650
4651 Adds postal invoicing to this customer.  If this customer is already configured
4652 to receive postal invoices, does nothing.
4653
4654 =cut
4655
4656 sub invoicing_list_addpost {
4657   my $self = shift;
4658   return if grep { $_ eq 'POST' } $self->invoicing_list;
4659   my @invoicing_list = $self->invoicing_list;
4660   push @invoicing_list, 'POST';
4661   $self->invoicing_list(\@invoicing_list);
4662 }
4663
4664 =item invoicing_list_emailonly
4665
4666 Returns the list of email invoice recipients (invoicing_list without non-email
4667 destinations such as POST and FAX).
4668
4669 =cut
4670
4671 sub invoicing_list_emailonly {
4672   my $self = shift;
4673   warn "$me invoicing_list_emailonly called"
4674     if $DEBUG;
4675   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4676 }
4677
4678 =item invoicing_list_emailonly_scalar
4679
4680 Returns the list of email invoice recipients (invoicing_list without non-email
4681 destinations such as POST and FAX) as a comma-separated scalar.
4682
4683 =cut
4684
4685 sub invoicing_list_emailonly_scalar {
4686   my $self = shift;
4687   warn "$me invoicing_list_emailonly_scalar called"
4688     if $DEBUG;
4689   join(', ', $self->invoicing_list_emailonly);
4690 }
4691
4692 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4693
4694 Returns an array of customers referred by this customer (referral_custnum set
4695 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
4696 customers referred by customers referred by this customer and so on, inclusive.
4697 The default behavior is DEPTH 1 (no recursion).
4698
4699 =cut
4700
4701 sub referral_cust_main {
4702   my $self = shift;
4703   my $depth = @_ ? shift : 1;
4704   my $exclude = @_ ? shift : {};
4705
4706   my @cust_main =
4707     map { $exclude->{$_->custnum}++; $_; }
4708       grep { ! $exclude->{ $_->custnum } }
4709         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4710
4711   if ( $depth > 1 ) {
4712     push @cust_main,
4713       map { $_->referral_cust_main($depth-1, $exclude) }
4714         @cust_main;
4715   }
4716
4717   @cust_main;
4718 }
4719
4720 =item referral_cust_main_ncancelled
4721
4722 Same as referral_cust_main, except only returns customers with uncancelled
4723 packages.
4724
4725 =cut
4726
4727 sub referral_cust_main_ncancelled {
4728   my $self = shift;
4729   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4730 }
4731
4732 =item referral_cust_pkg [ DEPTH ]
4733
4734 Like referral_cust_main, except returns a flat list of all unsuspended (and
4735 uncancelled) packages for each customer.  The number of items in this list may
4736 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4737
4738 =cut
4739
4740 sub referral_cust_pkg {
4741   my $self = shift;
4742   my $depth = @_ ? shift : 1;
4743
4744   map { $_->unsuspended_pkgs }
4745     grep { $_->unsuspended_pkgs }
4746       $self->referral_cust_main($depth);
4747 }
4748
4749 =item referring_cust_main
4750
4751 Returns the single cust_main record for the customer who referred this customer
4752 (referral_custnum), or false.
4753
4754 =cut
4755
4756 sub referring_cust_main {
4757   my $self = shift;
4758   return '' unless $self->referral_custnum;
4759   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4760 }
4761
4762 =item credit AMOUNT, REASON
4763
4764 Applies a credit to this customer.  If there is an error, returns the error,
4765 otherwise returns false.
4766
4767 =cut
4768
4769 sub credit {
4770   my( $self, $amount, $reason, %options ) = @_;
4771   my $cust_credit = new FS::cust_credit {
4772     'custnum' => $self->custnum,
4773     'amount'  => $amount,
4774     'reason'  => $reason,
4775   };
4776   $cust_credit->insert(%options);
4777 }
4778
4779 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4780
4781 Creates a one-time charge for this customer.  If there is an error, returns
4782 the error, otherwise returns false.
4783
4784 =cut
4785
4786 sub charge {
4787   my $self = shift;
4788   my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4789   if ( ref( $_[0] ) ) {
4790     $amount     = $_[0]->{amount};
4791     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4792     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4793     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
4794                                            : '$'. sprintf("%.2f",$amount);
4795     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4796     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4797     $additional = $_[0]->{additional};
4798   }else{
4799     $amount     = shift;
4800     $quantity   = 1;
4801     $pkg        = @_ ? shift : 'One-time charge';
4802     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
4803     $taxclass   = @_ ? shift : '';
4804     $additional = [];
4805   }
4806
4807   local $SIG{HUP} = 'IGNORE';
4808   local $SIG{INT} = 'IGNORE';
4809   local $SIG{QUIT} = 'IGNORE';
4810   local $SIG{TERM} = 'IGNORE';
4811   local $SIG{TSTP} = 'IGNORE';
4812   local $SIG{PIPE} = 'IGNORE';
4813
4814   my $oldAutoCommit = $FS::UID::AutoCommit;
4815   local $FS::UID::AutoCommit = 0;
4816   my $dbh = dbh;
4817
4818   my $part_pkg = new FS::part_pkg ( {
4819     'pkg'      => $pkg,
4820     'comment'  => $comment,
4821     'plan'     => 'flat',
4822     'freq'     => 0,
4823     'disabled' => 'Y',
4824     'classnum' => $classnum ? $classnum : '',
4825     'taxclass' => $taxclass,
4826   } );
4827
4828   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4829                         ( 0 .. @$additional - 1 )
4830                   ),
4831                   'additional_count' => scalar(@$additional),
4832                   'setup_fee' => $amount,
4833                 );
4834
4835   my $error = $part_pkg->insert( options => \%options );
4836   if ( $error ) {
4837     $dbh->rollback if $oldAutoCommit;
4838     return $error;
4839   }
4840
4841   my $pkgpart = $part_pkg->pkgpart;
4842   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4843   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4844     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4845     $error = $type_pkgs->insert;
4846     if ( $error ) {
4847       $dbh->rollback if $oldAutoCommit;
4848       return $error;
4849     }
4850   }
4851
4852   my $cust_pkg = new FS::cust_pkg ( {
4853     'custnum'  => $self->custnum,
4854     'pkgpart'  => $pkgpart,
4855     'quantity' => $quantity,
4856   } );
4857
4858   $error = $cust_pkg->insert;
4859   if ( $error ) {
4860     $dbh->rollback if $oldAutoCommit;
4861     return $error;
4862   }
4863
4864   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4865   '';
4866
4867 }
4868
4869 #=item charge_postal_fee
4870 #
4871 #Applies a one time charge this customer.  If there is an error,
4872 #returns the error, returns the cust_pkg charge object or false
4873 #if there was no charge.
4874 #
4875 #=cut
4876 #
4877 # This should be a customer event.  For that to work requires that bill
4878 # also be a customer event.
4879
4880 sub charge_postal_fee {
4881   my $self = shift;
4882
4883   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4884   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4885
4886   my $cust_pkg = new FS::cust_pkg ( {
4887     'custnum'  => $self->custnum,
4888     'pkgpart'  => $pkgpart,
4889     'quantity' => 1,
4890   } );
4891
4892   my $error = $cust_pkg->insert;
4893   $error ? $error : $cust_pkg;
4894 }
4895
4896 =item cust_bill
4897
4898 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4899
4900 =cut
4901
4902 sub cust_bill {
4903   my $self = shift;
4904   sort { $a->_date <=> $b->_date }
4905     qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4906 }
4907
4908 =item open_cust_bill
4909
4910 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4911 customer.
4912
4913 =cut
4914
4915 sub open_cust_bill {
4916   my $self = shift;
4917   grep { $_->owed > 0 } $self->cust_bill;
4918 }
4919
4920 =item cust_credit
4921
4922 Returns all the credits (see L<FS::cust_credit>) for this customer.
4923
4924 =cut
4925
4926 sub cust_credit {
4927   my $self = shift;
4928   sort { $a->_date <=> $b->_date }
4929     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4930 }
4931
4932 =item cust_pay
4933
4934 Returns all the payments (see L<FS::cust_pay>) for this customer.
4935
4936 =cut
4937
4938 sub cust_pay {
4939   my $self = shift;
4940   sort { $a->_date <=> $b->_date }
4941     qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4942 }
4943
4944 =item cust_pay_void
4945
4946 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4947
4948 =cut
4949
4950 sub cust_pay_void {
4951   my $self = shift;
4952   sort { $a->_date <=> $b->_date }
4953     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4954 }
4955
4956 =item cust_pay_batch
4957
4958 Returns all batched payments (see L<FS::cust_pay_void>) for this customer.
4959
4960 =cut
4961
4962 sub cust_pay_batch {
4963   my $self = shift;
4964   sort { $a->_date <=> $b->_date }
4965     qsearch( 'cust_pay_batch', { 'custnum' => $self->custnum } )
4966 }
4967
4968 =item cust_refund
4969
4970 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4971
4972 =cut
4973
4974 sub cust_refund {
4975   my $self = shift;
4976   sort { $a->_date <=> $b->_date }
4977     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4978 }
4979
4980 =item name
4981
4982 Returns a name string for this customer, either "Company (Last, First)" or
4983 "Last, First".
4984
4985 =cut
4986
4987 sub name {
4988   my $self = shift;
4989   my $name = $self->contact;
4990   $name = $self->company. " ($name)" if $self->company;
4991   $name;
4992 }
4993
4994 =item ship_name
4995
4996 Returns a name string for this (service/shipping) contact, either
4997 "Company (Last, First)" or "Last, First".
4998
4999 =cut
5000
5001 sub ship_name {
5002   my $self = shift;
5003   if ( $self->get('ship_last') ) { 
5004     my $name = $self->ship_contact;
5005     $name = $self->ship_company. " ($name)" if $self->ship_company;
5006     $name;
5007   } else {
5008     $self->name;
5009   }
5010 }
5011
5012 =item contact
5013
5014 Returns this customer's full (billing) contact name only, "Last, First"
5015
5016 =cut
5017
5018 sub contact {
5019   my $self = shift;
5020   $self->get('last'). ', '. $self->first;
5021 }
5022
5023 =item ship_contact
5024
5025 Returns this customer's full (shipping) contact name only, "Last, First"
5026
5027 =cut
5028
5029 sub ship_contact {
5030   my $self = shift;
5031   $self->get('ship_last')
5032     ? $self->get('ship_last'). ', '. $self->ship_first
5033     : $self->contact;
5034 }
5035
5036 =item country_full
5037
5038 Returns this customer's full country name
5039
5040 =cut
5041
5042 sub country_full {
5043   my $self = shift;
5044   code2country($self->country);
5045 }
5046
5047 =item geocode DATA_VENDOR
5048
5049 Returns a value for the customer location as encoded by DATA_VENDOR.
5050 Currently this only makes sense for "CCH" as DATA_VENDOR.
5051
5052 =cut
5053
5054 sub geocode {
5055   my ($self, $data_vendor) = (shift, shift);  #always cch for now
5056
5057   my $prefix = ( $conf->exists('tax-ship_address') && length($self->ship_last) )
5058                ? 'ship_'
5059                : '';
5060
5061   my ($zip,$plus4) = split /-/, $self->get("${prefix}zip")
5062     if $self->country eq 'US';
5063
5064   #CCH specific location stuff
5065   my $extra_sql = "AND plus4lo <= '$plus4' AND plus4hi >= '$plus4'";
5066
5067   my $geocode = '';
5068   my $cust_tax_location =
5069     qsearchs( {
5070                 'table'     => 'cust_tax_location', 
5071                 'hashref'   => { 'zip' => $zip, 'data_vendor' => $data_vendor },
5072                 'extra_sql' => $extra_sql,
5073               }
5074             );
5075   $geocode = $cust_tax_location->geocode
5076     if $cust_tax_location;
5077
5078   $geocode;
5079 }
5080
5081 =item cust_status
5082
5083 =item status
5084
5085 Returns a status string for this customer, currently:
5086
5087 =over 4
5088
5089 =item prospect - No packages have ever been ordered
5090
5091 =item active - One or more recurring packages is active
5092
5093 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
5094
5095 =item suspended - All non-cancelled recurring packages are suspended
5096
5097 =item cancelled - All recurring packages are cancelled
5098
5099 =back
5100
5101 =cut
5102
5103 sub status { shift->cust_status(@_); }
5104
5105 sub cust_status {
5106   my $self = shift;
5107   for my $status (qw( prospect active inactive suspended cancelled )) {
5108     my $method = $status.'_sql';
5109     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
5110     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
5111     $sth->execute( ($self->custnum) x $numnum )
5112       or die "Error executing 'SELECT $sql': ". $sth->errstr;
5113     return $status if $sth->fetchrow_arrayref->[0];
5114   }
5115 }
5116
5117 =item ucfirst_cust_status
5118
5119 =item ucfirst_status
5120
5121 Returns the status with the first character capitalized.
5122
5123 =cut
5124
5125 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
5126
5127 sub ucfirst_cust_status {
5128   my $self = shift;
5129   ucfirst($self->cust_status);
5130 }
5131
5132 =item statuscolor
5133
5134 Returns a hex triplet color string for this customer's status.
5135
5136 =cut
5137
5138 use vars qw(%statuscolor);
5139 tie %statuscolor, 'Tie::IxHash',
5140   'prospect'  => '7e0079', #'000000', #black?  naw, purple
5141   'active'    => '00CC00', #green
5142   'inactive'  => '0000CC', #blue
5143   'suspended' => 'FF9900', #yellow
5144   'cancelled' => 'FF0000', #red
5145 ;
5146
5147 sub statuscolor { shift->cust_statuscolor(@_); }
5148
5149 sub cust_statuscolor {
5150   my $self = shift;
5151   $statuscolor{$self->cust_status};
5152 }
5153
5154 =item tickets
5155
5156 Returns an array of hashes representing the customer's RT tickets.
5157
5158 =cut
5159
5160 sub tickets {
5161   my $self = shift;
5162
5163   my $num = $conf->config('cust_main-max_tickets') || 10;
5164   my @tickets = ();
5165
5166   unless ( $conf->config('ticket_system-custom_priority_field') ) {
5167
5168     @tickets = @{ FS::TicketSystem->customer_tickets($self->custnum, $num) };
5169
5170   } else {
5171
5172     foreach my $priority (
5173       $conf->config('ticket_system-custom_priority_field-values'), ''
5174     ) {
5175       last if scalar(@tickets) >= $num;
5176       push @tickets, 
5177         @{ FS::TicketSystem->customer_tickets( $self->custnum,
5178                                                $num - scalar(@tickets),
5179                                                $priority,
5180                                              )
5181          };
5182     }
5183   }
5184   (@tickets);
5185 }
5186
5187 # Return services representing svc_accts in customer support packages
5188 sub support_services {
5189   my $self = shift;
5190   my %packages = map { $_ => 1 } $conf->config('support_packages');
5191
5192   grep { $_->pkg_svc && $_->pkg_svc->primary_svc eq 'Y' }
5193     grep { $_->part_svc->svcdb eq 'svc_acct' }
5194     map { $_->cust_svc }
5195     grep { exists $packages{ $_->pkgpart } }
5196     $self->ncancelled_pkgs;
5197
5198 }
5199
5200 =back
5201
5202 =head1 CLASS METHODS
5203
5204 =over 4
5205
5206 =item statuses
5207
5208 Class method that returns the list of possible status strings for customers
5209 (see L<the status method|/status>).  For example:
5210
5211   @statuses = FS::cust_main->statuses();
5212
5213 =cut
5214
5215 sub statuses {
5216   #my $self = shift; #could be class...
5217   keys %statuscolor;
5218 }
5219
5220 =item prospect_sql
5221
5222 Returns an SQL expression identifying prospective cust_main records (customers
5223 with no packages ever ordered)
5224
5225 =cut
5226
5227 use vars qw($select_count_pkgs);
5228 $select_count_pkgs =
5229   "SELECT COUNT(*) FROM cust_pkg
5230     WHERE cust_pkg.custnum = cust_main.custnum";
5231
5232 sub select_count_pkgs_sql {
5233   $select_count_pkgs;
5234 }
5235
5236 sub prospect_sql { "
5237   0 = ( $select_count_pkgs )
5238 "; }
5239
5240 =item active_sql
5241
5242 Returns an SQL expression identifying active cust_main records (customers with
5243 active recurring packages).
5244
5245 =cut
5246
5247 sub active_sql { "
5248   0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
5249       )
5250 "; }
5251
5252 =item inactive_sql
5253
5254 Returns an SQL expression identifying inactive cust_main records (customers with
5255 no active recurring packages, but otherwise unsuspended/uncancelled).
5256
5257 =cut
5258
5259 sub inactive_sql { "
5260   0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5261   AND
5262   0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5263 "; }
5264
5265 =item susp_sql
5266 =item suspended_sql
5267
5268 Returns an SQL expression identifying suspended cust_main records.
5269
5270 =cut
5271
5272
5273 sub suspended_sql { susp_sql(@_); }
5274 sub susp_sql { "
5275     0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
5276     AND
5277     0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
5278 "; }
5279
5280 =item cancel_sql
5281 =item cancelled_sql
5282
5283 Returns an SQL expression identifying cancelled cust_main records.
5284
5285 =cut
5286
5287 sub cancelled_sql { cancel_sql(@_); }
5288 sub cancel_sql {
5289
5290   my $recurring_sql = FS::cust_pkg->recurring_sql;
5291   my $cancelled_sql = FS::cust_pkg->cancelled_sql;
5292
5293   "
5294         0 < ( $select_count_pkgs )
5295     AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql   )
5296     AND 0 = ( $select_count_pkgs AND $recurring_sql
5297                   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
5298             )
5299     AND 0 = (  $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
5300   ";
5301
5302 }
5303
5304 =item uncancel_sql
5305 =item uncancelled_sql
5306
5307 Returns an SQL expression identifying un-cancelled cust_main records.
5308
5309 =cut
5310
5311 sub uncancelled_sql { uncancel_sql(@_); }
5312 sub uncancel_sql { "
5313   ( 0 < ( $select_count_pkgs
5314                    AND ( cust_pkg.cancel IS NULL
5315                          OR cust_pkg.cancel = 0
5316                        )
5317         )
5318     OR 0 = ( $select_count_pkgs )
5319   )
5320 "; }
5321
5322 =item balance_sql
5323
5324 Returns an SQL fragment to retreive the balance.
5325
5326 =cut
5327
5328 sub balance_sql { "
5329     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
5330         WHERE cust_bill.custnum   = cust_main.custnum     )
5331   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
5332         WHERE cust_pay.custnum    = cust_main.custnum     )
5333   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
5334         WHERE cust_credit.custnum = cust_main.custnum     )
5335   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
5336         WHERE cust_refund.custnum = cust_main.custnum     )
5337 "; }
5338
5339 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5340
5341 Returns an SQL fragment to retreive the balance for this customer, only
5342 considering invoices with date earlier than START_TIME, and optionally not
5343 later than END_TIME (total_owed_date minus total_credited minus
5344 total_unapplied_payments).
5345
5346 Times are specified as SQL fragments or numeric
5347 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
5348 L<Date::Parse> for conversion functions.  The empty string can be passed
5349 to disable that time constraint completely.
5350
5351 Available options are:
5352
5353 =over 4
5354
5355 =item unapplied_date
5356
5357 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)
5358
5359 =item total
5360
5361 (unused.  obsolete?)
5362 set to true to remove all customer comparison clauses, for totals
5363
5364 =item where
5365
5366 (unused.  obsolete?)
5367 WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
5368
5369 =item join
5370
5371 (unused.  obsolete?)
5372 JOIN clause (typically used with the total option)
5373
5374 =back
5375
5376 =cut
5377
5378 sub balance_date_sql {
5379   my( $class, $start, $end, %opt ) = @_;
5380
5381   my $owed         = FS::cust_bill->owed_sql;
5382   my $unapp_refund = FS::cust_refund->unapplied_sql;
5383   my $unapp_credit = FS::cust_credit->unapplied_sql;
5384   my $unapp_pay    = FS::cust_pay->unapplied_sql;
5385
5386   my $j = $opt{'join'} || '';
5387
5388   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
5389   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
5390   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
5391   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
5392
5393   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
5394     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
5395     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
5396     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
5397   ";
5398
5399 }
5400
5401 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
5402
5403 Helper method for balance_date_sql; name (and usage) subject to change
5404 (suggestions welcome).
5405
5406 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
5407 cust_refund, cust_credit or cust_pay).
5408
5409 If TABLE is "cust_bill" or the unapplied_date option is true, only
5410 considers records with date earlier than START_TIME, and optionally not
5411 later than END_TIME .
5412
5413 =cut
5414
5415 sub _money_table_where {
5416   my( $class, $table, $start, $end, %opt ) = @_;
5417
5418   my @where = ();
5419   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
5420   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
5421     push @where, "$table._date <= $start" if defined($start) && length($start);
5422     push @where, "$table._date >  $end"   if defined($end)   && length($end);
5423   }
5424   push @where, @{$opt{'where'}} if $opt{'where'};
5425   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
5426
5427   $where;
5428
5429 }
5430
5431 =item search_sql HASHREF
5432
5433 (Class method)
5434
5435 Returns a qsearch hash expression to search for parameters specified in HREF.
5436 Valid parameters are
5437
5438 =over 4
5439
5440 =item agentnum
5441
5442 =item status
5443
5444 =item cancelled_pkgs
5445
5446 bool
5447
5448 =item signupdate
5449
5450 listref of start date, end date
5451
5452 =item payby
5453
5454 listref
5455
5456 =item current_balance
5457
5458 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
5459
5460 =item cust_fields
5461
5462 =item flattened_pkgs
5463
5464 bool
5465
5466 =back
5467
5468 =cut
5469
5470 sub search_sql {
5471   my ($class, $params) = @_;
5472
5473   my $dbh = dbh;
5474
5475   my @where = ();
5476   my $orderby;
5477
5478   ##
5479   # parse agent
5480   ##
5481
5482   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
5483     push @where,
5484       "cust_main.agentnum = $1";
5485   }
5486
5487   ##
5488   # parse status
5489   ##
5490
5491   #prospect active inactive suspended cancelled
5492   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
5493     my $method = $params->{'status'}. '_sql';
5494     #push @where, $class->$method();
5495     push @where, FS::cust_main->$method();
5496   }
5497   
5498   ##
5499   # parse cancelled package checkbox
5500   ##
5501
5502   my $pkgwhere = "";
5503
5504   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
5505     unless $params->{'cancelled_pkgs'};
5506
5507   ##
5508   # dates
5509   ##
5510
5511   foreach my $field (qw( signupdate )) {
5512
5513     next unless exists($params->{$field});
5514
5515     my($beginning, $ending) = @{$params->{$field}};
5516
5517     push @where,
5518       "cust_main.$field IS NOT NULL",
5519       "cust_main.$field >= $beginning",
5520       "cust_main.$field <= $ending";
5521
5522     $orderby ||= "ORDER BY cust_main.$field";
5523
5524   }
5525
5526   ###
5527   # payby
5528   ###
5529
5530   my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
5531   if ( @payby ) {
5532     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
5533   }
5534
5535   ##
5536   # amounts
5537   ##
5538
5539   #my $balance_sql = $class->balance_sql();
5540   my $balance_sql = FS::cust_main->balance_sql();
5541
5542   push @where, map { s/current_balance/$balance_sql/; $_ }
5543                    @{ $params->{'current_balance'} };
5544
5545   ##
5546   # setup queries, subs, etc. for the search
5547   ##
5548
5549   $orderby ||= 'ORDER BY custnum';
5550
5551   # here is the agent virtualization
5552   push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
5553
5554   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
5555
5556   my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum  ) ';
5557
5558   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
5559
5560   my $select = join(', ', 
5561                  'cust_main.custnum',
5562                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
5563                );
5564
5565   my(@extra_headers) = ();
5566   my(@extra_fields)  = ();
5567
5568   if ($params->{'flattened_pkgs'}) {
5569
5570     if ($dbh->{Driver}->{Name} eq 'Pg') {
5571
5572       $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
5573
5574     }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
5575       $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
5576       $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
5577     }else{
5578       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
5579            "omitting packing information from report.";
5580     }
5581
5582     my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
5583
5584     my $sth = dbh->prepare($header_query) or die dbh->errstr;
5585     $sth->execute() or die $sth->errstr;
5586     my $headerrow = $sth->fetchrow_arrayref;
5587     my $headercount = $headerrow ? $headerrow->[0] : 0;
5588     while($headercount) {
5589       unshift @extra_headers, "Package ". $headercount;
5590       unshift @extra_fields, eval q!sub {my $c = shift;
5591                                          my @a = split '\|', $c->magic;
5592                                          my $p = $a[!.--$headercount. q!];
5593                                          $p;
5594                                         };!;
5595     }
5596
5597   }
5598
5599   my $sql_query = {
5600     'table'         => 'cust_main',
5601     'select'        => $select,
5602     'hashref'       => {},
5603     'extra_sql'     => $extra_sql,
5604     'order_by'      => $orderby,
5605     'count_query'   => $count_query,
5606     'extra_headers' => \@extra_headers,
5607     'extra_fields'  => \@extra_fields,
5608   };
5609
5610 }
5611
5612 =item email_search_sql HASHREF
5613
5614 (Class method)
5615
5616 Emails a notice to the specified customers.
5617
5618 Valid parameters are those of the L<search_sql> method, plus the following:
5619
5620 =over 4
5621
5622 =item from
5623
5624 From: address
5625
5626 =item subject
5627
5628 Email Subject:
5629
5630 =item html_body
5631
5632 HTML body
5633
5634 =item text_body
5635
5636 Text body
5637
5638 =item job
5639
5640 Optional job queue job for status updates.
5641
5642 =back
5643
5644 Returns an error message, or false for success.
5645
5646 If an error occurs during any email, stops the enture send and returns that
5647 error.  Presumably if you're getting SMTP errors aborting is better than 
5648 retrying everything.
5649
5650 =cut
5651
5652 sub email_search_sql {
5653   my($class, $params) = @_;
5654
5655   my $from = delete $params->{from};
5656   my $subject = delete $params->{subject};
5657   my $html_body = delete $params->{html_body};
5658   my $text_body = delete $params->{text_body};
5659
5660   my $job = delete $params->{'job'};
5661
5662   my $sql_query = $class->search_sql($params);
5663
5664   my $count_query   = delete($sql_query->{'count_query'});
5665   my $count_sth = dbh->prepare($count_query)
5666     or die "Error preparing $count_query: ". dbh->errstr;
5667   $count_sth->execute
5668     or die "Error executing $count_query: ". $count_sth->errstr;
5669   my $count_arrayref = $count_sth->fetchrow_arrayref;
5670   my $num_cust = $count_arrayref->[0];
5671
5672   #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
5673   #my @extra_fields  = @{ delete($sql_query->{'extra_fields'})  };
5674
5675
5676   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
5677
5678   #eventually order+limit magic to reduce memory use?
5679   foreach my $cust_main ( qsearch($sql_query) ) {
5680
5681     my $to = $cust_main->invoicing_list_emailonly_scalar;
5682     next unless $to;
5683
5684     my $error = send_email(
5685       generate_email(
5686         'from'      => $from,
5687         'to'        => $to,
5688         'subject'   => $subject,
5689         'html_body' => $html_body,
5690         'text_body' => $text_body,
5691       )
5692     );
5693     return $error if $error;
5694
5695     if ( $job ) { #progressbar foo
5696       $num++;
5697       if ( time - $min_sec > $last ) {
5698         my $error = $job->update_statustext(
5699           int( 100 * $num / $num_cust )
5700         );
5701         die $error if $error;
5702         $last = time;
5703       }
5704     }
5705
5706   }
5707
5708   return '';
5709 }
5710
5711 use Storable qw(thaw);
5712 use Data::Dumper;
5713 use MIME::Base64;
5714 sub process_email_search_sql {
5715   my $job = shift;
5716   #warn "$me process_re_X $method for job $job\n" if $DEBUG;
5717
5718   my $param = thaw(decode_base64(shift));
5719   warn Dumper($param) if $DEBUG;
5720
5721   $param->{'job'} = $job;
5722
5723   my $error = FS::cust_main->email_search_sql( $param );
5724   die $error if $error;
5725
5726 }
5727
5728 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
5729
5730 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
5731 records.  Currently, I<first>, I<last> and/or I<company> may be specified (the
5732 appropriate ship_ field is also searched).
5733
5734 Additional options are the same as FS::Record::qsearch
5735
5736 =cut
5737
5738 sub fuzzy_search {
5739   my( $self, $fuzzy, $hash, @opt) = @_;
5740   #$self
5741   $hash ||= {};
5742   my @cust_main = ();
5743
5744   check_and_rebuild_fuzzyfiles();
5745   foreach my $field ( keys %$fuzzy ) {
5746
5747     my $all = $self->all_X($field);
5748     next unless scalar(@$all);
5749
5750     my %match = ();
5751     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5752
5753     my @fcust = ();
5754     foreach ( keys %match ) {
5755       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5756       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5757     }
5758     my %fsaw = ();
5759     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5760   }
5761
5762   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5763   my %saw = ();
5764   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5765
5766   @cust_main;
5767
5768 }
5769
5770 =item masked FIELD
5771
5772 Returns a masked version of the named field
5773
5774 =cut
5775
5776 sub masked {
5777 my ($self,$field) = @_;
5778
5779 # Show last four
5780
5781 'x'x(length($self->getfield($field))-4).
5782   substr($self->getfield($field), (length($self->getfield($field))-4));
5783
5784 }
5785
5786 =back
5787
5788 =head1 SUBROUTINES
5789
5790 =over 4
5791
5792 =item smart_search OPTION => VALUE ...
5793
5794 Accepts the following options: I<search>, the string to search for.  The string
5795 will be searched for as a customer number, phone number, name or company name,
5796 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5797 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5798 skip fuzzy matching when an exact match is found.
5799
5800 Any additional options are treated as an additional qualifier on the search
5801 (i.e. I<agentnum>).
5802
5803 Returns a (possibly empty) array of FS::cust_main objects.
5804
5805 =cut
5806
5807 sub smart_search {
5808   my %options = @_;
5809
5810   #here is the agent virtualization
5811   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5812
5813   my @cust_main = ();
5814
5815   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5816   my $search = delete $options{'search'};
5817   ( my $alphanum_search = $search ) =~ s/\W//g;
5818   
5819   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5820
5821     #false laziness w/Record::ut_phone
5822     my $phonen = "$1-$2-$3";
5823     $phonen .= " x$4" if $4;
5824
5825     push @cust_main, qsearch( {
5826       'table'   => 'cust_main',
5827       'hashref' => { %options },
5828       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5829                      ' ( '.
5830                          join(' OR ', map "$_ = '$phonen'",
5831                                           qw( daytime night fax
5832                                               ship_daytime ship_night ship_fax )
5833                              ).
5834                      ' ) '.
5835                      " AND $agentnums_sql", #agent virtualization
5836     } );
5837
5838     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5839       #try looking for matches with extensions unless one was specified
5840
5841       push @cust_main, qsearch( {
5842         'table'   => 'cust_main',
5843         'hashref' => { %options },
5844         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5845                        ' ( '.
5846                            join(' OR ', map "$_ LIKE '$phonen\%'",
5847                                             qw( daytime night
5848                                                 ship_daytime ship_night )
5849                                ).
5850                        ' ) '.
5851                        " AND $agentnums_sql", #agent virtualization
5852       } );
5853
5854     }
5855
5856   # custnum search (also try agent_custid), with some tweaking options if your
5857   # legacy cust "numbers" have letters
5858   } elsif ( $search =~ /^\s*(\d+)\s*$/
5859             || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5860                  && $search =~ /^\s*(\w\w?\d+)\s*$/
5861                )
5862           )
5863   {
5864
5865     push @cust_main, qsearch( {
5866       'table'     => 'cust_main',
5867       'hashref'   => { 'custnum' => $1, %options },
5868       'extra_sql' => " AND $agentnums_sql", #agent virtualization
5869     } );
5870
5871     push @cust_main, qsearch( {
5872       'table'     => 'cust_main',
5873       'hashref'   => { 'agent_custid' => $1, %options },
5874       'extra_sql' => " AND $agentnums_sql", #agent virtualization
5875     } );
5876
5877   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5878
5879     my($company, $last, $first) = ( $1, $2, $3 );
5880
5881     # "Company (Last, First)"
5882     #this is probably something a browser remembered,
5883     #so just do an exact search
5884
5885     foreach my $prefix ( '', 'ship_' ) {
5886       push @cust_main, qsearch( {
5887         'table'     => 'cust_main',
5888         'hashref'   => { $prefix.'first'   => $first,
5889                          $prefix.'last'    => $last,
5890                          $prefix.'company' => $company,
5891                          %options,
5892                        },
5893         'extra_sql' => " AND $agentnums_sql",
5894       } );
5895     }
5896
5897   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5898                                               # try (ship_){last,company}
5899
5900     my $value = lc($1);
5901
5902     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5903     # # full strings the browser remembers won't work
5904     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5905
5906     use Lingua::EN::NameParse;
5907     my $NameParse = new Lingua::EN::NameParse(
5908              auto_clean     => 1,
5909              allow_reversed => 1,
5910     );
5911
5912     my($last, $first) = ( '', '' );
5913     #maybe disable this too and just rely on NameParse?
5914     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5915     
5916       ($last, $first) = ( $1, $2 );
5917     
5918     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
5919     } elsif ( ! $NameParse->parse($value) ) {
5920
5921       my %name = $NameParse->components;
5922       $first = $name{'given_name_1'};
5923       $last  = $name{'surname_1'};
5924
5925     }
5926
5927     if ( $first && $last ) {
5928
5929       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5930
5931       #exact
5932       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5933       $sql .= "
5934         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5935            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5936         )";
5937
5938       push @cust_main, qsearch( {
5939         'table'     => 'cust_main',
5940         'hashref'   => \%options,
5941         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5942       } );
5943
5944       # or it just be something that was typed in... (try that in a sec)
5945
5946     }
5947
5948     my $q_value = dbh->quote($value);
5949
5950     #exact
5951     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5952     $sql .= " (    LOWER(last)         = $q_value
5953                 OR LOWER(company)      = $q_value
5954                 OR LOWER(ship_last)    = $q_value
5955                 OR LOWER(ship_company) = $q_value
5956               )";
5957
5958     push @cust_main, qsearch( {
5959       'table'     => 'cust_main',
5960       'hashref'   => \%options,
5961       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5962     } );
5963
5964     #no exact match, trying substring/fuzzy
5965     #always do substring & fuzzy (unless they're explicity config'ed off)
5966     #getting complaints searches are not returning enough
5967     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
5968
5969       #still some false laziness w/search_sql (was search/cust_main.cgi)
5970
5971       #substring
5972
5973       my @hashrefs = (
5974         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
5975         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5976       );
5977
5978       if ( $first && $last ) {
5979
5980         push @hashrefs,
5981           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
5982             'last'         => { op=>'ILIKE', value=>"%$last%" },
5983           },
5984           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
5985             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
5986           },
5987         ;
5988
5989       } else {
5990
5991         push @hashrefs,
5992           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
5993           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
5994         ;
5995       }
5996
5997       foreach my $hashref ( @hashrefs ) {
5998
5999         push @cust_main, qsearch( {
6000           'table'     => 'cust_main',
6001           'hashref'   => { %$hashref,
6002                            %options,
6003                          },
6004           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
6005         } );
6006
6007       }
6008
6009       #fuzzy
6010       my @fuzopts = (
6011         \%options,                #hashref
6012         '',                       #select
6013         " AND $agentnums_sql",    #extra_sql  #agent virtualization
6014       );
6015
6016       if ( $first && $last ) {
6017         push @cust_main, FS::cust_main->fuzzy_search(
6018           { 'last'   => $last,    #fuzzy hashref
6019             'first'  => $first }, #
6020           @fuzopts
6021         );
6022       }
6023       foreach my $field ( 'last', 'company' ) {
6024         push @cust_main,
6025           FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
6026       }
6027
6028     }
6029
6030     #eliminate duplicates
6031     my %saw = ();
6032     @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6033
6034   }
6035
6036   @cust_main;
6037
6038 }
6039
6040 =item email_search
6041
6042 Accepts the following options: I<email>, the email address to search for.  The
6043 email address will be searched for as an email invoice destination and as an
6044 svc_acct account.
6045
6046 #Any additional options are treated as an additional qualifier on the search
6047 #(i.e. I<agentnum>).
6048
6049 Returns a (possibly empty) array of FS::cust_main objects (but usually just
6050 none or one).
6051
6052 =cut
6053
6054 sub email_search {
6055   my %options = @_;
6056
6057   local($DEBUG) = 1;
6058
6059   my $email = delete $options{'email'};
6060
6061   #we're only being used by RT at the moment... no agent virtualization yet
6062   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
6063
6064   my @cust_main = ();
6065
6066   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
6067
6068     my ( $user, $domain ) = ( $1, $2 );
6069
6070     warn "$me smart_search: searching for $user in domain $domain"
6071       if $DEBUG;
6072
6073     push @cust_main,
6074       map $_->cust_main,
6075           qsearch( {
6076                      'table'     => 'cust_main_invoice',
6077                      'hashref'   => { 'dest' => $email },
6078                    }
6079                  );
6080
6081     push @cust_main,
6082       map  $_->cust_main,
6083       grep $_,
6084       map  $_->cust_svc->cust_pkg,
6085           qsearch( {
6086                      'table'     => 'svc_acct',
6087                      'hashref'   => { 'username' => $user, },
6088                      'extra_sql' =>
6089                        'AND ( SELECT domain FROM svc_domain
6090                                 WHERE svc_acct.domsvc = svc_domain.svcnum
6091                             ) = '. dbh->quote($domain),
6092                    }
6093                  );
6094   }
6095
6096   my %saw = ();
6097   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
6098
6099   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
6100     if $DEBUG;
6101
6102   @cust_main;
6103
6104 }
6105
6106 =item check_and_rebuild_fuzzyfiles
6107
6108 =cut
6109
6110 use vars qw(@fuzzyfields);
6111 @fuzzyfields = ( 'last', 'first', 'company' );
6112
6113 sub check_and_rebuild_fuzzyfiles {
6114   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6115   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
6116 }
6117
6118 =item rebuild_fuzzyfiles
6119
6120 =cut
6121
6122 sub rebuild_fuzzyfiles {
6123
6124   use Fcntl qw(:flock);
6125
6126   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6127   mkdir $dir, 0700 unless -d $dir;
6128
6129   foreach my $fuzzy ( @fuzzyfields ) {
6130
6131     open(LOCK,">>$dir/cust_main.$fuzzy")
6132       or die "can't open $dir/cust_main.$fuzzy: $!";
6133     flock(LOCK,LOCK_EX)
6134       or die "can't lock $dir/cust_main.$fuzzy: $!";
6135
6136     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
6137       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
6138
6139     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
6140       my $sth = dbh->prepare("SELECT $field FROM cust_main".
6141                              " WHERE $field != '' AND $field IS NOT NULL");
6142       $sth->execute or die $sth->errstr;
6143
6144       while ( my $row = $sth->fetchrow_arrayref ) {
6145         print CACHE $row->[0]. "\n";
6146       }
6147
6148     } 
6149
6150     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
6151   
6152     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
6153     close LOCK;
6154   }
6155
6156 }
6157
6158 =item all_X
6159
6160 =cut
6161
6162 sub all_X {
6163   my( $self, $field ) = @_;
6164   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6165   open(CACHE,"<$dir/cust_main.$field")
6166     or die "can't open $dir/cust_main.$field: $!";
6167   my @array = map { chomp; $_; } <CACHE>;
6168   close CACHE;
6169   \@array;
6170 }
6171
6172 =item append_fuzzyfiles LASTNAME COMPANY
6173
6174 =cut
6175
6176 sub append_fuzzyfiles {
6177   #my( $first, $last, $company ) = @_;
6178
6179   &check_and_rebuild_fuzzyfiles;
6180
6181   use Fcntl qw(:flock);
6182
6183   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
6184
6185   foreach my $field (qw( first last company )) {
6186     my $value = shift;
6187
6188     if ( $value ) {
6189
6190       open(CACHE,">>$dir/cust_main.$field")
6191         or die "can't open $dir/cust_main.$field: $!";
6192       flock(CACHE,LOCK_EX)
6193         or die "can't lock $dir/cust_main.$field: $!";
6194
6195       print CACHE "$value\n";
6196
6197       flock(CACHE,LOCK_UN)
6198         or die "can't unlock $dir/cust_main.$field: $!";
6199       close CACHE;
6200     }
6201
6202   }
6203
6204   1;
6205 }
6206
6207 =item batch_import
6208
6209 =cut
6210
6211 sub batch_import {
6212   my $param = shift;
6213   #warn join('-',keys %$param);
6214   my $fh = $param->{filehandle};
6215   my $agentnum = $param->{agentnum};
6216
6217   my $refnum = $param->{refnum};
6218   my $pkgpart = $param->{pkgpart};
6219
6220   #my @fields = @{$param->{fields}};
6221   my $format = $param->{'format'};
6222   my @fields;
6223   my $payby;
6224   if ( $format eq 'simple' ) {
6225     @fields = qw( cust_pkg.setup dayphone first last
6226                   address1 address2 city state zip comments );
6227     $payby = 'BILL';
6228   } elsif ( $format eq 'extended' ) {
6229     @fields = qw( agent_custid refnum
6230                   last first address1 address2 city state zip country
6231                   daytime night
6232                   ship_last ship_first ship_address1 ship_address2
6233                   ship_city ship_state ship_zip ship_country
6234                   payinfo paycvv paydate
6235                   invoicing_list
6236                   cust_pkg.pkgpart
6237                   svc_acct.username svc_acct._password 
6238                 );
6239     $payby = 'BILL';
6240  } elsif ( $format eq 'extended-plus_company' ) {
6241     @fields = qw( agent_custid refnum
6242                   last first company address1 address2 city state zip country
6243                   daytime night
6244                   ship_last ship_first ship_company ship_address1 ship_address2
6245                   ship_city ship_state ship_zip ship_country
6246                   payinfo paycvv paydate
6247                   invoicing_list
6248                   cust_pkg.pkgpart
6249                   svc_acct.username svc_acct._password 
6250                 );
6251     $payby = 'BILL';
6252   } else {
6253     die "unknown format $format";
6254   }
6255
6256   eval "use Text::CSV_XS;";
6257   die $@ if $@;
6258
6259   my $csv = new Text::CSV_XS;
6260   #warn $csv;
6261   #warn $fh;
6262
6263   my $imported = 0;
6264   #my $columns;
6265
6266   local $SIG{HUP} = 'IGNORE';
6267   local $SIG{INT} = 'IGNORE';
6268   local $SIG{QUIT} = 'IGNORE';
6269   local $SIG{TERM} = 'IGNORE';
6270   local $SIG{TSTP} = 'IGNORE';
6271   local $SIG{PIPE} = 'IGNORE';
6272
6273   my $oldAutoCommit = $FS::UID::AutoCommit;
6274   local $FS::UID::AutoCommit = 0;
6275   my $dbh = dbh;
6276   
6277   #while ( $columns = $csv->getline($fh) ) {
6278   my $line;
6279   while ( defined($line=<$fh>) ) {
6280
6281     $csv->parse($line) or do {
6282       $dbh->rollback if $oldAutoCommit;
6283       return "can't parse: ". $csv->error_input();
6284     };
6285
6286     my @columns = $csv->fields();
6287     #warn join('-',@columns);
6288
6289     my %cust_main = (
6290       agentnum => $agentnum,
6291       refnum   => $refnum,
6292       country  => $conf->config('countrydefault') || 'US',
6293       payby    => $payby, #default
6294       paydate  => '12/2037', #default
6295     );
6296     my $billtime = time;
6297     my %cust_pkg = ( pkgpart => $pkgpart );
6298     my %svc_acct = ();
6299     foreach my $field ( @fields ) {
6300
6301       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
6302
6303         #$cust_pkg{$1} = str2time( shift @$columns );
6304         if ( $1 eq 'pkgpart' ) {
6305           $cust_pkg{$1} = shift @columns;
6306         } elsif ( $1 eq 'setup' ) {
6307           $billtime = str2time(shift @columns);
6308         } else {
6309           $cust_pkg{$1} = str2time( shift @columns );
6310         } 
6311
6312       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
6313
6314         $svc_acct{$1} = shift @columns;
6315         
6316       } else {
6317
6318         #refnum interception
6319         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
6320
6321           my $referral = $columns[0];
6322           my %hash = ( 'referral' => $referral,
6323                        'agentnum' => $agentnum,
6324                        'disabled' => '',
6325                      );
6326
6327           my $part_referral = qsearchs('part_referral', \%hash )
6328                               || new FS::part_referral \%hash;
6329
6330           unless ( $part_referral->refnum ) {
6331             my $error = $part_referral->insert;
6332             if ( $error ) {
6333               $dbh->rollback if $oldAutoCommit;
6334               return "can't auto-insert advertising source: $referral: $error";
6335             }
6336           }
6337
6338           $columns[0] = $part_referral->refnum;
6339         }
6340
6341         #$cust_main{$field} = shift @$columns; 
6342         $cust_main{$field} = shift @columns; 
6343       }
6344     }
6345
6346     $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
6347
6348     my $invoicing_list = $cust_main{'invoicing_list'}
6349                            ? [ delete $cust_main{'invoicing_list'} ]
6350                            : [];
6351
6352     my $cust_main = new FS::cust_main ( \%cust_main );
6353
6354     use Tie::RefHash;
6355     tie my %hash, 'Tie::RefHash'; #this part is important
6356
6357     if ( $cust_pkg{'pkgpart'} ) {
6358       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
6359
6360       my @svc_acct = ();
6361       if ( $svc_acct{'username'} ) {
6362         my $part_pkg = $cust_pkg->part_pkg;
6363         unless ( $part_pkg ) {
6364           $dbh->rollback if $oldAutoCommit;
6365           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
6366         } 
6367         $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
6368         push @svc_acct, new FS::svc_acct ( \%svc_acct )
6369       }
6370
6371       $hash{$cust_pkg} = \@svc_acct;
6372     }
6373
6374     my $error = $cust_main->insert( \%hash, $invoicing_list );
6375
6376     if ( $error ) {
6377       $dbh->rollback if $oldAutoCommit;
6378       return "can't insert customer for $line: $error";
6379     }
6380
6381     if ( $format eq 'simple' ) {
6382
6383       #false laziness w/bill.cgi
6384       $error = $cust_main->bill( 'time' => $billtime );
6385       if ( $error ) {
6386         $dbh->rollback if $oldAutoCommit;
6387         return "can't bill customer for $line: $error";
6388       }
6389   
6390       $error = $cust_main->apply_payments_and_credits;
6391       if ( $error ) {
6392         $dbh->rollback if $oldAutoCommit;
6393         return "can't bill customer for $line: $error";
6394       }
6395
6396       $error = $cust_main->collect();
6397       if ( $error ) {
6398         $dbh->rollback if $oldAutoCommit;
6399         return "can't collect customer for $line: $error";
6400       }
6401
6402     }
6403
6404     $imported++;
6405   }
6406
6407   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6408
6409   return "Empty file!" unless $imported;
6410
6411   ''; #no error
6412
6413 }
6414
6415 =item batch_charge
6416
6417 =cut
6418
6419 sub batch_charge {
6420   my $param = shift;
6421   #warn join('-',keys %$param);
6422   my $fh = $param->{filehandle};
6423   my @fields = @{$param->{fields}};
6424
6425   eval "use Text::CSV_XS;";
6426   die $@ if $@;
6427
6428   my $csv = new Text::CSV_XS;
6429   #warn $csv;
6430   #warn $fh;
6431
6432   my $imported = 0;
6433   #my $columns;
6434
6435   local $SIG{HUP} = 'IGNORE';
6436   local $SIG{INT} = 'IGNORE';
6437   local $SIG{QUIT} = 'IGNORE';
6438   local $SIG{TERM} = 'IGNORE';
6439   local $SIG{TSTP} = 'IGNORE';
6440   local $SIG{PIPE} = 'IGNORE';
6441
6442   my $oldAutoCommit = $FS::UID::AutoCommit;
6443   local $FS::UID::AutoCommit = 0;
6444   my $dbh = dbh;
6445   
6446   #while ( $columns = $csv->getline($fh) ) {
6447   my $line;
6448   while ( defined($line=<$fh>) ) {
6449
6450     $csv->parse($line) or do {
6451       $dbh->rollback if $oldAutoCommit;
6452       return "can't parse: ". $csv->error_input();
6453     };
6454
6455     my @columns = $csv->fields();
6456     #warn join('-',@columns);
6457
6458     my %row = ();
6459     foreach my $field ( @fields ) {
6460       $row{$field} = shift @columns;
6461     }
6462
6463     my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
6464     unless ( $cust_main ) {
6465       $dbh->rollback if $oldAutoCommit;
6466       return "unknown custnum $row{'custnum'}";
6467     }
6468
6469     if ( $row{'amount'} > 0 ) {
6470       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
6471       if ( $error ) {
6472         $dbh->rollback if $oldAutoCommit;
6473         return $error;
6474       }
6475       $imported++;
6476     } elsif ( $row{'amount'} < 0 ) {
6477       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
6478                                       $row{'pkg'}                         );
6479       if ( $error ) {
6480         $dbh->rollback if $oldAutoCommit;
6481         return $error;
6482       }
6483       $imported++;
6484     } else {
6485       #hmm?
6486     }
6487
6488   }
6489
6490   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
6491
6492   return "Empty file!" unless $imported;
6493
6494   ''; #no error
6495
6496 }
6497
6498 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6499
6500 Sends a templated email notification to the customer (see L<Text::Template>).
6501
6502 OPTIONS is a hash and may include
6503
6504 I<from> - the email sender (default is invoice_from)
6505
6506 I<to> - comma-separated scalar or arrayref of recipients 
6507    (default is invoicing_list)
6508
6509 I<subject> - The subject line of the sent email notification
6510    (default is "Notice from company_name")
6511
6512 I<extra_fields> - a hashref of name/value pairs which will be substituted
6513    into the template
6514
6515 The following variables are vavailable in the template.
6516
6517 I<$first> - the customer first name
6518 I<$last> - the customer last name
6519 I<$company> - the customer company
6520 I<$payby> - a description of the method of payment for the customer
6521             # would be nice to use FS::payby::shortname
6522 I<$payinfo> - the account information used to collect for this customer
6523 I<$expdate> - the expiration of the customer payment in seconds from epoch
6524
6525 =cut
6526
6527 sub notify {
6528   my ($customer, $template, %options) = @_;
6529
6530   return unless $conf->exists($template);
6531
6532   my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
6533   $from = $options{from} if exists($options{from});
6534
6535   my $to = join(',', $customer->invoicing_list_emailonly);
6536   $to = $options{to} if exists($options{to});
6537   
6538   my $subject = "Notice from " . $conf->config('company_name')
6539     if $conf->exists('company_name');
6540   $subject = $options{subject} if exists($options{subject});
6541
6542   my $notify_template = new Text::Template (TYPE => 'ARRAY',
6543                                             SOURCE => [ map "$_\n",
6544                                               $conf->config($template)]
6545                                            )
6546     or die "can't create new Text::Template object: Text::Template::ERROR";
6547   $notify_template->compile()
6548     or die "can't compile template: Text::Template::ERROR";
6549
6550   $FS::notify_template::_template::company_name = $conf->config('company_name');
6551   $FS::notify_template::_template::company_address =
6552     join("\n", $conf->config('company_address') ). "\n";
6553
6554   my $paydate = $customer->paydate || '2037-12-31';
6555   $FS::notify_template::_template::first = $customer->first;
6556   $FS::notify_template::_template::last = $customer->last;
6557   $FS::notify_template::_template::company = $customer->company;
6558   $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
6559   my $payby = $customer->payby;
6560   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6561   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6562
6563   #credit cards expire at the end of the month/year of their exp date
6564   if ($payby eq 'CARD' || $payby eq 'DCRD') {
6565     $FS::notify_template::_template::payby = 'credit card';
6566     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6567     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6568     $expire_time--;
6569   }elsif ($payby eq 'COMP') {
6570     $FS::notify_template::_template::payby = 'complimentary account';
6571   }else{
6572     $FS::notify_template::_template::payby = 'current method';
6573   }
6574   $FS::notify_template::_template::expdate = $expire_time;
6575
6576   for (keys %{$options{extra_fields}}){
6577     no strict "refs";
6578     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
6579   }
6580
6581   send_email(from => $from,
6582              to => $to,
6583              subject => $subject,
6584              body => $notify_template->fill_in( PACKAGE =>
6585                                                 'FS::notify_template::_template'                                              ),
6586             );
6587
6588 }
6589
6590 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
6591
6592 Generates a templated notification to the customer (see L<Text::Template>).
6593
6594 OPTIONS is a hash and may include
6595
6596 I<extra_fields> - a hashref of name/value pairs which will be substituted
6597    into the template.  These values may override values mentioned below
6598    and those from the customer record.
6599
6600 The following variables are available in the template instead of or in addition
6601 to the fields of the customer record.
6602
6603 I<$payby> - a description of the method of payment for the customer
6604             # would be nice to use FS::payby::shortname
6605 I<$payinfo> - the masked account information used to collect for this customer
6606 I<$expdate> - the expiration of the customer payment method in seconds from epoch
6607 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress or company_address
6608
6609 =cut
6610
6611 sub generate_letter {
6612   my ($self, $template, %options) = @_;
6613
6614   return unless $conf->exists($template);
6615
6616   my $letter_template = new Text::Template
6617                         ( TYPE       => 'ARRAY',
6618                           SOURCE     => [ map "$_\n", $conf->config($template)],
6619                           DELIMITERS => [ '[@--', '--@]' ],
6620                         )
6621     or die "can't create new Text::Template object: Text::Template::ERROR";
6622
6623   $letter_template->compile()
6624     or die "can't compile template: Text::Template::ERROR";
6625
6626   my %letter_data = map { $_ => $self->$_ } $self->fields;
6627   $letter_data{payinfo} = $self->mask_payinfo;
6628
6629   #my $paydate = $self->paydate || '2037-12-31';
6630   my $paydate = $self->paydate =~ /^\S+$/ ? $self->paydate : '2037-12-31';
6631
6632   my $payby = $self->payby;
6633   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
6634   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
6635
6636   #credit cards expire at the end of the month/year of their exp date
6637   if ($payby eq 'CARD' || $payby eq 'DCRD') {
6638     $letter_data{payby} = 'credit card';
6639     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
6640     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
6641     $expire_time--;
6642   }elsif ($payby eq 'COMP') {
6643     $letter_data{payby} = 'complimentary account';
6644   }else{
6645     $letter_data{payby} = 'current method';
6646   }
6647   $letter_data{expdate} = $expire_time;
6648
6649   for (keys %{$options{extra_fields}}){
6650     $letter_data{$_} = $options{extra_fields}->{$_};
6651   }
6652
6653   unless(exists($letter_data{returnaddress})){
6654     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
6655                                                   $self->agent_template)
6656                      );
6657     if ( length($retadd) ) {
6658       $letter_data{returnaddress} = $retadd;
6659     } elsif ( grep /\S/, $conf->config('company_address') ) {
6660       $letter_data{returnaddress} =
6661         join( '\\*'."\n", map s/( {2,})/'~' x length($1)/eg,
6662                           $conf->config('company_address')
6663         );
6664     } else {
6665       $letter_data{returnaddress} = '~';
6666     }
6667   }
6668
6669   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
6670
6671   $letter_data{company_name} = $conf->config('company_name');
6672
6673   my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
6674   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
6675                            DIR      => $dir,
6676                            SUFFIX   => '.tex',
6677                            UNLINK   => 0,
6678                          ) or die "can't open temp file: $!\n";
6679
6680   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
6681   close $fh;
6682   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
6683   return $1;
6684 }
6685
6686 =item print_ps TEMPLATE 
6687
6688 Returns an postscript letter filled in from TEMPLATE, as a scalar.
6689
6690 =cut
6691
6692 sub print_ps {
6693   my $self = shift;
6694   my $file = $self->generate_letter(@_);
6695   FS::Misc::generate_ps($file);
6696 }
6697
6698 =item print TEMPLATE
6699
6700 Prints the filled in template.
6701
6702 TEMPLATE is the name of a L<Text::Template> to fill in and print.
6703
6704 =cut
6705
6706 sub queueable_print {
6707   my %opt = @_;
6708
6709   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
6710     or die "invalid customer number: " . $opt{custvnum};
6711
6712   my $error = $self->print( $opt{template} );
6713   die $error if $error;
6714 }
6715
6716 sub print {
6717   my ($self, $template) = (shift, shift);
6718   do_print [ $self->print_ps($template) ];
6719 }
6720
6721 sub agent_template {
6722   my $self = shift;
6723   $self->_agent_plandata('agent_templatename');
6724 }
6725
6726 sub agent_invoice_from {
6727   my $self = shift;
6728   $self->_agent_plandata('agent_invoice_from');
6729 }
6730
6731 sub _agent_plandata {
6732   my( $self, $option ) = @_;
6733
6734   #yuck.  this whole thing needs to be reconciled better with 1.9's idea of
6735   #agent-specific Conf
6736
6737   use FS::part_event::Condition;
6738   
6739   my $agentnum = $self->agentnum;
6740
6741   my $regexp = '';
6742   if ( driver_name =~ /^Pg/i ) {
6743     $regexp = '~';
6744   } elsif ( driver_name =~ /^mysql/i ) {
6745     $regexp = 'REGEXP';
6746   } else {
6747     die "don't know how to use regular expressions in ". driver_name. " databases";
6748   }
6749
6750   my $part_event_option =
6751     qsearchs({
6752       'select'    => 'part_event_option.*',
6753       'table'     => 'part_event_option',
6754       'addl_from' => q{
6755         LEFT JOIN part_event USING ( eventpart )
6756         LEFT JOIN part_event_option AS peo_agentnum
6757           ON ( part_event.eventpart = peo_agentnum.eventpart
6758                AND peo_agentnum.optionname = 'agentnum'
6759                AND peo_agentnum.optionvalue }. $regexp. q{ '(^|,)}. $agentnum. q{(,|$)'
6760              )
6761         LEFT JOIN part_event_option AS peo_cust_bill_age
6762           ON ( part_event.eventpart = peo_cust_bill_age.eventpart
6763                AND peo_cust_bill_age.optionname = 'cust_bill_age'
6764              )
6765       },
6766       #'hashref'   => { 'optionname' => $option },
6767       #'hashref'   => { 'part_event_option.optionname' => $option },
6768       'extra_sql' =>
6769         " WHERE part_event_option.optionname = ". dbh->quote($option).
6770         " AND action = 'cust_bill_send_agent' ".
6771         " AND ( disabled IS NULL OR disabled != 'Y' ) ".
6772         " AND peo_agentnum.optionname = 'agentnum' ".
6773         " AND agentnum IS NULL OR agentnum = $agentnum ".
6774         " ORDER BY
6775            CASE WHEN peo_cust_bill_age.optionname != 'cust_bill_age'
6776            THEN -1
6777            ELSE ". FS::part_event::Condition->age2seconds_sql('peo_cust_bill_age.optionvalue').
6778         " END
6779           , part_event.weight".
6780         " LIMIT 1"
6781     });
6782     
6783   unless ( $part_event_option ) {
6784     return $self->agent->invoice_template || ''
6785       if $option eq 'agent_templatename';
6786     return '';
6787   }
6788
6789   $part_event_option->optionvalue;
6790
6791 }
6792
6793 sub queued_bill {
6794   ## actual sub, not a method, designed to be called from the queue.
6795   ## sets up the customer, and calls the bill_and_collect
6796   my (%args) = @_; #, ($time, $invoice_time, $check_freq, $resetup) = @_;
6797   my $cust_main = qsearchs( 'cust_main', { custnum => $args{'custnum'} } );
6798       $cust_main->bill_and_collect(
6799         %args,
6800       );
6801 }
6802
6803 =back
6804
6805 =head1 BUGS
6806
6807 The delete method.
6808
6809 The delete method should possibly take an FS::cust_main object reference
6810 instead of a scalar customer number.
6811
6812 Bill and collect options should probably be passed as references instead of a
6813 list.
6814
6815 There should probably be a configuration file with a list of allowed credit
6816 card types.
6817
6818 No multiple currency support (probably a larger project than just this module).
6819
6820 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6821
6822 Birthdates rely on negative epoch values.
6823
6824 The payby for card/check batches is broken.  With mixed batching, bad
6825 things will happen.
6826
6827 B<collect> I<invoice_time> should be renamed I<time>, like B<bill>.
6828
6829 =head1 SEE ALSO
6830
6831 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6832 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6833 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
6834
6835 =cut
6836
6837 1;
6838