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 );
14 use FS::cust_credit_bill;
20 $me = '[ FS::cust_credit ]';
23 $otaker_upgrade_kludge = 0;
25 #ask FS::UID to run this stuff for us later
26 $FS::UID::callback{'FS::cust_credit'} = sub {
29 $unsuspendauto = $conf->exists('unsuspendauto');
33 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
34 'cancel_credit_type' => 'Cancellation Credit',
35 'signup_credit_type' => 'Self-Service Credit',
40 FS::cust_credit - Object methods for cust_credit records
46 $record = new FS::cust_credit \%hash;
47 $record = new FS::cust_credit { 'column' => 'value' };
49 $error = $record->insert;
51 $error = $new_record->replace($old_record);
53 $error = $record->delete;
55 $error = $record->check;
59 An FS::cust_credit object represents a credit; the equivalent of a negative
60 B<cust_bill> record (see L<FS::cust_bill>). FS::cust_credit inherits from
61 FS::Record. The following fields are currently supported:
67 Primary key (assigned automatically for new credits)
71 Customer (see L<FS::cust_main>)
79 Specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
80 L<Time::Local> and L<Date::Parse> for conversion functions.
84 Order taker (see L<FS::access_user>)
92 Reason (see L<FS::reason>)
100 Books closed flag, empty or `Y'
104 Desired pkgnum when using experimental package balances.
114 Creates a new credit. To add the credit to the database, see L<"insert">.
118 sub table { 'cust_credit'; }
119 sub cust_linked { $_[0]->cust_main_custnum; }
120 sub cust_unlinked_msg {
122 "WARNING: can't find cust_main.custnum ". $self->custnum.
123 ' (cust_credit.crednum '. $self->crednum. ')';
128 Adds this credit to the database ("Posts" the credit). If there is an error,
129 returns the error, otherwise returns false.
134 my ($self, %options) = @_;
136 local $SIG{HUP} = 'IGNORE';
137 local $SIG{INT} = 'IGNORE';
138 local $SIG{QUIT} = 'IGNORE';
139 local $SIG{TERM} = 'IGNORE';
140 local $SIG{TSTP} = 'IGNORE';
141 local $SIG{PIPE} = 'IGNORE';
143 my $oldAutoCommit = $FS::UID::AutoCommit;
144 local $FS::UID::AutoCommit = 0;
147 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
148 my $old_balance = $cust_main->balance;
150 unless ($self->reasonnum) {
151 my $result = $self->reason( $self->getfield('reason'),
152 exists($options{ 'reason_type' })
153 ? ('reason_type' => $options{ 'reason_type' })
157 $dbh->rollback if $oldAutoCommit;
158 return "failed to set reason for $me"; #: ". $dbh->errstr;
162 $self->setfield('reason', '');
164 my $error = $self->SUPER::insert;
166 $dbh->rollback if $oldAutoCommit;
167 return "error inserting $self: $error";
170 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
172 #false laziness w/ cust_credit::insert
173 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
174 my @errors = $cust_main->unsuspend;
176 # side-fx with nested transactions? upstack rolls back?
177 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
183 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
191 Unless the closed flag is set, deletes this credit and all associated
192 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
193 the void method instead to leave a record of the deleted credit.
197 # very similar to FS::cust_pay::delete
200 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
202 local $SIG{HUP} = 'IGNORE';
203 local $SIG{INT} = 'IGNORE';
204 local $SIG{QUIT} = 'IGNORE';
205 local $SIG{TERM} = 'IGNORE';
206 local $SIG{TSTP} = 'IGNORE';
207 local $SIG{PIPE} = 'IGNORE';
209 my $oldAutoCommit = $FS::UID::AutoCommit;
210 local $FS::UID::AutoCommit = 0;
213 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
214 my $error = $cust_credit_bill->delete;
216 $dbh->rollback if $oldAutoCommit;
221 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
222 my $error = $cust_credit_refund->delete;
224 $dbh->rollback if $oldAutoCommit;
229 my $error = $self->SUPER::delete(@_);
231 $dbh->rollback if $oldAutoCommit;
235 if ( $conf->config('deletecredits') ne '' ) {
237 my $cust_main = $self->cust_main;
239 my $error = send_email(
240 'from' => $conf->config('invoice_from', $self->cust_main->agentnum),
241 #invoice_from??? well as good as any
242 'to' => $conf->config('deletecredits'),
243 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
245 "This is an automatic message from your Freeside installation\n",
246 "informing you that the following credit has been deleted:\n",
248 'crednum: '. $self->crednum. "\n",
249 'custnum: '. $self->custnum.
250 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
251 'amount: $'. sprintf("%.2f", $self->amount). "\n",
252 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
253 'reason: '. $self->reason. "\n",
258 $dbh->rollback if $oldAutoCommit;
259 return "can't send credit deletion notification: $error";
264 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
270 =item replace OLD_RECORD
272 You can, but probably shouldn't modify credits...
277 #return "Can't modify credit!"
279 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
280 $self->SUPER::replace(@_);
285 Checks all fields to make sure this is a valid credit. If there is an error,
286 returns the error, otherwise returns false. Called by the insert and replace
294 $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
297 $self->ut_numbern('crednum')
298 || $self->ut_number('custnum')
299 || $self->ut_numbern('_date')
300 || $self->ut_money('amount')
301 || $self->ut_alphan('otaker')
302 || $self->ut_textn('reason')
303 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
304 || $self->ut_textn('addlinfo')
305 || $self->ut_enum('closed', [ '', 'Y' ])
306 || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
307 || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
309 return $error if $error;
311 return "amount must be > 0 " if $self->amount <= 0;
313 return "amount must be greater or equal to amount applied"
314 if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
316 return "Unknown customer"
317 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
319 $self->_date(time) unless $self->_date;
324 =item cust_credit_refund
326 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
330 sub cust_credit_refund {
332 map { $_ } #return $self->num_cust_credit_refund unless wantarray;
333 sort { $a->_date <=> $b->_date }
334 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
338 =item cust_credit_bill
340 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
345 sub cust_credit_bill {
347 map { $_ } #return $self->num_cust_credit_bill unless wantarray;
348 sort { $a->_date <=> $b->_date }
349 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
355 Returns the amount of this credit that is still unapplied/outstanding;
356 amount minus all refund applications (see L<FS::cust_credit_refund>) and
357 applications to invoices (see L<FS::cust_credit_bill>).
363 my $amount = $self->amount;
364 $amount -= $_->amount foreach ( $self->cust_credit_refund );
365 $amount -= $_->amount foreach ( $self->cust_credit_bill );
366 sprintf( "%.2f", $amount );
371 Deprecated name for the unapplied method.
377 #carp "cust_credit->credited deprecated; use ->unapplied";
378 $self->unapplied(@_);
383 Returns the customer (see L<FS::cust_main>) for this credit.
389 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
395 Returns the text of the associated reason (see L<FS::reason>) for this credit.
400 my ($self, $value, %options) = @_;
403 my $typenum = $options{'reason_type'};
405 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
406 local $FS::UID::AutoCommit = 0; # a transaction if it matters
408 if ( defined( $value ) ) {
409 my $hashref = { 'reason' => $value };
410 $hashref->{'reason_type'} = $typenum if $typenum;
411 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
412 my $extra_sql = " AND reason_type.class='R'";
414 $reason = qsearchs( { 'table' => 'reason',
415 'hashref' => $hashref,
416 'addl_from' => $addl_from,
417 'extra_sql' => $extra_sql,
420 if (!$reason && $typenum) {
421 $reason = new FS::reason( { 'reason_type' => $typenum,
425 my $error = $reason->insert;
427 warn "error inserting reason: $error\n";
432 $self->reasonnum($reason ? $reason->reasonnum : '') ;
433 warn "$me reason used in set mode with non-existant reason -- clearing"
436 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
438 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
440 ( $reason ? $reason->reason : '' ).
441 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
446 # Used by FS::Upgrade to migrate to a new database.
448 sub _upgrade_data { # class method
449 my ($class, %opts) = @_;
451 warn "$me upgrading $class\n" if $DEBUG;
453 if (defined dbdef->table($class->table)->column('reason')) {
455 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
457 my @cust_credits = qsearch({ 'table' => $class->table,
459 'extra_sql' => 'WHERE reason IS NOT NULL',
462 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
463 warn "$me Found unmigrated reasons\n" if $DEBUG;
464 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
465 my $reason_type = qsearchs( 'reason_type', $hashref );
466 unless ($reason_type) {
467 $reason_type = new FS::reason_type( $hashref );
468 my $error = $reason_type->insert();
469 die "$class had error inserting FS::reason_type into database: $error\n"
473 $hashref = { 'reason_type' => $reason_type->typenum,
476 my $noreason = qsearchs( 'reason', $hashref );
478 $hashref->{'disabled'} = 'Y';
479 $noreason = new FS::reason( $hashref );
480 my $error = $noreason->insert();
481 die "can't insert legacy reason '(none)' into database: $error\n"
485 foreach my $cust_credit ( @cust_credits ) {
486 my $reason = $cust_credit->getfield('reason');
487 warn "Contemplating reason $reason\n" if $DEBUG > 1;
488 if ($reason =~ /\S/) {
489 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
490 or die "can't insert legacy reason $reason into database\n";
492 $cust_credit->reasonnum($noreason->reasonnum);
495 $cust_credit->setfield('reason', '');
496 my $error = $cust_credit->replace;
498 warn "*** WARNING: error replacing reason in $class ".
499 $cust_credit->crednum. ": $error ***\n"
504 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
506 foreach ( keys %reasontype_map ) {
507 unless ($conf->config($_)) { # hmmmm
508 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
509 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
510 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
511 my $reason_type = qsearchs( 'reason_type', $hashref );
512 unless ($reason_type) {
513 $reason_type = new FS::reason_type( $hashref );
514 my $error = $reason_type->insert();
515 die "$class had error inserting FS::reason_type into database: $error\n"
518 $conf->set($_, $reason_type->typenum);
522 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
524 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
525 my $reason_type = qsearchs( 'reason_type', $hashref );
526 unless ($reason_type) {
527 $reason_type = new FS::reason_type( $hashref );
528 my $error = $reason_type->insert();
529 die "$class had error inserting FS::reason_type into database: $error\n"
533 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
534 foreach my $plan ( @plans ) {
535 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
536 unless ($pkg->option('reason_type', 1) ) {
537 my $plandata = $pkg->plandata.
538 "reason_type=". $reason_type->typenum. "\n";
539 $pkg->plandata($plandata);
541 $pkg->replace( undef,
542 'pkg_svc' => { map { $_->svcpart => $_->quantity }
545 'primary_svc' => $pkg->svcpart,
547 die "failed setting reason_type option: $error"
554 local($otaker_upgrade_kludge) = 1;
555 $class->_upgrade_otaker(%opts);
567 Returns an SQL fragment to retreive the unapplied amount.
572 my ($class, $start, $end) = @_;
574 my $bill_start = $start ? "AND cust_credit_bill._date <= $start" : '';
575 my $bill_end = $end ? "AND cust_credit_bill._date > $end" : '';
576 my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
577 my $refund_end = $end ? "AND cust_credit_refund._date > $end" : '';
581 ( SELECT SUM(amount) FROM cust_credit_refund
582 WHERE cust_credit.crednum = cust_credit_refund.crednum
583 $refund_start $refund_end )
587 ( SELECT SUM(amount) FROM cust_credit_bill
588 WHERE cust_credit.crednum = cust_credit_bill.crednum
589 $bill_start $bill_end )
598 Deprecated name for the unapplied_sql method.
605 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
607 #$class->unapplied_sql(@_);
615 The delete method. The replace method.
617 B<credited> and B<credited_sql> are now called B<unapplied> and
618 B<unapplied_sql>. The old method names should start to give warnings.
622 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
623 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base