4 use vars qw( @ISA $conf $Debug $import );
10 use Business::CreditCard;
11 use FS::UID qw( getotaker dbh );
12 use FS::Record qw( qsearchs qsearch dbdef );
15 use FS::cust_bill_pkg;
18 use FS::part_referral;
19 use FS::cust_main_county;
21 use FS::cust_main_invoice;
22 use FS::cust_credit_bill;
23 use FS::cust_bill_pay;
24 use FS::prepay_credit;
27 use FS::part_bill_event;
28 use FS::cust_bill_event;
30 @ISA = qw( FS::Record );
37 #ask FS::UID to run this stuff for us later
38 $FS::UID::callback{'FS::cust_main'} = sub {
40 #yes, need it for stuff below (prolly should be cached)
45 my ( $hashref, $cache ) = @_;
46 if ( exists $hashref->{'pkgnum'} ) {
47 # #@{ $self->{'_pkgnum'} } = ();
48 my $subcache = $cache->subcache( 'pkgnum', 'cust_pkg', $hashref->{custnum});
49 $self->{'_pkgnum'} = $subcache;
50 #push @{ $self->{'_pkgnum'} },
51 FS::cust_pkg->new_or_cached($hashref, $subcache) if $hashref->{pkgnum};
57 FS::cust_main - Object methods for cust_main records
63 $record = new FS::cust_main \%hash;
64 $record = new FS::cust_main { 'column' => 'value' };
66 $error = $record->insert;
68 $error = $new_record->replace($old_record);
70 $error = $record->delete;
72 $error = $record->check;
74 @cust_pkg = $record->all_pkgs;
76 @cust_pkg = $record->ncancelled_pkgs;
78 @cust_pkg = $record->suspended_pkgs;
80 $error = $record->bill;
81 $error = $record->bill %options;
82 $error = $record->bill 'time' => $time;
84 $error = $record->collect;
85 $error = $record->collect %options;
86 $error = $record->collect 'invoice_time' => $time,
87 'batch_card' => 'yes',
88 'report_badcard' => 'yes',
93 An FS::cust_main object represents a customer. FS::cust_main inherits from
94 FS::Record. The following fields are currently supported:
98 =item custnum - primary key (assigned automatically for new customers)
100 =item agentnum - agent (see L<FS::agent>)
102 =item refnum - referral (see L<FS::part_referral>)
108 =item ss - social security number (optional)
110 =item company - (optional)
114 =item address2 - (optional)
118 =item county - (optional, see L<FS::cust_main_county>)
120 =item state - (see L<FS::cust_main_county>)
124 =item country - (see L<FS::cust_main_county>)
126 =item daytime - phone (optional)
128 =item night - phone (optional)
130 =item fax - phone (optional)
132 =item ship_first - name
134 =item ship_last - name
136 =item ship_company - (optional)
140 =item ship_address2 - (optional)
144 =item ship_county - (optional, see L<FS::cust_main_county>)
146 =item ship_state - (see L<FS::cust_main_county>)
150 =item ship_country - (see L<FS::cust_main_county>)
152 =item ship_daytime - phone (optional)
154 =item ship_night - phone (optional)
156 =item ship_fax - phone (optional)
158 =item payby - `CARD' (credit cards), `BILL' (billing), `COMP' (free), or `PREPAY' (special billing type: applies a credit - see L<FS::prepay_credit> and sets billing type to BILL)
160 =item payinfo - card number, P.O., comp issuer (4-8 lowercase alphanumerics; think username) or prepayment identifier (see L<FS::prepay_credit>)
162 =item paydate - expiration date, mm/yyyy, m/yyyy, mm/yy or m/yy
164 =item payname - name on card or billing name
166 =item tax - tax exempt, empty or `Y'
168 =item otaker - order taker (assigned automatically, see L<FS::UID>)
170 =item comments - comments (optional)
180 Creates a new customer. To add the customer to the database, see L<"insert">.
182 Note that this stores the hash reference, not a distinct copy of the hash it
183 points to. You can ask the object for a copy with the I<hash> method.
187 sub table { 'cust_main'; }
189 =item insert [ CUST_PKG_HASHREF [ , INVOICING_LIST_ARYREF ] ]
191 Adds this customer to the database. If there is an error, returns the error,
192 otherwise returns false.
194 CUST_PKG_HASHREF: If you pass a Tie::RefHash data structure to the insert
195 method containing FS::cust_pkg and FS::svc_I<tablename> objects, all records
196 are inserted atomicly, or the transaction is rolled back. Passing an empty
197 hash reference is equivalent to not supplying this parameter. There should be
198 a better explanation of this, but until then, here's an example:
201 tie %hash, 'Tie::RefHash'; #this part is important
203 $cust_pkg => [ $svc_acct ],
206 $cust_main->insert( \%hash );
208 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
209 be set as the invoicing list (see L<"invoicing_list">). Errors return as
210 expected and rollback the entire transaction; it is not necessary to call
211 check_invoicing_list first. The invoicing_list is set after the records in the
212 CUST_PKG_HASHREF above are inserted, so it is now possible to set an
213 invoicing_list destination to the newly-created svc_acct. Here's an example:
215 $cust_main->insert( {}, [ $email, 'POST' ] );
223 local $SIG{HUP} = 'IGNORE';
224 local $SIG{INT} = 'IGNORE';
225 local $SIG{QUIT} = 'IGNORE';
226 local $SIG{TERM} = 'IGNORE';
227 local $SIG{TSTP} = 'IGNORE';
228 local $SIG{PIPE} = 'IGNORE';
230 my $oldAutoCommit = $FS::UID::AutoCommit;
231 local $FS::UID::AutoCommit = 0;
236 if ( $self->payby eq 'PREPAY' ) {
237 $self->payby('BILL');
238 my $prepay_credit = qsearchs(
240 { 'identifier' => $self->payinfo },
244 warn "WARNING: can't find pre-found prepay_credit: ". $self->payinfo
245 unless $prepay_credit;
246 $amount = $prepay_credit->amount;
247 $seconds = $prepay_credit->seconds;
248 my $error = $prepay_credit->delete;
250 $dbh->rollback if $oldAutoCommit;
251 return "removing prepay_credit (transaction rolled back): $error";
255 my $error = $self->SUPER::insert;
257 $dbh->rollback if $oldAutoCommit;
258 return "inserting cust_main record (transaction rolled back): $error";
261 if ( @param ) { # CUST_PKG_HASHREF
262 my $cust_pkgs = shift @param;
263 foreach my $cust_pkg ( keys %$cust_pkgs ) {
264 $cust_pkg->custnum( $self->custnum );
265 $error = $cust_pkg->insert;
267 $dbh->rollback if $oldAutoCommit;
268 return "inserting cust_pkg (transaction rolled back): $error";
270 foreach my $svc_something ( @{$cust_pkgs->{$cust_pkg}} ) {
271 $svc_something->pkgnum( $cust_pkg->pkgnum );
272 if ( $seconds && $svc_something->isa('FS::svc_acct') ) {
273 $svc_something->seconds( $svc_something->seconds + $seconds );
276 $error = $svc_something->insert;
278 $dbh->rollback if $oldAutoCommit;
279 return "inserting svc_ (transaction rolled back): $error";
286 $dbh->rollback if $oldAutoCommit;
287 return "No svc_acct record to apply pre-paid time";
290 if ( @param ) { # INVOICING_LIST_ARYREF
291 my $invoicing_list = shift @param;
292 $error = $self->check_invoicing_list( $invoicing_list );
294 $dbh->rollback if $oldAutoCommit;
295 return "checking invoicing_list (transaction rolled back): $error";
297 $self->invoicing_list( $invoicing_list );
301 my $cust_credit = new FS::cust_credit {
302 'custnum' => $self->custnum,
305 $error = $cust_credit->insert;
307 $dbh->rollback if $oldAutoCommit;
308 return "inserting credit (transaction rolled back): $error";
312 #false laziness with sub replace
313 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
314 $error = $queue->insert($self->getfield('last'), $self->company);
316 $dbh->rollback if $oldAutoCommit;
317 return "queueing job (transaction rolled back): $error";
320 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
321 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
322 $error = $queue->insert($self->getfield('last'), $self->company);
324 $dbh->rollback if $oldAutoCommit;
325 return "queueing job (transaction rolled back): $error";
330 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
335 =item delete NEW_CUSTNUM
337 This deletes the customer. If there is an error, returns the error, otherwise
340 This will completely remove all traces of the customer record. This is not
341 what you want when a customer cancels service; for that, cancel all of the
342 customer's packages (see L<FS::cust_pkg/cancel>).
344 If the customer has any uncancelled packages, you need to pass a new (valid)
345 customer number for those packages to be transferred to. Cancelled packages
346 will be deleted. Did I mention that this is NOT what you want when a customer
347 cancels service and that you really should be looking see L<FS::cust_pkg/cancel>?
349 You can't delete a customer with invoices (see L<FS::cust_bill>),
350 or credits (see L<FS::cust_credit>), payments (see L<FS::cust_pay>) or
351 refunds (see L<FS::cust_refund>).
358 local $SIG{HUP} = 'IGNORE';
359 local $SIG{INT} = 'IGNORE';
360 local $SIG{QUIT} = 'IGNORE';
361 local $SIG{TERM} = 'IGNORE';
362 local $SIG{TSTP} = 'IGNORE';
363 local $SIG{PIPE} = 'IGNORE';
365 my $oldAutoCommit = $FS::UID::AutoCommit;
366 local $FS::UID::AutoCommit = 0;
369 if ( qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) ) {
370 $dbh->rollback if $oldAutoCommit;
371 return "Can't delete a customer with invoices";
373 if ( qsearch( 'cust_credit', { 'custnum' => $self->custnum } ) ) {
374 $dbh->rollback if $oldAutoCommit;
375 return "Can't delete a customer with credits";
377 if ( qsearch( 'cust_pay', { 'custnum' => $self->custnum } ) ) {
378 $dbh->rollback if $oldAutoCommit;
379 return "Can't delete a customer with payments";
381 if ( qsearch( 'cust_refund', { 'custnum' => $self->custnum } ) ) {
382 $dbh->rollback if $oldAutoCommit;
383 return "Can't delete a customer with refunds";
386 my @cust_pkg = $self->ncancelled_pkgs;
388 my $new_custnum = shift;
389 unless ( qsearchs( 'cust_main', { 'custnum' => $new_custnum } ) ) {
390 $dbh->rollback if $oldAutoCommit;
391 return "Invalid new customer number: $new_custnum";
393 foreach my $cust_pkg ( @cust_pkg ) {
394 my %hash = $cust_pkg->hash;
395 $hash{'custnum'} = $new_custnum;
396 my $new_cust_pkg = new FS::cust_pkg ( \%hash );
397 my $error = $new_cust_pkg->replace($cust_pkg);
399 $dbh->rollback if $oldAutoCommit;
404 my @cancelled_cust_pkg = $self->all_pkgs;
405 foreach my $cust_pkg ( @cancelled_cust_pkg ) {
406 my $error = $cust_pkg->delete;
408 $dbh->rollback if $oldAutoCommit;
413 foreach my $cust_main_invoice ( #(email invoice destinations, not invoices)
414 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } )
416 my $error = $cust_main_invoice->delete;
418 $dbh->rollback if $oldAutoCommit;
423 my $error = $self->SUPER::delete;
425 $dbh->rollback if $oldAutoCommit;
429 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
434 =item replace OLD_RECORD [ INVOICING_LIST_ARYREF ]
436 Replaces the OLD_RECORD with this one in the database. If there is an error,
437 returns the error, otherwise returns false.
439 INVOICING_LIST_ARYREF: If you pass an arrarref to the insert method, it will
440 be set as the invoicing list (see L<"invoicing_list">). Errors return as
441 expected and rollback the entire transaction; it is not necessary to call
442 check_invoicing_list first. Here's an example:
444 $new_cust_main->replace( $old_cust_main, [ $email, 'POST' ] );
453 local $SIG{HUP} = 'IGNORE';
454 local $SIG{INT} = 'IGNORE';
455 local $SIG{QUIT} = 'IGNORE';
456 local $SIG{TERM} = 'IGNORE';
457 local $SIG{TSTP} = 'IGNORE';
458 local $SIG{PIPE} = 'IGNORE';
460 my $oldAutoCommit = $FS::UID::AutoCommit;
461 local $FS::UID::AutoCommit = 0;
464 my $error = $self->SUPER::replace($old);
467 $dbh->rollback if $oldAutoCommit;
471 if ( @param ) { # INVOICING_LIST_ARYREF
472 my $invoicing_list = shift @param;
473 $error = $self->check_invoicing_list( $invoicing_list );
475 $dbh->rollback if $oldAutoCommit;
478 $self->invoicing_list( $invoicing_list );
481 #false laziness with sub insert
482 my $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
483 $error = $queue->insert($self->getfield('last'), $self->company);
485 $dbh->rollback if $oldAutoCommit;
486 return "queueing job (transaction rolled back): $error";
489 if ( defined $self->dbdef_table->column('ship_last') && $self->ship_last ) {
490 $queue = new FS::queue { 'job' => 'FS::cust_main::append_fuzzyfiles' };
491 $error = $queue->insert($self->getfield('last'), $self->company);
493 $dbh->rollback if $oldAutoCommit;
494 return "queueing job (transaction rolled back): $error";
499 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
506 Checks all fields to make sure this is a valid customer record. If there is
507 an error, returns the error, otherwise returns false. Called by the insert
516 $self->ut_numbern('custnum')
517 || $self->ut_number('agentnum')
518 || $self->ut_number('refnum')
519 || $self->ut_name('last')
520 || $self->ut_name('first')
521 || $self->ut_textn('company')
522 || $self->ut_text('address1')
523 || $self->ut_textn('address2')
524 || $self->ut_text('city')
525 || $self->ut_textn('county')
526 || $self->ut_textn('state')
527 || $self->ut_country('country')
528 || $self->ut_anything('comments')
529 || $self->ut_numbern('referral_custnum')
531 #barf. need message catalogs. i18n. etc.
532 $error .= "Please select a referral."
533 if $error =~ /^Illegal or empty \(numeric\) refnum: /;
534 return $error if $error;
536 return "Unknown agent"
537 unless qsearchs( 'agent', { 'agentnum' => $self->agentnum } );
539 return "Unknown referral"
540 unless qsearchs( 'part_referral', { 'refnum' => $self->refnum } );
542 return "Unknown referring custnum ". $self->referral_custnum
543 unless ! $self->referral_custnum
544 || qsearchs( 'cust_main', { 'custnum' => $self->referral_custnum } );
546 if ( $self->ss eq '' ) {
551 $ss =~ /^(\d{3})(\d{2})(\d{4})$/
552 or return "Illegal social security number: ". $self->ss;
553 $self->ss("$1-$2-$3");
557 unless ( qsearchs('cust_main_county', {
558 'country' => $self->country,
561 return "Unknown state/county/country: ".
562 $self->state. "/". $self->county. "/". $self->country
563 unless qsearchs('cust_main_county',{
564 'state' => $self->state,
565 'county' => $self->county,
566 'country' => $self->country,
572 $self->ut_phonen('daytime', $self->country)
573 || $self->ut_phonen('night', $self->country)
574 || $self->ut_phonen('fax', $self->country)
575 || $self->ut_zip('zip', $self->country)
577 return $error if $error;
580 last first company address1 address2 city county state zip
581 country daytime night fax
584 if ( defined $self->dbdef_table->column('ship_last') ) {
585 if ( grep { $self->getfield($_) ne $self->getfield("ship_$_") } @addfields
586 && grep $self->getfield("ship_$_"), grep $_ ne 'state', @addfields
590 $self->ut_name('ship_last')
591 || $self->ut_name('ship_first')
592 || $self->ut_textn('ship_company')
593 || $self->ut_text('ship_address1')
594 || $self->ut_textn('ship_address2')
595 || $self->ut_text('ship_city')
596 || $self->ut_textn('ship_county')
597 || $self->ut_textn('ship_state')
598 || $self->ut_country('ship_country')
600 return $error if $error;
602 #false laziness with above
603 unless ( qsearchs('cust_main_county', {
604 'country' => $self->ship_country,
607 return "Unknown ship_state/ship_county/ship_country: ".
608 $self->ship_state. "/". $self->ship_county. "/". $self->ship_country
609 unless qsearchs('cust_main_county',{
610 'state' => $self->ship_state,
611 'county' => $self->ship_county,
612 'country' => $self->ship_country,
618 $self->ut_phonen('ship_daytime', $self->ship_country)
619 || $self->ut_phonen('ship_night', $self->ship_country)
620 || $self->ut_phonen('ship_fax', $self->ship_country)
621 || $self->ut_zip('ship_zip', $self->ship_country)
623 return $error if $error;
625 } else { # ship_ info eq billing info, so don't store dup info in database
626 $self->setfield("ship_$_", '')
627 foreach qw( last first company address1 address2 city county state zip
628 country daytime night fax );
632 $self->payby =~ /^(CARD|BILL|COMP|PREPAY)$/
633 or return "Illegal payby: ". $self->payby;
636 if ( $self->payby eq 'CARD' ) {
638 my $payinfo = $self->payinfo;
640 $payinfo =~ /^(\d{13,16})$/
641 or return "Illegal credit card number: ". $self->payinfo;
643 $self->payinfo($payinfo);
645 or return "Illegal credit card number: ". $self->payinfo;
646 return "Unknown card type" if cardtype($self->payinfo) eq "Unknown";
648 } elsif ( $self->payby eq 'BILL' ) {
650 $error = $self->ut_textn('payinfo');
651 return "Illegal P.O. number: ". $self->payinfo if $error;
653 } elsif ( $self->payby eq 'COMP' ) {
655 $error = $self->ut_textn('payinfo');
656 return "Illegal comp account issuer: ". $self->payinfo if $error;
658 } elsif ( $self->payby eq 'PREPAY' ) {
660 my $payinfo = $self->payinfo;
661 $payinfo =~ s/\W//g; #anything else would just confuse things
662 $self->payinfo($payinfo);
663 $error = $self->ut_alpha('payinfo');
664 return "Illegal prepayment identifier: ". $self->payinfo if $error;
665 return "Unknown prepayment identifier"
666 unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
670 if ( $self->paydate eq '' || $self->paydate eq '-' ) {
671 return "Expriation date required"
672 unless $self->payby eq 'BILL' || $self->payby eq 'PREPAY';
675 $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/
676 or return "Illegal expiration date: ". $self->paydate;
677 if ( length($2) == 4 ) {
678 $self->paydate("$2-$1-01");
680 $self->paydate("20$2-$1-01");
684 if ( $self->payname eq '' ) {
685 $self->payname( $self->first. " ". $self->getfield('last') );
687 $self->payname =~ /^([\w \,\.\-\']+)$/
688 or return "Illegal billing name: ". $self->payname;
692 $self->tax =~ /^(Y?)$/ or return "Illegal tax: ". $self->tax;
695 $self->otaker(getotaker);
702 Returns all packages (see L<FS::cust_pkg>) for this customer.
708 if ( $self->{'_pkgnum'} ) {
709 values %{ $self->{'_pkgnum'}->cache };
711 qsearch( 'cust_pkg', { 'custnum' => $self->custnum });
715 =item ncancelled_pkgs
717 Returns all non-cancelled packages (see L<FS::cust_pkg>) for this customer.
721 sub ncancelled_pkgs {
723 if ( $self->{'_pkgnum'} ) {
724 grep { ! $_->getfield('cancel') } values %{ $self->{'_pkgnum'}->cache };
726 @{ [ # force list context
727 qsearch( 'cust_pkg', {
728 'custnum' => $self->custnum,
731 qsearch( 'cust_pkg', {
732 'custnum' => $self->custnum,
741 Returns all suspended packages (see L<FS::cust_pkg>) for this customer.
747 grep { $_->susp } $self->ncancelled_pkgs;
750 =item unflagged_suspended_pkgs
752 Returns all unflagged suspended packages (see L<FS::cust_pkg>) for this
753 customer (thouse packages without the `manual_flag' set).
757 sub unflagged_suspended_pkgs {
759 return $self->suspended_pkgs
760 unless dbdef->table('cust_pkg')->column('manual_flag');
761 grep { ! $_->manual_flag } $self->suspended_pkgs;
764 =item unsuspended_pkgs
766 Returns all unsuspended (and uncancelled) packages (see L<FS::cust_pkg>) for
771 sub unsuspended_pkgs {
773 grep { ! $_->susp } $self->ncancelled_pkgs;
778 Unsuspends all unflagged suspended packages (see L</unflagged_suspended_pkgs>
779 and L<FS::cust_pkg>) for this customer. Always returns a list: an empty list
780 on success or a list of errors.
786 grep { $_->unsuspend } $self->suspended_pkgs;
791 Suspends all unsuspended packages (see L<FS::cust_pkg>) for this customer.
792 Always returns a list: an empty list on success or a list of errors.
798 grep { $_->suspend } $self->unsuspended_pkgs;
803 Cancels all uncancelled packages (see L<FS::cust_pkg>) for this customer.
804 Always returns a list: an empty list on success or a list of errors.
810 grep { $_->cancel } $self->ncancelled_pkgs;
815 Generates invoices (see L<FS::cust_bill>) for this customer. Usually used in
816 conjunction with the collect method.
818 Options are passed as name-value pairs.
820 The only currently available option is `time', which bills the customer as if
821 it were that time. It is specified as a UNIX timestamp; see
822 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
823 functions. For example:
827 $cust_main->bill( 'time' => str2time('April 20th, 2001') );
829 If there is an error, returns the error, otherwise returns false.
834 my( $self, %options ) = @_;
835 my $time = $options{'time'} || time;
840 local $SIG{HUP} = 'IGNORE';
841 local $SIG{INT} = 'IGNORE';
842 local $SIG{QUIT} = 'IGNORE';
843 local $SIG{TERM} = 'IGNORE';
844 local $SIG{TSTP} = 'IGNORE';
845 local $SIG{PIPE} = 'IGNORE';
847 my $oldAutoCommit = $FS::UID::AutoCommit;
848 local $FS::UID::AutoCommit = 0;
851 # find the packages which are due for billing, find out how much they are
852 # & generate invoice database.
854 my( $total_setup, $total_recur ) = ( 0, 0 );
855 my( $taxable_setup, $taxable_recur ) = ( 0, 0 );
856 my @cust_bill_pkg = ();
858 foreach my $cust_pkg (
859 qsearch('cust_pkg', { 'custnum' => $self->custnum } )
862 #NO!! next if $cust_pkg->cancel;
863 next if $cust_pkg->getfield('cancel');
865 #? to avoid use of uninitialized value errors... ?
866 $cust_pkg->setfield('bill', '')
867 unless defined($cust_pkg->bill);
869 my $part_pkg = qsearchs( 'part_pkg', { 'pkgpart' => $cust_pkg->pkgpart } );
871 #so we don't modify cust_pkg record unnecessarily
872 my $cust_pkg_mod_flag = 0;
873 my %hash = $cust_pkg->hash;
874 my $old_cust_pkg = new FS::cust_pkg \%hash;
878 unless ( $cust_pkg->setup ) {
879 my $setup_prog = $part_pkg->getfield('setup');
880 $setup_prog =~ /^(.*)$/ or do {
881 $dbh->rollback if $oldAutoCommit;
882 return "Illegal setup for pkgpart ". $part_pkg->pkgpart.
888 ##$cpt->permit(); #what is necessary?
889 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
890 #$setup = $cpt->reval($setup_prog);
891 $setup = eval $setup_prog;
892 unless ( defined($setup) ) {
893 $dbh->rollback if $oldAutoCommit;
894 return "Error eval-ing part_pkg->setup pkgpart ". $part_pkg->pkgpart.
895 "(expression $setup_prog): $@";
897 $cust_pkg->setfield('setup',$time);
898 $cust_pkg_mod_flag=1;
904 if ( $part_pkg->getfield('freq') > 0 &&
905 ! $cust_pkg->getfield('susp') &&
906 ( $cust_pkg->getfield('bill') || 0 ) < $time
908 my $recur_prog = $part_pkg->getfield('recur');
909 $recur_prog =~ /^(.*)$/ or do {
910 $dbh->rollback if $oldAutoCommit;
911 return "Illegal recur for pkgpart ". $part_pkg->pkgpart.
916 # shared with $recur_prog
917 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
920 ##$cpt->permit(); #what is necessary?
921 #$cpt->share(qw( $cust_pkg )); #can $cpt now use $cust_pkg methods?
922 #$recur = $cpt->reval($recur_prog);
923 $recur = eval $recur_prog;
924 unless ( defined($recur) ) {
925 $dbh->rollback if $oldAutoCommit;
926 return "Error eval-ing part_pkg->recur pkgpart ". $part_pkg->pkgpart.
927 "(expression $recur_prog): $@";
929 #change this bit to use Date::Manip? CAREFUL with timezones (see
930 # mailing list archive)
931 my ($sec,$min,$hour,$mday,$mon,$year) =
932 (localtime($sdate) )[0,1,2,3,4,5];
934 #pro-rating magic - if $recur_prog fiddles $sdate, want to use that
935 # only for figuring next bill date, nothing else, so, reset $sdate again
937 $sdate = $cust_pkg->bill || $cust_pkg->setup || $time;
939 $mon += $part_pkg->getfield('freq');
940 until ( $mon < 12 ) { $mon -= 12; $year++; }
941 $cust_pkg->setfield('bill',
942 timelocal($sec,$min,$hour,$mday,$mon,$year));
943 $cust_pkg_mod_flag = 1;
946 warn "\$setup is undefined" unless defined($setup);
947 warn "\$recur is undefined" unless defined($recur);
948 warn "\$cust_pkg->bill is undefined" unless defined($cust_pkg->bill);
950 if ( $cust_pkg_mod_flag ) {
951 $error=$cust_pkg->replace($old_cust_pkg);
952 if ( $error ) { #just in case
953 $dbh->rollback if $oldAutoCommit;
954 return "Error modifying pkgnum ". $cust_pkg->pkgnum. ": $error";
956 $setup = sprintf( "%.2f", $setup );
957 $recur = sprintf( "%.2f", $recur );
959 $dbh->rollback if $oldAutoCommit;
960 return "negative setup $setup for pkgnum ". $cust_pkg->pkgnum;
963 $dbh->rollback if $oldAutoCommit;
964 return "negative recur $recur for pkgnum ". $cust_pkg->pkgnum;
966 if ( $setup > 0 || $recur > 0 ) {
967 my $cust_bill_pkg = new FS::cust_bill_pkg ({
968 'pkgnum' => $cust_pkg->pkgnum,
972 'edate' => $cust_pkg->bill,
974 push @cust_bill_pkg, $cust_bill_pkg;
975 $total_setup += $setup;
976 $total_recur += $recur;
977 $taxable_setup += $setup
978 unless $part_pkg->dbdef_table->column('setuptax')
979 || $part_pkg->setuptax =~ /^Y$/i;
980 $taxable_recur += $recur
981 unless $part_pkg->dbdef_table->column('recurtax')
982 || $part_pkg->recurtax =~ /^Y$/i;
988 my $charged = sprintf( "%.2f", $total_setup + $total_recur );
989 my $taxable_charged = sprintf( "%.2f", $taxable_setup + $taxable_recur );
991 unless ( @cust_bill_pkg ) {
992 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
996 unless ( $self->tax =~ /Y/i
997 || $self->payby eq 'COMP'
998 || $taxable_charged == 0 ) {
999 my $cust_main_county = qsearchs('cust_main_county',{
1000 'state' => $self->state,
1001 'county' => $self->county,
1002 'country' => $self->country,
1004 my $tax = sprintf( "%.2f",
1005 $taxable_charged * ( $cust_main_county->getfield('tax') / 100 )
1009 $charged = sprintf( "%.2f", $charged+$tax );
1011 my $cust_bill_pkg = new FS::cust_bill_pkg ({
1018 push @cust_bill_pkg, $cust_bill_pkg;
1022 my $cust_bill = new FS::cust_bill ( {
1023 'custnum' => $self->custnum,
1025 'charged' => $charged,
1027 $error = $cust_bill->insert;
1029 $dbh->rollback if $oldAutoCommit;
1030 return "can't create invoice for customer #". $self->custnum. ": $error";
1033 my $invnum = $cust_bill->invnum;
1035 foreach $cust_bill_pkg ( @cust_bill_pkg ) {
1037 $cust_bill_pkg->invnum($invnum);
1038 $error = $cust_bill_pkg->insert;
1040 $dbh->rollback if $oldAutoCommit;
1041 return "can't create invoice line item for customer #". $self->custnum.
1046 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1050 =item collect OPTIONS
1052 (Attempt to) collect money for this customer's outstanding invoices (see
1053 L<FS::cust_bill>). Usually used after the bill method.
1055 Depending on the value of `payby', this may print an invoice (`BILL'), charge
1056 a credit card (`CARD'), or just add any necessary (pseudo-)payment (`COMP').
1058 Most actions are now triggered by invoice events; see L<FS::part_bill_event>
1059 and the invoice events web interface.
1061 If there is an error, returns the error, otherwise returns false.
1063 Options are passed as name-value pairs.
1065 Currently available options are:
1067 invoice_time - Use this time when deciding when to print invoices and
1068 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>
1069 for conversion functions.
1071 batch_card - This option is deprecated. See the invoice events web interface
1072 to control whether cards are batched or run against a realtime gateway.
1074 report_badcard - This option is deprecated.
1076 force_print - This option is deprecated; see the invoice events web interface.
1081 my( $self, %options ) = @_;
1082 my $invoice_time = $options{'invoice_time'} || time;
1085 local $SIG{HUP} = 'IGNORE';
1086 local $SIG{INT} = 'IGNORE';
1087 local $SIG{QUIT} = 'IGNORE';
1088 local $SIG{TERM} = 'IGNORE';
1089 local $SIG{TSTP} = 'IGNORE';
1090 local $SIG{PIPE} = 'IGNORE';
1092 my $oldAutoCommit = $FS::UID::AutoCommit;
1093 local $FS::UID::AutoCommit = 0;
1096 my $balance = $self->balance;
1097 warn "collect: balance $balance" if $Debug;
1098 unless ( $balance > 0 ) { #redundant?????
1099 $dbh->rollback if $oldAutoCommit; #hmm
1103 foreach my $cust_bill (
1104 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1107 #this has to be before next's
1108 my $amount = sprintf( "%.2f", $balance < $cust_bill->owed
1112 $balance = sprintf( "%.2f", $balance - $amount );
1114 next unless $cust_bill->owed > 0;
1116 # don't try to charge for the same invoice if it's already in a batch
1117 #next if qsearchs( 'cust_pay_batch', { 'invnum' => $cust_bill->invnum } );
1119 warn "invnum ". $cust_bill->invnum. " (owed ". $cust_bill->owed. ", amount $amount, balance $balance)" if $Debug;
1121 next unless $amount > 0;
1123 foreach my $part_bill_event (
1124 sort { $a->seconds <=> $b->seconds
1125 || $a->weight <=> $b->weight
1126 || $a->eventpart <=> $b->eventpart }
1127 grep { $_->seconds <= ( $invoice_time - $cust_bill->_date )
1128 && ! qsearchs( 'cust_bill_event', {
1129 'invnum' => $cust_bill->invnum,
1130 'eventpart' => $_->eventpart } )
1132 qsearch('part_bill_event', { 'payby' => $self->payby,
1133 'disabled' => '', } )
1136 my $cust_main = $self; #for callback
1137 my $error = eval $part_bill_event->eventcode;
1141 warn "Error running invoice event (". $part_bill_event->eventcode.
1146 #add cust_bill_event
1147 my $cust_bill_event = new FS::cust_bill_event {
1148 'invnum' => $cust_bill->invnum,
1149 'eventpart' => $part_bill_event->eventpart,
1150 '_date' => $invoice_time,
1152 $cust_bill_event->insert;
1154 #$dbh->rollback if $oldAutoCommit;
1155 #return "error: $error";
1157 # gah, even with transactions.
1158 $dbh->commit if $oldAutoCommit; #well.
1159 my $e = 'WARNING: Event run but database not updated - '.
1160 'error inserting cust_bill_event, invnum #'. $cust_bill->invnum.
1161 ', eventpart '. $part_bill_event->eventpart.
1173 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1180 Returns the total owed for this customer on all invoices
1181 (see L<FS::cust_bill/owed>).
1187 $self->total_owed_date(2145859200); #12/31/2037
1190 =item total_owed_date TIME
1192 Returns the total owed for this customer on all invoices with date earlier than
1193 TIME. TIME is specified as a UNIX timestamp; see L<perlfunc/"time">). Also
1194 see L<Time::Local> and L<Date::Parse> for conversion functions.
1198 sub total_owed_date {
1202 foreach my $cust_bill (
1203 grep { $_->_date <= $time }
1204 qsearch('cust_bill', { 'custnum' => $self->custnum, } )
1206 $total_bill += $cust_bill->owed;
1208 sprintf( "%.2f", $total_bill );
1213 Applies (see L<FS::cust_credit_bill>) unapplied credits (see L<FS::cust_credit>)
1214 to outstanding invoice balances in chronological order and returns the value
1215 of any remaining unapplied credits available for refund
1216 (see L<FS::cust_refund>).
1223 return 0 unless $self->total_credited;
1225 my @credits = sort { $b->_date <=> $a->_date} (grep { $_->credited > 0 }
1226 qsearch('cust_credit', { 'custnum' => $self->custnum } ) );
1228 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1229 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1233 foreach my $cust_bill ( @invoices ) {
1236 if ( !defined($credit) || $credit->credited == 0) {
1237 $credit = pop @credits or last;
1240 if ($cust_bill->owed >= $credit->credited) {
1241 $amount=$credit->credited;
1243 $amount=$cust_bill->owed;
1246 my $cust_credit_bill = new FS::cust_credit_bill ( {
1247 'crednum' => $credit->crednum,
1248 'invnum' => $cust_bill->invnum,
1249 'amount' => $amount,
1251 my $error = $cust_credit_bill->insert;
1252 die $error if $error;
1254 redo if ($cust_bill->owed > 0);
1258 return $self->total_credited;
1261 =item apply_payments
1263 Applies (see L<FS::cust_bill_pay>) unapplied payments (see L<FS::cust_pay>)
1264 to outstanding invoice balances in chronological order.
1266 #and returns the value of any remaining unapplied payments.
1270 sub apply_payments {
1275 my @payments = sort { $b->_date <=> $a->_date } ( grep { $_->unapplied > 0 }
1276 qsearch('cust_pay', { 'custnum' => $self->custnum } ) );
1278 my @invoices = sort { $a->_date <=> $b->_date} (grep { $_->owed > 0 }
1279 qsearch('cust_bill', { 'custnum' => $self->custnum } ) );
1283 foreach my $cust_bill ( @invoices ) {
1286 if ( !defined($payment) || $payment->unapplied == 0 ) {
1287 $payment = pop @payments or last;
1290 if ( $cust_bill->owed >= $payment->unapplied ) {
1291 $amount = $payment->unapplied;
1293 $amount = $cust_bill->owed;
1296 my $cust_bill_pay = new FS::cust_bill_pay ( {
1297 'paynum' => $payment->paynum,
1298 'invnum' => $cust_bill->invnum,
1299 'amount' => $amount,
1301 my $error = $cust_bill_pay->insert;
1302 die $error if $error;
1304 redo if ( $cust_bill->owed > 0);
1308 return $self->total_unapplied_payments;
1311 =item total_credited
1313 Returns the total outstanding credit (see L<FS::cust_credit>) for this
1314 customer. See L<FS::cust_credit/credited>.
1318 sub total_credited {
1320 my $total_credit = 0;
1321 foreach my $cust_credit ( qsearch('cust_credit', {
1322 'custnum' => $self->custnum,
1324 $total_credit += $cust_credit->credited;
1326 sprintf( "%.2f", $total_credit );
1329 =item total_unapplied_payments
1331 Returns the total unapplied payments (see L<FS::cust_pay>) for this customer.
1332 See L<FS::cust_pay/unapplied>.
1336 sub total_unapplied_payments {
1338 my $total_unapplied = 0;
1339 foreach my $cust_pay ( qsearch('cust_pay', {
1340 'custnum' => $self->custnum,
1342 $total_unapplied += $cust_pay->unapplied;
1344 sprintf( "%.2f", $total_unapplied );
1349 Returns the balance for this customer (total_owed minus total_credited
1350 minus total_unapplied_payments).
1357 $self->total_owed - $self->total_credited - $self->total_unapplied_payments
1361 =item balance_date TIME
1363 Returns the balance for this customer, only considering invoices with date
1364 earlier than TIME (total_owed_date minus total_credited minus
1365 total_unapplied_payments). TIME is specified as a UNIX timestamp; see
1366 L<perlfunc/"time">). Also see L<Time::Local> and L<Date::Parse> for conversion
1375 $self->total_owed_date($time)
1376 - $self->total_credited
1377 - $self->total_unapplied_payments
1381 =item invoicing_list [ ARRAYREF ]
1383 If an arguement is given, sets these email addresses as invoice recipients
1384 (see L<FS::cust_main_invoice>). Errors are not fatal and are not reported
1385 (except as warnings), so use check_invoicing_list first.
1387 Returns a list of email addresses (with svcnum entries expanded).
1389 Note: You can clear the invoicing list by passing an empty ARRAYREF. You can
1390 check it without disturbing anything by passing nothing.
1392 This interface may change in the future.
1396 sub invoicing_list {
1397 my( $self, $arrayref ) = @_;
1399 my @cust_main_invoice;
1400 if ( $self->custnum ) {
1401 @cust_main_invoice =
1402 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1404 @cust_main_invoice = ();
1406 foreach my $cust_main_invoice ( @cust_main_invoice ) {
1407 #warn $cust_main_invoice->destnum;
1408 unless ( grep { $cust_main_invoice->address eq $_ } @{$arrayref} ) {
1409 #warn $cust_main_invoice->destnum;
1410 my $error = $cust_main_invoice->delete;
1411 warn $error if $error;
1414 if ( $self->custnum ) {
1415 @cust_main_invoice =
1416 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1418 @cust_main_invoice = ();
1420 my %seen = map { $_->address => 1 } @cust_main_invoice;
1421 foreach my $address ( @{$arrayref} ) {
1422 #unless ( grep { $address eq $_->address } @cust_main_invoice ) {
1423 next if exists $seen{$address} && $seen{$address};
1424 $seen{$address} = 1;
1425 my $cust_main_invoice = new FS::cust_main_invoice ( {
1426 'custnum' => $self->custnum,
1429 my $error = $cust_main_invoice->insert;
1430 warn $error if $error;
1433 if ( $self->custnum ) {
1435 qsearch( 'cust_main_invoice', { 'custnum' => $self->custnum } );
1441 =item check_invoicing_list ARRAYREF
1443 Checks these arguements as valid input for the invoicing_list method. If there
1444 is an error, returns the error, otherwise returns false.
1448 sub check_invoicing_list {
1449 my( $self, $arrayref ) = @_;
1450 foreach my $address ( @{$arrayref} ) {
1451 my $cust_main_invoice = new FS::cust_main_invoice ( {
1452 'custnum' => $self->custnum,
1455 my $error = $self->custnum
1456 ? $cust_main_invoice->check
1457 : $cust_main_invoice->checkdest
1459 return $error if $error;
1464 =item default_invoicing_list
1466 Sets the invoicing list to all accounts associated with this customer.
1470 sub default_invoicing_list {
1473 foreach my $cust_pkg ( $self->all_pkgs ) {
1474 my @cust_svc = qsearch('cust_svc', { 'pkgnum' => $cust_pkg->pkgnum } );
1476 map { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1477 grep { qsearchs('svc_acct', { 'svcnum' => $_->svcnum } ) }
1479 push @list, map { $_->email } @svc_acct;
1481 $self->invoicing_list(\@list);
1484 =item invoicing_list_addpost
1486 Adds postal invoicing to this customer. If this customer is already configured
1487 to receive postal invoices, does nothing.
1491 sub invoicing_list_addpost {
1493 return if grep { $_ eq 'POST' } $self->invoicing_list;
1494 my @invoicing_list = $self->invoicing_list;
1495 push @invoicing_list, 'POST';
1496 $self->invoicing_list(\@invoicing_list);
1499 =item referral_cust_main [ DEPTH [ EXCLUDE_HASHREF ] ]
1501 Returns an array of customers referred by this customer (referral_custnum set
1502 to this custnum). If DEPTH is given, recurses up to the given depth, returning
1503 customers referred by customers referred by this customer and so on, inclusive.
1504 The default behavior is DEPTH 1 (no recursion).
1508 sub referral_cust_main {
1510 my $depth = @_ ? shift : 1;
1511 my $exclude = @_ ? shift : {};
1514 map { $exclude->{$_->custnum}++; $_; }
1515 grep { ! $exclude->{ $_->custnum } }
1516 qsearch( 'cust_main', { 'referral_custnum' => $self->custnum } );
1520 map { $_->referral_cust_main($depth-1, $exclude) }
1527 =item referral_cust_main_ncancelled
1529 Same as referral_cust_main, except only returns customers with uncancelled
1534 sub referral_cust_main_ncancelled {
1536 grep { scalar($_->ncancelled_pkgs) } $self->referral_cust_main;
1539 =item referral_cust_pkg [ DEPTH ]
1541 Like referral_cust_main, except returns a flat list of all unsuspended (and
1542 uncancelled) packages for each customer. The number of items in this list may
1543 be useful for comission calculations (perhaps after a C<grep { my $pkgpart = $_->pkgpart; grep { $_ == $pkgpart } @commission_worthy_pkgparts> } $cust_main-> ).
1547 sub referral_cust_pkg {
1549 my $depth = @_ ? shift : 1;
1551 map { $_->unsuspended_pkgs }
1552 grep { $_->unsuspended_pkgs }
1553 $self->referral_cust_main($depth);
1556 =item credit AMOUNT, REASON
1558 Applies a credit to this customer. If there is an error, returns the error,
1559 otherwise returns false.
1564 my( $self, $amount, $reason ) = @_;
1565 my $cust_credit = new FS::cust_credit {
1566 'custnum' => $self->custnum,
1567 'amount' => $amount,
1568 'reason' => $reason,
1570 $cust_credit->insert;
1573 =item charge AMOUNT PKG COMMENT
1575 Creates a one-time charge for this customer. If there is an error, returns
1576 the error, otherwise returns false.
1581 my ( $self, $amount, $pkg, $comment ) = @_;
1583 my $part_pkg = new FS::part_pkg ( {
1584 'pkg' => $pkg || 'One-time charge',
1585 'comment' => $comment,
1602 =item check_and_rebuild_fuzzyfiles
1606 sub check_and_rebuild_fuzzyfiles {
1607 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1608 -e "$dir/cust_main.last" && -e "$dir/cust_main.company"
1609 or &rebuild_fuzzyfiles;
1612 =item rebuild_fuzzyfiles
1616 sub rebuild_fuzzyfiles {
1618 use Fcntl qw(:flock);
1620 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1624 open(LASTLOCK,">>$dir/cust_main.last")
1625 or die "can't open $dir/cust_main.last: $!";
1626 flock(LASTLOCK,LOCK_EX)
1627 or die "can't lock $dir/cust_main.last: $!";
1629 my @all_last = map $_->getfield('last'), qsearch('cust_main', {});
1631 grep $_, map $_->getfield('ship_last'), qsearch('cust_main',{})
1632 if defined dbdef->table('cust_main')->column('ship_last');
1634 open (LASTCACHE,">$dir/cust_main.last.tmp")
1635 or die "can't open $dir/cust_main.last.tmp: $!";
1636 print LASTCACHE join("\n", @all_last), "\n";
1637 close LASTCACHE or die "can't close $dir/cust_main.last.tmp: $!";
1639 rename "$dir/cust_main.last.tmp", "$dir/cust_main.last";
1644 open(COMPANYLOCK,">>$dir/cust_main.company")
1645 or die "can't open $dir/cust_main.company: $!";
1646 flock(COMPANYLOCK,LOCK_EX)
1647 or die "can't lock $dir/cust_main.company: $!";
1649 my @all_company = grep $_ ne '', map $_->company, qsearch('cust_main',{});
1651 grep $_ ne '', map $_->ship_company, qsearch('cust_main', {})
1652 if defined dbdef->table('cust_main')->column('ship_last');
1654 open (COMPANYCACHE,">$dir/cust_main.company.tmp")
1655 or die "can't open $dir/cust_main.company.tmp: $!";
1656 print COMPANYCACHE join("\n", @all_company), "\n";
1657 close COMPANYCACHE or die "can't close $dir/cust_main.company.tmp: $!";
1659 rename "$dir/cust_main.company.tmp", "$dir/cust_main.company";
1669 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1670 open(LASTCACHE,"<$dir/cust_main.last")
1671 or die "can't open $dir/cust_main.last: $!";
1672 my @array = map { chomp; $_; } <LASTCACHE>;
1682 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1683 open(COMPANYCACHE,"<$dir/cust_main.company")
1684 or die "can't open $dir/cust_main.last: $!";
1685 my @array = map { chomp; $_; } <COMPANYCACHE>;
1690 =item append_fuzzyfiles LASTNAME COMPANY
1694 sub append_fuzzyfiles {
1695 my( $last, $company ) = @_;
1697 &check_and_rebuild_fuzzyfiles;
1699 use Fcntl qw(:flock);
1701 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
1705 open(LAST,">>$dir/cust_main.last")
1706 or die "can't open $dir/cust_main.last: $!";
1708 or die "can't lock $dir/cust_main.last: $!";
1710 print LAST "$last\n";
1713 or die "can't unlock $dir/cust_main.last: $!";
1719 open(COMPANY,">>$dir/cust_main.company")
1720 or die "can't open $dir/cust_main.company: $!";
1721 flock(COMPANY,LOCK_EX)
1722 or die "can't lock $dir/cust_main.company: $!";
1724 print COMPANY "$company\n";
1726 flock(COMPANY,LOCK_UN)
1727 or die "can't unlock $dir/cust_main.company: $!";
1741 The delete method should possibly take an FS::cust_main object reference
1742 instead of a scalar customer number.
1744 Bill and collect options should probably be passed as references instead of a
1747 There should probably be a configuration file with a list of allowed credit
1750 No multiple currency support (probably a larger project than just this module).
1754 L<FS::Record>, L<FS::cust_pkg>, L<FS::cust_bill>, L<FS::cust_credit>
1755 L<FS::agent>, L<FS::part_referral>, L<FS::cust_main_county>,
1756 L<FS::cust_main_invoice>, L<FS::UID>, schema.html from the base documentation.