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 $otaker_upgrade_kludge );
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 $otaker_upgrade_kludge = 0;
24 #ask FS::UID to run this stuff for us later
25 $FS::UID::callback{'FS::cust_credit'} = sub {
28 $unsuspendauto = $conf->exists('unsuspendauto');
32 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
33 'cancel_credit_type' => 'Cancellation Credit',
34 'signup_credit_type' => 'Self-Service Credit',
39 FS::cust_credit - Object methods for cust_credit records
45 $record = new FS::cust_credit \%hash;
46 $record = new FS::cust_credit { 'column' => 'value' };
48 $error = $record->insert;
50 $error = $new_record->replace($old_record);
52 $error = $record->delete;
54 $error = $record->check;
58 An FS::cust_credit object represents a credit; the equivalent of a negative
59 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
60 FS::Record. The following fields are currently supported:
66 Primary key (assigned automatically for new credits)
70 Customer (see L<FS::cust_main>)
78 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
79 L<Time::Local> and L<Date::Parse> for conversion functions.
83 Order taker (see L<FS::access_user>)
91 Reason (see L<FS::reason>)
99 Books closed flag, empty or `Y'
103 Desired pkgnum when using experimental package balances.
113 Creates a new credit. To add the credit to the database, see L<"insert">.
117 sub table { 'cust_credit'; }
118 sub cust_linked { $_[0]->cust_main_custnum; }
119 sub cust_unlinked_msg {
121 "WARNING: can't find cust_main.custnum ". $self->custnum.
122 ' (cust_credit.crednum '. $self->crednum. ')';
127 Adds this credit to the database ("Posts" the credit). If there is an error,
128 returns the error, otherwise returns false.
133 my ($self, %options) = @_;
135 local $SIG{HUP} = 'IGNORE';
136 local $SIG{INT} = 'IGNORE';
137 local $SIG{QUIT} = 'IGNORE';
138 local $SIG{TERM} = 'IGNORE';
139 local $SIG{TSTP} = 'IGNORE';
140 local $SIG{PIPE} = 'IGNORE';
142 my $oldAutoCommit = $FS::UID::AutoCommit;
143 local $FS::UID::AutoCommit = 0;
146 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
147 my $old_balance = $cust_main->balance;
149 unless ($self->reasonnum) {
150 my $result = $self->reason( $self->getfield('reason'),
151 exists($options{ 'reason_type' })
152 ? ('reason_type' => $options{ 'reason_type' })
156 $dbh->rollback if $oldAutoCommit;
157 return "failed to set reason for $me"; #: ". $dbh->errstr;
161 $self->setfield('reason', '');
163 my $error = $self->SUPER::insert;
165 $dbh->rollback if $oldAutoCommit;
166 return "error inserting $self: $error";
169 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
171 #false laziness w/ cust_credit::insert
172 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
173 my @errors = $cust_main->unsuspend;
175 # side-fx with nested transactions? upstack rolls back?
176 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
182 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
190 Unless the closed flag is set, deletes this credit and all associated
191 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
192 the void method instead to leave a record of the deleted credit.
196 # very similar to FS::cust_pay::delete
199 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
201 local $SIG{HUP} = 'IGNORE';
202 local $SIG{INT} = 'IGNORE';
203 local $SIG{QUIT} = 'IGNORE';
204 local $SIG{TERM} = 'IGNORE';
205 local $SIG{TSTP} = 'IGNORE';
206 local $SIG{PIPE} = 'IGNORE';
208 my $oldAutoCommit = $FS::UID::AutoCommit;
209 local $FS::UID::AutoCommit = 0;
212 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
213 my $error = $cust_credit_bill->delete;
215 $dbh->rollback if $oldAutoCommit;
220 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
221 my $error = $cust_credit_refund->delete;
223 $dbh->rollback if $oldAutoCommit;
228 my $error = $self->SUPER::delete(@_);
230 $dbh->rollback if $oldAutoCommit;
234 if ( $conf->config('deletecredits') ne '' ) {
236 my $cust_main = $self->cust_main;
238 my $error = send_email(
239 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
240 #invoice_from??? well as good as any
241 'to' => $conf->config('deletecredits'),
242 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
244 "This is an automatic message from your Freeside installation\n",
245 "informing you that the following credit has been deleted:\n",
247 'crednum: '. $self->crednum. "\n",
248 'custnum: '. $self->custnum.
249 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
250 'amount: $'. sprintf("%.2f", $self->amount). "\n",
251 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
252 'reason: '. $self->reason. "\n",
257 $dbh->rollback if $oldAutoCommit;
258 return "can't send credit deletion notification: $error";
263 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
269 =item replace OLD_RECORD
271 You can, but probably shouldn't modify credits...
276 #return "Can't modify credit!"
278 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
279 $self->SUPER::replace(@_);
284 Checks all fields to make sure this is a valid credit. If there is an error,
285 returns the error, otherwise returns false. Called by the insert and replace
293 $self->otaker(getotaker) unless ($self->otaker);
296 $self->ut_numbern('crednum')
297 || $self->ut_number('custnum')
298 || $self->ut_numbern('_date')
299 || $self->ut_money('amount')
300 || $self->ut_alphan('otaker')
301 || $self->ut_textn('reason')
302 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
303 || $self->ut_textn('addlinfo')
304 || $self->ut_enum('closed', [ '', 'Y' ])
305 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
306 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
308 return $error if $error;
310 return "amount must be > 0 " if $self->amount <= 0;
312 return "amount must be greater or equal to amount applied"
313 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
315 return "Unknown customer"
316 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
318 $self->_date(time) unless $self->_date;
323 =item cust_credit_refund
325 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
329 sub cust_credit_refund {
331 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
332 sort { $a->_date <=> $b->_date }
333 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
337 =item cust_credit_bill
339 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
344 sub cust_credit_bill {
346 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
347 sort { $a->_date <=> $b->_date }
348 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
354 Returns the amount of this credit that is still unapplied/outstanding;
355 amount minus all refund applications (see L<FS::cust_credit_refund>) and
356 applications to invoices (see L<FS::cust_credit_bill>).
362 my $amount = $self->amount;
363 $amount -= $_->amount foreach ( $self->cust_credit_refund );
364 $amount -= $_->amount foreach ( $self->cust_credit_bill );
365 sprintf( "%.2f", $amount );
370 Deprecated name for the unapplied method.
376 #carp "cust_credit->credited deprecated; use ->unapplied";
377 $self->unapplied(@_);
382 Returns the customer (see L<FS::cust_main>) for this credit.
388 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
394 Returns the text of the associated reason (see L<FS::reason>) for this credit.
399 my ($self, $value, %options) = @_;
402 my $typenum = $options{'reason_type'};
404 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
405 local $FS::UID::AutoCommit = 0; # a transaction if it matters
407 if ( defined( $value ) ) {
408 my $hashref = { 'reason' => $value };
409 $hashref->{'reason_type'} = $typenum if $typenum;
410 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
411 my $extra_sql = " AND reason_type.class='R'";
413 $reason = qsearchs( { 'table' => 'reason',
414 'hashref' => $hashref,
415 'addl_from' => $addl_from,
416 'extra_sql' => $extra_sql,
419 if (!$reason && $typenum) {
420 $reason = new FS::reason( { 'reason_type' => $typenum,
424 my $error = $reason->insert;
426 warn "error inserting reason: $error\n";
431 $self->reasonnum($reason ? $reason->reasonnum : '') ;
432 warn "$me reason used in set mode with non-existant reason -- clearing"
435 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
437 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
439 ( $reason ? $reason->reason : '' ).
440 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
445 # Used by FS::Upgrade to migrate to a new database.
447 sub _upgrade_data { # class method
448 my ($class, %opts) = @_;
450 warn "$me upgrading $class\n" if $DEBUG;
452 if (defined dbdef->table($class->table)->column('reason')) {
454 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
456 my @cust_credits = qsearch({ 'table' => $class->table,
458 'extra_sql' => 'WHERE reason IS NOT NULL',
461 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
462 warn "$me Found unmigrated reasons\n" if $DEBUG;
463 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
464 my $reason_type = qsearchs( 'reason_type', $hashref );
465 unless ($reason_type) {
466 $reason_type = new FS::reason_type( $hashref );
467 my $error = $reason_type->insert();
468 die "$class had error inserting FS::reason_type into database: $error\n"
472 $hashref = { 'reason_type' => $reason_type->typenum,
475 my $noreason = qsearchs( 'reason', $hashref );
477 $hashref->{'disabled'} = 'Y';
478 $noreason = new FS::reason( $hashref );
479 my $error = $noreason->insert();
480 die "can't insert legacy reason '(none)' into database: $error\n"
484 foreach my $cust_credit ( @cust_credits ) {
485 my $reason = $cust_credit->getfield('reason');
486 warn "Contemplating reason $reason\n" if $DEBUG > 1;
487 if ($reason =~ /\S/) {
488 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
489 or die "can't insert legacy reason $reason into database\n";
491 $cust_credit->reasonnum($noreason->reasonnum);
494 $cust_credit->setfield('reason', '');
495 my $error = $cust_credit->replace;
497 warn "*** WARNING: error replacing reason in $class ".
498 $cust_credit->crednum. ": $error ***\n"
503 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
505 foreach ( keys %reasontype_map ) {
506 unless ($conf->config($_)) { # hmmmm
507 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
508 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
509 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
510 my $reason_type = qsearchs( 'reason_type', $hashref );
511 unless ($reason_type) {
512 $reason_type = new FS::reason_type( $hashref );
513 my $error = $reason_type->insert();
514 die "$class had error inserting FS::reason_type into database: $error\n"
517 $conf->set($_, $reason_type->typenum);
521 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
523 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
524 my $reason_type = qsearchs( 'reason_type', $hashref );
525 unless ($reason_type) {
526 $reason_type = new FS::reason_type( $hashref );
527 my $error = $reason_type->insert();
528 die "$class had error inserting FS::reason_type into database: $error\n"
532 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
533 foreach my $plan ( @plans ) {
534 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
535 unless ($pkg->option('reason_type', 1) ) {
536 my $plandata = $pkg->plandata.
537 "reason_type=". $reason_type->typenum. "\n";
538 $pkg->plandata($plandata);
540 $pkg->replace( undef,
541 'pkg_svc' => { map { $_->svcpart => $_->quantity }
544 'primary_svc' => $pkg->svcpart,
546 die "failed setting reason_type option: $error"
553 local($otaker_upgrade_kludge) = 1;
554 $class->_upgrade_otaker(%opts);
566 Returns an SQL fragment to retreive the unapplied amount.
571 my ($class, $start, $end) = @_;
573 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
574 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
575 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
576 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
580 ( SELECT SUM(amount) FROM cust_credit_refund
581 WHERE cust_credit.crednum = cust_credit_refund.crednum
582 $refund_start $refund_end )
586 ( SELECT SUM(amount) FROM cust_credit_bill
587 WHERE cust_credit.crednum = cust_credit_bill.crednum
588 $bill_start $bill_end )
597 Deprecated name for the unapplied_sql method.
604 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
606 #$class->unapplied_sql(@_);
614 The delete method. The replace method.
616 B<credited> and B<credited_sql> are now called B<unapplied> and
617 B<unapplied_sql>. The old method names should start to give warnings.
621 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
622 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base