4 use vars qw( @ISA @EXPORT_OK $conf $DEBUG $import @encrypted_fields);
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
10 eval "use Time::Local;";
11 die "Time::Local minimum version 1.05 required with Perl versions before 5.6"
12 if $] < 5.006 && !defined($Time::Local::VERSION);
13 #eval "use Time::Local qw(timelocal timelocal_nocheck);";
14 eval "use Time::Local qw(timelocal_nocheck);";
18 use String::Approx qw(amatch);
19 use Business::CreditCard;
20 use FS::UID qw( getotaker dbh );
21 use FS::Record qw( qsearchs qsearch dbdef );
22 use FS::Misc qw( send_email );
26 use FS::cust_bill_pkg;
28 use FS::cust_pay_void;
31 use FS::part_referral;
32 use FS::cust_main_county;
34 use FS::cust_main_invoice;
35 use FS::cust_credit_bill;
36 use FS::cust_bill_pay;
37 use FS::prepay_credit;
40 use FS::part_bill_event;
41 use FS::cust_bill_event;
42 use FS::cust_tax_exempt;
44 use FS::Msgcat qw(gettext);
46 @ISA = qw( FS::Record );
48 @EXPORT_OK = qw( smart_search );
50 $realtime_bop_decline_quiet = 0;
57 @encrypted_fields = ('payinfo', 'paycvv');
59 #ask FS::UID to run this stuff for us later
60 #$FS::UID::callback{'FS::cust_main'} = sub {
61 install_callback FS::UID sub {
63 #yes, need it for stuff below (prolly should be cached)
68 my ( $hashref, $cache ) = @_;
69 if ( exists $hashref->{'pkgnum'} ) {
70 # #@{ $self->{'_pkgnum'} } = ();
71 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
72 $self->{'_pkgnum'} = $subcache;
73 #push @{ $self->{'_pkgnum'} },
74 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
80 FS::cust_main - Object methods for cust_main records
86 $record = new FS::cust_main \%hash;
87 $record = new FS::cust_main { 'column' => 'value' };
89 $error = $record->insert;
91 $error = $new_record->replace($old_record);
93 $error = $record->delete;
95 $error = $record->check;
97 @cust_pkg = $record->all_pkgs;
99 @cust_pkg = $record->ncancelled_pkgs;
101 @cust_pkg = $record->suspended_pkgs;
103 $error = $record->bill;
104 $error = $record->bill %options;
105 $error = $record->bill 'time' => $time;
107 $error = $record->collect;
108 $error = $record->collect %options;
109 $error = $record->collect 'invoice_time' => $time,
110 'batch_card' => 'yes',
111 'report_badcard' => 'yes',
116 An FS::cust_main object represents a customer. FS::cust_main inherits from
117 FS::Record. The following fields are currently supported:
121 =item custnum - primary key (assigned automatically for new customers)
123 =item agentnum - agent (see L<FS::agent>)
125 =item refnum - Advertising source (see L<FS::part_referral>)
131 =item ss - social security number (optional)
133 =item company - (optional)
137 =item address2 - (optional)
141 =item county - (optional, see L<FS::cust_main_county>)
143 =item state - (see L<FS::cust_main_county>)
147 =item country - (see L<FS::cust_main_county>)
149 =item daytime - phone (optional)
151 =item night - phone (optional)
153 =item fax - phone (optional)
155 =item ship_first - name
157 =item ship_last - name
159 =item ship_company - (optional)
163 =item ship_address2 - (optional)
167 =item ship_county - (optional, see L<FS::cust_main_county>)
169 =item ship_state - (see L<FS::cust_main_county>)
173 =item ship_country - (see L<FS::cust_main_county>)
175 =item ship_daytime - phone (optional)
177 =item ship_night - phone (optional)
179 =item ship_fax - phone (optional)
183 I<CARD> (credit card - automatic), I<DCRD> (credit card - on-demand), I<CHEK> (electronic check - automatic), I<DCHK> (electronic check - on-demand), I<LECB> (Phone bill billing), I<BILL> (billing), I<COMP> (free), or I<PREPAY> (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to I<BILL>)
187 Card Number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
192 my($self,$payinfo) = @_;
193 if ( defined($payinfo) ) {
194 $self->paymask($payinfo);
195 $self->setfield('payinfo', $payinfo); # This is okay since we are the 'setter'
197 $payinfo = $self->getfield('payinfo'); # This is okay since we are the 'getter'
205 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
209 =item paymask - Masked payment type
215 Mask all but the last four characters.
219 Mask all but last 2 of account number and bank routing number.
223 Do nothing, return the unmasked string.
232 # If it doesn't exist then generate it
233 my $paymask=$self->getfield('paymask');
234 if (!defined($value) && (!defined($paymask) || $paymask eq '')) {
235 $value = $self->payinfo;
238 if ( defined($value) && !$self->is_encrypted($value)) {
239 my $payinfo = $value;
240 my $payby = $self->payby;
241 if ($payby eq 'CARD' || $payby eq 'DCARD') { # Credit Cards (Show last four)
242 $paymask = 'x'x(length($payinfo)-4). substr($payinfo,(length($payinfo)-4));
243 } elsif ($payby eq 'CHEK' ||
244 $payby eq 'DCHK' ) { # Checks (Show last 2 @ bank)
245 my( $account, $aba ) = split('@', $payinfo );
246 $paymask = 'x'x(length($account)-2). substr($account,(length($account)-2))."@".$aba;
247 } else { # Tie up loose ends
250 $self->setfield('paymask', $paymask); # This is okay since we are the 'setter'
251 } elsif (defined($value) && $self->is_encrypted($value)) {
260 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
262 =item payname - name on card or billing name
264 =item tax - tax exempt, empty or `Y'
266 =item otaker - order taker (assigned automatically, see L<FS::UID>)
268 =item comments - comments (optional)
270 =item referral_custnum - referring customer number
280 Creates a new customer. To add the customer to the database, see L<"insert">.
282 Note that this stores the hash reference, not a distinct copy of the hash it
283 points to. You can ask the object for a copy with the I<hash> method.
287 sub table { 'cust_main'; }
289 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] [ , OPTION => VALUE ... ] ]
291 Adds this customer to the database. If there is an error, returns the error,
292 otherwise returns false.
294 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
295 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
296 are inserted atomicly, or the transaction is rolled back. Passing an empty
297 hash reference is equivalent to not supplying this parameter. There should be
298 a better explanation of this, but until then, here's an example:
301 tie %hash, 'Tie::RefHash'; #this part is important
303 $cust_pkg => [ $svc_acct ],
306 $cust_main->insert( \%hash );
308 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
309 be set as the invoicing list (see L<"invoicing_list">). Errors return as
310 expected and rollback the entire transaction; it is not necessary to call
311 check_invoicing_list first. The invoicing_list is set after the records in the
312 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
313 invoicing_list destination to the newly-created svc_acct. Here's an example:
315 $cust_main->insert( {}, [ $email, 'POST' ] );
317 Currently available options are: I<depend_jobnum> and I<noexport>.
319 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
320 on the supplied jobnum (they will not run until the specific job completes).
321 This can be used to defer provisioning until some action completes (such
322 as running the customer's credit card sucessfully).
324 The I<noexport> option is deprecated. If I<noexport> is set true, no
325 provisioning jobs (exports) are scheduled. (You can schedule them later with
326 the B<reexport> method.)
332 my $cust_pkgs = @_ ? shift : {};
333 my $invoicing_list = @_ ? shift : '';
335 warn "FS::cust_main::insert called with options ".
336 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
339 local $SIG{HUP} = 'IGNORE';
340 local $SIG{INT} = 'IGNORE';
341 local $SIG{QUIT} = 'IGNORE';
342 local $SIG{TERM} = 'IGNORE';
343 local $SIG{TSTP} = 'IGNORE';
344 local $SIG{PIPE} = 'IGNORE';
346 my $oldAutoCommit = $FS::UID::AutoCommit;
347 local $FS::UID::AutoCommit = 0;
350 my $prepay_credit = '';
352 if ( $self->payby eq 'PREPAY' ) {
353 $self->payby('BILL');
354 $prepay_credit = qsearchs(
356 { 'identifier' => $self->payinfo },
360 unless ( $prepay_credit ) {
361 $dbh->rollback if $oldAutoCommit;
362 return "Invalid prepaid card: ". $self->payinfo;
364 $seconds = $prepay_credit->seconds;
365 if ( $prepay_credit->agentnum ) {
366 if ( $self->agentnum && $self->agentnum != $prepay_credit->agentnum ) {
367 $dbh->rollback if $oldAutoCommit;
368 return "prepaid card not valid for agent ". $self->agentnum;
370 $self->agentnum($prepay_credit->agentnum);
372 my $error = $prepay_credit->delete;
374 $dbh->rollback if $oldAutoCommit;
375 return "removing prepay_credit (transaction rolled back): $error";
379 my $error = $self->SUPER::insert;
381 $dbh->rollback if $oldAutoCommit;
382 #return "inserting cust_main record (transaction rolled back): $error";
387 if ( $invoicing_list ) {
388 $error = $self->check_invoicing_list( $invoicing_list );
390 $dbh->rollback if $oldAutoCommit;
391 return "checking invoicing_list (transaction rolled back): $error";
393 $self->invoicing_list( $invoicing_list );
397 $error = $self->order_pkgs($cust_pkgs, \$seconds, %options);
399 $dbh->rollback if $oldAutoCommit;
404 $dbh->rollback if $oldAutoCommit;
405 return "No svc_acct record to apply pre-paid time";
408 if ( $prepay_credit && $prepay_credit->amount ) {
409 my $cust_pay = new FS::cust_pay {
410 'custnum' => $self->custnum,
411 'paid' => $prepay_credit->amount,
412 #'_date' => #date the prepaid card was purchased???
414 'payinfo' => $prepay_credit->identifier,
416 $error = $cust_pay->insert;
418 $dbh->rollback if $oldAutoCommit;
419 return "inserting prepayment (transaction rolled back): $error";
423 $error = $self->queue_fuzzyfiles_update;
425 $dbh->rollback if $oldAutoCommit;
426 return "updating fuzzy search cache: $error";
429 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
434 =item order_pkgs HASHREF, [ SECONDSREF, [ , OPTION => VALUE ... ] ]
436 Like the insert method on an existing record, this method orders a package
437 and included services atomicaly. Pass a Tie::RefHash data structure to this
438 method containing FS::cust_pkg and FS::svc_I<tablename> objects. There should
439 be a better explanation of this, but until then, here's an example:
442 tie %hash, 'Tie::RefHash'; #this part is important
444 $cust_pkg => [ $svc_acct ],
447 $cust_main->order_pkgs( \%hash, \'0', 'noexport'=>1 );
449 Services can be new, in which case they are inserted, or existing unaudited
450 services, in which case they are linked to the newly-created package.
452 Currently available options are: I<depend_jobnum> and I<noexport>.
454 If I<depend_jobnum> is set, all provisioning jobs will have a dependancy
455 on the supplied jobnum (they will not run until the specific job completes).
456 This can be used to defer provisioning until some action completes (such
457 as running the customer's credit card sucessfully).
459 The I<noexport> option is deprecated. If I<noexport> is set true, no
460 provisioning jobs (exports) are scheduled. (You can schedule them later with
461 the B<reexport> method for each cust_pkg object. Using the B<reexport> method
462 on the cust_main object is not recommended, as existing services will also be
469 my $cust_pkgs = shift;
472 my %svc_options = ();
473 $svc_options{'depend_jobnum'} = $options{'depend_jobnum'}
474 if exists $options{'depend_jobnum'};
475 warn "FS::cust_main::order_pkgs called with options ".
476 join(', ', map { "$_: $options{$_}" } keys %options ). "\n"
479 local $SIG{HUP} = 'IGNORE';
480 local $SIG{INT} = 'IGNORE';
481 local $SIG{QUIT} = 'IGNORE';
482 local $SIG{TERM} = 'IGNORE';
483 local $SIG{TSTP} = 'IGNORE';
484 local $SIG{PIPE} = 'IGNORE';
486 my $oldAutoCommit = $FS::UID::AutoCommit;
487 local $FS::UID::AutoCommit = 0;
490 local $FS::svc_Common::noexport_hack = 1 if $options{'noexport'};
492 foreach my $cust_pkg ( keys %$cust_pkgs ) {
493 $cust_pkg->custnum( $self->custnum );
494 my $error = $cust_pkg->insert;
496 $dbh->rollback if $oldAutoCommit;
497 return "inserting cust_pkg (transaction rolled back): $error";
499 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
500 if ( $svc_something->svcnum ) {
501 my $old_cust_svc = $svc_something->cust_svc;
502 my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
503 $new_cust_svc->pkgnum( $cust_pkg->pkgnum);
504 $error = $new_cust_svc->replace($old_cust_svc);
506 $svc_something->pkgnum( $cust_pkg->pkgnum );
507 if ( $seconds && $$seconds && $svc_something->isa('FS::svc_acct') ) {
508 $svc_something->seconds( $svc_something->seconds + $$seconds );
511 $error = $svc_something->insert(%svc_options);
514 $dbh->rollback if $oldAutoCommit;
515 #return "inserting svc_ (transaction rolled back): $error";
521 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
527 This method is deprecated. See the I<depend_jobnum> option to the insert and
528 order_pkgs methods for a better way to defer provisioning.
530 Re-schedules all exports by calling the B<reexport> method of all associated
531 packages (see L<FS::cust_pkg>). If there is an error, returns the error;
532 otherwise returns false.
539 carp "warning: FS::cust_main::reexport is deprectated; ".
540 "use the depend_jobnum option to insert or order_pkgs to delay export";
542 local $SIG{HUP} = 'IGNORE';
543 local $SIG{INT} = 'IGNORE';
544 local $SIG{QUIT} = 'IGNORE';
545 local $SIG{TERM} = 'IGNORE';
546 local $SIG{TSTP} = 'IGNORE';
547 local $SIG{PIPE} = 'IGNORE';
549 my $oldAutoCommit = $FS::UID::AutoCommit;
550 local $FS::UID::AutoCommit = 0;
553 foreach my $cust_pkg ( $self->ncancelled_pkgs ) {
554 my $error = $cust_pkg->reexport;
556 $dbh->rollback if $oldAutoCommit;
561 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
566 =item delete NEW_CUSTNUM
568 This deletes the customer. If there is an error, returns the error, otherwise
571 This will completely remove all traces of the customer record. This is not
572 what you want when a customer cancels service; for that, cancel all of the
573 customer's packages (see L</cancel>).
575 If the customer has any uncancelled packages, you need to pass a new (valid)
576 customer number for those packages to be transferred to. Cancelled packages
577 will be deleted. Did I mention that this is NOT what you want when a customer
578 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
580 You can't delete a customer with invoices (see L<FS::cust_bill>),
581 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
582 refunds (see L<FS::cust_refund>).
589 local $SIG{HUP} = 'IGNORE';
590 local $SIG{INT} = 'IGNORE';
591 local $SIG{QUIT} = 'IGNORE';
592 local $SIG{TERM} = 'IGNORE';
593 local $SIG{TSTP} = 'IGNORE';
594 local $SIG{PIPE} = 'IGNORE';
596 my $oldAutoCommit = $FS::UID::AutoCommit;
597 local $FS::UID::AutoCommit = 0;
600 if ( $self->cust_bill ) {
601 $dbh->rollback if $oldAutoCommit;
602 return "Can't delete a customer with invoices";
604 if ( $self->cust_credit ) {
605 $dbh->rollback if $oldAutoCommit;
606 return "Can't delete a customer with credits";
608 if ( $self->cust_pay ) {
609 $dbh->rollback if $oldAutoCommit;
610 return "Can't delete a customer with payments";
612 if ( $self->cust_refund ) {
613 $dbh->rollback if $oldAutoCommit;
614 return "Can't delete a customer with refunds";
617 my @cust_pkg = $self->ncancelled_pkgs;
619 my $new_custnum = shift;
620 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
621 $dbh->rollback if $oldAutoCommit;
622 return "Invalid new customer number: $new_custnum";
624 foreach my $cust_pkg ( @cust_pkg ) {
625 my %hash = $cust_pkg->hash;
626 $hash{'custnum'} = $new_custnum;
627 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
628 my $error = $new_cust_pkg->replace($cust_pkg);
630 $dbh->rollback if $oldAutoCommit;
635 my @cancelled_cust_pkg = $self->all_pkgs;
636 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
637 my $error = $cust_pkg->delete;
639 $dbh->rollback if $oldAutoCommit;
644 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
645 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
647 my $error = $cust_main_invoice->delete;
649 $dbh->rollback if $oldAutoCommit;
654 my $error = $self->SUPER::delete;
656 $dbh->rollback if $oldAutoCommit;
660 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
665 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
667 Replaces the OLD_RECORD with this one in the database. If there is an error,
668 returns the error, otherwise returns false.
670 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
671 be set as the invoicing list (see L<"invoicing_list">). Errors return as
672 expected and rollback the entire transaction; it is not necessary to call
673 check_invoicing_list first. Here's an example:
675 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
684 local $SIG{HUP} = 'IGNORE';
685 local $SIG{INT} = 'IGNORE';
686 local $SIG{QUIT} = 'IGNORE';
687 local $SIG{TERM} = 'IGNORE';
688 local $SIG{TSTP} = 'IGNORE';
689 local $SIG{PIPE} = 'IGNORE';
691 # If the mask is blank then try to set it - if we can...
692 if (!defined($self->getfield('paymask')) || $self->getfield('paymask') eq '') {
693 $self->paymask($self->payinfo);
696 # We absolutely have to have an old vs. new record to make this work.
697 if (!defined($old)) {
698 $old = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
701 if ( $self->payby eq 'COMP' && $self->payby ne $old->payby
702 && $conf->config('users-allow_comp') ) {
703 return "You are not permitted to create complimentary accounts."
704 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
707 my $oldAutoCommit = $FS::UID::AutoCommit;
708 local $FS::UID::AutoCommit = 0;
711 my $error = $self->SUPER::replace($old);
714 $dbh->rollback if $oldAutoCommit;
718 if ( @param ) { # INVOICING_LIST_ARYREF
719 my $invoicing_list = shift @param;
720 $error = $self->check_invoicing_list( $invoicing_list );
722 $dbh->rollback if $oldAutoCommit;
725 $self->invoicing_list( $invoicing_list );
728 if ( $self->payby =~ /^(CARD|CHEK|LECB)$/ &&
729 grep { $self->get($_) ne $old->get($_) } qw(payinfo paydate payname) ) {
730 # card/check/lec info has changed, want to retry realtime_ invoice events
731 my $error = $self->retry_realtime;
733 $dbh->rollback if $oldAutoCommit;
738 $error = $self->queue_fuzzyfiles_update;
740 $dbh->rollback if $oldAutoCommit;
741 return "updating fuzzy search cache: $error";
744 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
749 =item queue_fuzzyfiles_update
751 Used by insert & replace to update the fuzzy search cache
755 sub queue_fuzzyfiles_update {
758 local $SIG{HUP} = 'IGNORE';
759 local $SIG{INT} = 'IGNORE';
760 local $SIG{QUIT} = 'IGNORE';
761 local $SIG{TERM} = 'IGNORE';
762 local $SIG{TSTP} = 'IGNORE';
763 local $SIG{PIPE} = 'IGNORE';
765 my $oldAutoCommit = $FS::UID::AutoCommit;
766 local $FS::UID::AutoCommit = 0;
769 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
770 my $error = $queue->insert($self->getfield('last'), $self->company);
772 $dbh->rollback if $oldAutoCommit;
773 return "queueing job (transaction rolled back): $error";
776 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
777 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
778 $error = $queue->insert($self->getfield('ship_last'), $self->ship_company);
780 $dbh->rollback if $oldAutoCommit;
781 return "queueing job (transaction rolled back): $error";
785 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
792 Checks all fields to make sure this is a valid customer record. If there is
793 an error, returns the error, otherwise returns false. Called by the insert
801 #warn "BEFORE: \n". $self->_dump;
804 $self->ut_numbern('custnum')
805 || $self->ut_number('agentnum')
806 || $self->ut_number('refnum')
807 || $self->ut_name('last')
808 || $self->ut_name('first')
809 || $self->ut_textn('company')
810 || $self->ut_text('address1')
811 || $self->ut_textn('address2')
812 || $self->ut_text('city')
813 || $self->ut_textn('county')
814 || $self->ut_textn('state')
815 || $self->ut_country('country')
816 || $self->ut_anything('comments')
817 || $self->ut_numbern('referral_custnum')
819 #barf. need message catalogs. i18n. etc.
820 $error .= "Please select an advertising source."
821 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
822 return $error if $error;
824 return "Unknown agent"
825 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
827 return "Unknown refnum"
828 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
830 return "Unknown referring custnum ". $self->referral_custnum
831 unless ! $self->referral_custnum
832 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
834 if ( $self->ss eq '' ) {
839 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
840 or return "Illegal social security number: ". $self->ss;
841 $self->ss("$1-$2-$3");
845 # bad idea to disable, causes billing to fail because of no tax rates later
846 # unless ( $import ) {
847 unless ( qsearch('cust_main_county', {
848 'country' => $self->country,
851 return "Unknown state/county/country: ".
852 $self->state. "/". $self->county. "/". $self->country
853 unless qsearch('cust_main_county',{
854 'state' => $self->state,
855 'county' => $self->county,
856 'country' => $self->country,
862 $self->ut_phonen('daytime', $self->country)
863 || $self->ut_phonen('night', $self->country)
864 || $self->ut_phonen('fax', $self->country)
865 || $self->ut_zip('zip', $self->country)
867 return $error if $error;
870 last first company address1 address2 city county state zip
871 country daytime night fax
874 if ( defined $self->dbdef_table->column('ship_last') ) {
875 if ( scalar ( grep { $self->getfield($_) ne $self->getfield("ship_$_") }
877 && scalar ( grep { $self->getfield("ship_$_") ne '' } @addfields )
881 $self->ut_name('ship_last')
882 || $self->ut_name('ship_first')
883 || $self->ut_textn('ship_company')
884 || $self->ut_text('ship_address1')
885 || $self->ut_textn('ship_address2')
886 || $self->ut_text('ship_city')
887 || $self->ut_textn('ship_county')
888 || $self->ut_textn('ship_state')
889 || $self->ut_country('ship_country')
891 return $error if $error;
893 #false laziness with above
894 unless ( qsearchs('cust_main_county', {
895 'country' => $self->ship_country,
898 return "Unknown ship_state/ship_county/ship_country: ".
899 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
900 unless qsearchs('cust_main_county',{
901 'state' => $self->ship_state,
902 'county' => $self->ship_county,
903 'country' => $self->ship_country,
909 $self->ut_phonen('ship_daytime', $self->ship_country)
910 || $self->ut_phonen('ship_night', $self->ship_country)
911 || $self->ut_phonen('ship_fax', $self->ship_country)
912 || $self->ut_zip('ship_zip', $self->ship_country)
914 return $error if $error;
916 } else { # ship_ info eq billing info, so don't store dup info in database
917 $self->setfield("ship_$_", '')
918 foreach qw( last first company address1 address2 city county state zip
919 country daytime night fax );
923 $self->payby =~ /^(CARD|DCRD|CHEK|DCHK|LECB|BILL|COMP|PREPAY)$/
924 or return "Illegal payby: ". $self->payby;
926 # If it is encrypted and the private key is not availaible then we can't
927 # check the credit card.
929 my $check_payinfo = 1;
931 if ($self->is_encrypted($self->payinfo)) {
937 if ( $check_payinfo && ($self->payby eq 'CARD' || $self->payby eq 'DCRD')) {
939 my $payinfo = $self->payinfo;
941 $payinfo =~ /^(\d{13,16})$/
942 or return gettext('invalid_card'); # . ": ". $self->payinfo;
944 $self->payinfo($payinfo);
946 or return gettext('invalid_card'); # . ": ". $self->payinfo;
947 return gettext('unknown_card_type')
948 if cardtype($self->payinfo) eq "Unknown";
949 if ( defined $self->dbdef_table->column('paycvv') ) {
950 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
951 if ( cardtype($self->payinfo) eq 'American Express card' ) {
952 $self->paycvv =~ /^(\d{4})$/
953 or return "CVV2 (CID) for American Express cards is four digits.";
956 $self->paycvv =~ /^(\d{3})$/
957 or return "CVV2 (CVC2/CID) is three digits.";
965 } elsif ($check_payinfo && ( $self->payby eq 'CHEK' || $self->payby eq 'DCHK' )) {
967 my $payinfo = $self->payinfo;
968 $payinfo =~ s/[^\d\@]//g;
969 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
971 $self->payinfo($payinfo);
972 $self->paycvv('') if $self->dbdef_table->column('paycvv');
974 } elsif ( $self->payby eq 'LECB' ) {
976 my $payinfo = $self->payinfo;
978 $payinfo =~ /^1?(\d{10})$/ or return 'invalid btn billing telephone number';
980 $self->payinfo($payinfo);
981 $self->paycvv('') if $self->dbdef_table->column('paycvv');
983 } elsif ( $self->payby eq 'BILL' ) {
985 $error = $self->ut_textn('payinfo');
986 return "Illegal P.O. number: ". $self->payinfo if $error;
987 $self->paycvv('') if $self->dbdef_table->column('paycvv');
989 } elsif ( $self->payby eq 'COMP' ) {
991 if ( !$self->custnum && $conf->config('users-allow_comp') ) {
992 return "You are not permitted to create complimentary accounts."
993 unless grep { $_ eq getotaker } $conf->config('users-allow_comp');
996 $error = $self->ut_textn('payinfo');
997 return "Illegal comp account issuer: ". $self->payinfo if $error;
998 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1000 } elsif ( $self->payby eq 'PREPAY' ) {
1002 my $payinfo = $self->payinfo;
1003 $payinfo =~ s/\W//g; #anything else would just confuse things
1004 $self->payinfo($payinfo);
1005 $error = $self->ut_alpha('payinfo');
1006 return "Illegal prepayment identifier: ". $self->payinfo if $error;
1007 return "Unknown prepayment identifier"
1008 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
1009 $self->paycvv('') if $self->dbdef_table->column('paycvv');
1013 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
1014 return "Expriation date required"
1015 unless $self->payby =~ /^(BILL|PREPAY|CHEK|LECB)$/;
1019 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
1020 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
1021 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
1022 ( $m, $y ) = ( $3, "20$2" );
1024 return "Illegal expiration date: ". $self->paydate;
1026 $self->paydate("$y-$m-01");
1027 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
1028 return gettext('expired_card')
1029 if !$import && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
1032 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
1033 ( ! $conf->exists('require_cardname')
1034 || $self->payby !~ /^(CARD|DCRD)$/ )
1036 $self->payname( $self->first. " ". $self->getfield('last') );
1038 $self->payname =~ /^([\w \,\.\-\'\&]+)$/
1039 or return gettext('illegal_name'). " payname: ". $self->payname;
1043 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
1046 $self->otaker(getotaker) unless $self->otaker;
1048 #warn "AFTER: \n". $self->_dump;
1050 $self->SUPER::check;
1055 Returns all packages (see L<FS::cust_pkg>) for this customer.
1061 if ( $self->{'_pkgnum'} ) {
1062 values %{ $self->{'_pkgnum'}->cache };
1064 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
1068 =item ncancelled_pkgs
1070 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
1074 sub ncancelled_pkgs {
1076 if ( $self->{'_pkgnum'} ) {
1077 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
1079 @{ [ # force list context
1080 qsearch( 'cust_pkg', {
1081 'custnum' => $self->custnum,
1084 qsearch( 'cust_pkg', {
1085 'custnum' => $self->custnum,
1092 =item suspended_pkgs
1094 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
1098 sub suspended_pkgs {
1100 grep { $_->susp } $self->ncancelled_pkgs;
1103 =item unflagged_suspended_pkgs
1105 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
1106 customer (thouse packages without the `manual_flag' set).
1110 sub unflagged_suspended_pkgs {
1112 return $self->suspended_pkgs
1113 unless dbdef->table('cust_pkg')->column('manual_flag');
1114 grep { ! $_->manual_flag } $self->suspended_pkgs;
1117 =item unsuspended_pkgs
1119 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
1124 sub unsuspended_pkgs {
1126 grep { ! $_->susp } $self->ncancelled_pkgs;
1129 =item num_cancelled_pkgs
1131 Returns the number of cancelled packages (see L<FS::cust_pkg>) for this
1136 sub num_cancelled_pkgs {
1138 $self->num_pkgs("cancel IS NOT NULL AND cust_pkg.cancel != 0");
1142 my( $self, $sql ) = @_;
1143 my $sth = dbh->prepare(
1144 "SELECT COUNT(*) FROM cust_pkg WHERE custnum = ? AND $sql"
1145 ) or die dbh->errstr;
1146 $sth->execute($self->custnum) or die $sth->errstr;
1147 $sth->fetchrow_arrayref->[0];
1152 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
1153 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
1154 on success or a list of errors.
1160 grep { $_->unsuspend } $self->suspended_pkgs;
1165 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
1166 Always returns a list: an empty list on success or a list of errors.
1172 grep { $_->suspend } $self->unsuspended_pkgs;
1175 =item suspend_if_pkgpart PKGPART [ , PKGPART ... ]
1177 Suspends all unsuspended packages (see L<FS::cust_pkg>) matching the listed
1178 PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list on
1179 success or a list of errors.
1183 sub suspend_if_pkgpart {
1186 grep { $_->suspend }
1187 grep { my $pkgpart = $_->pkgpart; grep { $pkgpart eq $_ } @pkgparts }
1188 $self->unsuspended_pkgs;
1191 =item suspend_unless_pkgpart PKGPART [ , PKGPART ... ]
1193 Suspends all unsuspended packages (see L<FS::cust_pkg>) unless they match the
1194 listed PKGPARTs (see L<FS::part_pkg>). Always returns a list: an empty list
1195 on success or a list of errors.
1199 sub suspend_unless_pkgpart {
1202 grep { $_->suspend }
1203 grep { my $pkgpart = $_->pkgpart; ! grep { $pkgpart eq $_ } @pkgparts }
1204 $self->unsuspended_pkgs;
1207 =item cancel [ OPTION => VALUE ... ]
1209 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
1211 Available options are: I<quiet>
1213 I<quiet> can be set true to supress email cancellation notices.
1215 Always returns a list: an empty list on success or a list of errors.
1221 grep { $_ } map { $_->cancel(@_) } $self->ncancelled_pkgs;
1226 Returns the agent (see L<FS::agent>) for this customer.
1232 qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
1237 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
1238 conjunction with the collect method.
1240 Options are passed as name-value pairs.
1242 Currently available options are:
1244 resetup - if set true, re-charges setup fees.
1246 time - bills the customer as if it were that time. Specified as a UNIX
1247 timestamp; see L<perlfunc/"time">). Also see L<Time::Local> and
1248 L<Date::Parse> for conversion functions. For example:
1252 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
1255 If there is an error, returns the error, otherwise returns false.
1260 my( $self, %options ) = @_;
1261 return '' if $self->payby eq 'COMP';
1262 warn "bill customer ". $self->custnum if $DEBUG;
1264 my $time = $options{'time'} || time;
1269 local $SIG{HUP} = 'IGNORE';
1270 local $SIG{INT} = 'IGNORE';
1271 local $SIG{QUIT} = 'IGNORE';
1272 local $SIG{TERM} = 'IGNORE';
1273 local $SIG{TSTP} = 'IGNORE';
1274 local $SIG{PIPE} = 'IGNORE';
1276 my $oldAutoCommit = $FS::UID::AutoCommit;
1277 local $FS::UID::AutoCommit = 0;
1280 $self->select_for_update; #mutex
1282 # find the packages which are due for billing, find out how much they are
1283 # & generate invoice database.
1285 my( $total_setup, $total_recur ) = ( 0, 0 );
1286 #my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
1287 my @cust_bill_pkg = ();
1289 #my $taxable_charged = 0;##
1294 foreach my $cust_pkg (
1295 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
1298 #NO!! next if $cust_pkg->cancel;
1299 next if $cust_pkg->getfield('cancel');
1301 warn " bill package ". $cust_pkg->pkgnum if $DEBUG;
1303 #? to avoid use of uninitialized value errors... ?
1304 $cust_pkg->setfield('bill', '')
1305 unless defined($cust_pkg->bill);
1307 my $part_pkg = $cust_pkg->part_pkg;
1309 my %hash = $cust_pkg->hash;
1310 my $old_cust_pkg = new FS::cust_pkg \%hash;
1316 if ( !$cust_pkg->setup || $options{'resetup'} ) {
1318 warn " bill setup" if $DEBUG;
1320 $setup = eval { $cust_pkg->calc_setup( $time ) };
1322 $dbh->rollback if $oldAutoCommit;
1326 $cust_pkg->setfield('setup', $time) unless $cust_pkg->setup;
1332 if ( $part_pkg->getfield('freq') ne '0' &&
1333 ! $cust_pkg->getfield('susp') &&
1334 ( $cust_pkg->getfield('bill') || 0 ) <= $time
1337 warn " bill recur" if $DEBUG;
1339 # XXX shared with $recur_prog
1340 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1342 $recur = eval { $cust_pkg->calc_recur( \$sdate, \@details ) };
1344 $dbh->rollback if $oldAutoCommit;
1348 #change this bit to use Date::Manip? CAREFUL with timezones (see
1349 # mailing list archive)
1350 my ($sec,$min,$hour,$mday,$mon,$year) =
1351 (localtime($sdate) )[0,1,2,3,4,5];
1353 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
1354 # only for figuring next bill date, nothing else, so, reset $sdate again
1356 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
1357 $cust_pkg->last_bill($sdate)
1358 if $cust_pkg->dbdef_table->column('last_bill');
1360 if ( $part_pkg->freq =~ /^\d+$/ ) {
1361 $mon += $part_pkg->freq;
1362 until ( $mon < 12 ) { $mon -= 12; $year++; }
1363 } elsif ( $part_pkg->freq =~ /^(\d+)w$/ ) {
1365 $mday += $weeks * 7;
1366 } elsif ( $part_pkg->freq =~ /^(\d+)d$/ ) {
1370 $dbh->rollback if $oldAutoCommit;
1371 return "unparsable frequency: ". $part_pkg->freq;
1373 $cust_pkg->setfield('bill',
1374 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year));
1377 warn "\$setup is undefined" unless defined($setup);
1378 warn "\$recur is undefined" unless defined($recur);
1379 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
1381 if ( $cust_pkg->modified ) {
1383 warn " package ". $cust_pkg->pkgnum. " modified; updating\n" if $DEBUG;
1385 $error=$cust_pkg->replace($old_cust_pkg);
1386 if ( $error ) { #just in case
1387 $dbh->rollback if $oldAutoCommit;
1388 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
1391 $setup = sprintf( "%.2f", $setup );
1392 $recur = sprintf( "%.2f", $recur );
1393 if ( $setup < 0 && ! $conf->exists('allow_negative_charges') ) {
1394 $dbh->rollback if $oldAutoCommit;
1395 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
1397 if ( $recur < 0 && ! $conf->exists('allow_negative_charges') ) {
1398 $dbh->rollback if $oldAutoCommit;
1399 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
1401 if ( $setup != 0 || $recur != 0 ) {
1402 warn " charges (setup=$setup, recur=$recur); queueing line items\n"
1404 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1405 'pkgnum' => $cust_pkg->pkgnum,
1409 'edate' => $cust_pkg->bill,
1410 'details' => \@details,
1412 push @cust_bill_pkg, $cust_bill_pkg;
1413 $total_setup += $setup;
1414 $total_recur += $recur;
1416 unless ( $self->tax =~ /Y/i || $self->payby eq 'COMP' ) {
1418 my @taxes = qsearch( 'cust_main_county', {
1419 'state' => $self->state,
1420 'county' => $self->county,
1421 'country' => $self->country,
1422 'taxclass' => $part_pkg->taxclass,
1425 @taxes = qsearch( 'cust_main_county', {
1426 'state' => $self->state,
1427 'county' => $self->county,
1428 'country' => $self->country,
1433 #one more try at a whole-country tax rate
1435 @taxes = qsearch( 'cust_main_county', {
1438 'country' => $self->country,
1443 # maybe eliminate this entirely, along with all the 0% records
1445 $dbh->rollback if $oldAutoCommit;
1447 "fatal: can't find tax rate for state/county/country/taxclass ".
1448 join('/', ( map $self->$_(), qw(state county country) ),
1449 $part_pkg->taxclass ). "\n";
1452 foreach my $tax ( @taxes ) {
1454 my $taxable_charged = 0;
1455 $taxable_charged += $setup
1456 unless $part_pkg->setuptax =~ /^Y$/i
1457 || $tax->setuptax =~ /^Y$/i;
1458 $taxable_charged += $recur
1459 unless $part_pkg->recurtax =~ /^Y$/i
1460 || $tax->recurtax =~ /^Y$/i;
1461 next unless $taxable_charged;
1463 if ( $tax->exempt_amount && $tax->exempt_amount > 0 ) {
1464 my ($mon,$year) = (localtime($sdate) )[4,5];
1466 my $freq = $part_pkg->freq || 1;
1467 if ( $freq !~ /(\d+)$/ ) {
1468 $dbh->rollback if $oldAutoCommit;
1469 return "daily/weekly package definitions not (yet?)".
1470 " compatible with monthly tax exemptions";
1472 my $taxable_per_month = sprintf("%.2f", $taxable_charged / $freq );
1473 foreach my $which_month ( 1 .. $freq ) {
1475 'custnum' => $self->custnum,
1476 'taxnum' => $tax->taxnum,
1477 'year' => 1900+$year,
1480 #until ( $mon < 12 ) { $mon -= 12; $year++; }
1481 until ( $mon < 13 ) { $mon -= 12; $year++; }
1482 my $cust_tax_exempt =
1483 qsearchs('cust_tax_exempt', \%hash)
1484 || new FS::cust_tax_exempt( { %hash, 'amount' => 0 } );
1485 my $remaining_exemption = sprintf("%.2f",
1486 $tax->exempt_amount - $cust_tax_exempt->amount );
1487 if ( $remaining_exemption > 0 ) {
1488 my $addl = $remaining_exemption > $taxable_per_month
1489 ? $taxable_per_month
1490 : $remaining_exemption;
1491 $taxable_charged -= $addl;
1492 my $new_cust_tax_exempt = new FS::cust_tax_exempt ( {
1493 $cust_tax_exempt->hash,
1495 sprintf("%.2f", $cust_tax_exempt->amount + $addl),
1497 $error = $new_cust_tax_exempt->exemptnum
1498 ? $new_cust_tax_exempt->replace($cust_tax_exempt)
1499 : $new_cust_tax_exempt->insert;
1501 $dbh->rollback if $oldAutoCommit;
1502 return "fatal: can't update cust_tax_exempt: $error";
1505 } # if $remaining_exemption > 0
1507 } #foreach $which_month
1509 } #if $tax->exempt_amount
1511 $taxable_charged = sprintf( "%.2f", $taxable_charged);
1513 #$tax += $taxable_charged * $cust_main_county->tax / 100
1514 $tax{ $tax->taxname || 'Tax' } +=
1515 $taxable_charged * $tax->tax / 100
1517 } #foreach my $tax ( @taxes )
1519 } #unless $self->tax =~ /Y/i || $self->payby eq 'COMP'
1521 } #if $setup != 0 || $recur != 0
1523 } #if $cust_pkg->modified
1525 } #foreach my $cust_pkg
1527 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
1528 # my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
1530 unless ( @cust_bill_pkg ) { #don't create invoices with no line items
1531 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1535 # unless ( $self->tax =~ /Y/i
1536 # || $self->payby eq 'COMP'
1537 # || $taxable_charged == 0 ) {
1538 # my $cust_main_county = qsearchs('cust_main_county',{
1539 # 'state' => $self->state,
1540 # 'county' => $self->county,
1541 # 'country' => $self->country,
1542 # } ) or die "fatal: can't find tax rate for state/county/country ".
1543 # $self->state. "/". $self->county. "/". $self->country. "\n";
1544 # my $tax = sprintf( "%.2f",
1545 # $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1548 if ( dbdef->table('cust_bill_pkg')->column('itemdesc') ) { #1.5 schema
1550 foreach my $taxname ( grep { $tax{$_} > 0 } keys %tax ) {
1551 my $tax = sprintf("%.2f", $tax{$taxname} );
1552 $charged = sprintf( "%.2f", $charged+$tax );
1554 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1560 'itemdesc' => $taxname,
1562 push @cust_bill_pkg, $cust_bill_pkg;
1565 } else { #1.4 schema
1568 foreach ( values %tax ) { $tax += $_ };
1569 $tax = sprintf("%.2f", $tax);
1571 $charged = sprintf( "%.2f", $charged+$tax );
1573 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1580 push @cust_bill_pkg, $cust_bill_pkg;
1585 my $cust_bill = new FS::cust_bill ( {
1586 'custnum' => $self->custnum,
1588 'charged' => $charged,
1590 $error = $cust_bill->insert;
1592 $dbh->rollback if $oldAutoCommit;
1593 return "can't create invoice for customer #". $self->custnum. ": $error";
1596 my $invnum = $cust_bill->invnum;
1598 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1600 $cust_bill_pkg->invnum($invnum);
1601 $error = $cust_bill_pkg->insert;
1603 $dbh->rollback if $oldAutoCommit;
1604 return "can't create invoice line item for customer #". $self->custnum.
1609 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1613 =item collect OPTIONS
1615 (Attempt to) collect money for this customer's outstanding invoices (see
1616 L<FS::cust_bill>). Usually used after the bill method.
1618 Depending on the value of `payby', this may print or email an invoice (I<BILL>,
1619 I<DCRD>, or I<DCHK>), charge a credit card (I<CARD>), charge via electronic
1620 check/ACH (I<CHEK>), or just add any necessary (pseudo-)payment (I<COMP>).
1622 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1623 and the invoice events web interface.
1625 If there is an error, returns the error, otherwise returns false.
1627 Options are passed as name-value pairs.
1629 Currently available options are:
1631 invoice_time - Use this time when deciding when to print invoices and
1632 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>
1633 for conversion functions.
1635 retry - Retry card/echeck/LEC transactions even when not scheduled by invoice
1638 retry_card - Deprecated alias for 'retry'
1640 batch_card - This option is deprecated. See the invoice events web interface
1641 to control whether cards are batched or run against a realtime gateway.
1643 report_badcard - This option is deprecated.
1645 force_print - This option is deprecated; see the invoice events web interface.
1647 quiet - set true to surpress email card/ACH decline notices.
1652 my( $self, %options ) = @_;
1653 my $invoice_time = $options{'invoice_time'} || time;
1656 local $SIG{HUP} = 'IGNORE';
1657 local $SIG{INT} = 'IGNORE';
1658 local $SIG{QUIT} = 'IGNORE';
1659 local $SIG{TERM} = 'IGNORE';
1660 local $SIG{TSTP} = 'IGNORE';
1661 local $SIG{PIPE} = 'IGNORE';
1663 my $oldAutoCommit = $FS::UID::AutoCommit;
1664 local $FS::UID::AutoCommit = 0;
1667 $self->select_for_update; #mutex
1669 my $balance = $self->balance;
1670 warn "collect customer ". $self->custnum. ": balance $balance" if $DEBUG;
1671 unless ( $balance > 0 ) { #redundant?????
1672 $dbh->rollback if $oldAutoCommit; #hmm
1676 if ( exists($options{'retry_card'}) ) {
1677 carp 'retry_card option passed to collect is deprecated; use retry';
1678 $options{'retry'} ||= $options{'retry_card'};
1680 if ( exists($options{'retry'}) && $options{'retry'} ) {
1681 my $error = $self->retry_realtime;
1683 $dbh->rollback if $oldAutoCommit;
1688 foreach my $cust_bill ( $self->open_cust_bill ) {
1690 # don't try to charge for the same invoice if it's already in a batch
1691 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1693 last if $self->balance <= 0;
1695 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ")"
1698 foreach my $part_bill_event (
1699 sort { $a->seconds <=> $b->seconds
1700 || $a->weight <=> $b->weight
1701 || $a->eventpart <=> $b->eventpart }
1702 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1703 && ! qsearch( 'cust_bill_event', {
1704 'invnum' => $cust_bill->invnum,
1705 'eventpart' => $_->eventpart,
1709 qsearch('part_bill_event', { 'payby' => $self->payby,
1710 'disabled' => '', } )
1713 last if $cust_bill->owed <= 0 # don't run subsequent events if owed<=0
1714 || $self->balance <= 0; # or if balance<=0
1716 warn "calling invoice event (". $part_bill_event->eventcode. ")\n"
1718 my $cust_main = $self; #for callback
1722 local $realtime_bop_decline_quiet = 1 if $options{'quiet'};
1723 local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
1724 $error = eval $part_bill_event->eventcode;
1728 my $statustext = '';
1732 } elsif ( $error ) {
1734 $statustext = $error;
1739 #add cust_bill_event
1740 my $cust_bill_event = new FS::cust_bill_event {
1741 'invnum' => $cust_bill->invnum,
1742 'eventpart' => $part_bill_event->eventpart,
1743 #'_date' => $invoice_time,
1745 'status' => $status,
1746 'statustext' => $statustext,
1748 $error = $cust_bill_event->insert;
1750 #$dbh->rollback if $oldAutoCommit;
1751 #return "error: $error";
1753 # gah, even with transactions.
1754 $dbh->commit if $oldAutoCommit; #well.
1755 my $e = 'WARNING: Event run but database not updated - '.
1756 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1757 ', eventpart '. $part_bill_event->eventpart.
1768 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1773 =item retry_realtime
1775 Schedules realtime credit card / electronic check / LEC billing events for
1776 for retry. Useful if card information has changed or manual retry is desired.
1777 The 'collect' method must be called to actually retry the transaction.
1779 Implementation details: For each of this customer's open invoices, changes
1780 the status of the first "done" (with statustext error) realtime processing
1785 sub retry_realtime {
1788 local $SIG{HUP} = 'IGNORE';
1789 local $SIG{INT} = 'IGNORE';
1790 local $SIG{QUIT} = 'IGNORE';
1791 local $SIG{TERM} = 'IGNORE';
1792 local $SIG{TSTP} = 'IGNORE';
1793 local $SIG{PIPE} = 'IGNORE';
1795 my $oldAutoCommit = $FS::UID::AutoCommit;
1796 local $FS::UID::AutoCommit = 0;
1799 foreach my $cust_bill (
1800 grep { $_->cust_bill_event }
1801 $self->open_cust_bill
1803 my @cust_bill_event =
1804 sort { $a->part_bill_event->seconds <=> $b->part_bill_event->seconds }
1806 #$_->part_bill_event->plan eq 'realtime-card'
1807 $_->part_bill_event->eventcode =~
1808 /\$cust_bill\->realtime_(card|ach|lec)/
1809 && $_->status eq 'done'
1812 $cust_bill->cust_bill_event;
1813 next unless @cust_bill_event;
1814 my $error = $cust_bill_event[0]->retry;
1816 $dbh->rollback if $oldAutoCommit;
1817 return "error scheduling invoice event for retry: $error";
1822 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1827 =item realtime_bop METHOD AMOUNT [ OPTION => VALUE ... ]
1829 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
1830 via a Business::OnlinePayment realtime gateway. See
1831 L<http://420.am/business-onlinepayment> for supported gateways.
1833 Available methods are: I<CC>, I<ECHECK> and I<LEC>
1835 Available options are: I<description>, I<invnum>, I<quiet>
1837 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1838 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1839 if set, will override the value from the customer record.
1841 I<description> is a free-text field passed to the gateway. It defaults to
1842 "Internet services".
1844 If an I<invnum> is specified, this payment (if sucessful) is applied to the
1845 specified invoice. If you don't specify an I<invnum> you might want to
1846 call the B<apply_payments> method.
1848 I<quiet> can be set true to surpress email decline notices.
1850 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
1855 my( $self, $method, $amount, %options ) = @_;
1857 warn "$self $method $amount\n";
1858 warn " $_ => $options{$_}\n" foreach keys %options;
1861 $options{'description'} ||= 'Internet services';
1864 die "Real-time processing not enabled\n"
1865 unless $conf->exists('business-onlinepayment');
1866 eval "use Business::OnlinePayment";
1870 my $bop_config = 'business-onlinepayment';
1871 $bop_config .= '-ach'
1872 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
1873 my ( $processor, $login, $password, $action, @bop_options ) =
1874 $conf->config($bop_config);
1875 $action ||= 'normal authorization';
1876 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1877 die "No real-time processor is enabled - ".
1878 "did you set the business-onlinepayment configuration value?\n"
1883 my $address = exists($options{'address1'})
1884 ? $options{'address1'}
1886 my $address2 = exists($options{'address2'})
1887 ? $options{'address2'}
1889 $address .= ", ". $address2 if length($address2);
1891 my $o_payname = exists($options{'payname'})
1892 ? $options{'payname'}
1894 my($payname, $payfirst, $paylast);
1895 if ( $o_payname && $method ne 'ECHECK' ) {
1896 ($payname = $o_payname) =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1897 or return "Illegal payname $payname";
1898 ($payfirst, $paylast) = ($1, $2);
1900 $payfirst = $self->getfield('first');
1901 $paylast = $self->getfield('last');
1902 $payname = "$payfirst $paylast";
1905 my @invoicing_list = grep { $_ ne 'POST' } $self->invoicing_list;
1906 if ( $conf->exists('emailinvoiceauto')
1907 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1908 push @invoicing_list, $self->all_emails;
1910 my $email = $invoicing_list[0];
1912 my $payinfo = exists($options{'payinfo'})
1913 ? $options{'payinfo'}
1917 if ( $method eq 'CC' ) {
1919 $content{card_number} = $payinfo;
1920 my $paydate = exists($options{'paydate'})
1921 ? $options{'paydate'}
1923 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1924 $content{expiration} = "$2/$1";
1926 if ( defined $self->dbdef_table->column('paycvv') ) {
1927 my $paycvv = exists($options{'paycvv'})
1928 ? $options{'paycvv'}
1930 $content{cvv2} = $self->paycvv
1934 $content{recurring_billing} = 'YES'
1935 if qsearch('cust_pay', { 'custnum' => $self->custnum,
1937 'payinfo' => $payinfo,
1940 } elsif ( $method eq 'ECHECK' ) {
1941 ( $content{account_number}, $content{routing_code} ) =
1942 split('@', $payinfo);
1943 $content{bank_name} = $o_payname;
1944 $content{account_type} = 'CHECKING';
1945 $content{account_name} = $payname;
1946 $content{customer_org} = $self->company ? 'B' : 'I';
1947 $content{customer_ssn} = exists($options{'ss'})
1950 } elsif ( $method eq 'LEC' ) {
1951 $content{phone} = $payinfo;
1956 my( $action1, $action2 ) = split(/\s*\,\s*/, $action );
1958 my $transaction = new Business::OnlinePayment( $processor, @bop_options );
1959 $transaction->content(
1962 'password' => $password,
1963 'action' => $action1,
1964 'description' => $options{'description'},
1965 'amount' => $amount,
1966 'invoice_number' => $options{'invnum'},
1967 'customer_id' => $self->custnum,
1968 'last_name' => $paylast,
1969 'first_name' => $payfirst,
1971 'address' => $address,
1972 'city' => ( exists($options{'city'})
1975 'state' => ( exists($options{'state'})
1978 'zip' => ( exists($options{'zip'})
1981 'country' => ( exists($options{'country'})
1982 ? $options{'country'}
1984 'referer' => 'http://cleanwhisker.420.am/',
1986 'phone' => $self->daytime || $self->night,
1989 $transaction->submit();
1991 if ( $transaction->is_success() && $action2 ) {
1992 my $auth = $transaction->authorization;
1993 my $ordernum = $transaction->can('order_number')
1994 ? $transaction->order_number
1998 new Business::OnlinePayment( $processor, @bop_options );
2005 password => $password,
2006 order_number => $ordernum,
2008 authorization => $auth,
2009 description => $options{'description'},
2012 foreach my $field (qw( authorization_source_code returned_ACI transaction_identifier validation_code
2013 transaction_sequence_num local_transaction_date
2014 local_transaction_time AVS_result_code )) {
2015 $capture{$field} = $transaction->$field() if $transaction->can($field);
2018 $capture->content( %capture );
2022 unless ( $capture->is_success ) {
2023 my $e = "Authorization sucessful but capture failed, custnum #".
2024 $self->custnum. ': '. $capture->result_code.
2025 ": ". $capture->error_message;
2032 #remove paycvv after initial transaction
2033 #false laziness w/misc/process/payment.cgi - check both to make sure working
2035 if ( defined $self->dbdef_table->column('paycvv')
2036 && length($self->paycvv)
2037 && ! grep { $_ eq cardtype($payinfo) } $conf->config('cvv-save')
2039 my $error = $self->remove_cvv;
2041 warn "error removing cvv: $error\n";
2046 if ( $transaction->is_success() ) {
2048 my %method2payby = (
2054 my $paybatch = "$processor:". $transaction->authorization;
2055 $paybatch .= ':'. $transaction->order_number
2056 if $transaction->can('order_number')
2057 && length($transaction->order_number);
2059 my $cust_pay = new FS::cust_pay ( {
2060 'custnum' => $self->custnum,
2061 'invnum' => $options{'invnum'},
2064 'payby' => $method2payby{$method},
2065 'payinfo' => $payinfo,
2066 'paybatch' => $paybatch,
2068 my $error = $cust_pay->insert;
2070 $cust_pay->invnum(''); #try again with no specific invnum
2071 my $error2 = $cust_pay->insert;
2073 # gah, even with transactions.
2074 my $e = 'WARNING: Card/ACH debited but database not updated - '.
2075 "error inserting payment ($processor): $error2".
2076 " (previously tried insert with invnum #$options{'invnum'}" .
2082 return ''; #no error
2086 my $perror = "$processor error: ". $transaction->error_message;
2088 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
2089 && $conf->exists('emaildecline')
2090 && grep { $_ ne 'POST' } $self->invoicing_list
2091 && ! grep { $transaction->error_message =~ /$_/ }
2092 $conf->config('emaildecline-exclude')
2094 my @templ = $conf->config('declinetemplate');
2095 my $template = new Text::Template (
2097 SOURCE => [ map "$_\n", @templ ],
2098 ) or return "($perror) can't create template: $Text::Template::ERROR";
2099 $template->compile()
2100 or return "($perror) can't compile template: $Text::Template::ERROR";
2102 my $templ_hash = { error => $transaction->error_message };
2104 my $error = send_email(
2105 'from' => $conf->config('invoice_from'),
2106 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
2107 'subject' => 'Your payment could not be processed',
2108 'body' => [ $template->fill_in(HASH => $templ_hash) ],
2111 $perror .= " (also received error sending decline notification: $error)"
2123 Removes the I<paycvv> field from the database directly.
2125 If there is an error, returns the error, otherwise returns false.
2131 my $sth = dbh->prepare("UPDATE cust_main SET paycvv = '' WHERE custnum = ?")
2132 or return dbh->errstr;
2133 $sth->execute($self->custnum)
2134 or return $sth->errstr;
2139 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
2141 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
2142 via a Business::OnlinePayment realtime gateway. See
2143 L<http://420.am/business-onlinepayment> for supported gateways.
2145 Available methods are: I<CC>, I<ECHECK> and I<LEC>
2147 Available options are: I<amount>, I<reason>, I<paynum>
2149 Most gateways require a reference to an original payment transaction to refund,
2150 so you probably need to specify a I<paynum>.
2152 I<amount> defaults to the original amount of the payment if not specified.
2154 I<reason> specifies a reason for the refund.
2156 Implementation note: If I<amount> is unspecified or equal to the amount of the
2157 orignal payment, first an attempt is made to "void" the transaction via
2158 the gateway (to cancel a not-yet settled transaction) and then if that fails,
2159 the normal attempt is made to "refund" ("credit") the transaction via the
2160 gateway is attempted.
2162 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
2163 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
2164 #if set, will override the value from the customer record.
2166 #If an I<invnum> is specified, this payment (if sucessful) is applied to the
2167 #specified invoice. If you don't specify an I<invnum> you might want to
2168 #call the B<apply_payments> method.
2172 #some false laziness w/realtime_bop, not enough to make it worth merging
2173 #but some useful small subs should be pulled out
2174 sub realtime_refund_bop {
2175 my( $self, $method, %options ) = @_;
2177 warn "$self $method refund\n";
2178 warn " $_ => $options{$_}\n" foreach keys %options;
2182 die "Real-time processing not enabled\n"
2183 unless $conf->exists('business-onlinepayment');
2184 eval "use Business::OnlinePayment";
2188 my $bop_config = 'business-onlinepayment';
2189 $bop_config .= '-ach'
2190 if $method eq 'ECHECK' && $conf->exists($bop_config. '-ach');
2191 my ( $processor, $login, $password, $unused_action, @bop_options ) =
2192 $conf->config($bop_config);
2193 #$action ||= 'normal authorization';
2194 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
2195 die "No real-time processor is enabled - ".
2196 "did you set the business-onlinepayment configuration value?\n"
2200 my $amount = $options{'amount'};
2201 my( $pay_processor, $auth, $order_number ) = ( '', '', '' );
2202 if ( $options{'paynum'} ) {
2203 warn "FS::cust_main::realtime_bop: paynum: $options{paynum}\n" if $DEBUG;
2204 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
2205 or return "Unknown paynum $options{'paynum'}";
2206 $amount ||= $cust_pay->paid;
2207 $cust_pay->paybatch =~ /^(\w+):([\w-]*)(:(\w+))?$/
2208 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
2209 $cust_pay->paybatch;
2210 ( $pay_processor, $auth, $order_number ) = ( $1, $2, $4 );
2211 return "processor of payment $options{'paynum'} $pay_processor does not".
2212 " match current processor $processor"
2213 unless $pay_processor eq $processor;
2215 return "neither amount nor paynum specified" unless $amount;
2220 'password' => $password,
2221 'order_number' => $order_number,
2222 'amount' => $amount,
2223 'referer' => 'http://cleanwhisker.420.am/',
2225 $content{authorization} = $auth
2226 if length($auth); #echeck/ACH transactions have an order # but no auth
2227 #(at least with authorize.net)
2229 #first try void if applicable
2230 if ( $cust_pay && $cust_pay->paid == $amount ) { #and check dates?
2231 warn "FS::cust_main::realtime_bop: attempting void\n" if $DEBUG;
2232 my $void = new Business::OnlinePayment( $processor, @bop_options );
2233 $void->content( 'action' => 'void', %content );
2235 if ( $void->is_success ) {
2236 my $error = $cust_pay->void($options{'reason'});
2238 # gah, even with transactions.
2239 my $e = 'WARNING: Card/ACH voided but database not updated - '.
2240 "error voiding payment: $error";
2244 warn "FS::cust_main::realtime_bop: void successful\n" if $DEBUG;
2249 warn "FS::cust_main::realtime_bop: void unsuccessful, trying refund\n"
2253 my $address = $self->address1;
2254 $address .= ", ". $self->address2 if $self->address2;
2256 my($payname, $payfirst, $paylast);
2257 if ( $self->payname && $method ne 'ECHECK' ) {
2258 $payname = $self->payname;
2259 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
2260 or return "Illegal payname $payname";
2261 ($payfirst, $paylast) = ($1, $2);
2263 $payfirst = $self->getfield('first');
2264 $paylast = $self->getfield('last');
2265 $payname = "$payfirst $paylast";
2269 if ( $method eq 'CC' ) {
2272 $content{card_number} = $payinfo = $cust_pay->payinfo;
2273 #$self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2274 #$content{expiration} = "$2/$1";
2276 $content{card_number} = $payinfo = $self->payinfo;
2277 $self->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2278 $content{expiration} = "$2/$1";
2281 } elsif ( $method eq 'ECHECK' ) {
2282 ( $content{account_number}, $content{routing_code} ) =
2283 split('@', $payinfo = $self->payinfo);
2284 $content{bank_name} = $self->payname;
2285 $content{account_type} = 'CHECKING';
2286 $content{account_name} = $payname;
2287 $content{customer_org} = $self->company ? 'B' : 'I';
2288 $content{customer_ssn} = $self->ss;
2289 } elsif ( $method eq 'LEC' ) {
2290 $content{phone} = $payinfo = $self->payinfo;
2294 my $refund = new Business::OnlinePayment( $processor, @bop_options );
2295 my %sub_content = $refund->content(
2296 'action' => 'credit',
2297 'customer_id' => $self->custnum,
2298 'last_name' => $paylast,
2299 'first_name' => $payfirst,
2301 'address' => $address,
2302 'city' => $self->city,
2303 'state' => $self->state,
2304 'zip' => $self->zip,
2305 'country' => $self->country,
2308 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
2312 return "$processor error: ". $refund->error_message
2313 unless $refund->is_success();
2315 my %method2payby = (
2321 my $paybatch = "$processor:". $refund->authorization;
2322 $paybatch .= ':'. $refund->order_number
2323 if $refund->can('order_number') && $refund->order_number;
2325 while ( $cust_pay && $cust_pay->unappled < $amount ) {
2326 my @cust_bill_pay = $cust_pay->cust_bill_pay;
2327 last unless @cust_bill_pay;
2328 my $cust_bill_pay = pop @cust_bill_pay;
2329 my $error = $cust_bill_pay->delete;
2333 my $cust_refund = new FS::cust_refund ( {
2334 'custnum' => $self->custnum,
2335 'paynum' => $options{'paynum'},
2336 'refund' => $amount,
2338 'payby' => $method2payby{$method},
2339 'payinfo' => $payinfo,
2340 'paybatch' => $paybatch,
2341 'reason' => $options{'reason'} || 'card or ACH refund',
2343 my $error = $cust_refund->insert;
2345 $cust_refund->paynum(''); #try again with no specific paynum
2346 my $error2 = $cust_refund->insert;
2348 # gah, even with transactions.
2349 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
2350 "error inserting refund ($processor): $error2".
2351 " (previously tried insert with paynum #$options{'paynum'}" .
2364 Returns the total owed for this customer on all invoices
2365 (see L<FS::cust_bill/owed>).
2371 $self->total_owed_date(2145859200); #12/31/2037
2374 =item total_owed_date TIME
2376 Returns the total owed for this customer on all invoices with date earlier than
2377 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
2378 see L<Time::Local> and L<Date::Parse> for conversion functions.
2382 sub total_owed_date {
2386 foreach my $cust_bill (
2387 grep { $_->_date <= $time }
2388 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2390 $total_bill += $cust_bill->owed;
2392 sprintf( "%.2f", $total_bill );
2395 =item apply_credits OPTION => VALUE ...
2397 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
2398 to outstanding invoice balances in chronological order (or reverse
2399 chronological order if the I<order> option is set to B<newest>) and returns the
2400 value of any remaining unapplied credits available for refund (see
2401 L<FS::cust_refund>).
2409 return 0 unless $self->total_credited;
2411 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
2412 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
2414 my @invoices = $self->open_cust_bill;
2415 @invoices = sort { $b->_date <=> $a->_date } @invoices
2416 if defined($opt{'order'}) && $opt{'order'} eq 'newest';
2419 foreach my $cust_bill ( @invoices ) {
2422 if ( !defined($credit) || $credit->credited == 0) {
2423 $credit = pop @credits or last;
2426 if ($cust_bill->owed >= $credit->credited) {
2427 $amount=$credit->credited;
2429 $amount=$cust_bill->owed;
2432 my $cust_credit_bill = new FS::cust_credit_bill ( {
2433 'crednum' => $credit->crednum,
2434 'invnum' => $cust_bill->invnum,
2435 'amount' => $amount,
2437 my $error = $cust_credit_bill->insert;
2438 die $error if $error;
2440 redo if ($cust_bill->owed > 0);
2444 return $self->total_credited;
2447 =item apply_payments
2449 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
2450 to outstanding invoice balances in chronological order.
2452 #and returns the value of any remaining unapplied payments.
2456 sub apply_payments {
2461 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
2462 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
2464 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
2465 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
2469 foreach my $cust_bill ( @invoices ) {
2472 if ( !defined($payment) || $payment->unapplied == 0 ) {
2473 $payment = pop @payments or last;
2476 if ( $cust_bill->owed >= $payment->unapplied ) {
2477 $amount = $payment->unapplied;
2479 $amount = $cust_bill->owed;
2482 my $cust_bill_pay = new FS::cust_bill_pay ( {
2483 'paynum' => $payment->paynum,
2484 'invnum' => $cust_bill->invnum,
2485 'amount' => $amount,
2487 my $error = $cust_bill_pay->insert;
2488 die $error if $error;
2490 redo if ( $cust_bill->owed > 0);
2494 return $self->total_unapplied_payments;
2497 =item total_credited
2499 Returns the total outstanding credit (see L<FS::cust_credit>) for this
2500 customer. See L<FS::cust_credit/credited>.
2504 sub total_credited {
2506 my $total_credit = 0;
2507 foreach my $cust_credit ( qsearch('cust_credit', {
2508 'custnum' => $self->custnum,
2510 $total_credit += $cust_credit->credited;
2512 sprintf( "%.2f", $total_credit );
2515 =item total_unapplied_payments
2517 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
2518 See L<FS::cust_pay/unapplied>.
2522 sub total_unapplied_payments {
2524 my $total_unapplied = 0;
2525 foreach my $cust_pay ( qsearch('cust_pay', {
2526 'custnum' => $self->custnum,
2528 $total_unapplied += $cust_pay->unapplied;
2530 sprintf( "%.2f", $total_unapplied );
2535 Returns the balance for this customer (total_owed minus total_credited
2536 minus total_unapplied_payments).
2543 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
2547 =item balance_date TIME
2549 Returns the balance for this customer, only considering invoices with date
2550 earlier than TIME (total_owed_date minus total_credited minus
2551 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
2552 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
2561 $self->total_owed_date($time)
2562 - $self->total_credited
2563 - $self->total_unapplied_payments
2567 =item paydate_monthyear
2569 Returns a two-element list consisting of the month and year of this customer's
2570 paydate (credit card expiration date for CARD customers)
2574 sub paydate_monthyear {
2576 if ( $self->paydate =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #Pg date format
2578 } elsif ( $self->paydate =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
2585 =item payinfo_masked
2587 Returns a "masked" payinfo field appropriate to the payment type. Masked characters are replaced by 'x'es. Use this to display publicly accessable account Information.
2589 Credit Cards - Mask all but the last four characters.
2590 Checks - Mask all but last 2 of account number and bank routing number.
2591 Others - Do nothing, return the unmasked string.
2595 sub payinfo_masked {
2597 return $self->paymask;
2600 =item invoicing_list [ ARRAYREF ]
2602 If an arguement is given, sets these email addresses as invoice recipients
2603 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
2604 (except as warnings), so use check_invoicing_list first.
2606 Returns a list of email addresses (with svcnum entries expanded).
2608 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
2609 check it without disturbing anything by passing nothing.
2611 This interface may change in the future.
2615 sub invoicing_list {
2616 my( $self, $arrayref ) = @_;
2618 my @cust_main_invoice;
2619 if ( $self->custnum ) {
2620 @cust_main_invoice =
2621 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2623 @cust_main_invoice = ();
2625 foreach my $cust_main_invoice ( @cust_main_invoice ) {
2626 #warn $cust_main_invoice->destnum;
2627 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
2628 #warn $cust_main_invoice->destnum;
2629 my $error = $cust_main_invoice->delete;
2630 warn $error if $error;
2633 if ( $self->custnum ) {
2634 @cust_main_invoice =
2635 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2637 @cust_main_invoice = ();
2639 my %seen = map { $_->address => 1 } @cust_main_invoice;
2640 foreach my $address ( @{$arrayref} ) {
2641 next if exists $seen{$address} && $seen{$address};
2642 $seen{$address} = 1;
2643 my $cust_main_invoice = new FS::cust_main_invoice ( {
2644 'custnum' => $self->custnum,
2647 my $error = $cust_main_invoice->insert;
2648 warn $error if $error;
2651 if ( $self->custnum ) {
2653 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
2659 =item check_invoicing_list ARRAYREF
2661 Checks these arguements as valid input for the invoicing_list method. If there
2662 is an error, returns the error, otherwise returns false.
2666 sub check_invoicing_list {
2667 my( $self, $arrayref ) = @_;
2668 foreach my $address ( @{$arrayref} ) {
2670 if ($address eq 'FAX' and $self->getfield('fax') eq '') {
2671 return 'Can\'t add FAX invoice destination with a blank FAX number.';
2674 my $cust_main_invoice = new FS::cust_main_invoice ( {
2675 'custnum' => $self->custnum,
2678 my $error = $self->custnum
2679 ? $cust_main_invoice->check
2680 : $cust_main_invoice->checkdest
2682 return $error if $error;
2687 =item set_default_invoicing_list
2689 Sets the invoicing list to all accounts associated with this customer,
2690 overwriting any previous invoicing list.
2694 sub set_default_invoicing_list {
2696 $self->invoicing_list($self->all_emails);
2701 Returns the email addresses of all accounts provisioned for this customer.
2708 foreach my $cust_pkg ( $self->all_pkgs ) {
2709 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
2711 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2712 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
2714 $list{$_}=1 foreach map { $_->email } @svc_acct;
2719 =item invoicing_list_addpost
2721 Adds postal invoicing to this customer. If this customer is already configured
2722 to receive postal invoices, does nothing.
2726 sub invoicing_list_addpost {
2728 return if grep { $_ eq 'POST' } $self->invoicing_list;
2729 my @invoicing_list = $self->invoicing_list;
2730 push @invoicing_list, 'POST';
2731 $self->invoicing_list(\@invoicing_list);
2734 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
2736 Returns an array of customers referred by this customer (referral_custnum set
2737 to this custnum). If DEPTH is given, recurses up to the given depth, returning
2738 customers referred by customers referred by this customer and so on, inclusive.
2739 The default behavior is DEPTH 1 (no recursion).
2743 sub referral_cust_main {
2745 my $depth = @_ ? shift : 1;
2746 my $exclude = @_ ? shift : {};
2749 map { $exclude->{$_->custnum}++; $_; }
2750 grep { ! $exclude->{ $_->custnum } }
2751 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
2755 map { $_->referral_cust_main($depth-1, $exclude) }
2762 =item referral_cust_main_ncancelled
2764 Same as referral_cust_main, except only returns customers with uncancelled
2769 sub referral_cust_main_ncancelled {
2771 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
2774 =item referral_cust_pkg [ DEPTH ]
2776 Like referral_cust_main, except returns a flat list of all unsuspended (and
2777 uncancelled) packages for each customer. The number of items in this list may
2778 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
2782 sub referral_cust_pkg {
2784 my $depth = @_ ? shift : 1;
2786 map { $_->unsuspended_pkgs }
2787 grep { $_->unsuspended_pkgs }
2788 $self->referral_cust_main($depth);
2791 =item referring_cust_main
2793 Returns the single cust_main record for the customer who referred this customer
2794 (referral_custnum), or false.
2798 sub referring_cust_main {
2800 return '' unless $self->referral_custnum;
2801 qsearchs('cust_main', { 'custnum' => $self->referral_custnum } );
2804 =item credit AMOUNT, REASON
2806 Applies a credit to this customer. If there is an error, returns the error,
2807 otherwise returns false.
2812 my( $self, $amount, $reason ) = @_;
2813 my $cust_credit = new FS::cust_credit {
2814 'custnum' => $self->custnum,
2815 'amount' => $amount,
2816 'reason' => $reason,
2818 $cust_credit->insert;
2821 =item charge AMOUNT [ PKG [ COMMENT [ TAXCLASS ] ] ]
2823 Creates a one-time charge for this customer. If there is an error, returns
2824 the error, otherwise returns false.
2829 my ( $self, $amount ) = ( shift, shift );
2830 my $pkg = @_ ? shift : 'One-time charge';
2831 my $comment = @_ ? shift : '$'. sprintf("%.2f",$amount);
2832 my $taxclass = @_ ? shift : '';
2834 local $SIG{HUP} = 'IGNORE';
2835 local $SIG{INT} = 'IGNORE';
2836 local $SIG{QUIT} = 'IGNORE';
2837 local $SIG{TERM} = 'IGNORE';
2838 local $SIG{TSTP} = 'IGNORE';
2839 local $SIG{PIPE} = 'IGNORE';
2841 my $oldAutoCommit = $FS::UID::AutoCommit;
2842 local $FS::UID::AutoCommit = 0;
2845 my $part_pkg = new FS::part_pkg ( {
2847 'comment' => $comment,
2848 #'setup' => $amount,
2851 'plandata' => "setup_fee=$amount",
2854 'taxclass' => $taxclass,
2857 my $error = $part_pkg->insert;
2859 $dbh->rollback if $oldAutoCommit;
2863 my $pkgpart = $part_pkg->pkgpart;
2864 my %type_pkgs = ( 'typenum' => $self->agent->typenum, 'pkgpart' => $pkgpart );
2865 unless ( qsearchs('type_pkgs', \%type_pkgs ) ) {
2866 my $type_pkgs = new FS::type_pkgs \%type_pkgs;
2867 $error = $type_pkgs->insert;
2869 $dbh->rollback if $oldAutoCommit;
2874 my $cust_pkg = new FS::cust_pkg ( {
2875 'custnum' => $self->custnum,
2876 'pkgpart' => $pkgpart,
2879 $error = $cust_pkg->insert;
2881 $dbh->rollback if $oldAutoCommit;
2885 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2892 Returns all the invoices (see L<FS::cust_bill>) for this customer.
2898 sort { $a->_date <=> $b->_date }
2899 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
2902 =item open_cust_bill
2904 Returns all the open (owed > 0) invoices (see L<FS::cust_bill>) for this
2909 sub open_cust_bill {
2911 grep { $_->owed > 0 } $self->cust_bill;
2916 Returns all the credits (see L<FS::cust_credit>) for this customer.
2922 sort { $a->_date <=> $b->_date }
2923 qsearch( 'cust_credit', { 'custnum' => $self->custnum } )
2928 Returns all the payments (see L<FS::cust_pay>) for this customer.
2934 sort { $a->_date <=> $b->_date }
2935 qsearch( 'cust_pay', { 'custnum' => $self->custnum } )
2940 Returns all voided payments (see L<FS::cust_pay_void>) for this customer.
2946 sort { $a->_date <=> $b->_date }
2947 qsearch( 'cust_pay_void', { 'custnum' => $self->custnum } )
2953 Returns all the refunds (see L<FS::cust_refund>) for this customer.
2959 sort { $a->_date <=> $b->_date }
2960 qsearch( 'cust_refund', { 'custnum' => $self->custnum } )
2963 =item select_for_update
2965 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
2970 sub select_for_update {
2972 qsearch('cust_main', { 'custnum' => $self->custnum }, '*', 'FOR UPDATE' );
2977 Returns a name string for this customer, either "Company (Last, First)" or
2984 my $name = $self->get('last'). ', '. $self->first;
2985 $name = $self->company. " ($name)" if $self->company;
2991 Returns a status string for this customer, currently:
2995 =item prospect - No packages have ever been ordered
2997 =item active - One or more recurring packages is active
2999 =item suspended - All non-cancelled recurring packages are suspended
3001 =item cancelled - All recurring packages are cancelled
3009 for my $status (qw( prospect active suspended cancelled )) {
3010 my $method = $status.'_sql';
3011 my $numnum = ( my $sql = $self->$method() ) =~ s/cust_main\.custnum/?/g;
3012 my $sth = dbh->prepare("SELECT $sql") or die dbh->errstr;
3013 $sth->execute( ($self->custnum) x $numnum ) or die $sth->errstr;
3014 return $status if $sth->fetchrow_arrayref->[0];
3020 Returns a hex triplet color string for this customer's status.
3025 'prospect' => '000000',
3026 'active' => '00CC00',
3027 'suspended' => 'FF9900',
3028 'cancelled' => 'FF0000',
3032 $statuscolor{$self->status};
3037 =head1 CLASS METHODS
3043 Returns an SQL expression identifying prospective cust_main records (customers
3044 with no packages ever ordered)
3048 sub prospect_sql { "
3049 0 = ( SELECT COUNT(*) FROM cust_pkg
3050 WHERE cust_pkg.custnum = cust_main.custnum
3056 Returns an SQL expression identifying active cust_main records.
3061 0 < ( SELECT COUNT(*) FROM cust_pkg
3062 WHERE cust_pkg.custnum = cust_main.custnum
3063 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3064 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3071 Returns an SQL expression identifying suspended cust_main records.
3075 sub suspended_sql { susp_sql(@_); }
3077 0 < ( SELECT COUNT(*) FROM cust_pkg
3078 WHERE cust_pkg.custnum = cust_main.custnum
3079 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3081 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3082 WHERE cust_pkg.custnum = cust_main.custnum
3083 AND ( cust_pkg.susp IS NULL OR cust_pkg.susp = 0 )
3084 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3091 Returns an SQL expression identifying cancelled cust_main records.
3095 sub cancelled_sql { cancel_sql(@_); }
3097 0 < ( SELECT COUNT(*) FROM cust_pkg
3098 WHERE cust_pkg.custnum = cust_main.custnum
3100 AND 0 = ( SELECT COUNT(*) FROM cust_pkg
3101 WHERE cust_pkg.custnum = cust_main.custnum
3102 AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel = 0 )
3106 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
3108 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
3109 records. Currently, only I<last> or I<company> may be specified (the
3110 appropriate ship_ field is also searched if applicable).
3112 Additional options are the same as FS::Record::qsearch
3117 my( $self, $fuzzy, $hash, @opt) = @_;
3122 check_and_rebuild_fuzzyfiles();
3123 foreach my $field ( keys %$fuzzy ) {
3124 my $sub = \&{"all_$field"};
3126 $match{$_}=1 foreach ( amatch($fuzzy->{$field}, ['i'], @{ &$sub() } ) );
3128 foreach ( keys %match ) {
3129 push @cust_main, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
3130 push @cust_main, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt)
3131 if defined dbdef->table('cust_main')->column('ship_last');
3136 @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
3148 =item smart_search OPTION => VALUE ...
3150 Accepts the following options: I<search>, the string to search for. The string
3151 will be searched for as a customer number, last name or company name, first
3152 searching for an exact match then fuzzy and substring matches.
3154 Any additional options treated as an additional qualifier on the search
3157 Returns a (possibly empty) array of FS::cust_main objects.
3163 my $search = delete $options{'search'};
3166 if ( $search =~ /^\s*(\d+)\s*$/ ) { # customer # search
3168 push @cust_main, qsearch('cust_main', { 'custnum' => $1, %options } );
3170 } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { #value search
3173 my $q_value = dbh->quote($value);
3176 my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
3177 $sql .= " ( LOWER(last) = $q_value OR LOWER(company) = $q_value";
3178 $sql .= " OR LOWER(ship_last) = $q_value OR LOWER(ship_company) = $q_value"
3179 if defined dbdef->table('cust_main')->column('ship_last');
3182 push @cust_main, qsearch( 'cust_main', \%options, '', $sql );
3184 unless ( @cust_main ) { #no exact match, trying substring/fuzzy
3186 #still some false laziness w/ search/cust_main.cgi
3189 push @cust_main, qsearch( 'cust_main',
3190 { 'last' => { 'op' => 'ILIKE',
3191 'value' => "%$q_value%" },
3195 push @cust_main, qsearch( 'cust_main',
3196 { 'ship_last' => { 'op' => 'ILIKE',
3197 'value' => "%$q_value%" },
3202 if defined dbdef->table('cust_main')->column('ship_last');
3204 push @cust_main, qsearch( 'cust_main',
3205 { 'company' => { 'op' => 'ILIKE',
3206 'value' => "%$q_value%" },
3210 push @cust_main, qsearch( 'cust_main',
3211 { 'ship_company' => { 'op' => 'ILIKE',
3212 'value' => "%$q_value%" },
3216 if defined dbdef->table('cust_main')->column('ship_last');
3219 push @cust_main, FS::cust_main->fuzzy_search(
3220 { 'last' => $value },
3223 push @cust_main, FS::cust_main->fuzzy_search(
3224 { 'company' => $value },
3236 =item check_and_rebuild_fuzzyfiles
3240 sub check_and_rebuild_fuzzyfiles {
3241 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3242 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
3243 or &rebuild_fuzzyfiles;
3246 =item rebuild_fuzzyfiles
3250 sub rebuild_fuzzyfiles {
3252 use Fcntl qw(:flock);
3254 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3258 open(LASTLOCK,">>$dir/cust_main.last")
3259 or die "can't open $dir/cust_main.last: $!";
3260 flock(LASTLOCK,LOCK_EX)
3261 or die "can't lock $dir/cust_main.last: $!";
3263 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
3265 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
3266 if defined dbdef->table('cust_main')->column('ship_last');
3268 open (LASTCACHE,">$dir/cust_main.last.tmp")
3269 or die "can't open $dir/cust_main.last.tmp: $!";
3270 print LASTCACHE join("\n", @all_last), "\n";
3271 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
3273 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
3278 open(COMPANYLOCK,">>$dir/cust_main.company")
3279 or die "can't open $dir/cust_main.company: $!";
3280 flock(COMPANYLOCK,LOCK_EX)
3281 or die "can't lock $dir/cust_main.company: $!";
3283 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
3285 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
3286 if defined dbdef->table('cust_main')->column('ship_last');
3288 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
3289 or die "can't open $dir/cust_main.company.tmp: $!";
3290 print COMPANYCACHE join("\n", @all_company), "\n";
3291 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
3293 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
3303 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3304 open(LASTCACHE,"<$dir/cust_main.last")
3305 or die "can't open $dir/cust_main.last: $!";
3306 my @array = map { chomp; $_; } <LASTCACHE>;
3316 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3317 open(COMPANYCACHE,"<$dir/cust_main.company")
3318 or die "can't open $dir/cust_main.last: $!";
3319 my @array = map { chomp; $_; } <COMPANYCACHE>;
3324 =item append_fuzzyfiles LASTNAME COMPANY
3328 sub append_fuzzyfiles {
3329 my( $last, $company ) = @_;
3331 &check_and_rebuild_fuzzyfiles;
3333 use Fcntl qw(:flock);
3335 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
3339 open(LAST,">>$dir/cust_main.last")
3340 or die "can't open $dir/cust_main.last: $!";
3342 or die "can't lock $dir/cust_main.last: $!";
3344 print LAST "$last\n";
3347 or die "can't unlock $dir/cust_main.last: $!";
3353 open(COMPANY,">>$dir/cust_main.company")
3354 or die "can't open $dir/cust_main.company: $!";
3355 flock(COMPANY,LOCK_EX)
3356 or die "can't lock $dir/cust_main.company: $!";
3358 print COMPANY "$company\n";
3360 flock(COMPANY,LOCK_UN)
3361 or die "can't unlock $dir/cust_main.company: $!";
3375 #warn join('-',keys %$param);
3376 my $fh = $param->{filehandle};
3377 my $agentnum = $param->{agentnum};
3378 my $refnum = $param->{refnum};
3379 my $pkgpart = $param->{pkgpart};
3380 my @fields = @{$param->{fields}};
3382 eval "use Date::Parse;";
3384 eval "use Text::CSV_XS;";
3387 my $csv = new Text::CSV_XS;
3394 local $SIG{HUP} = 'IGNORE';
3395 local $SIG{INT} = 'IGNORE';
3396 local $SIG{QUIT} = 'IGNORE';
3397 local $SIG{TERM} = 'IGNORE';
3398 local $SIG{TSTP} = 'IGNORE';
3399 local $SIG{PIPE} = 'IGNORE';
3401 my $oldAutoCommit = $FS::UID::AutoCommit;
3402 local $FS::UID::AutoCommit = 0;
3405 #while ( $columns = $csv->getline($fh) ) {
3407 while ( defined($line=<$fh>) ) {
3409 $csv->parse($line) or do {
3410 $dbh->rollback if $oldAutoCommit;
3411 return "can't parse: ". $csv->error_input();
3414 my @columns = $csv->fields();
3415 #warn join('-',@columns);
3418 agentnum => $agentnum,
3420 country => $conf->config('countrydefault') || 'US',
3421 payby => 'BILL', #default
3422 paydate => '12/2037', #default
3424 my $billtime = time;
3425 my %cust_pkg = ( pkgpart => $pkgpart );
3426 foreach my $field ( @fields ) {
3427 if ( $field =~ /^cust_pkg\.(setup|bill|susp|expire|cancel)$/ ) {
3428 #$cust_pkg{$1} = str2time( shift @$columns );
3429 if ( $1 eq 'setup' ) {
3430 $billtime = str2time(shift @columns);
3432 $cust_pkg{$1} = str2time( shift @columns );
3435 #$cust_main{$field} = shift @$columns;
3436 $cust_main{$field} = shift @columns;
3440 my $cust_pkg = new FS::cust_pkg ( \%cust_pkg ) if $pkgpart;
3441 my $cust_main = new FS::cust_main ( \%cust_main );
3443 tie my %hash, 'Tie::RefHash'; #this part is important
3444 $hash{$cust_pkg} = [] if $pkgpart;
3445 my $error = $cust_main->insert( \%hash );
3448 $dbh->rollback if $oldAutoCommit;
3449 return "can't insert customer for $line: $error";
3452 #false laziness w/bill.cgi
3453 $error = $cust_main->bill( 'time' => $billtime );
3455 $dbh->rollback if $oldAutoCommit;
3456 return "can't bill customer for $line: $error";
3459 $cust_main->apply_payments;
3460 $cust_main->apply_credits;
3462 $error = $cust_main->collect();
3464 $dbh->rollback if $oldAutoCommit;
3465 return "can't collect customer for $line: $error";
3471 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3473 return "Empty file!" unless $imported;
3485 #warn join('-',keys %$param);
3486 my $fh = $param->{filehandle};
3487 my @fields = @{$param->{fields}};
3489 eval "use Date::Parse;";
3491 eval "use Text::CSV_XS;";
3494 my $csv = new Text::CSV_XS;
3501 local $SIG{HUP} = 'IGNORE';
3502 local $SIG{INT} = 'IGNORE';
3503 local $SIG{QUIT} = 'IGNORE';
3504 local $SIG{TERM} = 'IGNORE';
3505 local $SIG{TSTP} = 'IGNORE';
3506 local $SIG{PIPE} = 'IGNORE';
3508 my $oldAutoCommit = $FS::UID::AutoCommit;
3509 local $FS::UID::AutoCommit = 0;
3512 #while ( $columns = $csv->getline($fh) ) {
3514 while ( defined($line=<$fh>) ) {
3516 $csv->parse($line) or do {
3517 $dbh->rollback if $oldAutoCommit;
3518 return "can't parse: ". $csv->error_input();
3521 my @columns = $csv->fields();
3522 #warn join('-',@columns);
3525 foreach my $field ( @fields ) {
3526 $row{$field} = shift @columns;
3529 my $cust_main = qsearchs('cust_main', { 'custnum' => $row{'custnum'} } );
3530 unless ( $cust_main ) {
3531 $dbh->rollback if $oldAutoCommit;
3532 return "unknown custnum $row{'custnum'}";
3535 if ( $row{'amount'} > 0 ) {
3536 my $error = $cust_main->charge($row{'amount'}, $row{'pkg'});
3538 $dbh->rollback if $oldAutoCommit;
3542 } elsif ( $row{'amount'} < 0 ) {
3543 my $error = $cust_main->credit( sprintf( "%.2f", 0-$row{'amount'} ),
3546 $dbh->rollback if $oldAutoCommit;
3556 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
3558 return "Empty file!" unless $imported;
3570 The delete method should possibly take an FS::cust_main object reference
3571 instead of a scalar customer number.
3573 Bill and collect options should probably be passed as references instead of a
3576 There should probably be a configuration file with a list of allowed credit
3579 No multiple currency support (probably a larger project than just this module).
3581 payinfo_masked false laziness with cust_pay.pm and cust_refund.pm
3585 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
3586 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
3587 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.