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;
18 @ISA = qw( FS::cust_main_Mixin FS::Record );
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 (assigned automatically, see L<FS::UID>)
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_alpha('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')
305 return $error if $error;
307 return "amount must be > 0 " if $self->amount <= 0;
309 return "Unknown customer"
310 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
312 $self->_date(time) unless $self->_date;
317 =item cust_credit_refund
319 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
323 sub cust_credit_refund {
325 sort { $a->_date <=> $b->_date }
326 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
330 =item cust_credit_bill
332 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
337 sub cust_credit_bill {
339 sort { $a->_date <=> $b->_date }
340 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
346 Returns the amount of this credit that is still unapplied/outstanding;
347 amount minus all refund applications (see L<FS::cust_credit_refund>) and
348 applications to invoices (see L<FS::cust_credit_bill>).
354 my $amount = $self->amount;
355 $amount -= $_->amount foreach ( $self->cust_credit_refund );
356 $amount -= $_->amount foreach ( $self->cust_credit_bill );
357 sprintf( "%.2f", $amount );
362 Deprecated name for the unapplied method.
368 #carp "cust_credit->credited deprecated; use ->unapplied";
369 $self->unapplied(@_);
374 Returns the customer (see L<FS::cust_main>) for this credit.
380 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
386 Returns the text of the associated reason (see L<FS::reason>) for this credit.
391 my ($self, $value, %options) = @_;
394 my $typenum = $options{'reason_type'};
396 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
397 local $FS::UID::AutoCommit = 0; # a transaction if it matters
399 if ( defined( $value ) ) {
400 my $hashref = { 'reason' => $value };
401 $hashref->{'reason_type'} = $typenum if $typenum;
402 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
403 my $extra_sql = " AND reason_type.class='R'";
405 $reason = qsearchs( { 'table' => 'reason',
406 'hashref' => $hashref,
407 'addl_from' => $addl_from,
408 'extra_sql' => $extra_sql,
411 if (!$reason && $typenum) {
412 $reason = new FS::reason( { 'reason_type' => $typenum,
416 $reason->insert and $reason = undef;
419 $self->reasonnum($reason ? $reason->reasonnum : '') ;
420 warn "$me reason used in set mode with non-existant reason -- clearing"
423 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
425 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
427 ( $reason ? $reason->reason : '' ).
428 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
433 # Used by FS::Upgrade to migrate to a new database.
435 sub _upgrade_data { # class method
436 my ($class, %opts) = @_;
438 warn "$me upgrading $class\n" if $DEBUG;
440 if (defined dbdef->table($class->table)->column('reason')) {
442 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
444 my @cust_credits = qsearch({ 'table' => $class->table,
446 'extra_sql' => 'WHERE reason IS NOT NULL',
449 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
450 warn "$me Found unmigrated reasons\n" if $DEBUG;
451 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
452 my $reason_type = qsearchs( 'reason_type', $hashref );
453 unless ($reason_type) {
454 $reason_type = new FS::reason_type( $hashref );
455 my $error = $reason_type->insert();
456 die "$class had error inserting FS::reason_type into database: $error\n"
460 $hashref = { 'reason_type' => $reason_type->typenum,
463 my $noreason = qsearchs( 'reason', $hashref );
465 $hashref->{'disabled'} = 'Y';
466 $noreason = new FS::reason( $hashref );
467 my $error = $noreason->insert();
468 die "can't insert legacy reason '(none)' into database: $error\n"
472 foreach my $cust_credit ( @cust_credits ) {
473 my $reason = $cust_credit->getfield('reason');
474 warn "Contemplating reason $reason\n" if $DEBUG > 1;
475 if ($reason =~ /\S/) {
476 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
477 or die "can't insert legacy reason $reason into database\n";
479 $cust_credit->reasonnum($noreason->reasonnum);
482 $cust_credit->setfield('reason', '');
483 my $error = $cust_credit->replace;
485 warn "*** WARNING: error replacing reason in $class ".
486 $cust_credit->crednum. ": $error ***\n"
491 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
493 foreach ( keys %reasontype_map ) {
494 unless ($conf->config($_)) { # hmmmm
495 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
496 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
497 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
498 my $reason_type = qsearchs( 'reason_type', $hashref );
499 unless ($reason_type) {
500 $reason_type = new FS::reason_type( $hashref );
501 my $error = $reason_type->insert();
502 die "$class had error inserting FS::reason_type into database: $error\n"
505 $conf->set($_, $reason_type->typenum);
509 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
511 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
512 my $reason_type = qsearchs( 'reason_type', $hashref );
513 unless ($reason_type) {
514 $reason_type = new FS::reason_type( $hashref );
515 my $error = $reason_type->insert();
516 die "$class had error inserting FS::reason_type into database: $error\n"
520 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
521 foreach my $plan ( @plans ) {
522 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
523 unless ($pkg->option('reason_type', 1) ) {
524 my $plandata = $pkg->plandata.
525 "reason_type=". $reason_type->typenum. "\n";
526 $pkg->plandata($plandata);
528 $pkg->replace( undef,
529 'pkg_svc' => { map { $_->svcpart => $_->quantity }
532 'primary_svc' => $pkg->svcpart,
534 die "failed setting reason_type option: $error"
553 Returns an SQL fragment to retreive the unapplied amount.
562 ( SELECT SUM(amount) FROM cust_credit_refund
563 WHERE cust_credit.crednum = cust_credit_refund.crednum )
567 ( SELECT SUM(amount) FROM cust_credit_bill
568 WHERE cust_credit.crednum = cust_credit_bill.crednum )
577 Deprecated name for the unapplied_sql method.
584 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
586 #$class->unapplied_sql(@_);
594 The delete method. The replace method.
596 B<credited> and B<credited_sql> are now called B<unapplied> and
597 B<unapplied_sql>. The old method names should start to give warnings.
601 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
602 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base