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>)
92 Books closed flag, empty or `Y'
102 Creates a new credit. To add the credit to the database, see L<"insert">.
106 sub table { 'cust_credit'; }
107 sub cust_linked { $_[0]->cust_main_custnum; }
108 sub cust_unlinked_msg {
110 "WARNING: can't find cust_main.custnum ". $self->custnum.
111 ' (cust_credit.crednum '. $self->crednum. ')';
116 Adds this credit to the database ("Posts" the credit). If there is an error,
117 returns the error, otherwise returns false.
122 my ($self, %options) = @_;
124 local $SIG{HUP} = 'IGNORE';
125 local $SIG{INT} = 'IGNORE';
126 local $SIG{QUIT} = 'IGNORE';
127 local $SIG{TERM} = 'IGNORE';
128 local $SIG{TSTP} = 'IGNORE';
129 local $SIG{PIPE} = 'IGNORE';
131 my $oldAutoCommit = $FS::UID::AutoCommit;
132 local $FS::UID::AutoCommit = 0;
135 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
136 my $old_balance = $cust_main->balance;
138 unless ($self->reasonnum) {
139 my $result = $self->reason( $self->getfield('reason'),
140 exists($options{ 'reason_type' })
141 ? ('reason_type' => $options{ 'reason_type' })
145 $dbh->rollback if $oldAutoCommit;
146 return "failed to set reason for $me: ". $dbh->errstr;
150 $self->setfield('reason', '');
152 my $error = $self->SUPER::insert;
154 $dbh->rollback if $oldAutoCommit;
155 return "error inserting $self: $error";
158 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
160 #false laziness w/ cust_credit::insert
161 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
162 my @errors = $cust_main->unsuspend;
164 # side-fx with nested transactions? upstack rolls back?
165 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
171 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
179 Unless the closed flag is set, deletes this credit and all associated
180 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
181 the void method instead to leave a record of the deleted credit.
185 # very similar to FS::cust_pay::delete
188 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
190 local $SIG{HUP} = 'IGNORE';
191 local $SIG{INT} = 'IGNORE';
192 local $SIG{QUIT} = 'IGNORE';
193 local $SIG{TERM} = 'IGNORE';
194 local $SIG{TSTP} = 'IGNORE';
195 local $SIG{PIPE} = 'IGNORE';
197 my $oldAutoCommit = $FS::UID::AutoCommit;
198 local $FS::UID::AutoCommit = 0;
201 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
202 my $error = $cust_credit_bill->delete;
204 $dbh->rollback if $oldAutoCommit;
209 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
210 my $error = $cust_credit_refund->delete;
212 $dbh->rollback if $oldAutoCommit;
217 my $error = $self->SUPER::delete(@_);
219 $dbh->rollback if $oldAutoCommit;
223 if ( $conf->config('deletecredits') ne '' ) {
225 my $cust_main = $self->cust_main;
227 my $error = send_email(
228 'from' => $conf->config('invoice_from'), #??? well as good as any
229 'to' => $conf->config('deletecredits'),
230 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
232 "This is an automatic message from your Freeside installation\n",
233 "informing you that the following credit has been deleted:\n",
235 'crednum: '. $self->crednum. "\n",
236 'custnum: '. $self->custnum.
237 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
238 'amount: $'. sprintf("%.2f", $self->amount). "\n",
239 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
240 'reason: '. $self->reason. "\n",
245 $dbh->rollback if $oldAutoCommit;
246 return "can't send credit deletion notification: $error";
251 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
257 =item replace OLD_RECORD
259 You can, but probably shouldn't modify credits...
264 #return "Can't modify credit!"
266 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
267 $self->SUPER::replace(@_);
272 Checks all fields to make sure this is a valid credit. If there is an error,
273 returns the error, otherwise returns false. Called by the insert and replace
281 $self->otaker(getotaker) unless ($self->otaker);
284 $self->ut_numbern('crednum')
285 || $self->ut_number('custnum')
286 || $self->ut_numbern('_date')
287 || $self->ut_money('amount')
288 || $self->ut_alpha('otaker')
289 || $self->ut_textn('reason')
290 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
291 || $self->ut_enum('closed', [ '', 'Y' ])
293 return $error if $error;
295 return "amount must be > 0 " if $self->amount <= 0;
297 return "Unknown customer"
298 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
300 $self->_date(time) unless $self->_date;
305 =item cust_credit_refund
307 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
311 sub cust_credit_refund {
313 sort { $a->_date <=> $b->_date }
314 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
318 =item cust_credit_bill
320 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
325 sub cust_credit_bill {
327 sort { $a->_date <=> $b->_date }
328 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
334 Returns the amount of this credit that is still unapplied/outstanding;
335 amount minus all refund applications (see L<FS::cust_credit_refund>) and
336 applications to invoices (see L<FS::cust_credit_bill>).
342 my $amount = $self->amount;
343 $amount -= $_->amount foreach ( $self->cust_credit_refund );
344 $amount -= $_->amount foreach ( $self->cust_credit_bill );
345 sprintf( "%.2f", $amount );
350 Deprecated name for the unapplied method.
356 #carp "cust_credit->credited deprecated; use ->unapplied";
357 $self->unapplied(@_);
362 Returns the customer (see L<FS::cust_main>) for this credit.
368 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
374 Returns the text of the associated reason (see L<FS::reason>) for this credit.
379 my ($self, $value, %options) = @_;
382 my $typenum = $options{'reason_type'};
384 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
385 local $FS::UID::AutoCommit = 0; # a transaction if it matters
387 if ( defined( $value ) ) {
388 my $hashref = { 'reason' => $value };
389 $hashref->{'reason_type'} = $typenum if $typenum;
390 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
391 my $extra_sql = " AND reason_type.class='R'";
393 $reason = qsearchs( { 'table' => 'reason',
394 'hashref' => $hashref,
395 'addl_from' => $addl_from,
396 'extra_sql' => $extra_sql,
399 if (!$reason && $typenum) {
400 $reason = new FS::reason( { 'reason_type' => $typenum,
404 $reason->insert and $reason = undef;
407 $self->reasonnum($reason ? $reason->reasonnum : '') ;
408 warn "$me reason used in set mode with non-existant reason -- clearing"
411 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
413 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
415 $reason ? $reason->reason : '';
420 # Used by FS::Upgrade to migrate to a new database.
422 sub _upgrade_data { # class method
423 my ($class, %opts) = @_;
425 warn "$me upgrading $class\n" if $DEBUG;
427 if (defined dbdef->table($class->table)->column('reason')) {
429 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
431 my @cust_credits = qsearch({ 'table' => $class->table,
433 'extra_sql' => 'WHERE reason IS NOT NULL',
436 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
437 warn "$me Found unmigrated reasons\n" if $DEBUG;
438 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
439 my $reason_type = qsearchs( 'reason_type', $hashref );
440 unless ($reason_type) {
441 $reason_type = new FS::reason_type( $hashref );
442 my $error = $reason_type->insert();
443 die "$class had error inserting FS::reason_type into database: $error\n"
447 $hashref = { 'reason_type' => $reason_type->typenum,
450 my $noreason = qsearchs( 'reason', $hashref );
452 $hashref->{'disabled'} = 'Y';
453 $noreason = new FS::reason( $hashref );
454 my $error = $noreason->insert();
455 die "can't insert legacy reason '(none)' into database: $error\n"
459 foreach my $cust_credit ( @cust_credits ) {
460 my $reason = $cust_credit->getfield('reason');
461 warn "Contemplating reason $reason\n" if $DEBUG > 1;
462 if ($reason =~ /\S/) {
463 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
464 or die "can't insert legacy reason $reason into database\n";
466 $cust_credit->reasonnum($noreason->reasonnum);
469 $cust_credit->setfield('reason', '');
470 my $error = $cust_credit->replace;
472 warn "*** WARNING: error replacing reason in $class ".
473 $cust_credit->crednum. ": $error ***\n"
478 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
480 foreach ( keys %reasontype_map ) {
481 unless ($conf->config($_)) { # hmmmm
482 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
483 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
484 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
485 my $reason_type = qsearchs( 'reason_type', $hashref );
486 unless ($reason_type) {
487 $reason_type = new FS::reason_type( $hashref );
488 my $error = $reason_type->insert();
489 die "$class had error inserting FS::reason_type into database: $error\n"
492 # or clause for 1.7.x
493 $conf->set($_, $reason_type->typenum) or die "failed setting config";
497 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
499 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
500 my $reason_type = qsearchs( 'reason_type', $hashref );
501 unless ($reason_type) {
502 $reason_type = new FS::reason_type( $hashref );
503 my $error = $reason_type->insert();
504 die "$class had error inserting FS::reason_type into database: $error\n"
508 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
509 foreach my $plan ( @plans ) {
510 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
511 unless ($pkg->option('reason_type', 1) ) {
512 my $plandata = $pkg->plandata.
513 "reason_type=". $reason_type->typenum. "\n";
514 $pkg->plandata($plandata);
516 $pkg->replace( undef,
517 'pkg_svc' => { map { $_->svcpart => $_->quantity }
520 'primary_svc' => $pkg->svcpart,
522 die "failed setting reason_type option: $error"
541 Returns an SQL fragment to retreive the unapplied amount.
550 ( SELECT SUM(amount) FROM cust_credit_refund
551 WHERE cust_credit.crednum = cust_credit_refund.crednum )
555 ( SELECT SUM(amount) FROM cust_credit_bill
556 WHERE cust_credit.crednum = cust_credit_bill.crednum )
565 Deprecated name for the unapplied_sql method.
572 #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
574 #$class->unapplied_sql(@_);
582 The delete method. The replace method.
584 B<credited> and B<credited_sql> are now called B<unapplied> and
585 B<unapplied_sql>. The old method names should start to give warnings.
589 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
590 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base