1 package FS::cust_credit;
4 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::Record );
5 use vars qw( $conf $unsuspendauto $me $DEBUG );
7 use FS::UID qw( dbh getotaker );
8 use FS::Misc qw(send_email);
9 use FS::Record qw( qsearch qsearchs dbdef );
13 use FS::cust_credit_bill;
19 $me = '[ FS::cust_credit ]';
22 #ask FS::UID to run this stuff for us later
23 $FS::UID::callback{'FS::cust_credit'} = sub {
26 $unsuspendauto = $conf->exists('unsuspendauto');
30 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
31 'cancel_credit_type' => 'Cancellation Credit',
32 'signup_credit_type' => 'Self-Service Credit',
37 FS::cust_credit - Object methods for cust_credit records
43 $record = new FS::cust_credit \%hash;
44 $record = new FS::cust_credit { 'column' => 'value' };
46 $error = $record->insert;
48 $error = $new_record->replace($old_record);
50 $error = $record->delete;
52 $error = $record->check;
56 An FS::cust_credit object represents a credit; the equivalent of a negative
57 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
58 FS::Record. The following fields are currently supported:
64 Primary key (assigned automatically for new credits)
68 Customer (see L<FS::cust_main>)
76 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
77 L<Time::Local> and L<Date::Parse> for conversion functions.
81 Order taker (see L<FS::access_user>)
89 Reason (see L<FS::reason>)
97 Books closed flag, empty or `Y'
101 Desired pkgnum when using experimental package balances.
111 Creates a new credit. To add the credit to the database, see L<"insert">.
115 sub table { 'cust_credit'; }
116 sub cust_linked { $_[0]->cust_main_custnum; }
117 sub cust_unlinked_msg {
119 "WARNING: can't find cust_main.custnum ". $self->custnum.
120 ' (cust_credit.crednum '. $self->crednum. ')';
125 Adds this credit to the database ("Posts" the credit). If there is an error,
126 returns the error, otherwise returns false.
131 my ($self, %options) = @_;
133 local $SIG{HUP} = 'IGNORE';
134 local $SIG{INT} = 'IGNORE';
135 local $SIG{QUIT} = 'IGNORE';
136 local $SIG{TERM} = 'IGNORE';
137 local $SIG{TSTP} = 'IGNORE';
138 local $SIG{PIPE} = 'IGNORE';
140 my $oldAutoCommit = $FS::UID::AutoCommit;
141 local $FS::UID::AutoCommit = 0;
144 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
145 my $old_balance = $cust_main->balance;
147 unless ($self->reasonnum) {
148 my $result = $self->reason( $self->getfield('reason'),
149 exists($options{ 'reason_type' })
150 ? ('reason_type' => $options{ 'reason_type' })
154 $dbh->rollback if $oldAutoCommit;
155 return "failed to set reason for $me"; #: ". $dbh->errstr;
159 $self->setfield('reason', '');
161 my $error = $self->SUPER::insert;
163 $dbh->rollback if $oldAutoCommit;
164 return "error inserting $self: $error";
167 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
169 #false laziness w/ cust_credit::insert
170 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
171 my @errors = $cust_main->unsuspend;
173 # side-fx with nested transactions? upstack rolls back?
174 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
180 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
188 Unless the closed flag is set, deletes this credit and all associated
189 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
190 the void method instead to leave a record of the deleted credit.
194 # very similar to FS::cust_pay::delete
197 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
199 local $SIG{HUP} = 'IGNORE';
200 local $SIG{INT} = 'IGNORE';
201 local $SIG{QUIT} = 'IGNORE';
202 local $SIG{TERM} = 'IGNORE';
203 local $SIG{TSTP} = 'IGNORE';
204 local $SIG{PIPE} = 'IGNORE';
206 my $oldAutoCommit = $FS::UID::AutoCommit;
207 local $FS::UID::AutoCommit = 0;
210 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
211 my $error = $cust_credit_bill->delete;
213 $dbh->rollback if $oldAutoCommit;
218 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
219 my $error = $cust_credit_refund->delete;
221 $dbh->rollback if $oldAutoCommit;
226 my $error = $self->SUPER::delete(@_);
228 $dbh->rollback if $oldAutoCommit;
232 if ( $conf->config('deletecredits') ne '' ) {
234 my $cust_main = $self->cust_main;
236 my $error = send_email(
237 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
238 #invoice_from??? well as good as any
239 'to' => $conf->config('deletecredits'),
240 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
242 "This is an automatic message from your Freeside installation\n",
243 "informing you that the following credit has been deleted:\n",
245 'crednum: '. $self->crednum. "\n",
246 'custnum: '. $self->custnum.
247 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
248 'amount: $'. sprintf("%.2f", $self->amount). "\n",
249 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
250 'reason: '. $self->reason. "\n",
255 $dbh->rollback if $oldAutoCommit;
256 return "can't send credit deletion notification: $error";
261 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
267 =item replace OLD_RECORD
269 You can, but probably shouldn't modify credits...
274 #return "Can't modify credit!"
276 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
277 $self->SUPER::replace(@_);
282 Checks all fields to make sure this is a valid credit. If there is an error,
283 returns the error, otherwise returns false. Called by the insert and replace
291 $self->otaker(getotaker) unless ($self->otaker);
294 $self->ut_numbern('crednum')
295 || $self->ut_number('custnum')
296 || $self->ut_numbern('_date')
297 || $self->ut_money('amount')
298 || $self->ut_alphan('otaker')
299 || $self->ut_textn('reason')
300 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
301 || $self->ut_textn('addlinfo')
302 || $self->ut_enum('closed', [ '', 'Y' ])
303 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
304 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
306 return $error if $error;
308 return "amount must be > 0 " if $self->amount <= 0;
310 return "amount must be greater or equal to amount applied"
311 if $self->unapplied < 0;
313 return "Unknown customer"
314 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
316 $self->_date(time) unless $self->_date;
321 =item cust_credit_refund
323 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
327 sub cust_credit_refund {
329 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
330 sort { $a->_date <=> $b->_date }
331 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
335 =item cust_credit_bill
337 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
342 sub cust_credit_bill {
344 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
345 sort { $a->_date <=> $b->_date }
346 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
352 Returns the amount of this credit that is still unapplied/outstanding;
353 amount minus all refund applications (see L<FS::cust_credit_refund>) and
354 applications to invoices (see L<FS::cust_credit_bill>).
360 my $amount = $self->amount;
361 $amount -= $_->amount foreach ( $self->cust_credit_refund );
362 $amount -= $_->amount foreach ( $self->cust_credit_bill );
363 sprintf( "%.2f", $amount );
368 Deprecated name for the unapplied method.
374 #carp "cust_credit->credited deprecated; use ->unapplied";
375 $self->unapplied(@_);
380 Returns the customer (see L<FS::cust_main>) for this credit.
386 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
392 Returns the text of the associated reason (see L<FS::reason>) for this credit.
397 my ($self, $value, %options) = @_;
400 my $typenum = $options{'reason_type'};
402 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
403 local $FS::UID::AutoCommit = 0; # a transaction if it matters
405 if ( defined( $value ) ) {
406 my $hashref = { 'reason' => $value };
407 $hashref->{'reason_type'} = $typenum if $typenum;
408 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
409 my $extra_sql = " AND reason_type.class='R'";
411 $reason = qsearchs( { 'table' => 'reason',
412 'hashref' => $hashref,
413 'addl_from' => $addl_from,
414 'extra_sql' => $extra_sql,
417 if (!$reason && $typenum) {
418 $reason = new FS::reason( { 'reason_type' => $typenum,
422 my $error = $reason->insert;
424 warn "error inserting reason: $error\n";
429 $self->reasonnum($reason ? $reason->reasonnum : '') ;
430 warn "$me reason used in set mode with non-existant reason -- clearing"
433 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
435 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
437 ( $reason ? $reason->reason : '' ).
438 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
443 # Used by FS::Upgrade to migrate to a new database.
445 sub _upgrade_data { # class method
446 my ($class, %opts) = @_;
448 warn "$me upgrading $class\n" if $DEBUG;
450 if (defined dbdef->table($class->table)->column('reason')) {
452 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
454 my @cust_credits = qsearch({ 'table' => $class->table,
456 'extra_sql' => 'WHERE reason IS NOT NULL',
459 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
460 warn "$me Found unmigrated reasons\n" if $DEBUG;
461 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
462 my $reason_type = qsearchs( 'reason_type', $hashref );
463 unless ($reason_type) {
464 $reason_type = new FS::reason_type( $hashref );
465 my $error = $reason_type->insert();
466 die "$class had error inserting FS::reason_type into database: $error\n"
470 $hashref = { 'reason_type' => $reason_type->typenum,
473 my $noreason = qsearchs( 'reason', $hashref );
475 $hashref->{'disabled'} = 'Y';
476 $noreason = new FS::reason( $hashref );
477 my $error = $noreason->insert();
478 die "can't insert legacy reason '(none)' into database: $error\n"
482 foreach my $cust_credit ( @cust_credits ) {
483 my $reason = $cust_credit->getfield('reason');
484 warn "Contemplating reason $reason\n" if $DEBUG > 1;
485 if ($reason =~ /\S/) {
486 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
487 or die "can't insert legacy reason $reason into database\n";
489 $cust_credit->reasonnum($noreason->reasonnum);
492 $cust_credit->setfield('reason', '');
493 my $error = $cust_credit->replace;
495 warn "*** WARNING: error replacing reason in $class ".
496 $cust_credit->crednum. ": $error ***\n"
501 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
503 foreach ( keys %reasontype_map ) {
504 unless ($conf->config($_)) { # hmmmm
505 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
506 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
507 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
508 my $reason_type = qsearchs( 'reason_type', $hashref );
509 unless ($reason_type) {
510 $reason_type = new FS::reason_type( $hashref );
511 my $error = $reason_type->insert();
512 die "$class had error inserting FS::reason_type into database: $error\n"
515 $conf->set($_, $reason_type->typenum);
519 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
521 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
522 my $reason_type = qsearchs( 'reason_type', $hashref );
523 unless ($reason_type) {
524 $reason_type = new FS::reason_type( $hashref );
525 my $error = $reason_type->insert();
526 die "$class had error inserting FS::reason_type into database: $error\n"
530 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
531 foreach my $plan ( @plans ) {
532 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
533 unless ($pkg->option('reason_type', 1) ) {
534 my $plandata = $pkg->plandata.
535 "reason_type=". $reason_type->typenum. "\n";
536 $pkg->plandata($plandata);
538 $pkg->replace( undef,
539 'pkg_svc' => { map { $_->svcpart => $_->quantity }
542 'primary_svc' => $pkg->svcpart,
544 die "failed setting reason_type option: $error"
551 $class->_upgrade_otaker(%opts);
563 Returns an SQL fragment to retreive the unapplied amount.
568 my ($class, $start, $end) = @_;
570 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
571 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
572 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
573 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
577 ( SELECT SUM(amount) FROM cust_credit_refund
578 WHERE cust_credit.crednum = cust_credit_refund.crednum
579 $refund_start $refund_end )
583 ( SELECT SUM(amount) FROM cust_credit_bill
584 WHERE cust_credit.crednum = cust_credit_bill.crednum
585 $bill_start $bill_end )
594 Deprecated name for the unapplied_sql method.
601 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
603 #$class->unapplied_sql(@_);
611 The delete method. The replace method.
613 B<credited> and B<credited_sql> are now called B<unapplied> and
614 B<unapplied_sql>. The old method names should start to give warnings.
618 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
619 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base