postal invoice fees
[freeside.git] / FS / FS / cust_main.pm
1 package FS::cust_main;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG $me $conf @encrypted_fields
5              $import $skip_fuzzyfiles $ignore_expired_card @paytypes);
6 use vars qw( $realtime_bop_decline_quiet ); #ugh
7 use Safe;
8 use Carp;
9 use Exporter;
10 BEGIN {
11   eval "use Time::Local;";
12   die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
13     if $] < 5.006 && !defined($Time::Local::VERSION);
14   #eval "use Time::Local qw(timelocal timelocal_nocheck);";
15   eval "use Time::Local qw(timelocal_nocheck);";
16 }
17 use Digest::MD5 qw(md5_base64);
18 use Date::Format;
19 use Date::Parse;
20 #use Date::Manip;
21 use String::Approx qw(amatch);
22 use Business::CreditCard 0.28;
23 use Locale::Country;
24 use Data::Dumper;
25 use FS::UID qw( getotaker dbh driver_name );
26 use FS::Record qw( qsearchs qsearch dbdef );
27 use FS::Misc qw( generate_email send_email generate_ps do_print );
28 use FS::Msgcat qw(gettext);
29 use FS::cust_pkg;
30 use FS::cust_svc;
31 use FS::cust_bill;
32 use FS::cust_bill_pkg;
33 use FS::cust_pay;
34 use FS::cust_pay_pending;
35 use FS::cust_pay_void;
36 use FS::cust_credit;
37 use FS::cust_refund;
38 use FS::part_referral;
39 use FS::cust_main_county;
40 use FS::agent;
41 use FS::cust_main_invoice;
42 use FS::cust_credit_bill;
43 use FS::cust_bill_pay;
44 use FS::prepay_credit;
45 use FS::queue;
46 use FS::part_pkg;
47 use FS::part_bill_event qw(due_events);
48 use FS::cust_bill_event;
49 use FS::cust_tax_exempt;
50 use FS::cust_tax_exempt_pkg;
51 use FS::type_pkgs;
52 use FS::payment_gateway;
53 use FS::agent_payment_gateway;
54 use FS::banned_pay;
55 use FS::payinfo_Mixin;
56
57 @ISA = qw( FS::Record FS::payinfo_Mixin );
58
59 @EXPORT_OK = qw( smart_search );
60
61 $realtime_bop_decline_quiet = 0;
62
63 # 1 is mostly method/subroutine entry and options
64 # 2 traces progress of some operations
65 # 3 is even more information including possibly sensitive data
66 $DEBUG = 0;
67 $me = '[FS::cust_main]';
68
69 $import = 0;
70 $skip_fuzzyfiles = 0;
71 $ignore_expired_card = 0;
72
73 @encrypted_fields = ('payinfo', 'paycvv');
74 @paytypes = ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
75
76 #ask FS::UID to run this stuff for us later
77 #$FS::UID::callback{'FS::cust_main'} = sub { 
78 install_callback FS::UID sub { 
79   $conf = new FS::Conf;
80   #yes, need it for stuff below (prolly should be cached)
81 };
82
83 sub _cache {
84   my $self = shift;
85   my ( $hashref, $cache ) = @_;
86   if ( exists $hashref->{'pkgnum'} ) {
87     #@{ $self->{'_pkgnum'} } = ();
88     my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
89     $self->{'_pkgnum'} = $subcache;
90     #push @{ $self->{'_pkgnum'} },
91     FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
92   }
93 }
94
95 =head1 NAME
96
97 FS::cust_main - Object methods for cust_main records
98
99 =head1 SYNOPSIS
100
101   use FS::cust_main;
102
103   $record = new FS::cust_main \%hash;
104   $record = new FS::cust_main { 'column' => 'value' };
105
106   $error = $record->insert;
107
108   $error = $new_record->replace($old_record);
109
110   $error = $record->delete;
111
112   $error = $record->check;
113
114   @cust_pkg = $record->all_pkgs;
115
116   @cust_pkg = $record->ncancelled_pkgs;
117
118   @cust_pkg = $record->suspended_pkgs;
119
120   $error = $record->bill;
121   $error = $record->bill %options;
122   $error = $record->bill 'time' => $time;
123
124   $error = $record->collect;
125   $error = $record->collect %options;
126   $error = $record->collect 'invoice_time'   => $time,
127                           ;
128
129 =head1 DESCRIPTION
130
131 An FS::cust_main object represents a customer.  FS::cust_main inherits from 
132 FS::Record.  The following fields are currently supported:
133
134 =over 4
135
136 =item custnum - primary key (assigned automatically for new customers)
137
138 =item agentnum - agent (see L<FS::agent>)
139
140 =item refnum - Advertising source (see L<FS::part_referral>)
141
142 =item first - name
143
144 =item last - name
145
146 =item ss - social security number (optional)
147
148 =item company - (optional)
149
150 =item address1
151
152 =item address2 - (optional)
153
154 =item city
155
156 =item county - (optional, see L<FS::cust_main_county>)
157
158 =item state - (see L<FS::cust_main_county>)
159
160 =item zip
161
162 =item country - (see L<FS::cust_main_county>)
163
164 =item daytime - phone (optional)
165
166 =item night - phone (optional)
167
168 =item fax - phone (optional)
169
170 =item ship_first - name
171
172 =item ship_last - name
173
174 =item ship_company - (optional)
175
176 =item ship_address1
177
178 =item ship_address2 - (optional)
179
180 =item ship_city
181
182 =item ship_county - (optional, see L<FS::cust_main_county>)
183
184 =item ship_state - (see L<FS::cust_main_county>)
185
186 =item ship_zip
187
188 =item ship_country - (see L<FS::cust_main_county>)
189
190 =item ship_daytime - phone (optional)
191
192 =item ship_night - phone (optional)
193
194 =item ship_fax - phone (optional)
195
196 =item payby - Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
197
198 =item payinfo - Payment Information (See L<FS::payinfo_Mixin> for data format)
199
200 =item paymask - Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
201
202 =item paycvv
203
204 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
205
206 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
207
208 =item paystart_month - start date month (maestro/solo cards only)
209
210 =item paystart_year - start date year (maestro/solo cards only)
211
212 =item payissue - issue number (maestro/solo cards only)
213
214 =item payname - name on card or billing name
215
216 =item payip - IP address from which payment information was received
217
218 =item tax - tax exempt, empty or `Y'
219
220 =item otaker - order taker (assigned automatically, see L<FS::UID>)
221
222 =item comments - comments (optional)
223
224 =item referral_custnum - referring customer number
225
226 =item spool_cdr - Enable individual CDR spooling, 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($conf->config_binary('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   my $old = shift;
1074   my @param = @_;
1075   warn "$me replace called\n"
1076     if $DEBUG;
1077
1078   local $SIG{HUP} = 'IGNORE';
1079   local $SIG{INT} = 'IGNORE';
1080   local $SIG{QUIT} = 'IGNORE';
1081   local $SIG{TERM} = 'IGNORE';
1082   local $SIG{TSTP} = 'IGNORE';
1083   local $SIG{PIPE} = 'IGNORE';
1084
1085   # We absolutely have to have an old vs. new record to make this work.
1086   if (!defined($old)) {
1087     $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
1088   }
1089
1090   my $curuser = $FS::CurrentUser::CurrentUser;
1091   if (    $self->payby eq 'COMP'
1092        && $self->payby ne $old->payby
1093        && ! $curuser->access_right('Complimentary customer')
1094      )
1095   {
1096     return "You are not permitted to create complimentary accounts.";
1097   }
1098
1099   local($ignore_expired_card) = 1
1100     if $old->payby  =~ /^(CARD|DCRD)$/
1101     && $self->payby =~ /^(CARD|DCRD)$/
1102     && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
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   ;
1228   #barf.  need message catalogs.  i18n.  etc.
1229   $error .= "Please select an advertising source."
1230     if $error =~ /^Illegal or empty \(numeric\) refnum: /;
1231   return $error if $error;
1232
1233   return "Unknown agent"
1234     unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1235
1236   return "Unknown refnum"
1237     unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
1238
1239   return "Unknown referring custnum: ". $self->referral_custnum
1240     unless ! $self->referral_custnum 
1241            || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
1242
1243   if ( $self->ss eq '' ) {
1244     $self->ss('');
1245   } else {
1246     my $ss = $self->ss;
1247     $ss =~ s/\D//g;
1248     $ss =~ /^(\d{3})(\d{2})(\d{4})$/
1249       or return "Illegal social security number: ". $self->ss;
1250     $self->ss("$1-$2-$3");
1251   }
1252
1253
1254 # bad idea to disable, causes billing to fail because of no tax rates later
1255 #  unless ( $import ) {
1256     unless ( qsearch('cust_main_county', {
1257       'country' => $self->country,
1258       'state'   => '',
1259      } ) ) {
1260       return "Unknown state/county/country: ".
1261         $self->state. "/". $self->county. "/". $self->country
1262         unless qsearch('cust_main_county',{
1263           'state'   => $self->state,
1264           'county'  => $self->county,
1265           'country' => $self->country,
1266         } );
1267     }
1268 #  }
1269
1270   $error =
1271     $self->ut_phonen('daytime', $self->country)
1272     || $self->ut_phonen('night', $self->country)
1273     || $self->ut_phonen('fax', $self->country)
1274     || $self->ut_zip('zip', $self->country)
1275   ;
1276   return $error if $error;
1277
1278   if ( $conf->exists('cust_main-require_phone')
1279        && ! length($self->daytime) && ! length($self->night)
1280      ) {
1281
1282     my $daytime_label = FS::Msgcat::_gettext('daytime') =~ /^(daytime)?$/
1283                           ? 'Day Phone'
1284                           : FS::Msgcat::_gettext('daytime');
1285     my $night_label = FS::Msgcat::_gettext('night') =~ /^(night)?$/
1286                         ? 'Night Phone'
1287                         : FS::Msgcat::_gettext('night');
1288   
1289     return "$daytime_label or $night_label is required"
1290   
1291   }
1292
1293   if ( $self->has_ship_address
1294        && scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
1295                         $self->addr_fields )
1296      )
1297   {
1298     my $error =
1299       $self->ut_name('ship_last')
1300       || $self->ut_name('ship_first')
1301       || $self->ut_textn('ship_company')
1302       || $self->ut_text('ship_address1')
1303       || $self->ut_textn('ship_address2')
1304       || $self->ut_text('ship_city')
1305       || $self->ut_textn('ship_county')
1306       || $self->ut_textn('ship_state')
1307       || $self->ut_country('ship_country')
1308     ;
1309     return $error if $error;
1310
1311     #false laziness with above
1312     unless ( qsearchs('cust_main_county', {
1313       'country' => $self->ship_country,
1314       'state'   => '',
1315      } ) ) {
1316       return "Unknown ship_state/ship_county/ship_country: ".
1317         $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
1318         unless qsearch('cust_main_county',{
1319           'state'   => $self->ship_state,
1320           'county'  => $self->ship_county,
1321           'country' => $self->ship_country,
1322         } );
1323     }
1324     #eofalse
1325
1326     $error =
1327       $self->ut_phonen('ship_daytime', $self->ship_country)
1328       || $self->ut_phonen('ship_night', $self->ship_country)
1329       || $self->ut_phonen('ship_fax', $self->ship_country)
1330       || $self->ut_zip('ship_zip', $self->ship_country)
1331     ;
1332     return $error if $error;
1333
1334     return "Unit # is required."
1335       if $self->ship_address2 =~ /^\s*$/
1336       && $conf->exists('cust_main-require_address2');
1337
1338   } else { # ship_ info eq billing info, so don't store dup info in database
1339
1340     $self->setfield("ship_$_", '')
1341       foreach $self->addr_fields;
1342
1343     return "Unit # is required."
1344       if $self->address2 =~ /^\s*$/
1345       && $conf->exists('cust_main-require_address2');
1346
1347   }
1348
1349   #$self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY|CASH|WEST|MCRD)$/
1350   #  or return "Illegal payby: ". $self->payby;
1351   #$self->payby($1);
1352   FS::payby->can_payby($self->table, $self->payby)
1353     or return "Illegal payby: ". $self->payby;
1354
1355   $error =    $self->ut_numbern('paystart_month')
1356            || $self->ut_numbern('paystart_year')
1357            || $self->ut_numbern('payissue')
1358            || $self->ut_textn('paytype')
1359   ;
1360   return $error if $error;
1361
1362   if ( $self->payip eq '' ) {
1363     $self->payip('');
1364   } else {
1365     $error = $self->ut_ip('payip');
1366     return $error if $error;
1367   }
1368
1369   # If it is encrypted and the private key is not availaible then we can't
1370   # check the credit card.
1371
1372   my $check_payinfo = 1;
1373
1374   if ($self->is_encrypted($self->payinfo)) {
1375     $check_payinfo = 0;
1376   }
1377
1378   if ( $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
1379
1380     my $payinfo = $self->payinfo;
1381     $payinfo =~ s/\D//g;
1382     $payinfo =~ /^(\d{13,16})$/
1383       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1384     $payinfo = $1;
1385     $self->payinfo($payinfo);
1386     validate($payinfo)
1387       or return gettext('invalid_card'); # . ": ". $self->payinfo;
1388
1389     return gettext('unknown_card_type')
1390       if cardtype($self->payinfo) eq "Unknown";
1391
1392     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1393     if ( $ban ) {
1394       return 'Banned credit card: banned on '.
1395              time2str('%a %h %o at %r', $ban->_date).
1396              ' by '. $ban->otaker.
1397              ' (ban# '. $ban->bannum. ')';
1398     }
1399
1400     if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
1401       if ( cardtype($self->payinfo) eq 'American Express card' ) {
1402         $self->paycvv =~ /^(\d{4})$/
1403           or return "CVV2 (CID) for American Express cards is four digits.";
1404         $self->paycvv($1);
1405       } else {
1406         $self->paycvv =~ /^(\d{3})$/
1407           or return "CVV2 (CVC2/CID) is three digits.";
1408         $self->paycvv($1);
1409       }
1410     } else {
1411       $self->paycvv('');
1412     }
1413
1414     my $cardtype = cardtype($payinfo);
1415     if ( $cardtype =~ /^(Switch|Solo)$/i ) {
1416
1417       return "Start date or issue number is required for $cardtype cards"
1418         unless $self->paystart_month && $self->paystart_year or $self->payissue;
1419
1420       return "Start month must be between 1 and 12"
1421         if $self->paystart_month
1422            and $self->paystart_month < 1 || $self->paystart_month > 12;
1423
1424       return "Start year must be 1990 or later"
1425         if $self->paystart_year
1426            and $self->paystart_year < 1990;
1427
1428       return "Issue number must be beween 1 and 99"
1429         if $self->payissue
1430           and $self->payissue < 1 || $self->payissue > 99;
1431
1432     } else {
1433       $self->paystart_month('');
1434       $self->paystart_year('');
1435       $self->payissue('');
1436     }
1437
1438   } elsif ( $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
1439
1440     my $payinfo = $self->payinfo;
1441     $payinfo =~ s/[^\d\@]//g;
1442     if ( $conf->exists('echeck-nonus') ) {
1443       $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@aba';
1444       $payinfo = "$1\@$2";
1445     } else {
1446       $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
1447       $payinfo = "$1\@$2";
1448     }
1449     $self->payinfo($payinfo);
1450     $self->paycvv('');
1451
1452     my $ban = qsearchs('banned_pay', $self->_banned_pay_hashref);
1453     if ( $ban ) {
1454       return 'Banned ACH account: banned on '.
1455              time2str('%a %h %o at %r', $ban->_date).
1456              ' by '. $ban->otaker.
1457              ' (ban# '. $ban->bannum. ')';
1458     }
1459
1460   } elsif ( $self->payby eq 'LECB' ) {
1461
1462     my $payinfo = $self->payinfo;
1463     $payinfo =~ s/\D//g;
1464     $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
1465     $payinfo = $1;
1466     $self->payinfo($payinfo);
1467     $self->paycvv('');
1468
1469   } elsif ( $self->payby eq 'BILL' ) {
1470
1471     $error = $self->ut_textn('payinfo');
1472     return "Illegal P.O. number: ". $self->payinfo if $error;
1473     $self->paycvv('');
1474
1475   } elsif ( $self->payby eq 'COMP' ) {
1476
1477     my $curuser = $FS::CurrentUser::CurrentUser;
1478     if (    ! $self->custnum
1479          && ! $curuser->access_right('Complimentary customer')
1480        )
1481     {
1482       return "You are not permitted to create complimentary accounts."
1483     }
1484
1485     $error = $self->ut_textn('payinfo');
1486     return "Illegal comp account issuer: ". $self->payinfo if $error;
1487     $self->paycvv('');
1488
1489   } elsif ( $self->payby eq 'PREPAY' ) {
1490
1491     my $payinfo = $self->payinfo;
1492     $payinfo =~ s/\W//g; #anything else would just confuse things
1493     $self->payinfo($payinfo);
1494     $error = $self->ut_alpha('payinfo');
1495     return "Illegal prepayment identifier: ". $self->payinfo if $error;
1496     return "Unknown prepayment identifier"
1497       unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1498     $self->paycvv('');
1499
1500   }
1501
1502   if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1503     return "Expiration date required"
1504       unless $self->payby =~ /^(BILL|PREPAY|CHEK|DCHK|LECB|CASH|WEST|MCRD)$/;
1505     $self->paydate('');
1506   } else {
1507     my( $m, $y );
1508     if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1509       ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1510     } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1511       ( $m, $y ) = ( $3, "20$2" );
1512     } else {
1513       return "Illegal expiration date: ". $self->paydate;
1514     }
1515     $self->paydate("$y-$m-01");
1516     my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1517     return gettext('expired_card')
1518       if !$import
1519       && !$ignore_expired_card 
1520       && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1521   }
1522
1523   if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1524        ( ! $conf->exists('require_cardname')
1525          || $self->payby !~ /^(CARD|DCRD)$/  ) 
1526   ) {
1527     $self->payname( $self->first. " ". $self->getfield('last') );
1528   } else {
1529     $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1530       or return gettext('illegal_name'). " payname: ". $self->payname;
1531     $self->payname($1);
1532   }
1533
1534   foreach my $flag (qw( tax spool_cdr )) {
1535     $self->$flag() =~ /^(Y?)$/ or return "Illegal $flag: ". $self->$flag();
1536     $self->$flag($1);
1537   }
1538
1539   $self->otaker(getotaker) unless $self->otaker;
1540
1541   warn "$me check AFTER: \n". $self->_dump
1542     if $DEBUG > 2;
1543
1544   $self->SUPER::check;
1545 }
1546
1547 =item addr_fields 
1548
1549 Returns a list of fields which have ship_ duplicates.
1550
1551 =cut
1552
1553 sub addr_fields {
1554   qw( last first company
1555       address1 address2 city county state zip country
1556       daytime night fax
1557     );
1558 }
1559
1560 =item has_ship_address
1561
1562 Returns true if this customer record has a separate shipping address.
1563
1564 =cut
1565
1566 sub has_ship_address {
1567   my $self = shift;
1568   scalar( grep { $self->getfield("ship_$_") ne '' } $self->addr_fields );
1569 }
1570
1571 =item all_pkgs
1572
1573 Returns all packages (see L<FS::cust_pkg>) for this customer.
1574
1575 =cut
1576
1577 sub all_pkgs {
1578   my $self = shift;
1579
1580   return $self->num_pkgs unless wantarray;
1581
1582   my @cust_pkg = ();
1583   if ( $self->{'_pkgnum'} ) {
1584     @cust_pkg = values %{ $self->{'_pkgnum'}->cache };
1585   } else {
1586     @cust_pkg = qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1587   }
1588
1589   sort sort_packages @cust_pkg;
1590 }
1591
1592 =item ncancelled_pkgs
1593
1594 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1595
1596 =cut
1597
1598 sub ncancelled_pkgs {
1599   my $self = shift;
1600
1601   return $self->num_ncancelled_pkgs unless wantarray;
1602
1603   my @cust_pkg = ();
1604   if ( $self->{'_pkgnum'} ) {
1605
1606     @cust_pkg = grep { ! $_->getfield('cancel') }
1607                 values %{ $self->{'_pkgnum'}->cache };
1608
1609   } else {
1610
1611     @cust_pkg =
1612       qsearch( 'cust_pkg', {
1613                              'custnum' => $self->custnum,
1614                              'cancel'  => '',
1615                            });
1616     push @cust_pkg,
1617       qsearch( 'cust_pkg', {
1618                              'custnum' => $self->custnum,
1619                              'cancel'  => 0,
1620                            });
1621   }
1622
1623   sort sort_packages @cust_pkg;
1624
1625 }
1626
1627 # This should be generalized to use config options to determine order.
1628 sub sort_packages {
1629   if ( $a->get('cancel') and $b->get('cancel') ) {
1630     $a->pkgnum <=> $b->pkgnum;
1631   } elsif ( $a->get('cancel') or $b->get('cancel') ) {
1632     return -1 if $b->get('cancel');
1633     return  1 if $a->get('cancel');
1634     return 0;
1635   } else {
1636     $a->pkgnum <=> $b->pkgnum;
1637   }
1638 }
1639
1640 =item suspended_pkgs
1641
1642 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1643
1644 =cut
1645
1646 sub suspended_pkgs {
1647   my $self = shift;
1648   grep { $_->susp } $self->ncancelled_pkgs;
1649 }
1650
1651 =item unflagged_suspended_pkgs
1652
1653 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1654 customer (thouse packages without the `manual_flag' set).
1655
1656 =cut
1657
1658 sub unflagged_suspended_pkgs {
1659   my $self = shift;
1660   return $self->suspended_pkgs
1661     unless dbdef->table('cust_pkg')->column('manual_flag');
1662   grep { ! $_->manual_flag } $self->suspended_pkgs;
1663 }
1664
1665 =item unsuspended_pkgs
1666
1667 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1668 this customer.
1669
1670 =cut
1671
1672 sub unsuspended_pkgs {
1673   my $self = shift;
1674   grep { ! $_->susp } $self->ncancelled_pkgs;
1675 }
1676
1677 =item num_cancelled_pkgs
1678
1679 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1680 customer.
1681
1682 =cut
1683
1684 sub num_cancelled_pkgs {
1685   shift->num_pkgs("cust_pkg.cancel IS NOT NULL AND cust_pkg.cancel != 0");
1686 }
1687
1688 sub num_ncancelled_pkgs {
1689   shift->num_pkgs("( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )");
1690 }
1691
1692 sub num_pkgs {
1693   my( $self ) = shift;
1694   my $sql = scalar(@_) ? shift : '';
1695   $sql = "AND $sql" if $sql && $sql !~ /^\s*$/ && $sql !~ /^\s*AND/i;
1696   my $sth = dbh->prepare(
1697     "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? $sql"
1698   ) or die dbh->errstr;
1699   $sth->execute($self->custnum) or die $sth->errstr;
1700   $sth->fetchrow_arrayref->[0];
1701 }
1702
1703 =item unsuspend
1704
1705 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1706 and L<FS::cust_pkg>) for this customer.  Always returns a list: an empty list
1707 on success or a list of errors.
1708
1709 =cut
1710
1711 sub unsuspend {
1712   my $self = shift;
1713   grep { $_->unsuspend } $self->suspended_pkgs;
1714 }
1715
1716 =item suspend
1717
1718 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1719
1720 Returns a list: an empty list on success or a list of errors.
1721
1722 =cut
1723
1724 sub suspend {
1725   my $self = shift;
1726   grep { $_->suspend(@_) } $self->unsuspended_pkgs;
1727 }
1728
1729 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1730
1731 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1732 PKGPARTs (see L<FS::part_pkg>).
1733
1734 Returns a list: an empty list on success or a list of errors.
1735
1736 =cut
1737
1738 sub suspend_if_pkgpart {
1739   my $self = shift;
1740   my (@pkgparts, %opt);
1741   if (ref($_[0]) eq 'HASH'){
1742     @pkgparts = @{$_[0]{pkgparts}};
1743     %opt      = %{$_[0]};
1744   }else{
1745     @pkgparts = @_;
1746   }
1747   grep { $_->suspend(%opt) }
1748     grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1749       $self->unsuspended_pkgs;
1750 }
1751
1752 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1753
1754 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1755 listed PKGPARTs (see L<FS::part_pkg>).
1756
1757 Returns a list: an empty list on success or a list of errors.
1758
1759 =cut
1760
1761 sub suspend_unless_pkgpart {
1762   my $self = shift;
1763   my (@pkgparts, %opt);
1764   if (ref($_[0]) eq 'HASH'){
1765     @pkgparts = @{$_[0]{pkgparts}};
1766     %opt      = %{$_[0]};
1767   }else{
1768     @pkgparts = @_;
1769   }
1770   grep { $_->suspend(%opt) }
1771     grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1772       $self->unsuspended_pkgs;
1773 }
1774
1775 =item cancel [ OPTION => VALUE ... ]
1776
1777 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1778
1779 Available options are: I<quiet>, I<reasonnum>, and I<ban>
1780
1781 I<quiet> can be set true to supress email cancellation notices.
1782
1783 # I<reasonnum> can be set to a cancellation reason (see L<FS::cancel_reason>)
1784
1785 I<ban> can be set true to ban this customer's credit card or ACH information,
1786 if present.
1787
1788 Always returns a list: an empty list on success or a list of errors.
1789
1790 =cut
1791
1792 sub cancel {
1793   my $self = shift;
1794   my %opt = @_;
1795
1796   if ( $opt{'ban'} && $self->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/ ) {
1797
1798     #should try decryption (we might have the private key)
1799     # and if not maybe queue a job for the server that does?
1800     return ( "Can't (yet) ban encrypted credit cards" )
1801       if $self->is_encrypted($self->payinfo);
1802
1803     my $ban = new FS::banned_pay $self->_banned_pay_hashref;
1804     my $error = $ban->insert;
1805     return ( $error ) if $error;
1806
1807   }
1808
1809   grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1810 }
1811
1812 sub _banned_pay_hashref {
1813   my $self = shift;
1814
1815   my %payby2ban = (
1816     'CARD' => 'CARD',
1817     'DCRD' => 'CARD',
1818     'CHEK' => 'CHEK',
1819     'DCHK' => 'CHEK'
1820   );
1821
1822   {
1823     'payby'   => $payby2ban{$self->payby},
1824     'payinfo' => md5_base64($self->payinfo),
1825     #don't ever *search* on reason! #'reason'  =>
1826   };
1827 }
1828
1829 =item notes
1830
1831 Returns all notes (see L<FS::cust_main_note>) for this customer.
1832
1833 =cut
1834
1835 sub notes {
1836   my $self = shift;
1837   #order by?
1838   qsearch( 'cust_main_note',
1839            { 'custnum' => $self->custnum },
1840            '',
1841            'ORDER BY _DATE DESC'
1842          );
1843 }
1844
1845 =item agent
1846
1847 Returns the agent (see L<FS::agent>) for this customer.
1848
1849 =cut
1850
1851 sub agent {
1852   my $self = shift;
1853   qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1854 }
1855
1856 =item bill OPTIONS
1857
1858 Generates invoices (see L<FS::cust_bill>) for this customer.  Usually used in
1859 conjunction with the collect method.
1860
1861 If there is an error, returns the error, otherwise returns false.
1862
1863 Options are passed as name-value pairs.  Currently available options are:
1864
1865 =over 4
1866
1867 =item resetup - if set true, re-charges setup fees.
1868
1869 =item time - 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:
1870
1871  use Date::Parse;
1872  ...
1873  $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1874
1875 =item invoice_time - 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.
1876
1877 =back
1878
1879 =cut
1880
1881 sub bill {
1882   my( $self, %options ) = @_;
1883   return '' if $self->payby eq 'COMP';
1884   warn "$me bill customer ". $self->custnum. "\n"
1885     if $DEBUG;
1886
1887   my $time = $options{'time'} || time;
1888
1889   my $error;
1890
1891   #put below somehow?
1892   local $SIG{HUP} = 'IGNORE';
1893   local $SIG{INT} = 'IGNORE';
1894   local $SIG{QUIT} = 'IGNORE';
1895   local $SIG{TERM} = 'IGNORE';
1896   local $SIG{TSTP} = 'IGNORE';
1897   local $SIG{PIPE} = 'IGNORE';
1898
1899   my $oldAutoCommit = $FS::UID::AutoCommit;
1900   local $FS::UID::AutoCommit = 0;
1901   my $dbh = dbh;
1902
1903   $self->select_for_update; #mutex
1904
1905   #create a new invoice
1906   #(we'll remove it later if it doesn't actually need to be generated [contains
1907   # no line items] and we're inside a transaciton so nothing else will see it)
1908   my $cust_bill = new FS::cust_bill ( {
1909     'custnum' => $self->custnum,
1910     '_date'   => ( $options{'invoice_time'} || $time ),
1911     #'charged' => $charged,
1912     'charged' => 0,
1913   } );
1914   $error = $cust_bill->insert;
1915   if ( $error ) {
1916     $dbh->rollback if $oldAutoCommit;
1917     return "can't create invoice for customer #". $self->custnum. ": $error";
1918   }
1919   my $invnum = $cust_bill->invnum;
1920
1921   ###
1922   # find the packages which are due for billing, find out how much they are
1923   # & generate invoice database.
1924   ###
1925
1926   my( $total_setup, $total_recur, $postal_charge ) = ( 0, 0, 0 );
1927   my %tax;
1928   my @precommit_hooks = ();
1929
1930   my @cust_pkgs = qsearch('cust_pkg', { 'custnum' => $self->custnum } );
1931   foreach my $cust_pkg (@cust_pkgs) {
1932
1933     #NO!! next if $cust_pkg->cancel;  
1934     next if $cust_pkg->getfield('cancel');  
1935
1936     warn "  bill package ". $cust_pkg->pkgnum. "\n" if $DEBUG > 1;
1937
1938     #? to avoid use of uninitialized value errors... ?
1939     $cust_pkg->setfield('bill', '')
1940       unless defined($cust_pkg->bill);
1941  
1942     my $part_pkg = $cust_pkg->part_pkg;
1943
1944     my %hash = $cust_pkg->hash;
1945     my $old_cust_pkg = new FS::cust_pkg \%hash;
1946
1947     my @details = ();
1948
1949     ###
1950     # bill setup
1951     ###
1952
1953     my $setup = 0;
1954     my $unitsetup = 0;
1955     if ( ! $cust_pkg->setup &&
1956          (
1957            ( $conf->exists('disable_setup_suspended_pkgs') &&
1958             ! $cust_pkg->getfield('susp')
1959           ) || ! $conf->exists('disable_setup_suspended_pkgs')
1960          )
1961       || $options{'resetup'}
1962     ) {
1963     
1964       warn "    bill setup\n" if $DEBUG > 1;
1965
1966       $setup = eval { $cust_pkg->calc_setup( $time, \@details ) };
1967       if ( $@ ) {
1968         $dbh->rollback if $oldAutoCommit;
1969         return "$@ running calc_setup for $cust_pkg\n";
1970       }
1971
1972       $unitsetup = $cust_pkg->part_pkg->unit_setup || $setup; #XXX uuh
1973
1974       $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1975     }
1976
1977     ###
1978     # bill recurring fee
1979     ### 
1980
1981     #XXX unit stuff here too
1982     my $recur = 0;
1983     my $unitrecur = 0;
1984     my $sdate;
1985     if ( $part_pkg->getfield('freq') ne '0' &&
1986          ! $cust_pkg->getfield('susp') &&
1987          ( $cust_pkg->getfield('bill') || 0 ) <= $time
1988     ) {
1989
1990       # XXX should this be a package event?  probably.  events are called
1991       # at collection time at the moment, though...
1992       if ( $part_pkg->can('reset_usage') ) {
1993         warn "    resetting usage counters" if $DEBUG > 1;
1994         $part_pkg->reset_usage($cust_pkg);
1995       }
1996
1997       warn "    bill recur\n" if $DEBUG > 1;
1998
1999       # XXX shared with $recur_prog
2000       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2001
2002       #over two params!  lets at least switch to a hashref for the rest...
2003       my %param = ( 'precommit_hooks' => \@precommit_hooks, );
2004
2005       $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details, \%param ) };
2006       if ( $@ ) {
2007         $dbh->rollback if $oldAutoCommit;
2008         return "$@ running calc_recur for $cust_pkg\n";
2009       }
2010
2011       #change this bit to use Date::Manip? CAREFUL with timezones (see
2012       # mailing list archive)
2013       my ($sec,$min,$hour,$mday,$mon,$year) =
2014         (localtime($sdate) )[0,1,2,3,4,5];
2015
2016       #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
2017       # only for figuring next bill date, nothing else, so, reset $sdate again
2018       # here
2019       $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
2020       $cust_pkg->last_bill($sdate);
2021
2022       if ( $part_pkg->freq =~ /^\d+$/ ) {
2023         $mon += $part_pkg->freq;
2024         until ( $mon < 12 ) { $mon -= 12; $year++; }
2025       } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
2026         my $weeks = $1;
2027         $mday += $weeks * 7;
2028       } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
2029         my $days = $1;
2030         $mday += $days;
2031       } elsif ( $part_pkg->freq =~ /^(\d+)h$/ ) {
2032         my $hours = $1;
2033         $hour += $hours;
2034       } else {
2035         $dbh->rollback if $oldAutoCommit;
2036         return "unparsable frequency: ". $part_pkg->freq;
2037       }
2038       $cust_pkg->setfield('bill',
2039         timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
2040     }
2041
2042     warn "\$setup is undefined" unless defined($setup);
2043     warn "\$recur is undefined" unless defined($recur);
2044     warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
2045
2046     ###
2047     # If $cust_pkg has been modified, update it and create cust_bill_pkg records
2048     ###
2049
2050     if ( $cust_pkg->modified ) {  # hmmm.. and if the options are modified?
2051
2052       warn "  package ". $cust_pkg->pkgnum. " modified; updating\n"
2053         if $DEBUG >1;
2054
2055       $error=$cust_pkg->replace($old_cust_pkg,
2056                                 options => { $cust_pkg->options },
2057                                );
2058       if ( $error ) { #just in case
2059         $dbh->rollback if $oldAutoCommit;
2060         return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
2061       }
2062
2063       $setup = sprintf( "%.2f", $setup );
2064       $recur = sprintf( "%.2f", $recur );
2065       if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
2066         $dbh->rollback if $oldAutoCommit;
2067         return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
2068       }
2069       if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
2070         $dbh->rollback if $oldAutoCommit;
2071         return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
2072       }
2073
2074       if ( $setup != 0 || $recur != 0 ) {
2075
2076         unless ($postal_charge) {
2077           $postal_charge = 1;  # try only once
2078           my $postal_pkg = $self->charge_postal_fee();
2079           if ( $postal_pkg && !ref( $postal_pkg ) ) {
2080             $dbh->rollback if $oldAutoCommit;
2081             return "can't charge postal invoice fee for customer ".
2082               $self->custnum. ": $postal_pkg";
2083           }
2084           push @cust_pkgs, $postal_pkg if $postal_pkg;
2085         }
2086
2087         warn "    charges (setup=$setup, recur=$recur); adding line items\n"
2088           if $DEBUG > 1;
2089         my $cust_bill_pkg = new FS::cust_bill_pkg ({
2090           'invnum'    => $invnum,
2091           'pkgnum'    => $cust_pkg->pkgnum,
2092           'setup'     => $setup,
2093           'unitsetup' => $unitsetup,
2094           'recur'     => $recur,
2095           'unitrecur' => $unitrecur,
2096           'quantity'  => $cust_pkg->quantity,
2097           'sdate'     => $sdate,
2098           'edate'     => $cust_pkg->bill,
2099           'details'   => \@details,
2100         });
2101         $error = $cust_bill_pkg->insert;
2102         if ( $error ) {
2103           $dbh->rollback if $oldAutoCommit;
2104           return "can't create invoice line item for invoice #$invnum: $error";
2105         }
2106         $total_setup += $setup;
2107         $total_recur += $recur;
2108
2109         ###
2110         # handle taxes
2111         ###
2112
2113         unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
2114
2115           my $prefix = 
2116             ( $conf->exists('tax-ship_address') && length($self->ship_last) )
2117             ? 'ship_'
2118             : '';
2119           my %taxhash = map { $_ => $self->get("$prefix$_") }
2120                             qw( state county country );
2121
2122           $taxhash{'taxclass'} = $part_pkg->taxclass;
2123
2124           my @taxes = qsearch( 'cust_main_county', \%taxhash );
2125
2126           unless ( @taxes ) {
2127             $taxhash{'taxclass'} = '';
2128             @taxes =  qsearch( 'cust_main_county', \%taxhash );
2129           }
2130
2131           #one more try at a whole-country tax rate
2132           unless ( @taxes ) {
2133             $taxhash{$_} = '' foreach qw( state county );
2134             @taxes =  qsearch( 'cust_main_county', \%taxhash );
2135           }
2136
2137           # maybe eliminate this entirely, along with all the 0% records
2138           unless ( @taxes ) {
2139             $dbh->rollback if $oldAutoCommit;
2140             return
2141               "fatal: can't find tax rate for state/county/country/taxclass ".
2142               join('/', ( map $self->get("$prefix$_"),
2143                               qw(state county country)
2144                         ),
2145                         $part_pkg->taxclass ). "\n";
2146           }
2147   
2148           foreach my $tax ( @taxes ) {
2149
2150             my $taxable_charged = 0;
2151             $taxable_charged += $setup
2152               unless $part_pkg->setuptax =~ /^Y$/i
2153                   || $tax->setuptax =~ /^Y$/i;
2154             $taxable_charged += $recur
2155               unless $part_pkg->recurtax =~ /^Y$/i
2156                   || $tax->recurtax =~ /^Y$/i;
2157             next unless $taxable_charged;
2158
2159             if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
2160               #my ($mon,$year) = (localtime($sdate) )[4,5];
2161               my ($mon,$year) = (localtime( $sdate || $cust_bill->_date ) )[4,5];
2162               $mon++;
2163               my $freq = $part_pkg->freq || 1;
2164               if ( $freq !~ /(\d+)$/ ) {
2165                 $dbh->rollback if $oldAutoCommit;
2166                 return "daily/weekly package definitions not (yet?)".
2167                        " compatible with monthly tax exemptions";
2168               }
2169               my $taxable_per_month =
2170                 sprintf("%.2f", $taxable_charged / $freq );
2171
2172               #call the whole thing off if this customer has any old
2173               #exemption records...
2174               my @cust_tax_exempt =
2175                 qsearch( 'cust_tax_exempt' => { custnum=> $self->custnum } );
2176               if ( @cust_tax_exempt ) {
2177                 $dbh->rollback if $oldAutoCommit;
2178                 return
2179                   'this customer still has old-style tax exemption records; '.
2180                   'run bin/fs-migrate-cust_tax_exempt?';
2181               }
2182
2183               foreach my $which_month ( 1 .. $freq ) {
2184
2185                 #maintain the new exemption table now
2186                 my $sql = "
2187                   SELECT SUM(amount)
2188                     FROM cust_tax_exempt_pkg
2189                       LEFT JOIN cust_bill_pkg USING ( billpkgnum )
2190                       LEFT JOIN cust_bill     USING ( invnum     )
2191                     WHERE custnum = ?
2192                       AND taxnum  = ?
2193                       AND year    = ?
2194                       AND month   = ?
2195                 ";
2196                 my $sth = dbh->prepare($sql) or do {
2197                   $dbh->rollback if $oldAutoCommit;
2198                   return "fatal: can't lookup exising exemption: ". dbh->errstr;
2199                 };
2200                 $sth->execute(
2201                   $self->custnum,
2202                   $tax->taxnum,
2203                   1900+$year,
2204                   $mon,
2205                 ) or do {
2206                   $dbh->rollback if $oldAutoCommit;
2207                   return "fatal: can't lookup exising exemption: ". dbh->errstr;
2208                 };
2209                 my $existing_exemption = $sth->fetchrow_arrayref->[0] || 0;
2210                 
2211                 my $remaining_exemption =
2212                   $tax->exempt_amount - $existing_exemption;
2213                 if ( $remaining_exemption > 0 ) {
2214                   my $addl = $remaining_exemption > $taxable_per_month
2215                     ? $taxable_per_month
2216                     : $remaining_exemption;
2217                   $taxable_charged -= $addl;
2218
2219                   my $cust_tax_exempt_pkg = new FS::cust_tax_exempt_pkg ( {
2220                     'billpkgnum' => $cust_bill_pkg->billpkgnum,
2221                     'taxnum'     => $tax->taxnum,
2222                     'year'       => 1900+$year,
2223                     'month'      => $mon,
2224                     'amount'     => sprintf("%.2f", $addl ),
2225                   } );
2226                   $error = $cust_tax_exempt_pkg->insert;
2227                   if ( $error ) {
2228                     $dbh->rollback if $oldAutoCommit;
2229                     return "fatal: can't insert cust_tax_exempt_pkg: $error";
2230                   }
2231                 } # if $remaining_exemption > 0
2232
2233                 #++
2234                 $mon++;
2235                 #until ( $mon < 12 ) { $mon -= 12; $year++; }
2236                 until ( $mon < 13 ) { $mon -= 12; $year++; }
2237   
2238               } #foreach $which_month
2239   
2240             } #if $tax->exempt_amount
2241
2242             $taxable_charged = sprintf( "%.2f", $taxable_charged);
2243
2244             #$tax += $taxable_charged * $cust_main_county->tax / 100
2245             $tax{ $tax->taxname || 'Tax' } +=
2246               $taxable_charged * $tax->tax / 100
2247
2248           } #foreach my $tax ( @taxes )
2249
2250         } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
2251
2252       } #if $setup != 0 || $recur != 0
2253       
2254     } #if $cust_pkg->modified
2255
2256   } #foreach my $cust_pkg
2257
2258   unless ( $cust_bill->cust_bill_pkg ) {
2259     $cust_bill->delete; #don't create an invoice w/o line items
2260     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2261     return '';
2262   }
2263
2264   my $charged = sprintf( "%.2f", $total_setup + $total_recur );
2265
2266   foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
2267     my $tax = sprintf("%.2f", $tax{$taxname} );
2268     $charged = sprintf( "%.2f", $charged+$tax );
2269   
2270     my $cust_bill_pkg = new FS::cust_bill_pkg ({
2271       'invnum'   => $invnum,
2272       'pkgnum'   => 0,
2273       'setup'    => $tax,
2274       'recur'    => 0,
2275       'sdate'    => '',
2276       'edate'    => '',
2277       'itemdesc' => $taxname,
2278     });
2279     $error = $cust_bill_pkg->insert;
2280     if ( $error ) {
2281       $dbh->rollback if $oldAutoCommit;
2282       return "can't create invoice line item for invoice #$invnum: $error";
2283     }
2284     $total_setup += $tax;
2285
2286   }
2287
2288   $cust_bill->charged( sprintf( "%.2f", $total_setup + $total_recur ) );
2289   $error = $cust_bill->replace;
2290   if ( $error ) {
2291     $dbh->rollback if $oldAutoCommit;
2292     return "can't update charged for invoice #$invnum: $error";
2293   }
2294
2295   foreach my $hook ( @precommit_hooks ) { 
2296     eval {
2297       &{$hook}; #($self) ?
2298     };
2299     if ( $@ ) {
2300       $dbh->rollback if $oldAutoCommit;
2301       return "$@ running precommit hook $hook\n";
2302     }
2303   }
2304   
2305   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2306   ''; #no error
2307 }
2308
2309 =item collect OPTIONS
2310
2311 (Attempt to) collect money for this customer's outstanding invoices (see
2312 L<FS::cust_bill>).  Usually used after the bill method.
2313
2314 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
2315 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
2316 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
2317
2318 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
2319 and the invoice events web interface.
2320
2321 If there is an error, returns the error, otherwise returns false.
2322
2323 Options are passed as name-value pairs.
2324
2325 Currently available options are:
2326
2327 invoice_time - Use this time when deciding when to print invoices and
2328 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>
2329 for conversion functions.
2330
2331 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
2332 events.
2333
2334 quiet - set true to surpress email card/ACH decline notices.
2335
2336 freq - "1d" for the traditional, daily events (the default), or "1m" for the
2337 new monthly events
2338
2339 payby - allows for one time override of normal customer billing method
2340
2341 =cut
2342
2343 sub collect {
2344   my( $self, %options ) = @_;
2345   my $invoice_time = $options{'invoice_time'} || time;
2346
2347   #put below somehow?
2348   local $SIG{HUP} = 'IGNORE';
2349   local $SIG{INT} = 'IGNORE';
2350   local $SIG{QUIT} = 'IGNORE';
2351   local $SIG{TERM} = 'IGNORE';
2352   local $SIG{TSTP} = 'IGNORE';
2353   local $SIG{PIPE} = 'IGNORE';
2354
2355   my $oldAutoCommit = $FS::UID::AutoCommit;
2356   local $FS::UID::AutoCommit = 0;
2357   my $dbh = dbh;
2358
2359   $self->select_for_update; #mutex
2360
2361   my $balance = $self->balance;
2362   warn "$me collect customer ". $self->custnum. ": balance $balance\n"
2363     if $DEBUG;
2364   unless ( $balance > 0 ) { #redundant?????
2365     $dbh->rollback if $oldAutoCommit; #hmm
2366     return '';
2367   }
2368
2369   if ( exists($options{'retry_card'}) ) {
2370     carp 'retry_card option passed to collect is deprecated; use retry';
2371     $options{'retry'} ||= $options{'retry_card'};
2372   }
2373   if ( exists($options{'retry'}) && $options{'retry'} ) {
2374     my $error = $self->retry_realtime;
2375     if ( $error ) {
2376       $dbh->rollback if $oldAutoCommit;
2377       return $error;
2378     }
2379   }
2380
2381   my $extra_sql = '';
2382   if ( defined $options{'freq'} && $options{'freq'} eq '1m' ) {
2383     $extra_sql = " AND freq = '1m' ";
2384   } else {
2385     $extra_sql = " AND ( freq = '1d' OR freq IS NULL OR freq = '' ) ";
2386   }
2387
2388   foreach my $cust_bill ( $self->open_cust_bill ) {
2389
2390     # don't try to charge for the same invoice if it's already in a batch
2391     #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
2392
2393     last if $self->balance <= 0;
2394
2395     warn "  invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")\n"
2396       if $DEBUG > 1;
2397
2398     foreach my $part_bill_event ( due_events ( $cust_bill,
2399                                                exists($options{'payby'}) 
2400                                                  ? $options{'payby'}
2401                                                  : $self->payby,
2402                                                $invoice_time,
2403                                                $extra_sql ) ) {
2404
2405       last if $cust_bill->owed <= 0  # don't run subsequent events if owed<=0
2406            || $self->balance   <= 0; # or if balance<=0
2407
2408       {
2409         local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
2410         warn "  do_event " .  $cust_bill . " ". (%options) .  "\n"
2411           if $DEBUG > 1;
2412
2413         if (my $error = $part_bill_event->do_event($cust_bill, %options)) {
2414           # gah, even with transactions.
2415           $dbh->commit if $oldAutoCommit; #well.
2416           return $error;
2417         }
2418       }
2419
2420     }
2421
2422   }
2423
2424   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2425   '';
2426
2427 }
2428
2429 =item retry_realtime
2430
2431 Schedules realtime / batch  credit card / electronic check / LEC billing
2432 events for for retry.  Useful if card information has changed or manual
2433 retry is desired.  The 'collect' method must be called to actually retry
2434 the transaction.
2435
2436 Implementation details: For each of this customer's open invoices, changes
2437 the status of the first "done" (with statustext error) realtime processing
2438 event to "failed".
2439
2440 =cut
2441
2442 sub retry_realtime {
2443   my $self = shift;
2444
2445   local $SIG{HUP} = 'IGNORE';
2446   local $SIG{INT} = 'IGNORE';
2447   local $SIG{QUIT} = 'IGNORE';
2448   local $SIG{TERM} = 'IGNORE';
2449   local $SIG{TSTP} = 'IGNORE';
2450   local $SIG{PIPE} = 'IGNORE';
2451
2452   my $oldAutoCommit = $FS::UID::AutoCommit;
2453   local $FS::UID::AutoCommit = 0;
2454   my $dbh = dbh;
2455
2456   foreach my $cust_bill (
2457     grep { $_->cust_bill_event }
2458       $self->open_cust_bill
2459   ) {
2460     my @cust_bill_event =
2461       sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
2462         grep {
2463                #$_->part_bill_event->plan eq 'realtime-card'
2464                $_->part_bill_event->eventcode =~
2465                    /\$cust_bill\->(batch|realtime)_(card|ach|lec)/
2466                  && $_->status eq 'done'
2467                  && $_->statustext
2468              }
2469           $cust_bill->cust_bill_event;
2470     next unless @cust_bill_event;
2471     my $error = $cust_bill_event[0]->retry;
2472     if ( $error ) {
2473       $dbh->rollback if $oldAutoCommit;
2474       return "error scheduling invoice event for retry: $error";
2475     }
2476
2477   }
2478
2479   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2480   '';
2481
2482 }
2483
2484 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
2485
2486 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
2487 via a Business::OnlinePayment realtime gateway.  See
2488 L<http://420.am/business-onlinepayment> for supported gateways.
2489
2490 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2491
2492 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
2493
2494 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2495 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
2496 if set, will override the value from the customer record.
2497
2498 I<description> is a free-text field passed to the gateway.  It defaults to
2499 "Internet services".
2500
2501 If an I<invnum> is specified, this payment (if successful) is applied to the
2502 specified invoice.  If you don't specify an I<invnum> you might want to
2503 call the B<apply_payments> method.
2504
2505 I<quiet> can be set true to surpress email decline notices.
2506
2507 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
2508 resulting paynum, if any.
2509
2510 I<payunique> is a unique identifier for this payment.
2511
2512 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
2513
2514 =back
2515
2516 =cut
2517
2518 sub realtime_bop {
2519   my( $self, $method, $amount, %options ) = @_;
2520   if ( $DEBUG ) {
2521     warn "$me realtime_bop: $method $amount\n";
2522     warn "  $_ => $options{$_}\n" foreach keys %options;
2523   }
2524
2525   $options{'description'} ||= 'Internet services';
2526
2527   eval "use Business::OnlinePayment";  
2528   die $@ if $@;
2529
2530   my $payinfo = exists($options{'payinfo'})
2531                   ? $options{'payinfo'}
2532                   : $self->payinfo;
2533
2534   my %method2payby = (
2535     'CC'     => 'CARD',
2536     'ECHECK' => 'CHEK',
2537     'LEC'    => 'LECB',
2538   );
2539
2540   ###
2541   # select a gateway
2542   ###
2543
2544   my $taxclass = '';
2545   if ( $options{'invnum'} ) {
2546     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
2547     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
2548     my @taxclasses =
2549       map  { $_->part_pkg->taxclass }
2550       grep { $_ }
2551       map  { $_->cust_pkg }
2552       $cust_bill->cust_bill_pkg;
2553     unless ( grep { $taxclasses[0] ne $_ } @taxclasses ) { #unless there are
2554                                                            #different taxclasses
2555       $taxclass = $taxclasses[0];
2556     }
2557   }
2558
2559   #look for an agent gateway override first
2560   my $cardtype;
2561   if ( $method eq 'CC' ) {
2562     $cardtype = cardtype($payinfo);
2563   } elsif ( $method eq 'ECHECK' ) {
2564     $cardtype = 'ACH';
2565   } else {
2566     $cardtype = $method;
2567   }
2568
2569   my $override =
2570        qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2571                                            cardtype => $cardtype,
2572                                            taxclass => $taxclass,       } )
2573     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2574                                            cardtype => '',
2575                                            taxclass => $taxclass,       } )
2576     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2577                                            cardtype => $cardtype,
2578                                            taxclass => '',              } )
2579     || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
2580                                            cardtype => '',
2581                                            taxclass => '',              } );
2582
2583   my $payment_gateway = '';
2584   my( $processor, $login, $password, $action, @bop_options );
2585   if ( $override ) { #use a payment gateway override
2586
2587     $payment_gateway = $override->payment_gateway;
2588
2589     $processor   = $payment_gateway->gateway_module;
2590     $login       = $payment_gateway->gateway_username;
2591     $password    = $payment_gateway->gateway_password;
2592     $action      = $payment_gateway->gateway_action;
2593     @bop_options = $payment_gateway->options;
2594
2595   } else { #use the standard settings from the config
2596
2597     ( $processor, $login, $password, $action, @bop_options ) =
2598       $self->default_payment_gateway($method);
2599
2600   }
2601
2602   ###
2603   # massage data
2604   ###
2605
2606   my $address = exists($options{'address1'})
2607                     ? $options{'address1'}
2608                     : $self->address1;
2609   my $address2 = exists($options{'address2'})
2610                     ? $options{'address2'}
2611                     : $self->address2;
2612   $address .= ", ". $address2 if length($address2);
2613
2614   my $o_payname = exists($options{'payname'})
2615                     ? $options{'payname'}
2616                     : $self->payname;
2617   my($payname, $payfirst, $paylast);
2618   if ( $o_payname && $method ne 'ECHECK' ) {
2619     ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2620       or return "Illegal payname $payname";
2621     ($payfirst, $paylast) = ($1, $2);
2622   } else {
2623     $payfirst = $self->getfield('first');
2624     $paylast = $self->getfield('last');
2625     $payname =  "$payfirst $paylast";
2626   }
2627
2628   my @invoicing_list = $self->invoicing_list_emailonly;
2629   if ( $conf->exists('emailinvoiceautoalways')
2630        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
2631        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
2632     push @invoicing_list, $self->all_emails;
2633   }
2634
2635   my $email = ($conf->exists('business-onlinepayment-email-override'))
2636               ? $conf->config('business-onlinepayment-email-override')
2637               : $invoicing_list[0];
2638
2639   my %content = ();
2640
2641   my $payip = exists($options{'payip'})
2642                 ? $options{'payip'}
2643                 : $self->payip;
2644   $content{customer_ip} = $payip
2645     if length($payip);
2646
2647   $content{invoice_number} = $options{'invnum'}
2648     if exists($options{'invnum'}) && length($options{'invnum'});
2649
2650   $content{email_customer} = 
2651     (    $conf->exists('business-onlinepayment-email_customer')
2652       || $conf->exists('business-onlinepayment-email-override') );
2653       
2654   my $paydate = '';
2655   if ( $method eq 'CC' ) { 
2656
2657     $content{card_number} = $payinfo;
2658     $paydate = exists($options{'paydate'})
2659                     ? $options{'paydate'}
2660                     : $self->paydate;
2661     $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2662     $content{expiration} = "$2/$1";
2663
2664     my $paycvv = exists($options{'paycvv'})
2665                    ? $options{'paycvv'}
2666                    : $self->paycvv;
2667     $content{cvv2} = $paycvv
2668       if length($paycvv);
2669
2670     my $paystart_month = exists($options{'paystart_month'})
2671                            ? $options{'paystart_month'}
2672                            : $self->paystart_month;
2673
2674     my $paystart_year  = exists($options{'paystart_year'})
2675                            ? $options{'paystart_year'}
2676                            : $self->paystart_year;
2677
2678     $content{card_start} = "$paystart_month/$paystart_year"
2679       if $paystart_month && $paystart_year;
2680
2681     my $payissue       = exists($options{'payissue'})
2682                            ? $options{'payissue'}
2683                            : $self->payissue;
2684     $content{issue_number} = $payissue if $payissue;
2685
2686     $content{recurring_billing} = 'YES'
2687       if qsearch('cust_pay', { 'custnum' => $self->custnum,
2688                                'payby'   => 'CARD',
2689                                'payinfo' => $payinfo,
2690                              } )
2691       || qsearch('cust_pay', { 'custnum' => $self->custnum,
2692                                'payby'   => 'CARD',
2693                                'paymask' => $self->mask_payinfo('CARD', $payinfo),
2694                              } );
2695
2696
2697   } elsif ( $method eq 'ECHECK' ) {
2698     ( $content{account_number}, $content{routing_code} ) =
2699       split('@', $payinfo);
2700     $content{bank_name} = $o_payname;
2701     $content{bank_state} = exists($options{'paystate'})
2702                              ? $options{'paystate'}
2703                              : $self->getfield('paystate');
2704     $content{account_type} = exists($options{'paytype'})
2705                                ? uc($options{'paytype'}) || 'CHECKING'
2706                                : uc($self->getfield('paytype')) || 'CHECKING';
2707     $content{account_name} = $payname;
2708     $content{customer_org} = $self->company ? 'B' : 'I';
2709     $content{state_id}       = exists($options{'stateid'})
2710                                  ? $options{'stateid'}
2711                                  : $self->getfield('stateid');
2712     $content{state_id_state} = exists($options{'stateid_state'})
2713                                  ? $options{'stateid_state'}
2714                                  : $self->getfield('stateid_state');
2715     $content{customer_ssn} = exists($options{'ss'})
2716                                ? $options{'ss'}
2717                                : $self->ss;
2718   } elsif ( $method eq 'LEC' ) {
2719     $content{phone} = $payinfo;
2720   }
2721
2722   ###
2723   # run transaction(s)
2724   ###
2725
2726   my $balance = exists( $options{'balance'} )
2727                   ? $options{'balance'}
2728                   : $self->balance;
2729
2730   $self->select_for_update; #mutex ... just until we get our pending record in
2731
2732   #the checks here are intended to catch concurrent payments
2733   #double-form-submission prevention is taken care of in cust_pay_pending::check
2734
2735   #check the balance
2736   return "The customer's balance has changed; $method transaction aborted."
2737     if $self->balance < $balance;
2738     #&& $self->balance < $amount; #might as well anyway?
2739
2740   #also check and make sure there aren't *other* pending payments for this cust
2741
2742   my @pending = qsearch('cust_pay_pending', {
2743     'custnum' => $self->custnum,
2744     'status'  => { op=>'!=', value=>'done' } 
2745   });
2746   return "A payment is already being processed for this customer (".
2747          join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
2748          "); $method transaction aborted."
2749     if scalar(@pending);
2750
2751   #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
2752
2753   my $cust_pay_pending = new FS::cust_pay_pending {
2754     'custnum'    => $self->custnum,
2755     #'invnum'     => $options{'invnum'},
2756     'paid'       => $amount,
2757     '_date'      => '',
2758     'payby'      => $method2payby{$method},
2759     'payinfo'    => $payinfo,
2760     'paydate'    => $paydate,
2761     'status'     => 'new',
2762     'gatewaynum' => ( $payment_gateway ? $payment_gateway->gatewaynum : '' ),
2763   };
2764   $cust_pay_pending->payunique( $options{payunique} )
2765     if defined($options{payunique}) && length($options{payunique});
2766   my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
2767   return $cpp_new_err if $cpp_new_err;
2768
2769   my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
2770
2771   my $transaction = new Business::OnlinePayment( $processor, @bop_options );
2772   $transaction->content(
2773     'type'           => $method,
2774     'login'          => $login,
2775     'password'       => $password,
2776     'action'         => $action1,
2777     'description'    => $options{'description'},
2778     'amount'         => $amount,
2779     #'invoice_number' => $options{'invnum'},
2780     'customer_id'    => $self->custnum,
2781     'last_name'      => $paylast,
2782     'first_name'     => $payfirst,
2783     'name'           => $payname,
2784     'address'        => $address,
2785     'city'           => ( exists($options{'city'})
2786                             ? $options{'city'}
2787                             : $self->city          ),
2788     'state'          => ( exists($options{'state'})
2789                             ? $options{'state'}
2790                             : $self->state          ),
2791     'zip'            => ( exists($options{'zip'})
2792                             ? $options{'zip'}
2793                             : $self->zip          ),
2794     'country'        => ( exists($options{'country'})
2795                             ? $options{'country'}
2796                             : $self->country          ),
2797     'referer'        => 'http://cleanwhisker.420.am/',
2798     'email'          => $email,
2799     'phone'          => $self->daytime || $self->night,
2800     %content, #after
2801   );
2802
2803   $cust_pay_pending->status('pending');
2804   my $cpp_pending_err = $cust_pay_pending->replace;
2805   return $cpp_pending_err if $cpp_pending_err;
2806
2807   $transaction->submit();
2808
2809   if ( $transaction->is_success() && $action2 ) {
2810
2811     $cust_pay_pending->status('authorized');
2812     my $cpp_authorized_err = $cust_pay_pending->replace;
2813     return $cpp_authorized_err if $cpp_authorized_err;
2814
2815     my $auth = $transaction->authorization;
2816     my $ordernum = $transaction->can('order_number')
2817                    ? $transaction->order_number
2818                    : '';
2819
2820     my $capture =
2821       new Business::OnlinePayment( $processor, @bop_options );
2822
2823     my %capture = (
2824       %content,
2825       type           => $method,
2826       action         => $action2,
2827       login          => $login,
2828       password       => $password,
2829       order_number   => $ordernum,
2830       amount         => $amount,
2831       authorization  => $auth,
2832       description    => $options{'description'},
2833     );
2834
2835     foreach my $field (qw( authorization_source_code returned_ACI
2836                            transaction_identifier validation_code           
2837                            transaction_sequence_num local_transaction_date    
2838                            local_transaction_time AVS_result_code          )) {
2839       $capture{$field} = $transaction->$field() if $transaction->can($field);
2840     }
2841
2842     $capture->content( %capture );
2843
2844     $capture->submit();
2845
2846     unless ( $capture->is_success ) {
2847       my $e = "Authorization successful but capture failed, custnum #".
2848               $self->custnum. ': '.  $capture->result_code.
2849               ": ". $capture->error_message;
2850       warn $e;
2851       return $e;
2852     }
2853
2854   }
2855
2856   $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
2857   my $cpp_captured_err = $cust_pay_pending->replace;
2858   return $cpp_captured_err if $cpp_captured_err;
2859
2860   ###
2861   # remove paycvv after initial transaction
2862   ###
2863
2864   #false laziness w/misc/process/payment.cgi - check both to make sure working
2865   # correctly
2866   if ( defined $self->dbdef_table->column('paycvv')
2867        && length($self->paycvv)
2868        && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2869   ) {
2870     my $error = $self->remove_cvv;
2871     if ( $error ) {
2872       warn "WARNING: error removing cvv: $error\n";
2873     }
2874   }
2875
2876   ###
2877   # result handling
2878   ###
2879
2880   if ( $transaction->is_success() ) {
2881
2882     my $paybatch = '';
2883     if ( $payment_gateway ) { # agent override
2884       $paybatch = $payment_gateway->gatewaynum. '-';
2885     }
2886
2887     $paybatch .= "$processor:". $transaction->authorization;
2888
2889     $paybatch .= ':'. $transaction->order_number
2890       if $transaction->can('order_number')
2891       && length($transaction->order_number);
2892
2893     my $cust_pay = new FS::cust_pay ( {
2894        'custnum'  => $self->custnum,
2895        'invnum'   => $options{'invnum'},
2896        'paid'     => $amount,
2897        '_date'     => '',
2898        'payby'    => $method2payby{$method},
2899        'payinfo'  => $payinfo,
2900        'paybatch' => $paybatch,
2901        'paydate'  => $paydate,
2902     } );
2903     #doesn't hurt to know, even though the dup check is in cust_pay_pending now
2904     $cust_pay->payunique( $options{payunique} )
2905       if defined($options{payunique}) && length($options{payunique});
2906
2907     my $oldAutoCommit = $FS::UID::AutoCommit;
2908     local $FS::UID::AutoCommit = 0;
2909     my $dbh = dbh;
2910
2911     #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
2912
2913     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
2914
2915     if ( $error ) {
2916       $cust_pay->invnum(''); #try again with no specific invnum
2917       my $error2 = $cust_pay->insert( $options{'manual'} ?
2918                                       ( 'manual' => 1 ) : ()
2919                                     );
2920       if ( $error2 ) {
2921         # gah.  but at least we have a record of the state we had to abort in
2922         # from cust_pay_pending now.
2923         my $e = "WARNING: $method captured but payment not recorded - ".
2924                 "error inserting payment ($processor): $error2".
2925                 " (previously tried insert with invnum #$options{'invnum'}" .
2926                 ": $error ) - pending payment saved as paypendingnum ".
2927                 $cust_pay_pending->paypendingnum. "\n";
2928         warn $e;
2929         return $e;
2930       }
2931     }
2932
2933     if ( $options{'paynum_ref'} ) {
2934       ${ $options{'paynum_ref'} } = $cust_pay->paynum;
2935     }
2936
2937     $cust_pay_pending->status('done');
2938     $cust_pay_pending->statustext('captured');
2939     my $cpp_done_err = $cust_pay_pending->replace;
2940
2941     if ( $cpp_done_err ) {
2942
2943       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
2944       my $e = "WARNING: $method captured but payment not recorded - ".
2945               "error updating status for paypendingnum ".
2946               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
2947       warn $e;
2948       return $e;
2949
2950     } else {
2951
2952       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2953       return ''; #no error
2954
2955     }
2956
2957   } else {
2958
2959     my $perror = "$processor error: ". $transaction->error_message;
2960
2961     unless ( $transaction->error_message ) {
2962
2963       my $t_response;
2964       #this should be normalized :/
2965       #
2966       # bad, ad-hoc B:OP:PayflowPro "transaction_response" BS
2967       if ( $transaction->can('param')
2968            && $transaction->param('transaction_response') ) {
2969         $t_response = $transaction->param('transaction_response')
2970
2971       # slightly better, ad-hoc B:OP:TransactionCentral without "param"
2972       } elsif ( $transaction->can('response_page') ) {
2973         $t_response = {
2974                         'page'    => ( $transaction->can('response_page')
2975                                          ? $transaction->response_page
2976                                          : ''
2977                                      ),
2978                         'code'    => ( $transaction->can('response_code')
2979                                          ? $transaction->response_code
2980                                          : ''
2981                                      ),
2982                         'headers' => ( $transaction->can('response_headers')
2983                                          ? $transaction->response_headers
2984                                          : ''
2985                                      ),
2986                       };
2987       } else {
2988         $t_response .=
2989           "No additional debugging information available for $processor";
2990       }
2991
2992       $perror .= "No error_message returned from $processor -- ".
2993                  ( ref($t_response) ? Dumper($t_response) : $t_response );
2994
2995     }
2996
2997     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2998          && $conf->exists('emaildecline')
2999          && grep { $_ ne 'POST' } $self->invoicing_list
3000          && ! grep { $transaction->error_message =~ /$_/ }
3001                    $conf->config('emaildecline-exclude')
3002     ) {
3003       my @templ = $conf->config('declinetemplate');
3004       my $template = new Text::Template (
3005         TYPE   => 'ARRAY',
3006         SOURCE => [ map "$_\n", @templ ],
3007       ) or return "($perror) can't create template: $Text::Template::ERROR";
3008       $template->compile()
3009         or return "($perror) can't compile template: $Text::Template::ERROR";
3010
3011       my $templ_hash = { error => $transaction->error_message };
3012
3013       my $error = send_email(
3014         'from'    => $conf->config('invoice_from'),
3015         'to'      => [ grep { $_ ne 'POST' } $self->invoicing_list ],
3016         'subject' => 'Your payment could not be processed',
3017         'body'    => [ $template->fill_in(HASH => $templ_hash) ],
3018       );
3019
3020       $perror .= " (also received error sending decline notification: $error)"
3021         if $error;
3022
3023     }
3024
3025     $cust_pay_pending->status('done');
3026     $cust_pay_pending->statustext("declined: $perror");
3027     my $cpp_done_err = $cust_pay_pending->replace;
3028     if ( $cpp_done_err ) {
3029       my $e = "WARNING: $method declined but pending payment not resolved - ".
3030               "error updating status for paypendingnum ".
3031               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
3032       warn $e;
3033       $perror = "$e ($perror)";
3034     }
3035
3036     return $perror;
3037   }
3038
3039 }
3040
3041 =item default_payment_gateway
3042
3043 =cut
3044
3045 sub default_payment_gateway {
3046   my( $self, $method ) = @_;
3047
3048   die "Real-time processing not enabled\n"
3049     unless $conf->exists('business-onlinepayment');
3050
3051   #load up config
3052   my $bop_config = 'business-onlinepayment';
3053   $bop_config .= '-ach'
3054     if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
3055   my ( $processor, $login, $password, $action, @bop_options ) =
3056     $conf->config($bop_config);
3057   $action ||= 'normal authorization';
3058   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
3059   die "No real-time processor is enabled - ".
3060       "did you set the business-onlinepayment configuration value?\n"
3061     unless $processor;
3062
3063   ( $processor, $login, $password, $action, @bop_options )
3064 }
3065
3066 =item remove_cvv
3067
3068 Removes the I<paycvv> field from the database directly.
3069
3070 If there is an error, returns the error, otherwise returns false.
3071
3072 =cut
3073
3074 sub remove_cvv {
3075   my $self = shift;
3076   my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
3077     or return dbh->errstr;
3078   $sth->execute($self->custnum)
3079     or return $sth->errstr;
3080   $self->paycvv('');
3081   '';
3082 }
3083
3084 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
3085
3086 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
3087 via a Business::OnlinePayment realtime gateway.  See
3088 L<http://420.am/business-onlinepayment> for supported gateways.
3089
3090 Available methods are: I<CC>, I<ECHECK> and I<LEC>
3091
3092 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
3093
3094 Most gateways require a reference to an original payment transaction to refund,
3095 so you probably need to specify a I<paynum>.
3096
3097 I<amount> defaults to the original amount of the payment if not specified.
3098
3099 I<reason> specifies a reason for the refund.
3100
3101 I<paydate> specifies the expiration date for a credit card overriding the
3102 value from the customer record or the payment record. Specified as yyyy-mm-dd
3103
3104 Implementation note: If I<amount> is unspecified or equal to the amount of the
3105 orignal payment, first an attempt is made to "void" the transaction via
3106 the gateway (to cancel a not-yet settled transaction) and then if that fails,
3107 the normal attempt is made to "refund" ("credit") the transaction via the
3108 gateway is attempted.
3109
3110 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
3111 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
3112 #if set, will override the value from the customer record.
3113
3114 #If an I<invnum> is specified, this payment (if successful) is applied to the
3115 #specified invoice.  If you don't specify an I<invnum> you might want to
3116 #call the B<apply_payments> method.
3117
3118 =cut
3119
3120 #some false laziness w/realtime_bop, not enough to make it worth merging
3121 #but some useful small subs should be pulled out
3122 sub realtime_refund_bop {
3123   my( $self, $method, %options ) = @_;
3124   if ( $DEBUG ) {
3125     warn "$me realtime_refund_bop: $method refund\n";
3126     warn "  $_ => $options{$_}\n" foreach keys %options;
3127   }
3128
3129   eval "use Business::OnlinePayment";  
3130   die $@ if $@;
3131
3132   ###
3133   # look up the original payment and optionally a gateway for that payment
3134   ###
3135
3136   my $cust_pay = '';
3137   my $amount = $options{'amount'};
3138
3139   my( $processor, $login, $password, @bop_options ) ;
3140   my( $auth, $order_number ) = ( '', '', '' );
3141
3142   if ( $options{'paynum'} ) {
3143
3144     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
3145     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
3146       or return "Unknown paynum $options{'paynum'}";
3147     $amount ||= $cust_pay->paid;
3148
3149     $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
3150       or return "Can't parse paybatch for paynum $options{'paynum'}: ".
3151                 $cust_pay->paybatch;
3152     my $gatewaynum = '';
3153     ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
3154
3155     if ( $gatewaynum ) { #gateway for the payment to be refunded
3156
3157       my $payment_gateway =
3158         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
3159       die "payment gateway $gatewaynum not found"
3160         unless $payment_gateway;
3161
3162       $processor   = $payment_gateway->gateway_module;
3163       $login       = $payment_gateway->gateway_username;
3164       $password    = $payment_gateway->gateway_password;
3165       @bop_options = $payment_gateway->options;
3166
3167     } else { #try the default gateway
3168
3169       my( $conf_processor, $unused_action );
3170       ( $conf_processor, $login, $password, $unused_action, @bop_options ) =
3171         $self->default_payment_gateway($method);
3172
3173       return "processor of payment $options{'paynum'} $processor does not".
3174              " match default processor $conf_processor"
3175         unless $processor eq $conf_processor;
3176
3177     }
3178
3179
3180   } else { # didn't specify a paynum, so look for agent gateway overrides
3181            # like a normal transaction 
3182
3183     my $cardtype;
3184     if ( $method eq 'CC' ) {
3185       $cardtype = cardtype($self->payinfo);
3186     } elsif ( $method eq 'ECHECK' ) {
3187       $cardtype = 'ACH';
3188     } else {
3189       $cardtype = $method;
3190     }
3191     my $override =
3192            qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3193                                                cardtype => $cardtype,
3194                                                taxclass => '',              } )
3195         || qsearchs('agent_payment_gateway', { agentnum => $self->agentnum,
3196                                                cardtype => '',
3197                                                taxclass => '',              } );
3198
3199     if ( $override ) { #use a payment gateway override
3200  
3201       my $payment_gateway = $override->payment_gateway;
3202
3203       $processor   = $payment_gateway->gateway_module;
3204       $login       = $payment_gateway->gateway_username;
3205       $password    = $payment_gateway->gateway_password;
3206       #$action      = $payment_gateway->gateway_action;
3207       @bop_options = $payment_gateway->options;
3208
3209     } else { #use the standard settings from the config
3210
3211       my $unused_action;
3212       ( $processor, $login, $password, $unused_action, @bop_options ) =
3213         $self->default_payment_gateway($method);
3214
3215     }
3216
3217   }
3218   return "neither amount nor paynum specified" unless $amount;
3219
3220   my %content = (
3221     'type'           => $method,
3222     'login'          => $login,
3223     'password'       => $password,
3224     'order_number'   => $order_number,
3225     'amount'         => $amount,
3226     'referer'        => 'http://cleanwhisker.420.am/',
3227   );
3228   $content{authorization} = $auth
3229     if length($auth); #echeck/ACH transactions have an order # but no auth
3230                       #(at least with authorize.net)
3231
3232   my $disable_void_after;
3233   if ($conf->exists('disable_void_after')
3234       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
3235     $disable_void_after = $1;
3236   }
3237
3238   #first try void if applicable
3239   if ( $cust_pay && $cust_pay->paid == $amount
3240     && (
3241       ( not defined($disable_void_after) )
3242       || ( time < ($cust_pay->_date + $disable_void_after ) )
3243     )
3244   ) {
3245     warn "  attempting void\n" if $DEBUG > 1;
3246     my $void = new Business::OnlinePayment( $processor, @bop_options );
3247     $void->content( 'action' => 'void', %content );
3248     $void->submit();
3249     if ( $void->is_success ) {
3250       my $error = $cust_pay->void($options{'reason'});
3251       if ( $error ) {
3252         # gah, even with transactions.
3253         my $e = 'WARNING: Card/ACH voided but database not updated - '.
3254                 "error voiding payment: $error";
3255         warn $e;
3256         return $e;
3257       }
3258       warn "  void successful\n" if $DEBUG > 1;
3259       return '';
3260     }
3261   }
3262
3263   warn "  void unsuccessful, trying refund\n"
3264     if $DEBUG > 1;
3265
3266   #massage data
3267   my $address = $self->address1;
3268   $address .= ", ". $self->address2 if $self->address2;
3269
3270   my($payname, $payfirst, $paylast);
3271   if ( $self->payname && $method ne 'ECHECK' ) {
3272     $payname = $self->payname;
3273     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
3274       or return "Illegal payname $payname";
3275     ($payfirst, $paylast) = ($1, $2);
3276   } else {
3277     $payfirst = $self->getfield('first');
3278     $paylast = $self->getfield('last');
3279     $payname =  "$payfirst $paylast";
3280   }
3281
3282   my @invoicing_list = $self->invoicing_list_emailonly;
3283   if ( $conf->exists('emailinvoiceautoalways')
3284        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
3285        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
3286     push @invoicing_list, $self->all_emails;
3287   }
3288
3289   my $email = ($conf->exists('business-onlinepayment-email-override'))
3290               ? $conf->config('business-onlinepayment-email-override')
3291               : $invoicing_list[0];
3292
3293   my $payip = exists($options{'payip'})
3294                 ? $options{'payip'}
3295                 : $self->payip;
3296   $content{customer_ip} = $payip
3297     if length($payip);
3298
3299   my $payinfo = '';
3300   if ( $method eq 'CC' ) {
3301
3302     if ( $cust_pay ) {
3303       $content{card_number} = $payinfo = $cust_pay->payinfo;
3304       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
3305         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
3306         ($content{expiration} = "$2/$1");  # where available
3307     } else {
3308       $content{card_number} = $payinfo = $self->payinfo;
3309       (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
3310         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
3311       $content{expiration} = "$2/$1";
3312     }
3313
3314   } elsif ( $method eq 'ECHECK' ) {
3315
3316     if ( $cust_pay ) {
3317       $payinfo = $cust_pay->payinfo;
3318     } else {
3319       $payinfo = $self->payinfo;
3320     } 
3321     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
3322     $content{bank_name} = $self->payname;
3323     $content{account_type} = 'CHECKING';
3324     $content{account_name} = $payname;
3325     $content{customer_org} = $self->company ? 'B' : 'I';
3326     $content{customer_ssn} = $self->ss;
3327   } elsif ( $method eq 'LEC' ) {
3328     $content{phone} = $payinfo = $self->payinfo;
3329   }
3330
3331   #then try refund
3332   my $refund = new Business::OnlinePayment( $processor, @bop_options );
3333   my %sub_content = $refund->content(
3334     'action'         => 'credit',
3335     'customer_id'    => $self->custnum,
3336     'last_name'      => $paylast,
3337     'first_name'     => $payfirst,
3338     'name'           => $payname,
3339     'address'        => $address,
3340     'city'           => $self->city,
3341     'state'          => $self->state,
3342     'zip'            => $self->zip,
3343     'country'        => $self->country,
3344     'email'          => $email,
3345     'phone'          => $self->daytime || $self->night,
3346     %content, #after
3347   );
3348   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
3349     if $DEBUG > 1;
3350   $refund->submit();
3351
3352   return "$processor error: ". $refund->error_message
3353     unless $refund->is_success();
3354
3355   my %method2payby = (
3356     'CC'     => 'CARD',
3357     'ECHECK' => 'CHEK',
3358     'LEC'    => 'LECB',
3359   );
3360
3361   my $paybatch = "$processor:". $refund->authorization;
3362   $paybatch .= ':'. $refund->order_number
3363     if $refund->can('order_number') && $refund->order_number;
3364
3365   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
3366     my @cust_bill_pay = $cust_pay->cust_bill_pay;
3367     last unless @cust_bill_pay;
3368     my $cust_bill_pay = pop @cust_bill_pay;
3369     my $error = $cust_bill_pay->delete;
3370     last if $error;
3371   }
3372
3373   my $cust_refund = new FS::cust_refund ( {
3374     'custnum'  => $self->custnum,
3375     'paynum'   => $options{'paynum'},
3376     'refund'   => $amount,
3377     '_date'    => '',
3378     'payby'    => $method2payby{$method},
3379     'payinfo'  => $payinfo,
3380     'paybatch' => $paybatch,
3381     'reason'   => $options{'reason'} || 'card or ACH refund',
3382   } );
3383   my $error = $cust_refund->insert;
3384   if ( $error ) {
3385     $cust_refund->paynum(''); #try again with no specific paynum
3386     my $error2 = $cust_refund->insert;
3387     if ( $error2 ) {
3388       # gah, even with transactions.
3389       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
3390               "error inserting refund ($processor): $error2".
3391               " (previously tried insert with paynum #$options{'paynum'}" .
3392               ": $error )";
3393       warn $e;
3394       return $e;
3395     }
3396   }
3397
3398   ''; #no error
3399
3400 }
3401
3402 =item batch_card OPTION => VALUE...
3403
3404 Adds a payment for this invoice to the pending credit card batch (see
3405 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
3406 runs the payment using a realtime gateway.
3407
3408 =cut
3409
3410 sub batch_card {
3411   my ($self, %options) = @_;
3412
3413   my $amount;
3414   if (exists($options{amount})) {
3415     $amount = $options{amount};
3416   }else{
3417     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
3418   }
3419   return '' unless $amount > 0;
3420   
3421   my $invnum = delete $options{invnum};
3422   my $payby = $options{invnum} || $self->payby;  #dubious
3423
3424   if ($options{'realtime'}) {
3425     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
3426                                 $amount,
3427                                 %options,
3428                               );
3429   }
3430
3431   my $oldAutoCommit = $FS::UID::AutoCommit;
3432   local $FS::UID::AutoCommit = 0;
3433   my $dbh = dbh;
3434
3435   #this needs to handle mysql as well as Pg, like svc_acct.pm
3436   #(make it into a common function if folks need to do batching with mysql)
3437   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
3438     or return "Cannot lock pay_batch: " . $dbh->errstr;
3439
3440   my %pay_batch = (
3441     'status' => 'O',
3442     'payby'  => FS::payby->payby2payment($payby),
3443   );
3444
3445   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
3446
3447   unless ( $pay_batch ) {
3448     $pay_batch = new FS::pay_batch \%pay_batch;
3449     my $error = $pay_batch->insert;
3450     if ( $error ) {
3451       $dbh->rollback if $oldAutoCommit;
3452       die "error creating new batch: $error\n";
3453     }
3454   }
3455
3456   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
3457       'batchnum' => $pay_batch->batchnum,
3458       'custnum'  => $self->custnum,
3459   } );
3460
3461   foreach (qw( address1 address2 city state zip country payby payinfo paydate
3462                payname )) {
3463     $options{$_} = '' unless exists($options{$_});
3464   }
3465
3466   my $cust_pay_batch = new FS::cust_pay_batch ( {
3467     'batchnum' => $pay_batch->batchnum,
3468     'invnum'   => $invnum || 0,                    # is there a better value?
3469                                                    # this field should be
3470                                                    # removed...
3471                                                    # cust_bill_pay_batch now
3472     'custnum'  => $self->custnum,
3473     'last'     => $self->getfield('last'),
3474     'first'    => $self->getfield('first'),
3475     'address1' => $options{address1} || $self->address1,
3476     'address2' => $options{address2} || $self->address2,
3477     'city'     => $options{city}     || $self->city,
3478     'state'    => $options{state}    || $self->state,
3479     'zip'      => $options{zip}      || $self->zip,
3480     'country'  => $options{country}  || $self->country,
3481     'payby'    => $options{payby}    || $self->payby,
3482     'payinfo'  => $options{payinfo}  || $self->payinfo,
3483     'exp'      => $options{paydate}  || $self->paydate,
3484     'payname'  => $options{payname}  || $self->payname,
3485     'amount'   => $amount,                         # consolidating
3486   } );
3487   
3488   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
3489     if $old_cust_pay_batch;
3490
3491   my $error;
3492   if ($old_cust_pay_batch) {
3493     $error = $cust_pay_batch->replace($old_cust_pay_batch)
3494   } else {
3495     $error = $cust_pay_batch->insert;
3496   }
3497
3498   if ( $error ) {
3499     $dbh->rollback if $oldAutoCommit;
3500     die $error;
3501   }
3502
3503   my $unapplied = $self->total_credited + $self->total_unapplied_payments + $self->in_transit_payments;
3504   foreach my $cust_bill ($self->open_cust_bill) {
3505     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
3506     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
3507       'invnum' => $cust_bill->invnum,
3508       'paybatchnum' => $cust_pay_batch->paybatchnum,
3509       'amount' => $cust_bill->owed,
3510       '_date' => time,
3511     };
3512     if ($unapplied >= $cust_bill_pay_batch->amount){
3513       $unapplied -= $cust_bill_pay_batch->amount;
3514       next;
3515     }else{
3516       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
3517                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
3518     }
3519     $error = $cust_bill_pay_batch->insert;
3520     if ( $error ) {
3521       $dbh->rollback if $oldAutoCommit;
3522       die $error;
3523     }
3524   }
3525
3526   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3527   '';
3528 }
3529
3530 =item total_owed
3531
3532 Returns the total owed for this customer on all invoices
3533 (see L<FS::cust_bill/owed>).
3534
3535 =cut
3536
3537 sub total_owed {
3538   my $self = shift;
3539   $self->total_owed_date(2145859200); #12/31/2037
3540 }
3541
3542 =item total_owed_date TIME
3543
3544 Returns the total owed for this customer on all invoices with date earlier than
3545 TIME.  TIME is specified as a UNIX timestamp; see L<perlfunc/"time">).  Also
3546 see L<Time::Local> and L<Date::Parse> for conversion functions.
3547
3548 =cut
3549
3550 sub total_owed_date {
3551   my $self = shift;
3552   my $time = shift;
3553   my $total_bill = 0;
3554   foreach my $cust_bill (
3555     grep { $_->_date <= $time }
3556       qsearch('cust_bill', { 'custnum' => $self->custnum, } )
3557   ) {
3558     $total_bill += $cust_bill->owed;
3559   }
3560   sprintf( "%.2f", $total_bill );
3561 }
3562
3563 =item apply_payments_and_credits
3564
3565 Applies unapplied payments and credits.
3566
3567 In most cases, this new method should be used in place of sequential
3568 apply_payments and apply_credits methods.
3569
3570 If there is an error, returns the error, otherwise returns false.
3571
3572 =cut
3573
3574 sub apply_payments_and_credits {
3575   my $self = shift;
3576
3577   local $SIG{HUP} = 'IGNORE';
3578   local $SIG{INT} = 'IGNORE';
3579   local $SIG{QUIT} = 'IGNORE';
3580   local $SIG{TERM} = 'IGNORE';
3581   local $SIG{TSTP} = 'IGNORE';
3582   local $SIG{PIPE} = 'IGNORE';
3583
3584   my $oldAutoCommit = $FS::UID::AutoCommit;
3585   local $FS::UID::AutoCommit = 0;
3586   my $dbh = dbh;
3587
3588   $self->select_for_update; #mutex
3589
3590   foreach my $cust_bill ( $self->open_cust_bill ) {
3591     my $error = $cust_bill->apply_payments_and_credits;
3592     if ( $error ) {
3593       $dbh->rollback if $oldAutoCommit;
3594       return "Error applying: $error";
3595     }
3596   }
3597
3598   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3599   ''; #no error
3600
3601 }
3602
3603 =item apply_credits OPTION => VALUE ...
3604
3605 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
3606 to outstanding invoice balances in chronological order (or reverse
3607 chronological order if the I<order> option is set to B<newest>) and returns the
3608 value of any remaining unapplied credits available for refund (see
3609 L<FS::cust_refund>).
3610
3611 Dies if there is an error.
3612
3613 =cut
3614
3615 sub apply_credits {
3616   my $self = shift;
3617   my %opt = @_;
3618
3619   local $SIG{HUP} = 'IGNORE';
3620   local $SIG{INT} = 'IGNORE';
3621   local $SIG{QUIT} = 'IGNORE';
3622   local $SIG{TERM} = 'IGNORE';
3623   local $SIG{TSTP} = 'IGNORE';
3624   local $SIG{PIPE} = 'IGNORE';
3625
3626   my $oldAutoCommit = $FS::UID::AutoCommit;
3627   local $FS::UID::AutoCommit = 0;
3628   my $dbh = dbh;
3629
3630   $self->select_for_update; #mutex
3631
3632   unless ( $self->total_credited ) {
3633     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3634     return 0;
3635   }
3636
3637   my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
3638       qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
3639
3640   my @invoices = $self->open_cust_bill;
3641   @invoices = sort { $b->_date <=> $a->_date } @invoices
3642     if defined($opt{'order'}) && $opt{'order'} eq 'newest';
3643
3644   my $credit;
3645   foreach my $cust_bill ( @invoices ) {
3646     my $amount;
3647
3648     if ( !defined($credit) || $credit->credited == 0) {
3649       $credit = pop @credits or last;
3650     }
3651
3652     if ($cust_bill->owed >= $credit->credited) {
3653       $amount=$credit->credited;
3654     }else{
3655       $amount=$cust_bill->owed;
3656     }
3657     
3658     my $cust_credit_bill = new FS::cust_credit_bill ( {
3659       'crednum' => $credit->crednum,
3660       'invnum'  => $cust_bill->invnum,
3661       'amount'  => $amount,
3662     } );
3663     my $error = $cust_credit_bill->insert;
3664     if ( $error ) {
3665       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3666       die $error;
3667     }
3668     
3669     redo if ($cust_bill->owed > 0);
3670
3671   }
3672
3673   my $total_credited = $self->total_credited;
3674
3675   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3676
3677   return $total_credited;
3678 }
3679
3680 =item apply_payments
3681
3682 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
3683 to outstanding invoice balances in chronological order.
3684
3685  #and returns the value of any remaining unapplied payments.
3686
3687 Dies if there is an error.
3688
3689 =cut
3690
3691 sub apply_payments {
3692   my $self = shift;
3693
3694   local $SIG{HUP} = 'IGNORE';
3695   local $SIG{INT} = 'IGNORE';
3696   local $SIG{QUIT} = 'IGNORE';
3697   local $SIG{TERM} = 'IGNORE';
3698   local $SIG{TSTP} = 'IGNORE';
3699   local $SIG{PIPE} = 'IGNORE';
3700
3701   my $oldAutoCommit = $FS::UID::AutoCommit;
3702   local $FS::UID::AutoCommit = 0;
3703   my $dbh = dbh;
3704
3705   $self->select_for_update; #mutex
3706
3707   #return 0 unless
3708
3709   my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
3710       qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
3711
3712   my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
3713       qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
3714
3715   my $payment;
3716
3717   foreach my $cust_bill ( @invoices ) {
3718     my $amount;
3719
3720     if ( !defined($payment) || $payment->unapplied == 0 ) {
3721       $payment = pop @payments or last;
3722     }
3723
3724     if ( $cust_bill->owed >= $payment->unapplied ) {
3725       $amount = $payment->unapplied;
3726     } else {
3727       $amount = $cust_bill->owed;
3728     }
3729
3730     my $cust_bill_pay = new FS::cust_bill_pay ( {
3731       'paynum' => $payment->paynum,
3732       'invnum' => $cust_bill->invnum,
3733       'amount' => $amount,
3734     } );
3735     my $error = $cust_bill_pay->insert;
3736     if ( $error ) {
3737       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
3738       die $error;
3739     }
3740
3741     redo if ( $cust_bill->owed > 0);
3742
3743   }
3744
3745   my $total_unapplied_payments = $self->total_unapplied_payments;
3746
3747   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3748
3749   return $total_unapplied_payments;
3750 }
3751
3752 =item total_credited
3753
3754 Returns the total outstanding credit (see L<FS::cust_credit>) for this
3755 customer.  See L<FS::cust_credit/credited>.
3756
3757 =cut
3758
3759 sub total_credited {
3760   my $self = shift;
3761   my $total_credit = 0;
3762   foreach my $cust_credit ( qsearch('cust_credit', {
3763     'custnum' => $self->custnum,
3764   } ) ) {
3765     $total_credit += $cust_credit->credited;
3766   }
3767   sprintf( "%.2f", $total_credit );
3768 }
3769
3770 =item total_unapplied_payments
3771
3772 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
3773 See L<FS::cust_pay/unapplied>.
3774
3775 =cut
3776
3777 sub total_unapplied_payments {
3778   my $self = shift;
3779   my $total_unapplied = 0;
3780   foreach my $cust_pay ( qsearch('cust_pay', {
3781     'custnum' => $self->custnum,
3782   } ) ) {
3783     $total_unapplied += $cust_pay->unapplied;
3784   }
3785   sprintf( "%.2f", $total_unapplied );
3786 }
3787
3788 =item total_unapplied_refunds
3789
3790 Returns the total unrefunded refunds (see L<FS::cust_refund>) for this
3791 customer.  See L<FS::cust_refund/unapplied>.
3792
3793 =cut
3794
3795 sub total_unapplied_refunds {
3796   my $self = shift;
3797   my $total_unapplied = 0;
3798   foreach my $cust_refund ( qsearch('cust_refund', {
3799     'custnum' => $self->custnum,
3800   } ) ) {
3801     $total_unapplied += $cust_refund->unapplied;
3802   }
3803   sprintf( "%.2f", $total_unapplied );
3804 }
3805
3806 =item balance
3807
3808 Returns the balance for this customer (total_owed plus total_unrefunded, minus
3809 total_credited minus total_unapplied_payments).
3810
3811 =cut
3812
3813 sub balance {
3814   my $self = shift;
3815   sprintf( "%.2f",
3816       $self->total_owed
3817     + $self->total_unapplied_refunds
3818     - $self->total_credited
3819     - $self->total_unapplied_payments
3820   );
3821 }
3822
3823 =item balance_date TIME
3824
3825 Returns the balance for this customer, only considering invoices with date
3826 earlier than TIME (total_owed_date minus total_credited minus
3827 total_unapplied_payments).  TIME is specified as a UNIX timestamp; see
3828 L<perlfunc/"time">).  Also see L<Time::Local> and L<Date::Parse> for conversion
3829 functions.
3830
3831 =cut
3832
3833 sub balance_date {
3834   my $self = shift;
3835   my $time = shift;
3836   sprintf( "%.2f",
3837         $self->total_owed_date($time)
3838       + $self->total_unapplied_refunds
3839       - $self->total_credited
3840       - $self->total_unapplied_payments
3841   );
3842 }
3843
3844 =item in_transit_payments
3845
3846 Returns the total of requests for payments for this customer pending in 
3847 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
3848
3849 =cut
3850
3851 sub in_transit_payments {
3852   my $self = shift;
3853   my $in_transit_payments = 0;
3854   foreach my $pay_batch ( qsearch('pay_batch', {
3855     'status' => 'I',
3856   } ) ) {
3857     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
3858       'batchnum' => $pay_batch->batchnum,
3859       'custnum' => $self->custnum,
3860     } ) ) {
3861       $in_transit_payments += $cust_pay_batch->amount;
3862     }
3863   }
3864   sprintf( "%.2f", $in_transit_payments );
3865 }
3866
3867 =item paydate_monthyear
3868
3869 Returns a two-element list consisting of the month and year of this customer's
3870 paydate (credit card expiration date for CARD customers)
3871
3872 =cut
3873
3874 sub paydate_monthyear {
3875   my $self = shift;
3876   if ( $self->paydate  =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
3877     ( $2, $1 );
3878   } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
3879     ( $1, $3 );
3880   } else {
3881     ('', '');
3882   }
3883 }
3884
3885 =item invoicing_list [ ARRAYREF ]
3886
3887 If an arguement is given, sets these email addresses as invoice recipients
3888 (see L<FS::cust_main_invoice>).  Errors are not fatal and are not reported
3889 (except as warnings), so use check_invoicing_list first.
3890
3891 Returns a list of email addresses (with svcnum entries expanded).
3892
3893 Note: You can clear the invoicing list by passing an empty ARRAYREF.  You can
3894 check it without disturbing anything by passing nothing.
3895
3896 This interface may change in the future.
3897
3898 =cut
3899
3900 sub invoicing_list {
3901   my( $self, $arrayref ) = @_;
3902
3903   if ( $arrayref ) {
3904     my @cust_main_invoice;
3905     if ( $self->custnum ) {
3906       @cust_main_invoice = 
3907         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3908     } else {
3909       @cust_main_invoice = ();
3910     }
3911     foreach my $cust_main_invoice ( @cust_main_invoice ) {
3912       #warn $cust_main_invoice->destnum;
3913       unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
3914         #warn $cust_main_invoice->destnum;
3915         my $error = $cust_main_invoice->delete;
3916         warn $error if $error;
3917       }
3918     }
3919     if ( $self->custnum ) {
3920       @cust_main_invoice = 
3921         qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3922     } else {
3923       @cust_main_invoice = ();
3924     }
3925     my %seen = map { $_->address => 1 } @cust_main_invoice;
3926     foreach my $address ( @{$arrayref} ) {
3927       next if exists $seen{$address} && $seen{$address};
3928       $seen{$address} = 1;
3929       my $cust_main_invoice = new FS::cust_main_invoice ( {
3930         'custnum' => $self->custnum,
3931         'dest'    => $address,
3932       } );
3933       my $error = $cust_main_invoice->insert;
3934       warn $error if $error;
3935     }
3936   }
3937   
3938   if ( $self->custnum ) {
3939     map { $_->address }
3940       qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
3941   } else {
3942     ();
3943   }
3944
3945 }
3946
3947 =item check_invoicing_list ARRAYREF
3948
3949 Checks these arguements as valid input for the invoicing_list method.  If there
3950 is an error, returns the error, otherwise returns false.
3951
3952 =cut
3953
3954 sub check_invoicing_list {
3955   my( $self, $arrayref ) = @_;
3956
3957   foreach my $address ( @$arrayref ) {
3958
3959     if ($address eq 'FAX' and $self->getfield('fax') eq '') {
3960       return 'Can\'t add FAX invoice destination with a blank FAX number.';
3961     }
3962
3963     my $cust_main_invoice = new FS::cust_main_invoice ( {
3964       'custnum' => $self->custnum,
3965       'dest'    => $address,
3966     } );
3967     my $error = $self->custnum
3968                 ? $cust_main_invoice->check
3969                 : $cust_main_invoice->checkdest
3970     ;
3971     return $error if $error;
3972
3973   }
3974
3975   return "Email address required"
3976     if $conf->exists('cust_main-require_invoicing_list_email')
3977     && ! grep { $_ !~ /^([A-Z]+)$/ } @$arrayref;
3978
3979   '';
3980 }
3981
3982 =item set_default_invoicing_list
3983
3984 Sets the invoicing list to all accounts associated with this customer,
3985 overwriting any previous invoicing list.
3986
3987 =cut
3988
3989 sub set_default_invoicing_list {
3990   my $self = shift;
3991   $self->invoicing_list($self->all_emails);
3992 }
3993
3994 =item all_emails
3995
3996 Returns the email addresses of all accounts provisioned for this customer.
3997
3998 =cut
3999
4000 sub all_emails {
4001   my $self = shift;
4002   my %list;
4003   foreach my $cust_pkg ( $self->all_pkgs ) {
4004     my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
4005     my @svc_acct =
4006       map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4007         grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
4008           @cust_svc;
4009     $list{$_}=1 foreach map { $_->email } @svc_acct;
4010   }
4011   keys %list;
4012 }
4013
4014 =item invoicing_list_addpost
4015
4016 Adds postal invoicing to this customer.  If this customer is already configured
4017 to receive postal invoices, does nothing.
4018
4019 =cut
4020
4021 sub invoicing_list_addpost {
4022   my $self = shift;
4023   return if grep { $_ eq 'POST' } $self->invoicing_list;
4024   my @invoicing_list = $self->invoicing_list;
4025   push @invoicing_list, 'POST';
4026   $self->invoicing_list(\@invoicing_list);
4027 }
4028
4029 =item invoicing_list_emailonly
4030
4031 Returns the list of email invoice recipients (invoicing_list without non-email
4032 destinations such as POST and FAX).
4033
4034 =cut
4035
4036 sub invoicing_list_emailonly {
4037   my $self = shift;
4038   warn "$me invoicing_list_emailonly called"
4039     if $DEBUG;
4040   grep { $_ !~ /^([A-Z]+)$/ } $self->invoicing_list;
4041 }
4042
4043 =item invoicing_list_emailonly_scalar
4044
4045 Returns the list of email invoice recipients (invoicing_list without non-email
4046 destinations such as POST and FAX) as a comma-separated scalar.
4047
4048 =cut
4049
4050 sub invoicing_list_emailonly_scalar {
4051   my $self = shift;
4052   warn "$me invoicing_list_emailonly_scalar called"
4053     if $DEBUG;
4054   join(', ', $self->invoicing_list_emailonly);
4055 }
4056
4057 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
4058
4059 Returns an array of customers referred by this customer (referral_custnum set
4060 to this custnum).  If DEPTH is given, recurses up to the given depth, returning
4061 customers referred by customers referred by this customer and so on, inclusive.
4062 The default behavior is DEPTH 1 (no recursion).
4063
4064 =cut
4065
4066 sub referral_cust_main {
4067   my $self = shift;
4068   my $depth = @_ ? shift : 1;
4069   my $exclude = @_ ? shift : {};
4070
4071   my @cust_main =
4072     map { $exclude->{$_->custnum}++; $_; }
4073       grep { ! $exclude->{ $_->custnum } }
4074         qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
4075
4076   if ( $depth > 1 ) {
4077     push @cust_main,
4078       map { $_->referral_cust_main($depth-1, $exclude) }
4079         @cust_main;
4080   }
4081
4082   @cust_main;
4083 }
4084
4085 =item referral_cust_main_ncancelled
4086
4087 Same as referral_cust_main, except only returns customers with uncancelled
4088 packages.
4089
4090 =cut
4091
4092 sub referral_cust_main_ncancelled {
4093   my $self = shift;
4094   grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
4095 }
4096
4097 =item referral_cust_pkg [ DEPTH ]
4098
4099 Like referral_cust_main, except returns a flat list of all unsuspended (and
4100 uncancelled) packages for each customer.  The number of items in this list may
4101 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
4102
4103 =cut
4104
4105 sub referral_cust_pkg {
4106   my $self = shift;
4107   my $depth = @_ ? shift : 1;
4108
4109   map { $_->unsuspended_pkgs }
4110     grep { $_->unsuspended_pkgs }
4111       $self->referral_cust_main($depth);
4112 }
4113
4114 =item referring_cust_main
4115
4116 Returns the single cust_main record for the customer who referred this customer
4117 (referral_custnum), or false.
4118
4119 =cut
4120
4121 sub referring_cust_main {
4122   my $self = shift;
4123   return '' unless $self->referral_custnum;
4124   qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
4125 }
4126
4127 =item credit AMOUNT, REASON
4128
4129 Applies a credit to this customer.  If there is an error, returns the error,
4130 otherwise returns false.
4131
4132 =cut
4133
4134 sub credit {
4135   my( $self, $amount, $reason, %options ) = @_;
4136   my $cust_credit = new FS::cust_credit {
4137     'custnum' => $self->custnum,
4138     'amount'  => $amount,
4139     'reason'  => $reason,
4140   };
4141   $cust_credit->insert(%options);
4142 }
4143
4144 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
4145
4146 Creates a one-time charge for this customer.  If there is an error, returns
4147 the error, otherwise returns false.
4148
4149 =cut
4150
4151 sub charge {
4152   my $self = shift;
4153   my ( $amount, $quantity, $pkg, $comment, $taxclass, $additional, $classnum );
4154   if ( ref( $_[0] ) ) {
4155     $amount     = $_[0]->{amount};
4156     $quantity   = exists($_[0]->{quantity}) ? $_[0]->{quantity} : 1;
4157     $pkg        = exists($_[0]->{pkg}) ? $_[0]->{pkg} : 'One-time charge';
4158     $comment    = exists($_[0]->{comment}) ? $_[0]->{comment}
4159                                            : '$'. sprintf("%.2f",$amount);
4160     $taxclass   = exists($_[0]->{taxclass}) ? $_[0]->{taxclass} : '';
4161     $classnum   = exists($_[0]->{classnum}) ? $_[0]->{classnum} : '';
4162     $additional = $_[0]->{additional};
4163   }else{
4164     $amount     = shift;
4165     $quantity   = 1;
4166     $pkg        = @_ ? shift : 'One-time charge';
4167     $comment    = @_ ? shift : '$'. sprintf("%.2f",$amount);
4168     $taxclass   = @_ ? shift : '';
4169     $additional = [];
4170   }
4171
4172   local $SIG{HUP} = 'IGNORE';
4173   local $SIG{INT} = 'IGNORE';
4174   local $SIG{QUIT} = 'IGNORE';
4175   local $SIG{TERM} = 'IGNORE';
4176   local $SIG{TSTP} = 'IGNORE';
4177   local $SIG{PIPE} = 'IGNORE';
4178
4179   my $oldAutoCommit = $FS::UID::AutoCommit;
4180   local $FS::UID::AutoCommit = 0;
4181   my $dbh = dbh;
4182
4183   my $part_pkg = new FS::part_pkg ( {
4184     'pkg'      => $pkg,
4185     'comment'  => $comment,
4186     'plan'     => 'flat',
4187     'freq'     => 0,
4188     'disabled' => 'Y',
4189     'classnum' => $classnum ? $classnum : '',
4190     'taxclass' => $taxclass,
4191   } );
4192
4193   my %options = ( ( map { ("additional_info$_" => $additional->[$_] ) }
4194                         ( 0 .. @$additional - 1 )
4195                   ),
4196                   'additional_count' => scalar(@$additional),
4197                   'setup_fee' => $amount,
4198                 );
4199
4200   my $error = $part_pkg->insert( options => \%options );
4201   if ( $error ) {
4202     $dbh->rollback if $oldAutoCommit;
4203     return $error;
4204   }
4205
4206   my $pkgpart = $part_pkg->pkgpart;
4207   my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
4208   unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
4209     my $type_pkgs = new FS::type_pkgs \%type_pkgs;
4210     $error = $type_pkgs->insert;
4211     if ( $error ) {
4212       $dbh->rollback if $oldAutoCommit;
4213       return $error;
4214     }
4215   }
4216
4217   my $cust_pkg = new FS::cust_pkg ( {
4218     'custnum'  => $self->custnum,
4219     'pkgpart'  => $pkgpart,
4220     'quantity' => $quantity,
4221   } );
4222
4223   $error = $cust_pkg->insert;
4224   if ( $error ) {
4225     $dbh->rollback if $oldAutoCommit;
4226     return $error;
4227   }
4228
4229   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
4230   '';
4231
4232 }
4233
4234 #=item charge_postal_fee
4235 #
4236 #Applies a one time charge this customer.  If there is an error,
4237 #returns the error, returns the cust_pkg charge object or false
4238 #if there was no charge.
4239 #
4240 #=cut
4241 #
4242 # This should be a customer event.  For that to work requires that bill
4243 # also be a customer event.
4244
4245 sub charge_postal_fee {
4246   my $self = shift;
4247
4248   my $pkgpart = $conf->config('postal_invoice-fee_pkgpart');
4249   return '' unless ($pkgpart && grep { $_ eq 'POST' } $self->invoicing_list);
4250
4251   my $cust_pkg = new FS::cust_pkg ( {
4252     'custnum'  => $self->custnum,
4253     'pkgpart'  => $pkgpart,
4254     'quantity' => 1,
4255   } );
4256
4257   my $error = $cust_pkg->insert;
4258   $error ? $error : $cust_pkg;
4259 }
4260
4261 =item cust_bill
4262
4263 Returns all the invoices (see L<FS::cust_bill>) for this customer.
4264
4265 =cut
4266
4267 sub cust_bill {
4268   my $self = shift;
4269   sort { $a->_date <=> $b->_date }
4270     qsearch('cust_bill', { 'custnum' => $self->custnum, } )
4271 }
4272
4273 =item open_cust_bill
4274
4275 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
4276 customer.
4277
4278 =cut
4279
4280 sub open_cust_bill {
4281   my $self = shift;
4282   grep { $_->owed > 0 } $self->cust_bill;
4283 }
4284
4285 =item cust_credit
4286
4287 Returns all the credits (see L<FS::cust_credit>) for this customer.
4288
4289 =cut
4290
4291 sub cust_credit {
4292   my $self = shift;
4293   sort { $a->_date <=> $b->_date }
4294     qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
4295 }
4296
4297 =item cust_pay
4298
4299 Returns all the payments (see L<FS::cust_pay>) for this customer.
4300
4301 =cut
4302
4303 sub cust_pay {
4304   my $self = shift;
4305   sort { $a->_date <=> $b->_date }
4306     qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
4307 }
4308
4309 =item cust_pay_void
4310
4311 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
4312
4313 =cut
4314
4315 sub cust_pay_void {
4316   my $self = shift;
4317   sort { $a->_date <=> $b->_date }
4318     qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
4319 }
4320
4321
4322 =item cust_refund
4323
4324 Returns all the refunds (see L<FS::cust_refund>) for this customer.
4325
4326 =cut
4327
4328 sub cust_refund {
4329   my $self = shift;
4330   sort { $a->_date <=> $b->_date }
4331     qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
4332 }
4333
4334 =item name
4335
4336 Returns a name string for this customer, either "Company (Last, First)" or
4337 "Last, First".
4338
4339 =cut
4340
4341 sub name {
4342   my $self = shift;
4343   my $name = $self->contact;
4344   $name = $self->company. " ($name)" if $self->company;
4345   $name;
4346 }
4347
4348 =item ship_name
4349
4350 Returns a name string for this (service/shipping) contact, either
4351 "Company (Last, First)" or "Last, First".
4352
4353 =cut
4354
4355 sub ship_name {
4356   my $self = shift;
4357   if ( $self->get('ship_last') ) { 
4358     my $name = $self->ship_contact;
4359     $name = $self->ship_company. " ($name)" if $self->ship_company;
4360     $name;
4361   } else {
4362     $self->name;
4363   }
4364 }
4365
4366 =item contact
4367
4368 Returns this customer's full (billing) contact name only, "Last, First"
4369
4370 =cut
4371
4372 sub contact {
4373   my $self = shift;
4374   $self->get('last'). ', '. $self->first;
4375 }
4376
4377 =item ship_contact
4378
4379 Returns this customer's full (shipping) contact name only, "Last, First"
4380
4381 =cut
4382
4383 sub ship_contact {
4384   my $self = shift;
4385   $self->get('ship_last')
4386     ? $self->get('ship_last'). ', '. $self->ship_first
4387     : $self->contact;
4388 }
4389
4390 =item country_full
4391
4392 Returns this customer's full country name
4393
4394 =cut
4395
4396 sub country_full {
4397   my $self = shift;
4398   code2country($self->country);
4399 }
4400
4401 =item cust_status
4402
4403 =item status
4404
4405 Returns a status string for this customer, currently:
4406
4407 =over 4
4408
4409 =item prospect - No packages have ever been ordered
4410
4411 =item active - One or more recurring packages is active
4412
4413 =item inactive - No active recurring packages, but otherwise unsuspended/uncancelled (the inactive status is new - previously inactive customers were mis-identified as cancelled)
4414
4415 =item suspended - All non-cancelled recurring packages are suspended
4416
4417 =item cancelled - All recurring packages are cancelled
4418
4419 =back
4420
4421 =cut
4422
4423 sub status { shift->cust_status(@_); }
4424
4425 sub cust_status {
4426   my $self = shift;
4427   for my $status (qw( prospect active inactive suspended cancelled )) {
4428     my $method = $status.'_sql';
4429     my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
4430     my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
4431     $sth->execute( ($self->custnum) x $numnum )
4432       or die "Error executing 'SELECT $sql': ". $sth->errstr;
4433     return $status if $sth->fetchrow_arrayref->[0];
4434   }
4435 }
4436
4437 =item ucfirst_cust_status
4438
4439 =item ucfirst_status
4440
4441 Returns the status with the first character capitalized.
4442
4443 =cut
4444
4445 sub ucfirst_status { shift->ucfirst_cust_status(@_); }
4446
4447 sub ucfirst_cust_status {
4448   my $self = shift;
4449   ucfirst($self->cust_status);
4450 }
4451
4452 =item statuscolor
4453
4454 Returns a hex triplet color string for this customer's status.
4455
4456 =cut
4457
4458 use vars qw(%statuscolor);
4459 tie %statuscolor, 'Tie::IxHash',
4460   'prospect'  => '7e0079', #'000000', #black?  naw, purple
4461   'active'    => '00CC00', #green
4462   'inactive'  => '0000CC', #blue
4463   'suspended' => 'FF9900', #yellow
4464   'cancelled' => 'FF0000', #red
4465 ;
4466
4467 sub statuscolor { shift->cust_statuscolor(@_); }
4468
4469 sub cust_statuscolor {
4470   my $self = shift;
4471   $statuscolor{$self->cust_status};
4472 }
4473
4474 =back
4475
4476 =head1 CLASS METHODS
4477
4478 =over 4
4479
4480 =item statuses
4481
4482 Class method that returns the list of possible status strings for customers
4483 (see L<the status method|/status>).  For example:
4484
4485   @statuses = FS::cust_main->statuses();
4486
4487 =cut
4488
4489 sub statuses {
4490   #my $self = shift; #could be class...
4491   keys %statuscolor;
4492 }
4493
4494 =item prospect_sql
4495
4496 Returns an SQL expression identifying prospective cust_main records (customers
4497 with no packages ever ordered)
4498
4499 =cut
4500
4501 use vars qw($select_count_pkgs);
4502 $select_count_pkgs =
4503   "SELECT COUNT(*) FROM cust_pkg
4504     WHERE cust_pkg.custnum = cust_main.custnum";
4505
4506 sub select_count_pkgs_sql {
4507   $select_count_pkgs;
4508 }
4509
4510 sub prospect_sql { "
4511   0 = ( $select_count_pkgs )
4512 "; }
4513
4514 =item active_sql
4515
4516 Returns an SQL expression identifying active cust_main records (customers with
4517 active recurring packages).
4518
4519 =cut
4520
4521 sub active_sql { "
4522   0 < ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. "
4523       )
4524 "; }
4525
4526 =item inactive_sql
4527
4528 Returns an SQL expression identifying inactive cust_main records (customers with
4529 no active recurring packages, but otherwise unsuspended/uncancelled).
4530
4531 =cut
4532
4533 sub inactive_sql { "
4534   0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4535   AND
4536   0 < ( $select_count_pkgs AND ". FS::cust_pkg->inactive_sql. " )
4537 "; }
4538
4539 =item susp_sql
4540 =item suspended_sql
4541
4542 Returns an SQL expression identifying suspended cust_main records.
4543
4544 =cut
4545
4546
4547 sub suspended_sql { susp_sql(@_); }
4548 sub susp_sql { "
4549     0 < ( $select_count_pkgs AND ". FS::cust_pkg->suspended_sql. " )
4550     AND
4551     0 = ( $select_count_pkgs AND ". FS::cust_pkg->active_sql. " )
4552 "; }
4553
4554 =item cancel_sql
4555 =item cancelled_sql
4556
4557 Returns an SQL expression identifying cancelled cust_main records.
4558
4559 =cut
4560
4561 sub cancelled_sql { cancel_sql(@_); }
4562 sub cancel_sql {
4563
4564   my $recurring_sql = FS::cust_pkg->recurring_sql;
4565   my $cancelled_sql = FS::cust_pkg->cancelled_sql;
4566
4567   "
4568         0 < ( $select_count_pkgs )
4569     AND 0 < ( $select_count_pkgs AND $recurring_sql AND $cancelled_sql   )
4570     AND 0 = ( $select_count_pkgs AND $recurring_sql
4571                   AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
4572             )
4573   ";
4574
4575 }
4576
4577 =item uncancel_sql
4578 =item uncancelled_sql
4579
4580 Returns an SQL expression identifying un-cancelled cust_main records.
4581
4582 =cut
4583
4584 sub uncancelled_sql { uncancel_sql(@_); }
4585 sub uncancel_sql { "
4586   ( 0 < ( $select_count_pkgs
4587                    AND ( cust_pkg.cancel IS NULL
4588                          OR cust_pkg.cancel = 0
4589                        )
4590         )
4591     OR 0 = ( $select_count_pkgs )
4592   )
4593 "; }
4594
4595 =item balance_sql
4596
4597 Returns an SQL fragment to retreive the balance.
4598
4599 =cut
4600
4601 sub balance_sql { "
4602     ( SELECT COALESCE( SUM(charged), 0 ) FROM cust_bill
4603         WHERE cust_bill.custnum   = cust_main.custnum     )
4604   - ( SELECT COALESCE( SUM(paid),    0 ) FROM cust_pay
4605         WHERE cust_pay.custnum    = cust_main.custnum     )
4606   - ( SELECT COALESCE( SUM(amount),  0 ) FROM cust_credit
4607         WHERE cust_credit.custnum = cust_main.custnum     )
4608   + ( SELECT COALESCE( SUM(refund),  0 ) FROM cust_refund
4609         WHERE cust_refund.custnum = cust_main.custnum     )
4610 "; }
4611
4612 =item balance_date_sql START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4613
4614 Returns an SQL fragment to retreive the balance for this customer, only
4615 considering invoices with date earlier than START_TIME, and optionally not
4616 later than END_TIME (total_owed_date minus total_credited minus
4617 total_unapplied_payments).
4618
4619 Times are specified as SQL fragments or numeric
4620 UNIX timestamps; see L<perlfunc/"time">).  Also see L<Time::Local> and
4621 L<Date::Parse> for conversion functions.  The empty string can be passed
4622 to disable that time constraint completely.
4623
4624 Available options are:
4625
4626 =over 4
4627
4628 =item unapplied_date - 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)
4629
4630 =item total - set to true to remove all customer comparison clauses, for totals
4631
4632 =item where - WHERE clause hashref (elements "AND"ed together) (typically used with the total option)
4633
4634 =item join - JOIN clause (typically used with the total option)
4635
4636 =item 
4637
4638 =back
4639
4640 =cut
4641
4642 sub balance_date_sql {
4643   my( $class, $start, $end, %opt ) = @_;
4644
4645   my $owed         = FS::cust_bill->owed_sql;
4646   my $unapp_refund = FS::cust_refund->unapplied_sql;
4647   my $unapp_credit = FS::cust_credit->unapplied_sql;
4648   my $unapp_pay    = FS::cust_pay->unapplied_sql;
4649
4650   my $j = $opt{'join'} || '';
4651
4652   my $owed_wh   = $class->_money_table_where( 'cust_bill',   $start,$end,%opt );
4653   my $refund_wh = $class->_money_table_where( 'cust_refund', $start,$end,%opt );
4654   my $credit_wh = $class->_money_table_where( 'cust_credit', $start,$end,%opt );
4655   my $pay_wh    = $class->_money_table_where( 'cust_pay',    $start,$end,%opt );
4656
4657   "   ( SELECT COALESCE(SUM($owed),         0) FROM cust_bill   $j $owed_wh   )
4658     + ( SELECT COALESCE(SUM($unapp_refund), 0) FROM cust_refund $j $refund_wh )
4659     - ( SELECT COALESCE(SUM($unapp_credit), 0) FROM cust_credit $j $credit_wh )
4660     - ( SELECT COALESCE(SUM($unapp_pay),    0) FROM cust_pay    $j $pay_wh    )
4661   ";
4662
4663 }
4664
4665 =item _money_table_where TABLE START_TIME [ END_TIME [ OPTION => VALUE ... ] ]
4666
4667 Helper method for balance_date_sql; name (and usage) subject to change
4668 (suggestions welcome).
4669
4670 Returns a WHERE clause for the specified monetary TABLE (cust_bill,
4671 cust_refund, cust_credit or cust_pay).
4672
4673 If TABLE is "cust_bill" or the unapplied_date option is true, only
4674 considers records with date earlier than START_TIME, and optionally not
4675 later than END_TIME .
4676
4677 =cut
4678
4679 sub _money_table_where {
4680   my( $class, $table, $start, $end, %opt ) = @_;
4681
4682   my @where = ();
4683   push @where, "cust_main.custnum = $table.custnum" unless $opt{'total'};
4684   if ( $table eq 'cust_bill' || $opt{'unapplied_date'} ) {
4685     push @where, "$table._date <= $start" if defined($start) && length($start);
4686     push @where, "$table._date >  $end"   if defined($end)   && length($end);
4687   }
4688   push @where, @{$opt{'where'}} if $opt{'where'};
4689   my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where ) : '';
4690
4691   $where;
4692
4693 }
4694
4695 =item search_sql HASHREF
4696
4697 (Class method)
4698
4699 Returns a qsearch hash expression to search for parameters specified in HREF.
4700 Valid parameters are
4701
4702 =over 4
4703
4704 =item agentnum
4705
4706 =item status
4707
4708 =item cancelled_pkgs
4709
4710 bool
4711
4712 =item signupdate
4713
4714 listref of start date, end date
4715
4716 =item payby
4717
4718 listref
4719
4720 =item current_balance
4721
4722 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
4723
4724 =item cust_fields
4725
4726 =item flattened_pkgs
4727
4728 bool
4729
4730 =back
4731
4732 =cut
4733
4734 sub search_sql {
4735   my ($class, $params) = @_;
4736
4737   my $dbh = dbh;
4738
4739   my @where = ();
4740   my $orderby;
4741
4742   ##
4743   # parse agent
4744   ##
4745
4746   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
4747     push @where,
4748       "cust_main.agentnum = $1";
4749   }
4750
4751   ##
4752   # parse status
4753   ##
4754
4755   #prospect active inactive suspended cancelled
4756   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
4757     my $method = $params->{'status'}. '_sql';
4758     #push @where, $class->$method();
4759     push @where, FS::cust_main->$method();
4760   }
4761   
4762   ##
4763   # parse cancelled package checkbox
4764   ##
4765
4766   my $pkgwhere = "";
4767
4768   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
4769     unless $params->{'cancelled_pkgs'};
4770
4771   ##
4772   # dates
4773   ##
4774
4775   foreach my $field (qw( signupdate )) {
4776
4777     next unless exists($params->{$field});
4778
4779     my($beginning, $ending) = @{$params->{$field}};
4780
4781     push @where,
4782       "cust_main.$field IS NOT NULL",
4783       "cust_main.$field >= $beginning",
4784       "cust_main.$field <= $ending";
4785
4786     $orderby ||= "ORDER BY cust_main.$field";
4787
4788   }
4789
4790   ###
4791   # payby
4792   ###
4793
4794   my @payby = grep /^([A-Z]{4})$/, @{ $params->{'payby'} };
4795   if ( @payby ) {
4796     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )';
4797   }
4798
4799   ##
4800   # amounts
4801   ##
4802
4803   #my $balance_sql = $class->balance_sql();
4804   my $balance_sql = FS::cust_main->balance_sql();
4805
4806   push @where, map { s/current_balance/$balance_sql/; $_ }
4807                    @{ $params->{'current_balance'} };
4808
4809   ##
4810   # setup queries, subs, etc. for the search
4811   ##
4812
4813   $orderby ||= 'ORDER BY custnum';
4814
4815   # here is the agent virtualization
4816   push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
4817
4818   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
4819
4820   my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum  ) ';
4821
4822   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
4823
4824   my $select = join(', ', 
4825                  'cust_main.custnum',
4826                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
4827                );
4828
4829   my(@extra_headers) = ();
4830   my(@extra_fields)  = ();
4831
4832   if ($params->{'flattened_pkgs'}) {
4833
4834     if ($dbh->{Driver}->{Name} eq 'Pg') {
4835
4836       $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";
4837
4838     }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
4839       $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
4840       $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
4841     }else{
4842       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
4843            "omitting packing information from report.";
4844     }
4845
4846     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";
4847
4848     my $sth = dbh->prepare($header_query) or die dbh->errstr;
4849     $sth->execute() or die $sth->errstr;
4850     my $headerrow = $sth->fetchrow_arrayref;
4851     my $headercount = $headerrow ? $headerrow->[0] : 0;
4852     while($headercount) {
4853       unshift @extra_headers, "Package ". $headercount;
4854       unshift @extra_fields, eval q!sub {my $c = shift;
4855                                          my @a = split '\|', $c->magic;
4856                                          my $p = $a[!.--$headercount. q!];
4857                                          $p;
4858                                         };!;
4859     }
4860
4861   }
4862
4863   my $sql_query = {
4864     'table'         => 'cust_main',
4865     'select'        => $select,
4866     'hashref'       => {},
4867     'extra_sql'     => $extra_sql,
4868     'order_by'      => $orderby,
4869     'count_query'   => $count_query,
4870     'extra_headers' => \@extra_headers,
4871     'extra_fields'  => \@extra_fields,
4872   };
4873
4874 }
4875
4876 =item email_search_sql HASHREF
4877
4878 (Class method)
4879
4880 Emails a notice to the specified customers.
4881
4882 Valid parameters are those of the L<search_sql> method, plus the following:
4883
4884 =over 4
4885
4886 =item from
4887
4888 From: address
4889
4890 =item subject
4891
4892 Email Subject:
4893
4894 =item html_body
4895
4896 HTML body
4897
4898 =item text_body
4899
4900 Text body
4901
4902 =item job
4903
4904 Optional job queue job for status updates.
4905
4906 =back
4907
4908 Returns an error message, or false for success.
4909
4910 If an error occurs during any email, stops the enture send and returns that
4911 error.  Presumably if you're getting SMTP errors aborting is better than 
4912 retrying everything.
4913
4914 =cut
4915
4916 sub email_search_sql {
4917   my($class, $params) = @_;
4918
4919   my $from = delete $params->{from};
4920   my $subject = delete $params->{subject};
4921   my $html_body = delete $params->{html_body};
4922   my $text_body = delete $params->{text_body};
4923
4924   my $job = delete $params->{'job'};
4925
4926   my $sql_query = $class->search_sql($params);
4927
4928   my $count_query   = delete($sql_query->{'count_query'});
4929   my $count_sth = dbh->prepare($count_query)
4930     or die "Error preparing $count_query: ". dbh->errstr;
4931   $count_sth->execute
4932     or die "Error executing $count_query: ". $count_sth->errstr;
4933   my $count_arrayref = $count_sth->fetchrow_arrayref;
4934   my $num_cust = $count_arrayref->[0];
4935
4936   #my @extra_headers = @{ delete($sql_query->{'extra_headers'}) };
4937   #my @extra_fields  = @{ delete($sql_query->{'extra_fields'})  };
4938
4939
4940   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
4941
4942   #eventually order+limit magic to reduce memory use?
4943   foreach my $cust_main ( qsearch($sql_query) ) {
4944
4945     my $to = $cust_main->invoicing_list_emailonly_scalar;
4946     next unless $to;
4947
4948     my $error = send_email(
4949       generate_email(
4950         'from'      => $from,
4951         'to'        => $to,
4952         'subject'   => $subject,
4953         'html_body' => $html_body,
4954         'text_body' => $text_body,
4955       )
4956     );
4957     return $error if $error;
4958
4959     if ( $job ) { #progressbar foo
4960       $num++;
4961       if ( time - $min_sec > $last ) {
4962         my $error = $job->update_statustext(
4963           int( 100 * $num / $num_cust )
4964         );
4965         die $error if $error;
4966         $last = time;
4967       }
4968     }
4969
4970   }
4971
4972   return '';
4973 }
4974
4975 use Storable qw(thaw);
4976 use Data::Dumper;
4977 use MIME::Base64;
4978 sub process_email_search_sql {
4979   my $job = shift;
4980   #warn "$me process_re_X $method for job $job\n" if $DEBUG;
4981
4982   my $param = thaw(decode_base64(shift));
4983   warn Dumper($param) if $DEBUG;
4984
4985   $param->{'job'} = $job;
4986
4987   my $error = FS::cust_main->email_search_sql( $param );
4988   die $error if $error;
4989
4990 }
4991
4992 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
4993
4994 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
4995 records.  Currently, I<first>, I<last> and/or I<company> may be specified (the
4996 appropriate ship_ field is also searched).
4997
4998 Additional options are the same as FS::Record::qsearch
4999
5000 =cut
5001
5002 sub fuzzy_search {
5003   my( $self, $fuzzy, $hash, @opt) = @_;
5004   #$self
5005   $hash ||= {};
5006   my @cust_main = ();
5007
5008   check_and_rebuild_fuzzyfiles();
5009   foreach my $field ( keys %$fuzzy ) {
5010
5011     my $all = $self->all_X($field);
5012     next unless scalar(@$all);
5013
5014     my %match = ();
5015     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
5016
5017     my @fcust = ();
5018     foreach ( keys %match ) {
5019       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
5020       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
5021     }
5022     my %fsaw = ();
5023     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
5024   }
5025
5026   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
5027   my %saw = ();
5028   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
5029
5030   @cust_main;
5031
5032 }
5033
5034 =item masked FIELD
5035
5036  Returns a masked version of the named field
5037
5038 =cut
5039
5040 sub masked {
5041   my ($self, $field) = @_;
5042
5043   # Show last four
5044
5045   'x'x(length($self->getfield($field))-4).
5046     substr($self->getfield($field), (length($self->getfield($field))-4));
5047
5048 }
5049
5050 =back
5051
5052 =head1 SUBROUTINES
5053
5054 =over 4
5055
5056 =item smart_search OPTION => VALUE ...
5057
5058 Accepts the following options: I<search>, the string to search for.  The string
5059 will be searched for as a customer number, phone number, name or company name,
5060 as an exact, or, in some cases, a substring or fuzzy match (see the source code
5061 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
5062 skip fuzzy matching when an exact match is found.
5063
5064 Any additional options are treated as an additional qualifier on the search
5065 (i.e. I<agentnum>).
5066
5067 Returns a (possibly empty) array of FS::cust_main objects.
5068
5069 =cut
5070
5071 sub smart_search {
5072   my %options = @_;
5073
5074   #here is the agent virtualization
5075   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5076
5077   my @cust_main = ();
5078
5079   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
5080   my $search = delete $options{'search'};
5081   ( my $alphanum_search = $search ) =~ s/\W//g;
5082   
5083   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
5084
5085     #false laziness w/Record::ut_phone
5086     my $phonen = "$1-$2-$3";
5087     $phonen .= " x$4" if $4;
5088
5089     push @cust_main, qsearch( {
5090       'table'   => 'cust_main',
5091       'hashref' => { %options },
5092       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5093                      ' ( '.
5094                          join(' OR ', map "$_ = '$phonen'",
5095                                           qw( daytime night fax
5096                                               ship_daytime ship_night ship_fax )
5097                              ).
5098                      ' ) '.
5099                      " AND $agentnums_sql", #agent virtualization
5100     } );
5101
5102     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
5103       #try looking for matches with extensions unless one was specified
5104
5105       push @cust_main, qsearch( {
5106         'table'   => 'cust_main',
5107         'hashref' => { %options },
5108         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
5109                        ' ( '.
5110                            join(' OR ', map "$_ LIKE '$phonen\%'",
5111                                             qw( daytime night
5112                                                 ship_daytime ship_night )
5113                                ).
5114                        ' ) '.
5115                        " AND $agentnums_sql", #agent virtualization
5116       } );
5117
5118     }
5119
5120   # custnum search (also try agent_custid), with some tweaking options if your
5121   # legacy cust "numbers" have letters
5122   } elsif ( $search =~ /^\s*(\d+)\s*$/
5123             || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
5124                  && $search =~ /^\s*(\w\w?\d+)\s*$/
5125                )
5126           )
5127   {
5128
5129     push @cust_main, qsearch( {
5130       'table'     => 'cust_main',
5131       'hashref'   => { 'custnum' => $1, %options },
5132       'extra_sql' => " AND $agentnums_sql", #agent virtualization
5133     } );
5134
5135     push @cust_main, qsearch( {
5136       'table'     => 'cust_main',
5137       'hashref'   => { 'agent_custid' => $1, %options },
5138       'extra_sql' => " AND $agentnums_sql", #agent virtualization
5139     } );
5140
5141   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
5142
5143     my($company, $last, $first) = ( $1, $2, $3 );
5144
5145     # "Company (Last, First)"
5146     #this is probably something a browser remembered,
5147     #so just do an exact search
5148
5149     foreach my $prefix ( '', 'ship_' ) {
5150       push @cust_main, qsearch( {
5151         'table'     => 'cust_main',
5152         'hashref'   => { $prefix.'first'   => $first,
5153                          $prefix.'last'    => $last,
5154                          $prefix.'company' => $company,
5155                          %options,
5156                        },
5157         'extra_sql' => " AND $agentnums_sql",
5158       } );
5159     }
5160
5161   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
5162                                               # try (ship_){last,company}
5163
5164     my $value = lc($1);
5165
5166     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
5167     # # full strings the browser remembers won't work
5168     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
5169
5170     use Lingua::EN::NameParse;
5171     my $NameParse = new Lingua::EN::NameParse(
5172              auto_clean     => 1,
5173              allow_reversed => 1,
5174     );
5175
5176     my($last, $first) = ( '', '' );
5177     #maybe disable this too and just rely on NameParse?
5178     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
5179     
5180       ($last, $first) = ( $1, $2 );
5181     
5182     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
5183     } elsif ( ! $NameParse->parse($value) ) {
5184
5185       my %name = $NameParse->components;
5186       $first = $name{'given_name_1'};
5187       $last  = $name{'surname_1'};
5188
5189     }
5190
5191     if ( $first && $last ) {
5192
5193       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
5194
5195       #exact
5196       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5197       $sql .= "
5198         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
5199            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
5200         )";
5201
5202       push @cust_main, qsearch( {
5203         'table'     => 'cust_main',
5204         'hashref'   => \%options,
5205         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5206       } );
5207
5208       # or it just be something that was typed in... (try that in a sec)
5209
5210     }
5211
5212     my $q_value = dbh->quote($value);
5213
5214     #exact
5215     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
5216     $sql .= " (    LOWER(last)         = $q_value
5217                 OR LOWER(company)      = $q_value
5218                 OR LOWER(ship_last)    = $q_value
5219                 OR LOWER(ship_company) = $q_value
5220               )";
5221
5222     push @cust_main, qsearch( {
5223       'table'     => 'cust_main',
5224       'hashref'   => \%options,
5225       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
5226     } );
5227
5228     #always do substring & fuzzy,
5229     #getting complains searches are not returning enough
5230     unless ( @cust_main && $skip_fuzzy ) {  #no exact match, trying substring/fuzzy
5231
5232       #still some false laziness w/search_sql (was search/cust_main.cgi)
5233
5234       #substring
5235
5236       my @hashrefs = (
5237         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
5238         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
5239       );
5240
5241       if ( $first && $last ) {
5242
5243         push @hashrefs,
5244           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
5245             'last'         => { op=>'ILIKE', value=>"%$last%" },
5246           },
5247           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
5248             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
5249           },
5250         ;
5251
5252       } else {
5253
5254         push @hashrefs,
5255           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
5256           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
5257         ;
5258       }
5259
5260       foreach my $hashref ( @hashrefs ) {
5261
5262         push @cust_main, qsearch( {
5263           'table'     => 'cust_main',
5264           'hashref'   => { %$hashref,
5265                            %options,
5266                          },
5267           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
5268         } );
5269
5270       }
5271
5272       #fuzzy
5273       my @fuzopts = (
5274         \%options,                #hashref
5275         '',                       #select
5276         " AND $agentnums_sql",    #extra_sql  #agent virtualization
5277       );
5278
5279       if ( $first && $last ) {
5280         push @cust_main, FS::cust_main->fuzzy_search(
5281           { 'last'   => $last,    #fuzzy hashref
5282             'first'  => $first }, #
5283           @fuzopts
5284         );
5285       }
5286       foreach my $field ( 'last', 'company' ) {
5287         push @cust_main,
5288           FS::cust_main->fuzzy_search( { $field => $value }, @fuzopts );
5289       }
5290
5291     }
5292
5293     #eliminate duplicates
5294     my %saw = ();
5295     @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5296
5297   }
5298
5299   @cust_main;
5300
5301 }
5302
5303 =item email_search
5304
5305 Accepts the following options: I<email>, the email address to search for.  The
5306 email address will be searched for as an email invoice destination and as an
5307 svc_acct account.
5308
5309 #Any additional options are treated as an additional qualifier on the search
5310 #(i.e. I<agentnum>).
5311
5312 Returns a (possibly empty) array of FS::cust_main objects (but usually just
5313 none or one).
5314
5315 =cut
5316
5317 sub email_search {
5318   my %options = @_;
5319
5320   local($DEBUG) = 1;
5321
5322   my $email = delete $options{'email'};
5323
5324   #we're only being used by RT at the moment... no agent virtualization yet
5325   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
5326
5327   my @cust_main = ();
5328
5329   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
5330
5331     my ( $user, $domain ) = ( $1, $2 );
5332
5333     warn "$me smart_search: searching for $user in domain $domain"
5334       if $DEBUG;
5335
5336     push @cust_main,
5337       map $_->cust_main,
5338           qsearch( {
5339                      'table'     => 'cust_main_invoice',
5340                      'hashref'   => { 'dest' => $email },
5341                    }
5342                  );
5343
5344     push @cust_main,
5345       map  $_->cust_main,
5346       grep $_,
5347       map  $_->cust_svc->cust_pkg,
5348           qsearch( {
5349                      'table'     => 'svc_acct',
5350                      'hashref'   => { 'username' => $user, },
5351                      'extra_sql' =>
5352                        'AND ( SELECT domain FROM svc_domain
5353                                 WHERE svc_acct.domsvc = svc_domain.svcnum
5354                             ) = '. dbh->quote($domain),
5355                    }
5356                  );
5357   }
5358
5359   my %saw = ();
5360   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
5361
5362   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
5363     if $DEBUG;
5364
5365   @cust_main;
5366
5367 }
5368
5369 =item check_and_rebuild_fuzzyfiles
5370
5371 =cut
5372
5373 use vars qw(@fuzzyfields);
5374 @fuzzyfields = ( 'last', 'first', 'company' );
5375
5376 sub check_and_rebuild_fuzzyfiles {
5377   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5378   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
5379 }
5380
5381 =item rebuild_fuzzyfiles
5382
5383 =cut
5384
5385 sub rebuild_fuzzyfiles {
5386
5387   use Fcntl qw(:flock);
5388
5389   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5390   mkdir $dir, 0700 unless -d $dir;
5391
5392   foreach my $fuzzy ( @fuzzyfields ) {
5393
5394     open(LOCK,">>$dir/cust_main.$fuzzy")
5395       or die "can't open $dir/cust_main.$fuzzy: $!";
5396     flock(LOCK,LOCK_EX)
5397       or die "can't lock $dir/cust_main.$fuzzy: $!";
5398
5399     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
5400       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
5401
5402     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
5403       my $sth = dbh->prepare("SELECT $field FROM cust_main".
5404                              " WHERE $field != '' AND $field IS NOT NULL");
5405       $sth->execute or die $sth->errstr;
5406
5407       while ( my $row = $sth->fetchrow_arrayref ) {
5408         print CACHE $row->[0]. "\n";
5409       }
5410
5411     } 
5412
5413     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
5414   
5415     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
5416     close LOCK;
5417   }
5418
5419 }
5420
5421 =item all_X
5422
5423 =cut
5424
5425 sub all_X {
5426   my( $self, $field ) = @_;
5427   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5428   open(CACHE,"<$dir/cust_main.$field")
5429     or die "can't open $dir/cust_main.$field: $!";
5430   my @array = map { chomp; $_; } <CACHE>;
5431   close CACHE;
5432   \@array;
5433 }
5434
5435 =item append_fuzzyfiles LASTNAME COMPANY
5436
5437 =cut
5438
5439 sub append_fuzzyfiles {
5440   #my( $first, $last, $company ) = @_;
5441
5442   &check_and_rebuild_fuzzyfiles;
5443
5444   use Fcntl qw(:flock);
5445
5446   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
5447
5448   foreach my $field (qw( first last company )) {
5449     my $value = shift;
5450
5451     if ( $value ) {
5452
5453       open(CACHE,">>$dir/cust_main.$field")
5454         or die "can't open $dir/cust_main.$field: $!";
5455       flock(CACHE,LOCK_EX)
5456         or die "can't lock $dir/cust_main.$field: $!";
5457
5458       print CACHE "$value\n";
5459
5460       flock(CACHE,LOCK_UN)
5461         or die "can't unlock $dir/cust_main.$field: $!";
5462       close CACHE;
5463     }
5464
5465   }
5466
5467   1;
5468 }
5469
5470 =item batch_import
5471
5472 =cut
5473
5474 sub batch_import {
5475   my $param = shift;
5476   #warn join('-',keys %$param);
5477   my $fh = $param->{filehandle};
5478   my $agentnum = $param->{agentnum};
5479
5480   my $refnum = $param->{refnum};
5481   my $pkgpart = $param->{pkgpart};
5482
5483   #my @fields = @{$param->{fields}};
5484   my $format = $param->{'format'};
5485   my @fields;
5486   my $payby;
5487   if ( $format eq 'simple' ) {
5488     @fields = qw( cust_pkg.setup dayphone first last
5489                   address1 address2 city state zip comments );
5490     $payby = 'BILL';
5491   } elsif ( $format eq 'extended' ) {
5492     @fields = qw( agent_custid refnum
5493                   last first address1 address2 city state zip country
5494                   daytime night
5495                   ship_last ship_first ship_address1 ship_address2
5496                   ship_city ship_state ship_zip ship_country
5497                   payinfo paycvv paydate
5498                   invoicing_list
5499                   cust_pkg.pkgpart
5500                   svc_acct.username svc_acct._password 
5501                 );
5502     $payby = 'BILL';
5503  } elsif ( $format eq 'extended-plus_company' ) {
5504     @fields = qw( agent_custid refnum
5505                   last first company address1 address2 city state zip country
5506                   daytime night
5507                   ship_last ship_first ship_company ship_address1 ship_address2
5508                   ship_city ship_state ship_zip ship_country
5509                   payinfo paycvv paydate
5510                   invoicing_list
5511                   cust_pkg.pkgpart
5512                   svc_acct.username svc_acct._password 
5513                 );
5514     $payby = 'BILL';
5515   } else {
5516     die "unknown format $format";
5517   }
5518
5519   eval "use Text::CSV_XS;";
5520   die $@ if $@;
5521
5522   my $csv = new Text::CSV_XS;
5523   #warn $csv;
5524   #warn $fh;
5525
5526   my $imported = 0;
5527   #my $columns;
5528
5529   local $SIG{HUP} = 'IGNORE';
5530   local $SIG{INT} = 'IGNORE';
5531   local $SIG{QUIT} = 'IGNORE';
5532   local $SIG{TERM} = 'IGNORE';
5533   local $SIG{TSTP} = 'IGNORE';
5534   local $SIG{PIPE} = 'IGNORE';
5535
5536   my $oldAutoCommit = $FS::UID::AutoCommit;
5537   local $FS::UID::AutoCommit = 0;
5538   my $dbh = dbh;
5539   
5540   #while ( $columns = $csv->getline($fh) ) {
5541   my $line;
5542   while ( defined($line=<$fh>) ) {
5543
5544     $csv->parse($line) or do {
5545       $dbh->rollback if $oldAutoCommit;
5546       return "can't parse: ". $csv->error_input();
5547     };
5548
5549     my @columns = $csv->fields();
5550     #warn join('-',@columns);
5551
5552     my %cust_main = (
5553       agentnum => $agentnum,
5554       refnum   => $refnum,
5555       country  => $conf->config('countrydefault') || 'US',
5556       payby    => $payby, #default
5557       paydate  => '12/2037', #default
5558     );
5559     my $billtime = time;
5560     my %cust_pkg = ( pkgpart => $pkgpart );
5561     my %svc_acct = ();
5562     foreach my $field ( @fields ) {
5563
5564       if ( $field =~ /^cust_pkg\.(pkgpart|setup|bill|susp|adjourn|expire|cancel)$/ ) {
5565
5566         #$cust_pkg{$1} = str2time( shift @$columns );
5567         if ( $1 eq 'pkgpart' ) {
5568           $cust_pkg{$1} = shift @columns;
5569         } elsif ( $1 eq 'setup' ) {
5570           $billtime = str2time(shift @columns);
5571         } else {
5572           $cust_pkg{$1} = str2time( shift @columns );
5573         } 
5574
5575       } elsif ( $field =~ /^svc_acct\.(username|_password)$/ ) {
5576
5577         $svc_acct{$1} = shift @columns;
5578         
5579       } else {
5580
5581         #refnum interception
5582         if ( $field eq 'refnum' && $columns[0] !~ /^\s*(\d+)\s*$/ ) {
5583
5584           my $referral = $columns[0];
5585           my %hash = ( 'referral' => $referral,
5586                        'agentnum' => $agentnum,
5587                        'disabled' => '',
5588                      );
5589
5590           my $part_referral = qsearchs('part_referral', \%hash )
5591                               || new FS::part_referral \%hash;
5592
5593           unless ( $part_referral->refnum ) {
5594             my $error = $part_referral->insert;
5595             if ( $error ) {
5596               $dbh->rollback if $oldAutoCommit;
5597               return "can't auto-insert advertising source: $referral: $error";
5598             }
5599           }
5600
5601           $columns[0] = $part_referral->refnum;
5602         }
5603
5604         #$cust_main{$field} = shift @$columns; 
5605         $cust_main{$field} = shift @columns; 
5606       }
5607     }
5608
5609     $cust_main{'payby'} = 'CARD' if length($cust_main{'payinfo'});
5610
5611     my $invoicing_list = $cust_main{'invoicing_list'}
5612                            ? [ delete $cust_main{'invoicing_list'} ]
5613                            : [];
5614
5615     my $cust_main = new FS::cust_main ( \%cust_main );
5616
5617     use Tie::RefHash;
5618     tie my %hash, 'Tie::RefHash'; #this part is important
5619
5620     if ( $cust_pkg{'pkgpart'} ) {
5621       my $cust_pkg = new FS::cust_pkg ( \%cust_pkg );
5622
5623       my @svc_acct = ();
5624       if ( $svc_acct{'username'} ) {
5625         my $part_pkg = $cust_pkg->part_pkg;
5626         unless ( $part_pkg ) {
5627           $dbh->rollback if $oldAutoCommit;
5628           return "unknown pkgpart: ". $cust_pkg{'pkgpart'};
5629         } 
5630         $svc_acct{svcpart} = $part_pkg->svcpart( 'svc_acct' );
5631         push @svc_acct, new FS::svc_acct ( \%svc_acct )
5632       }
5633
5634       $hash{$cust_pkg} = \@svc_acct;
5635     }
5636
5637     my $error = $cust_main->insert( \%hash, $invoicing_list );
5638
5639     if ( $error ) {
5640       $dbh->rollback if $oldAutoCommit;
5641       return "can't insert customer for $line: $error";
5642     }
5643
5644     if ( $format eq 'simple' ) {
5645
5646       #false laziness w/bill.cgi
5647       $error = $cust_main->bill( 'time' => $billtime );
5648       if ( $error ) {
5649         $dbh->rollback if $oldAutoCommit;
5650         return "can't bill customer for $line: $error";
5651       }
5652   
5653       $error = $cust_main->apply_payments_and_credits;
5654       if ( $error ) {
5655         $dbh->rollback if $oldAutoCommit;
5656         return "can't bill customer for $line: $error";
5657       }
5658
5659       $error = $cust_main->collect();
5660       if ( $error ) {
5661         $dbh->rollback if $oldAutoCommit;
5662         return "can't collect customer for $line: $error";
5663       }
5664
5665     }
5666
5667     $imported++;
5668   }
5669
5670   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5671
5672   return "Empty file!" unless $imported;
5673
5674   ''; #no error
5675
5676 }
5677
5678 =item batch_charge
5679
5680 =cut
5681
5682 sub batch_charge {
5683   my $param = shift;
5684   #warn join('-',keys %$param);
5685   my $fh = $param->{filehandle};
5686   my @fields = @{$param->{fields}};
5687
5688   eval "use Text::CSV_XS;";
5689   die $@ if $@;
5690
5691   my $csv = new Text::CSV_XS;
5692   #warn $csv;
5693   #warn $fh;
5694
5695   my $imported = 0;
5696   #my $columns;
5697
5698   local $SIG{HUP} = 'IGNORE';
5699   local $SIG{INT} = 'IGNORE';
5700   local $SIG{QUIT} = 'IGNORE';
5701   local $SIG{TERM} = 'IGNORE';
5702   local $SIG{TSTP} = 'IGNORE';
5703   local $SIG{PIPE} = 'IGNORE';
5704
5705   my $oldAutoCommit = $FS::UID::AutoCommit;
5706   local $FS::UID::AutoCommit = 0;
5707   my $dbh = dbh;
5708   
5709   #while ( $columns = $csv->getline($fh) ) {
5710   my $line;
5711   while ( defined($line=<$fh>) ) {
5712
5713     $csv->parse($line) or do {
5714       $dbh->rollback if $oldAutoCommit;
5715       return "can't parse: ". $csv->error_input();
5716     };
5717
5718     my @columns = $csv->fields();
5719     #warn join('-',@columns);
5720
5721     my %row = ();
5722     foreach my $field ( @fields ) {
5723       $row{$field} = shift @columns;
5724     }
5725
5726     my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
5727     unless ( $cust_main ) {
5728       $dbh->rollback if $oldAutoCommit;
5729       return "unknown custnum $row{'custnum'}";
5730     }
5731
5732     if ( $row{'amount'} > 0 ) {
5733       my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
5734       if ( $error ) {
5735         $dbh->rollback if $oldAutoCommit;
5736         return $error;
5737       }
5738       $imported++;
5739     } elsif ( $row{'amount'} < 0 ) {
5740       my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
5741                                       $row{'pkg'}                         );
5742       if ( $error ) {
5743         $dbh->rollback if $oldAutoCommit;
5744         return $error;
5745       }
5746       $imported++;
5747     } else {
5748       #hmm?
5749     }
5750
5751   }
5752
5753   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
5754
5755   return "Empty file!" unless $imported;
5756
5757   ''; #no error
5758
5759 }
5760
5761 =item notify CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5762
5763 Sends a templated email notification to the customer (see L<Text::Template>).
5764
5765 OPTIONS is a hash and may include
5766
5767 I<from> - the email sender (default is invoice_from)
5768
5769 I<to> - comma-separated scalar or arrayref of recipients 
5770    (default is invoicing_list)
5771
5772 I<subject> - The subject line of the sent email notification
5773    (default is "Notice from company_name")
5774
5775 I<extra_fields> - a hashref of name/value pairs which will be substituted
5776    into the template
5777
5778 The following variables are vavailable in the template.
5779
5780 I<$first> - the customer first name
5781 I<$last> - the customer last name
5782 I<$company> - the customer company
5783 I<$payby> - a description of the method of payment for the customer
5784             # would be nice to use FS::payby::shortname
5785 I<$payinfo> - the account information used to collect for this customer
5786 I<$expdate> - the expiration of the customer payment in seconds from epoch
5787
5788 =cut
5789
5790 sub notify {
5791   my ($customer, $template, %options) = @_;
5792
5793   return unless $conf->exists($template);
5794
5795   my $from = $conf->config('invoice_from') if $conf->exists('invoice_from');
5796   $from = $options{from} if exists($options{from});
5797
5798   my $to = join(',', $customer->invoicing_list_emailonly);
5799   $to = $options{to} if exists($options{to});
5800   
5801   my $subject = "Notice from " . $conf->config('company_name')
5802     if $conf->exists('company_name');
5803   $subject = $options{subject} if exists($options{subject});
5804
5805   my $notify_template = new Text::Template (TYPE => 'ARRAY',
5806                                             SOURCE => [ map "$_\n",
5807                                               $conf->config($template)]
5808                                            )
5809     or die "can't create new Text::Template object: Text::Template::ERROR";
5810   $notify_template->compile()
5811     or die "can't compile template: Text::Template::ERROR";
5812
5813   my $paydate = $customer->paydate || '2037-12-31';
5814   $FS::notify_template::_template::first = $customer->first;
5815   $FS::notify_template::_template::last = $customer->last;
5816   $FS::notify_template::_template::company = $customer->company;
5817   $FS::notify_template::_template::payinfo = $customer->mask_payinfo;
5818   my $payby = $customer->payby;
5819   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5820   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5821
5822   #credit cards expire at the end of the month/year of their exp date
5823   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5824     $FS::notify_template::_template::payby = 'credit card';
5825     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5826     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5827     $expire_time--;
5828   }elsif ($payby eq 'COMP') {
5829     $FS::notify_template::_template::payby = 'complimentary account';
5830   }else{
5831     $FS::notify_template::_template::payby = 'current method';
5832   }
5833   $FS::notify_template::_template::expdate = $expire_time;
5834
5835   for (keys %{$options{extra_fields}}){
5836     no strict "refs";
5837     ${"FS::notify_template::_template::$_"} = $options{extra_fields}->{$_};
5838   }
5839
5840   send_email(from => $from,
5841              to => $to,
5842              subject => $subject,
5843              body => $notify_template->fill_in( PACKAGE =>
5844                                                 'FS::notify_template::_template'                                              ),
5845             );
5846
5847 }
5848
5849 =item generate_letter CUSTOMER_OBJECT TEMPLATE_NAME OPTIONS
5850
5851 Generates a templated notification to the customer (see L<Text::Template>).
5852
5853 OPTIONS is a hash and may include
5854
5855 I<extra_fields> - a hashref of name/value pairs which will be substituted
5856    into the template.  These values may override values mentioned below
5857    and those from the customer record.
5858
5859 The following variables are available in the template instead of or in addition
5860 to the fields of the customer record.
5861
5862 I<$payby> - a description of the method of payment for the customer
5863             # would be nice to use FS::payby::shortname
5864 I<$payinfo> - the masked account information used to collect for this customer
5865 I<$expdate> - the expiration of the customer payment method in seconds from epoch
5866 I<$returnaddress> - the return address defaults to invoice_latexreturnaddress
5867
5868 =cut
5869
5870 sub generate_letter {
5871   my ($self, $template, %options) = @_;
5872
5873   return unless $conf->exists($template);
5874
5875   my $letter_template = new Text::Template
5876                         ( TYPE       => 'ARRAY',
5877                           SOURCE     => [ map "$_\n", $conf->config($template)],
5878                           DELIMITERS => [ '[@--', '--@]' ],
5879                         )
5880     or die "can't create new Text::Template object: Text::Template::ERROR";
5881
5882   $letter_template->compile()
5883     or die "can't compile template: Text::Template::ERROR";
5884
5885   my %letter_data = map { $_ => $self->$_ } $self->fields;
5886   $letter_data{payinfo} = $self->mask_payinfo;
5887
5888   my $paydate = $self->paydate || '2037-12-31';
5889   my $payby = $self->payby;
5890   my ($payyear,$paymonth,$payday) = split (/-/,$paydate);
5891   my $expire_time = timelocal(0,0,0,$payday,--$paymonth,$payyear);
5892
5893   #credit cards expire at the end of the month/year of their exp date
5894   if ($payby eq 'CARD' || $payby eq 'DCRD') {
5895     $letter_data{payby} = 'credit card';
5896     ($paymonth < 11) ? $paymonth++ : ($paymonth=0, $payyear++);
5897     $expire_time = timelocal(0,0,0,$payday,$paymonth,$payyear);
5898     $expire_time--;
5899   }elsif ($payby eq 'COMP') {
5900     $letter_data{payby} = 'complimentary account';
5901   }else{
5902     $letter_data{payby} = 'current method';
5903   }
5904   $letter_data{expdate} = $expire_time;
5905
5906   for (keys %{$options{extra_fields}}){
5907     $letter_data{$_} = $options{extra_fields}->{$_};
5908   }
5909
5910   unless(exists($letter_data{returnaddress})){
5911     my $retadd = join("\n", $conf->config_orbase( 'invoice_latexreturnaddress',
5912                                                   $self->_agent_template)
5913                      );
5914
5915     $letter_data{returnaddress} = length($retadd) ? $retadd : '~';
5916   }
5917
5918   $letter_data{conf_dir} = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
5919
5920   my $dir = $FS::UID::conf_dir."cache.". $FS::UID::datasrc;
5921   my $fh = new File::Temp( TEMPLATE => 'letter.'. $self->custnum. '.XXXXXXXX',
5922                            DIR      => $dir,
5923                            SUFFIX   => '.tex',
5924                            UNLINK   => 0,
5925                          ) or die "can't open temp file: $!\n";
5926
5927   $letter_template->fill_in( OUTPUT => $fh, HASH => \%letter_data );
5928   close $fh;
5929   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
5930   return $1;
5931 }
5932
5933 =item print_ps TEMPLATE 
5934
5935 Returns an postscript letter filled in from TEMPLATE, as a scalar.
5936
5937 =cut
5938
5939 sub print_ps {
5940   my $self = shift;
5941   my $file = $self->generate_letter(@_);
5942   FS::Misc::generate_ps($file);
5943 }
5944
5945 =item print TEMPLATE
5946
5947 Prints the filled in template.
5948
5949 TEMPLATE is the name of a L<Text::Template> to fill in and print.
5950
5951 =cut
5952
5953 sub queueable_print {
5954   my %opt = @_;
5955
5956   my $self = qsearchs('cust_main', { 'custnum' => $opt{custnum} } )
5957     or die "invalid customer number: " . $opt{custvnum};
5958
5959   my $error = $self->print( $opt{template} );
5960   die $error if $error;
5961 }
5962
5963 sub print {
5964   my ($self, $template) = (shift, shift);
5965   do_print [ $self->print_ps($template) ];
5966 }
5967
5968 sub agent_template {
5969   my $self = shift;
5970   $self->_agent_plandata('agent_templatename');
5971 }
5972
5973 sub agent_invoice_from {
5974   my $self = shift;
5975   $self->_agent_plandata('agent_invoice_from');
5976 }
5977
5978 sub _agent_plandata {
5979   my( $self, $option ) = @_;
5980
5981   my $regexp = '';
5982   if ( driver_name =~ /^Pg/i ) {
5983     $regexp = '~';
5984   } elsif ( driver_name =~ /^mysql/i ) {
5985     $regexp = 'REGEXP';
5986   } else {
5987     die "don't know how to use regular expressions in ". driver_name. " databases";
5988   }
5989
5990   my $part_bill_event = qsearchs( 'part_bill_event',
5991     {
5992       'payby'     => $self->payby,
5993       'plan'      => 'send_agent',
5994       'plandata'  => { 'op'    => $regexp,
5995                        'value' => "(^|\n)agentnum ".
5996                                    '([0-9]*, )*'.
5997                                   $self->agentnum.
5998                                    '(, [0-9]*)*'.
5999                                   "(\n|\$)",
6000                      },
6001     },
6002     '',
6003     'ORDER BY seconds LIMIT 1'
6004   );
6005
6006   return '' unless $part_bill_event;
6007
6008   if ( $part_bill_event->plandata =~ /^$option (.*)$/m ) {
6009     return $1;
6010   } else {
6011     warn "can't parse part_bill_event eventpart#". $part_bill_event->eventpart.
6012          " plandata for $option";
6013     return '';
6014   }
6015
6016 }
6017
6018 =back
6019
6020 =head1 BUGS
6021
6022 The delete method.
6023
6024 The delete method should possibly take an FS::cust_main object reference
6025 instead of a scalar customer number.
6026
6027 Bill and collect options should probably be passed as references instead of a
6028 list.
6029
6030 There should probably be a configuration file with a list of allowed credit
6031 card types.
6032
6033 No multiple currency support (probably a larger project than just this module).
6034
6035 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
6036
6037 Birthdates rely on negative epoch values.
6038
6039 The payby for card/check batches is broken.  With mixed batching, bad
6040 things will happen.
6041
6042 =head1 SEE ALSO
6043
6044 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
6045 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
6046 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.
6047
6048 =cut
6049
6050 1;
6051