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', $self->cust_main->agentnum),
233 #invoice_from??? well as good as any
234 'to' => $conf->config('deletecredits'),
235 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
237 "This is an automatic message from your Freeside installation\n",
238 "informing you that the following credit has been deleted:\n",
240 'crednum: '. $self->crednum. "\n",
241 'custnum: '. $self->custnum.
242 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
243 'amount: $'. sprintf("%.2f", $self->amount). "\n",
244 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
245 'reason: '. $self->reason. "\n",
250 $dbh->rollback if $oldAutoCommit;
251 return "can't send credit deletion notification: $error";
256 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
262 =item replace OLD_RECORD
264 You can, but probably shouldn't modify credits...
269 #return "Can't modify credit!"
271 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
272 $self->SUPER::replace(@_);
277 Checks all fields to make sure this is a valid credit. If there is an error,
278 returns the error, otherwise returns false. Called by the insert and replace
286 $self->otaker(getotaker) unless ($self->otaker);
289 $self->ut_numbern('crednum')
290 || $self->ut_number('custnum')
291 || $self->ut_numbern('_date')
292 || $self->ut_money('amount')
293 || $self->ut_alpha('otaker')
294 || $self->ut_textn('reason')
295 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
296 || $self->ut_textn('addlinfo')
297 || $self->ut_enum('closed', [ '', 'Y' ])
299 return $error if $error;
301 return "amount must be > 0 " if $self->amount <= 0;
303 return "Unknown customer"
304 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
306 $self->_date(time) unless $self->_date;
311 =item cust_credit_refund
313 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
317 sub cust_credit_refund {
319 sort { $a->_date <=> $b->_date }
320 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
324 =item cust_credit_bill
326 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
331 sub cust_credit_bill {
333 sort { $a->_date <=> $b->_date }
334 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
340 Returns the amount of this credit that is still unapplied/outstanding;
341 amount minus all refund applications (see L<FS::cust_credit_refund>) and
342 applications to invoices (see L<FS::cust_credit_bill>).
348 my $amount = $self->amount;
349 $amount -= $_->amount foreach ( $self->cust_credit_refund );
350 $amount -= $_->amount foreach ( $self->cust_credit_bill );
351 sprintf( "%.2f", $amount );
356 Deprecated name for the unapplied method.
362 #carp "cust_credit->credited deprecated; use ->unapplied";
363 $self->unapplied(@_);
368 Returns the customer (see L<FS::cust_main>) for this credit.
374 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
380 Returns the text of the associated reason (see L<FS::reason>) for this credit.
385 my ($self, $value, %options) = @_;
388 my $typenum = $options{'reason_type'};
390 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
391 local $FS::UID::AutoCommit = 0; # a transaction if it matters
393 if ( defined( $value ) ) {
394 my $hashref = { 'reason' => $value };
395 $hashref->{'reason_type'} = $typenum if $typenum;
396 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
397 my $extra_sql = " AND reason_type.class='R'";
399 $reason = qsearchs( { 'table' => 'reason',
400 'hashref' => $hashref,
401 'addl_from' => $addl_from,
402 'extra_sql' => $extra_sql,
405 if (!$reason && $typenum) {
406 $reason = new FS::reason( { 'reason_type' => $typenum,
410 $reason->insert and $reason = undef;
413 $self->reasonnum($reason ? $reason->reasonnum : '') ;
414 warn "$me reason used in set mode with non-existant reason -- clearing"
417 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
419 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
421 ( $reason ? $reason->reason : '' ).
422 ( $self->addlinfo ? ' '.$self->addlinfo : '' );
427 # Used by FS::Upgrade to migrate to a new database.
429 sub _upgrade_data { # class method
430 my ($class, %opts) = @_;
432 warn "$me upgrading $class\n" if $DEBUG;
434 if (defined dbdef->table($class->table)->column('reason')) {
436 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
438 my @cust_credits = qsearch({ 'table' => $class->table,
440 'extra_sql' => 'WHERE reason IS NOT NULL',
443 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
444 warn "$me Found unmigrated reasons\n" if $DEBUG;
445 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
446 my $reason_type = qsearchs( 'reason_type', $hashref );
447 unless ($reason_type) {
448 $reason_type = new FS::reason_type( $hashref );
449 my $error = $reason_type->insert();
450 die "$class had error inserting FS::reason_type into database: $error\n"
454 $hashref = { 'reason_type' => $reason_type->typenum,
457 my $noreason = qsearchs( 'reason', $hashref );
459 $hashref->{'disabled'} = 'Y';
460 $noreason = new FS::reason( $hashref );
461 my $error = $noreason->insert();
462 die "can't insert legacy reason '(none)' into database: $error\n"
466 foreach my $cust_credit ( @cust_credits ) {
467 my $reason = $cust_credit->getfield('reason');
468 warn "Contemplating reason $reason\n" if $DEBUG > 1;
469 if ($reason =~ /\S/) {
470 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
471 or die "can't insert legacy reason $reason into database\n";
473 $cust_credit->reasonnum($noreason->reasonnum);
476 $cust_credit->setfield('reason', '');
477 my $error = $cust_credit->replace;
479 warn "*** WARNING: error replacing reason in $class ".
480 $cust_credit->crednum. ": $error ***\n"
485 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
487 foreach ( keys %reasontype_map ) {
488 unless ($conf->config($_)) { # hmmmm
489 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
490 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
491 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
492 my $reason_type = qsearchs( 'reason_type', $hashref );
493 unless ($reason_type) {
494 $reason_type = new FS::reason_type( $hashref );
495 my $error = $reason_type->insert();
496 die "$class had error inserting FS::reason_type into database: $error\n"
499 $conf->set($_, $reason_type->typenum);
503 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
505 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
506 my $reason_type = qsearchs( 'reason_type', $hashref );
507 unless ($reason_type) {
508 $reason_type = new FS::reason_type( $hashref );
509 my $error = $reason_type->insert();
510 die "$class had error inserting FS::reason_type into database: $error\n"
514 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
515 foreach my $plan ( @plans ) {
516 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
517 unless ($pkg->option('reason_type', 1) ) {
518 my $plandata = $pkg->plandata.
519 "reason_type=". $reason_type->typenum. "\n";
520 $pkg->plandata($plandata);
522 $pkg->replace( undef,
523 'pkg_svc' => { map { $_->svcpart => $_->quantity }
526 'primary_svc' => $pkg->svcpart,
528 die "failed setting reason_type option: $error"
547 Returns an SQL fragment to retreive the unapplied amount.
556 ( SELECT SUM(amount) FROM cust_credit_refund
557 WHERE cust_credit.crednum = cust_credit_refund.crednum )
561 ( SELECT SUM(amount) FROM cust_credit_bill
562 WHERE cust_credit.crednum = cust_credit_bill.crednum )
571 Deprecated name for the unapplied_sql method.
578 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
580 #$class->unapplied_sql(@_);
588 The delete method. The replace method.
590 B<credited> and B<credited_sql> are now called B<unapplied> and
591 B<unapplied_sql>. The old method names should start to give warnings.
595 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
596 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base