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;
12 use FS::cust_credit_bill;
17 @ISA = qw( FS::cust_main_Mixin FS::Record );
18 $me = '[ FS::cust_credit ]';
21 #ask FS::UID to run this stuff for us later
22 $FS::UID::callback{'FS::cust_credit'} = sub {
25 $unsuspendauto = $conf->exists('unsuspendauto');
29 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
30 'cancel_credit_type' => 'Cancellation Credit',
31 'signup_credit_type' => 'Self-Service Credit',
36 FS::cust_credit - Object methods for cust_credit records
42 $record = new FS::cust_credit \%hash;
43 $record = new FS::cust_credit { 'column' => 'value' };
45 $error = $record->insert;
47 $error = $new_record->replace($old_record);
49 $error = $record->delete;
51 $error = $record->check;
55 An FS::cust_credit object represents a credit; the equivalent of a negative
56 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
57 FS::Record. The following fields are currently supported:
63 Primary key (assigned automatically for new credits)
67 Customer (see L<FS::cust_main>)
75 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
76 L<Time::Local> and L<Date::Parse> for conversion functions.
80 Order taker (assigned automatically, see L<FS::UID>)
88 Reason (see L<FS::reason>)
96 Books closed flag, empty or `Y'
106 Creates a new credit. To add the credit to the database, see L<"insert">.
110 sub table { 'cust_credit'; }
111 sub cust_linked { $_[0]->cust_main_custnum; }
112 sub cust_unlinked_msg {
114 "WARNING: can't find cust_main.custnum ". $self->custnum.
115 ' (cust_credit.crednum '. $self->crednum. ')';
120 Adds this credit to the database ("Posts" the credit). If there is an error,
121 returns the error, otherwise returns false.
126 my ($self, %options) = @_;
128 local $SIG{HUP} = 'IGNORE';
129 local $SIG{INT} = 'IGNORE';
130 local $SIG{QUIT} = 'IGNORE';
131 local $SIG{TERM} = 'IGNORE';
132 local $SIG{TSTP} = 'IGNORE';
133 local $SIG{PIPE} = 'IGNORE';
135 my $oldAutoCommit = $FS::UID::AutoCommit;
136 local $FS::UID::AutoCommit = 0;
139 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
140 my $old_balance = $cust_main->balance;
142 unless ($self->reasonnum) {
143 my $result = $self->reason( $self->getfield('reason'),
144 exists($options{ 'reason_type' })
145 ? ('reason_type' => $options{ 'reason_type' })
149 $dbh->rollback if $oldAutoCommit;
150 return "failed to set reason for $me: ". $dbh->errstr;
154 $self->setfield('reason', '');
156 my $error = $self->SUPER::insert;
158 $dbh->rollback if $oldAutoCommit;
159 return "error inserting $self: $error";
162 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
164 #false laziness w/ cust_credit::insert
165 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
166 my @errors = $cust_main->unsuspend;
168 # side-fx with nested transactions? upstack rolls back?
169 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
175 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
183 Unless the closed flag is set, deletes this credit and all associated
184 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
185 the void method instead to leave a record of the deleted credit.
189 # very similar to FS::cust_pay::delete
192 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
194 local $SIG{HUP} = 'IGNORE';
195 local $SIG{INT} = 'IGNORE';
196 local $SIG{QUIT} = 'IGNORE';
197 local $SIG{TERM} = 'IGNORE';
198 local $SIG{TSTP} = 'IGNORE';
199 local $SIG{PIPE} = 'IGNORE';
201 my $oldAutoCommit = $FS::UID::AutoCommit;
202 local $FS::UID::AutoCommit = 0;
205 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
206 my $error = $cust_credit_bill->delete;
208 $dbh->rollback if $oldAutoCommit;
213 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
214 my $error = $cust_credit_refund->delete;
216 $dbh->rollback if $oldAutoCommit;
221 my $error = $self->SUPER::delete(@_);
223 $dbh->rollback if $oldAutoCommit;
227 if ( $conf->config('deletecredits') ne '' ) {
229 my $cust_main = $self->cust_main;
231 my $error = send_email(
232 'from' => $conf->config('invoice_from'), #??? well as good as any
233 'to' => $conf->config('deletecredits'),
234 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
236 "This is an automatic message from your Freeside installation\n",
237 "informing you that the following credit has been deleted:\n",
239 'crednum: '. $self->crednum. "\n",
240 'custnum: '. $self->custnum.
241 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
242 'amount: $'. sprintf("%.2f", $self->amount). "\n",
243 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
244 'reason: '. $self->reason. "\n",
249 $dbh->rollback if $oldAutoCommit;
250 return "can't send credit deletion notification: $error";
255 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
261 =item replace OLD_RECORD
263 You can, but probably shouldn't modify credits...
268 #return "Can't modify credit!"
270 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
271 $self->SUPER::replace(@_);
276 Checks all fields to make sure this is a valid credit. If there is an error,
277 returns the error, otherwise returns false. Called by the insert and replace
285 $self->otaker(getotaker) unless ($self->otaker);
288 $self->ut_numbern('crednum')
289 || $self->ut_number('custnum')
290 || $self->ut_numbern('_date')
291 || $self->ut_money('amount')
292 || $self->ut_alpha('otaker')
293 || $self->ut_textn('reason')
294 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
295 || $self->ut_textn('addlinfo')
296 || $self->ut_enum('closed', [ '', 'Y' ])
298 return $error if $error;
300 return "amount must be > 0 " if $self->amount <= 0;
302 return "Unknown customer"
303 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
305 $self->_date(time) unless $self->_date;
310 =item cust_credit_refund
312 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
316 sub cust_credit_refund {
318 sort { $a->_date <=> $b->_date }
319 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
323 =item cust_credit_bill
325 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
330 sub cust_credit_bill {
332 sort { $a->_date <=> $b->_date }
333 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
339 Returns the amount of this credit that is still unapplied/outstanding;
340 amount minus all refund applications (see L<FS::cust_credit_refund>) and
341 applications to invoices (see L<FS::cust_credit_bill>).
347 my $amount = $self->amount;
348 $amount -= $_->amount foreach ( $self->cust_credit_refund );
349 $amount -= $_->amount foreach ( $self->cust_credit_bill );
350 sprintf( "%.2f", $amount );
355 Deprecated name for the unapplied method.
361 #carp "cust_credit->credited deprecated; use ->unapplied";
362 $self->unapplied(@_);
367 Returns the customer (see L<FS::cust_main>) for this credit.
373 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
379 Returns the text of the associated reason (see L<FS::reason>) for this credit.
384 my ($self, $value, %options) = @_;
387 my $typenum = $options{'reason_type'};
389 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
390 local $FS::UID::AutoCommit = 0; # a transaction if it matters
392 if ( defined( $value ) ) {
393 my $hashref = { 'reason' => $value };
394 $hashref->{'reason_type'} = $typenum if $typenum;
395 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
396 my $extra_sql = " AND reason_type.class='R'";
398 $reason = qsearchs( { 'table' => 'reason',
399 'hashref' => $hashref,
400 'addl_from' => $addl_from,
401 'extra_sql' => $extra_sql,
404 if (!$reason && $typenum) {
405 $reason = new FS::reason( { 'reason_type' => $typenum,
409 $reason->insert and $reason = undef;
412 $self->reasonnum($reason ? $reason->reasonnum : '') ;
413 warn "$me reason used in set mode with non-existant reason -- clearing"
416 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
418 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
420 ( $reason ? $reason->reason : '' ).
421 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
426 # Used by FS::Upgrade to migrate to a new database.
428 sub _upgrade_data { # class method
429 my ($class, %opts) = @_;
431 warn "$me upgrading $class\n" if $DEBUG;
433 if (defined dbdef->table($class->table)->column('reason')) {
435 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
437 my @cust_credits = qsearch({ 'table' => $class->table,
439 'extra_sql' => 'WHERE reason IS NOT NULL',
442 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
443 warn "$me Found unmigrated reasons\n" if $DEBUG;
444 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
445 my $reason_type = qsearchs( 'reason_type', $hashref );
446 unless ($reason_type) {
447 $reason_type = new FS::reason_type( $hashref );
448 my $error = $reason_type->insert();
449 die "$class had error inserting FS::reason_type into database: $error\n"
453 $hashref = { 'reason_type' => $reason_type->typenum,
456 my $noreason = qsearchs( 'reason', $hashref );
458 $hashref->{'disabled'} = 'Y';
459 $noreason = new FS::reason( $hashref );
460 my $error = $noreason->insert();
461 die "can't insert legacy reason '(none)' into database: $error\n"
465 foreach my $cust_credit ( @cust_credits ) {
466 my $reason = $cust_credit->getfield('reason');
467 warn "Contemplating reason $reason\n" if $DEBUG > 1;
468 if ($reason =~ /\S/) {
469 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
470 or die "can't insert legacy reason $reason into database\n";
472 $cust_credit->reasonnum($noreason->reasonnum);
475 $cust_credit->setfield('reason', '');
476 my $error = $cust_credit->replace;
478 warn "*** WARNING: error replacing reason in $class ".
479 $cust_credit->crednum. ": $error ***\n"
484 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
486 foreach ( keys %reasontype_map ) {
487 unless ($conf->config($_)) { # hmmmm
488 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
489 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
490 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
491 my $reason_type = qsearchs( 'reason_type', $hashref );
492 unless ($reason_type) {
493 $reason_type = new FS::reason_type( $hashref );
494 my $error = $reason_type->insert();
495 die "$class had error inserting FS::reason_type into database: $error\n"
498 $conf->set($_, $reason_type->typenum);
502 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
504 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
505 my $reason_type = qsearchs( 'reason_type', $hashref );
506 unless ($reason_type) {
507 $reason_type = new FS::reason_type( $hashref );
508 my $error = $reason_type->insert();
509 die "$class had error inserting FS::reason_type into database: $error\n"
513 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
514 foreach my $plan ( @plans ) {
515 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
516 unless ($pkg->option('reason_type', 1) ) {
517 my $plandata = $pkg->plandata.
518 "reason_type=". $reason_type->typenum. "\n";
519 $pkg->plandata($plandata);
521 $pkg->replace( undef,
522 'pkg_svc' => { map { $_->svcpart => $_->quantity }
525 'primary_svc' => $pkg->svcpart,
527 die "failed setting reason_type option: $error"
546 Returns an SQL fragment to retreive the unapplied amount.
555 ( SELECT SUM(amount) FROM cust_credit_refund
556 WHERE cust_credit.crednum = cust_credit_refund.crednum )
560 ( SELECT SUM(amount) FROM cust_credit_bill
561 WHERE cust_credit.crednum = cust_credit_bill.crednum )
570 Deprecated name for the unapplied_sql method.
577 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
579 #$class->unapplied_sql(@_);
587 The delete method. The replace method.
589 B<credited> and B<credited_sql> are now called B<unapplied> and
590 B<unapplied_sql>. The old method names should start to give warnings.
594 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
595 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base