1 package FS::cust_credit;
4 use vars qw( @ISA $conf $unsuspendauto $me $DEBUG );
6 use FS::UID qw( dbh getotaker );
7 use FS::Misc qw(send_email);
8 use FS::Record qw( qsearch qsearchs dbdef );
9 use FS::cust_main_Mixin;
13 use FS::cust_credit_bill;
19 @ISA = qw( FS::cust_main_Mixin FS::Record );
20 $me = '[ FS::cust_credit ]';
23 #ask FS::UID to run this stuff for us later
24 $FS::UID::callback{'FS::cust_credit'} = sub {
27 $unsuspendauto = $conf->exists('unsuspendauto');
31 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
32 'cancel_credit_type' => 'Cancellation Credit',
33 'signup_credit_type' => 'Self-Service Credit',
38 FS::cust_credit - Object methods for cust_credit records
44 $record = new FS::cust_credit \%hash;
45 $record = new FS::cust_credit { 'column' => 'value' };
47 $error = $record->insert;
49 $error = $new_record->replace($old_record);
51 $error = $record->delete;
53 $error = $record->check;
57 An FS::cust_credit object represents a credit; the equivalent of a negative
58 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
59 FS::Record. The following fields are currently supported:
65 Primary key (assigned automatically for new credits)
69 Customer (see L<FS::cust_main>)
77 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
78 L<Time::Local> and L<Date::Parse> for conversion functions.
82 Order taker (assigned automatically, see L<FS::UID>)
90 Reason (see L<FS::reason>)
98 Books closed flag, empty or `Y'
102 Desired pkgnum when using experimental package balances.
112 Creates a new credit. To add the credit to the database, see L<"insert">.
116 sub table { 'cust_credit'; }
117 sub cust_linked { $_[0]->cust_main_custnum; }
118 sub cust_unlinked_msg {
120 "WARNING: can't find cust_main.custnum ". $self->custnum.
121 ' (cust_credit.crednum '. $self->crednum. ')';
126 Adds this credit to the database ("Posts" the credit). If there is an error,
127 returns the error, otherwise returns false.
132 my ($self, %options) = @_;
134 local $SIG{HUP} = 'IGNORE';
135 local $SIG{INT} = 'IGNORE';
136 local $SIG{QUIT} = 'IGNORE';
137 local $SIG{TERM} = 'IGNORE';
138 local $SIG{TSTP} = 'IGNORE';
139 local $SIG{PIPE} = 'IGNORE';
141 my $oldAutoCommit = $FS::UID::AutoCommit;
142 local $FS::UID::AutoCommit = 0;
145 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
146 my $old_balance = $cust_main->balance;
148 unless ($self->reasonnum) {
149 my $result = $self->reason( $self->getfield('reason'),
150 exists($options{ 'reason_type' })
151 ? ('reason_type' => $options{ 'reason_type' })
155 $dbh->rollback if $oldAutoCommit;
156 return "failed to set reason for $me: ". $dbh->errstr;
160 $self->setfield('reason', '');
162 my $error = $self->SUPER::insert;
164 $dbh->rollback if $oldAutoCommit;
165 return "error inserting $self: $error";
168 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
170 #false laziness w/ cust_credit::insert
171 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
172 my @errors = $cust_main->unsuspend;
174 # side-fx with nested transactions? upstack rolls back?
175 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
181 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
189 Unless the closed flag is set, deletes this credit and all associated
190 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
191 the void method instead to leave a record of the deleted credit.
195 # very similar to FS::cust_pay::delete
198 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
200 local $SIG{HUP} = 'IGNORE';
201 local $SIG{INT} = 'IGNORE';
202 local $SIG{QUIT} = 'IGNORE';
203 local $SIG{TERM} = 'IGNORE';
204 local $SIG{TSTP} = 'IGNORE';
205 local $SIG{PIPE} = 'IGNORE';
207 my $oldAutoCommit = $FS::UID::AutoCommit;
208 local $FS::UID::AutoCommit = 0;
211 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
212 my $error = $cust_credit_bill->delete;
214 $dbh->rollback if $oldAutoCommit;
219 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
220 my $error = $cust_credit_refund->delete;
222 $dbh->rollback if $oldAutoCommit;
227 my $error = $self->SUPER::delete(@_);
229 $dbh->rollback if $oldAutoCommit;
233 if ( $conf->config('deletecredits') ne '' ) {
235 my $cust_main = $self->cust_main;
237 my $error = send_email(
238 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
239 #invoice_from??? well as good as any
240 'to' => $conf->config('deletecredits'),
241 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
243 "This is an automatic message from your Freeside installation\n",
244 "informing you that the following credit has been deleted:\n",
246 'crednum: '. $self->crednum. "\n",
247 'custnum: '. $self->custnum.
248 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
249 'amount: $'. sprintf("%.2f", $self->amount). "\n",
250 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
251 'reason: '. $self->reason. "\n",
256 $dbh->rollback if $oldAutoCommit;
257 return "can't send credit deletion notification: $error";
262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
268 =item replace OLD_RECORD
270 You can, but probably shouldn't modify credits...
275 #return "Can't modify credit!"
277 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
278 $self->SUPER::replace(@_);
283 Checks all fields to make sure this is a valid credit. If there is an error,
284 returns the error, otherwise returns false. Called by the insert and replace
292 $self->otaker(getotaker) unless ($self->otaker);
295 $self->ut_numbern('crednum')
296 || $self->ut_number('custnum')
297 || $self->ut_numbern('_date')
298 || $self->ut_money('amount')
299 || $self->ut_alpha('otaker')
300 || $self->ut_textn('reason')
301 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
302 || $self->ut_textn('addlinfo')
303 || $self->ut_enum('closed', [ '', 'Y' ])
304 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
305 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
307 return $error if $error;
309 return "amount must be > 0 " if $self->amount <= 0;
311 return "Unknown customer"
312 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
314 $self->_date(time) unless $self->_date;
319 =item cust_credit_refund
321 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
325 sub cust_credit_refund {
327 sort { $a->_date <=> $b->_date }
328 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
332 =item cust_credit_bill
334 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
339 sub cust_credit_bill {
341 sort { $a->_date <=> $b->_date }
342 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
348 Returns the amount of this credit that is still unapplied/outstanding;
349 amount minus all refund applications (see L<FS::cust_credit_refund>) and
350 applications to invoices (see L<FS::cust_credit_bill>).
356 my $amount = $self->amount;
357 $amount -= $_->amount foreach ( $self->cust_credit_refund );
358 $amount -= $_->amount foreach ( $self->cust_credit_bill );
359 sprintf( "%.2f", $amount );
364 Deprecated name for the unapplied method.
370 #carp "cust_credit->credited deprecated; use ->unapplied";
371 $self->unapplied(@_);
376 Returns the customer (see L<FS::cust_main>) for this credit.
382 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
388 Returns the text of the associated reason (see L<FS::reason>) for this credit.
393 my ($self, $value, %options) = @_;
396 my $typenum = $options{'reason_type'};
398 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
399 local $FS::UID::AutoCommit = 0; # a transaction if it matters
401 if ( defined( $value ) ) {
402 my $hashref = { 'reason' => $value };
403 $hashref->{'reason_type'} = $typenum if $typenum;
404 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
405 my $extra_sql = " AND reason_type.class='R'";
407 $reason = qsearchs( { 'table' => 'reason',
408 'hashref' => $hashref,
409 'addl_from' => $addl_from,
410 'extra_sql' => $extra_sql,
413 if (!$reason && $typenum) {
414 $reason = new FS::reason( { 'reason_type' => $typenum,
418 $reason->insert and $reason = undef;
421 $self->reasonnum($reason ? $reason->reasonnum : '') ;
422 warn "$me reason used in set mode with non-existant reason -- clearing"
425 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
427 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
429 ( $reason ? $reason->reason : '' ).
430 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
435 # Used by FS::Upgrade to migrate to a new database.
437 sub _upgrade_data { # class method
438 my ($class, %opts) = @_;
440 warn "$me upgrading $class\n" if $DEBUG;
442 if (defined dbdef->table($class->table)->column('reason')) {
444 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
446 my @cust_credits = qsearch({ 'table' => $class->table,
448 'extra_sql' => 'WHERE reason IS NOT NULL',
451 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
452 warn "$me Found unmigrated reasons\n" if $DEBUG;
453 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
454 my $reason_type = qsearchs( 'reason_type', $hashref );
455 unless ($reason_type) {
456 $reason_type = new FS::reason_type( $hashref );
457 my $error = $reason_type->insert();
458 die "$class had error inserting FS::reason_type into database: $error\n"
462 $hashref = { 'reason_type' => $reason_type->typenum,
465 my $noreason = qsearchs( 'reason', $hashref );
467 $hashref->{'disabled'} = 'Y';
468 $noreason = new FS::reason( $hashref );
469 my $error = $noreason->insert();
470 die "can't insert legacy reason '(none)' into database: $error\n"
474 foreach my $cust_credit ( @cust_credits ) {
475 my $reason = $cust_credit->getfield('reason');
476 warn "Contemplating reason $reason\n" if $DEBUG > 1;
477 if ($reason =~ /\S/) {
478 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
479 or die "can't insert legacy reason $reason into database\n";
481 $cust_credit->reasonnum($noreason->reasonnum);
484 $cust_credit->setfield('reason', '');
485 my $error = $cust_credit->replace;
487 warn "*** WARNING: error replacing reason in $class ".
488 $cust_credit->crednum. ": $error ***\n"
493 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
495 foreach ( keys %reasontype_map ) {
496 unless ($conf->config($_)) { # hmmmm
497 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
498 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
499 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
500 my $reason_type = qsearchs( 'reason_type', $hashref );
501 unless ($reason_type) {
502 $reason_type = new FS::reason_type( $hashref );
503 my $error = $reason_type->insert();
504 die "$class had error inserting FS::reason_type into database: $error\n"
507 $conf->set($_, $reason_type->typenum);
511 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
513 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
514 my $reason_type = qsearchs( 'reason_type', $hashref );
515 unless ($reason_type) {
516 $reason_type = new FS::reason_type( $hashref );
517 my $error = $reason_type->insert();
518 die "$class had error inserting FS::reason_type into database: $error\n"
522 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
523 foreach my $plan ( @plans ) {
524 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
525 unless ($pkg->option('reason_type', 1) ) {
526 my $plandata = $pkg->plandata.
527 "reason_type=". $reason_type->typenum. "\n";
528 $pkg->plandata($plandata);
530 $pkg->replace( undef,
531 'pkg_svc' => { map { $_->svcpart => $_->quantity }
534 'primary_svc' => $pkg->svcpart,
536 die "failed setting reason_type option: $error"
555 Returns an SQL fragment to retreive the unapplied amount.
560 my ($class, $start, $end) = @_;
562 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
563 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
564 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
565 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
569 ( SELECT SUM(amount) FROM cust_credit_refund
570 WHERE cust_credit.crednum = cust_credit_refund.crednum
571 $refund_start $refund_end )
575 ( SELECT SUM(amount) FROM cust_credit_bill
576 WHERE cust_credit.crednum = cust_credit_bill.crednum
577 $bill_start $bill_end )
586 Deprecated name for the unapplied_sql method.
593 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
595 #$class->unapplied_sql(@_);
603 The delete method. The replace method.
605 B<credited> and B<credited_sql> are now called B<unapplied> and
606 B<unapplied_sql>. The old method names should start to give warnings.
610 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
611 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base