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:
61 =item crednum - primary key (assigned automatically for new credits)
63 =item custnum - customer (see L<FS::cust_main>)
65 =item amount - amount of the credit
67 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
68 L<Time::Local> and L<Date::Parse> for conversion functions.
70 =item otaker - order taker (assigned automatically, see L<FS::UID>)
72 =item reason - text ( deprecated )
74 =item reasonum - int reason (see L<FS::reason>)
76 =item closed - books closed flag, empty or `Y'
86 Creates a new credit. To add the credit to the database, see L<"insert">.
90 sub table { 'cust_credit'; }
91 sub cust_linked { $_[0]->cust_main_custnum; }
92 sub cust_unlinked_msg {
94 "WARNING: can't find cust_main.custnum ". $self->custnum.
95 ' (cust_credit.crednum '. $self->crednum. ')';
100 Adds this credit to the database ("Posts" the credit). If there is an error,
101 returns the error, otherwise returns false.
106 my ($self, %options) = @_;
108 local $SIG{HUP} = 'IGNORE';
109 local $SIG{INT} = 'IGNORE';
110 local $SIG{QUIT} = 'IGNORE';
111 local $SIG{TERM} = 'IGNORE';
112 local $SIG{TSTP} = 'IGNORE';
113 local $SIG{PIPE} = 'IGNORE';
115 my $oldAutoCommit = $FS::UID::AutoCommit;
116 local $FS::UID::AutoCommit = 0;
119 my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
120 my $old_balance = $cust_main->balance;
122 unless ($self->reasonnum) {
123 my $result = $self->reason( $self->getfield('reason'),
124 exists($options{ 'reason_type' })
125 ? ('reason_type' => $options{ 'reason_type' })
129 $dbh->rollback if $oldAutoCommit;
130 return "failed to set reason for $me: ". $dbh->errstr;
134 $self->setfield('reason', '');
136 my $error = $self->SUPER::insert;
138 $dbh->rollback if $oldAutoCommit;
139 return "error inserting $self: $error";
142 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
144 #false laziness w/ cust_credit::insert
145 if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
146 my @errors = $cust_main->unsuspend;
148 # side-fx with nested transactions? upstack rolls back?
149 warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
155 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
163 Unless the closed flag is set, deletes this credit and all associated
164 applications (see L<FS::cust_credit_bill>). In most cases, you want to use
165 the void method instead to leave a record of the deleted credit.
169 # very similar to FS::cust_pay::delete
172 return "Can't delete closed credit" if $self->closed =~ /^Y/i;
174 local $SIG{HUP} = 'IGNORE';
175 local $SIG{INT} = 'IGNORE';
176 local $SIG{QUIT} = 'IGNORE';
177 local $SIG{TERM} = 'IGNORE';
178 local $SIG{TSTP} = 'IGNORE';
179 local $SIG{PIPE} = 'IGNORE';
181 my $oldAutoCommit = $FS::UID::AutoCommit;
182 local $FS::UID::AutoCommit = 0;
185 foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
186 my $error = $cust_credit_bill->delete;
188 $dbh->rollback if $oldAutoCommit;
193 foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
194 my $error = $cust_credit_refund->delete;
196 $dbh->rollback if $oldAutoCommit;
201 my $error = $self->SUPER::delete(@_);
203 $dbh->rollback if $oldAutoCommit;
207 if ( $conf->config('deletecredits') ne '' ) {
209 my $cust_main = $self->cust_main;
211 my $error = send_email(
212 'from' => $conf->config('invoice_from'), #??? well as good as any
213 'to' => $conf->config('deletecredits'),
214 'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
216 "This is an automatic message from your Freeside installation\n",
217 "informing you that the following credit has been deleted:\n",
219 'crednum: '. $self->crednum. "\n",
220 'custnum: '. $self->custnum.
221 " (". $cust_main->last. ", ". $cust_main->first. ")\n",
222 'amount: $'. sprintf("%.2f", $self->amount). "\n",
223 'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
224 'reason: '. $self->reason. "\n",
229 $dbh->rollback if $oldAutoCommit;
230 return "can't send credit deletion notification: $error";
235 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
241 =item replace OLD_RECORD
243 You can, but probably shouldn't modify credits...
248 #return "Can't modify credit!"
250 return "Can't modify closed credit" if $self->closed =~ /^Y/i;
251 $self->SUPER::replace(@_);
256 Checks all fields to make sure this is a valid credit. If there is an error,
257 returns the error, otherwise returns false. Called by the insert and replace
266 $self->ut_numbern('crednum')
267 || $self->ut_number('custnum')
268 || $self->ut_numbern('_date')
269 || $self->ut_money('amount')
270 || $self->ut_textn('reason')
271 || $self->ut_foreign_key('reasonnum', 'reason', 'reasonnum')
272 || $self->ut_enum('closed', [ '', 'Y' ])
274 return $error if $error;
276 return "amount must be > 0 " if $self->amount <= 0;
278 return "Unknown customer"
279 unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
281 $self->_date(time) unless $self->_date;
283 $self->otaker(getotaker) unless ($self->otaker);
290 Depreciated. See the cust_credit_refund method.
292 #Returns all refunds (see L<FS::cust_refund>) for this credit.
298 croak "FS::cust_credit->cust_pay depreciated; see ".
299 "FS::cust_credit->cust_credit_refund";
301 #sort { $a->_date <=> $b->_date }
302 # qsearch( 'cust_refund', { 'crednum' => $self->crednum } )
306 =item cust_credit_refund
308 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
312 sub cust_credit_refund {
314 sort { $a->_date <=> $b->_date }
315 qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
319 =item cust_credit_bill
321 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
326 sub cust_credit_bill {
328 sort { $a->_date <=> $b->_date }
329 qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
335 Returns the amount of this credit that is still outstanding; which is
336 amount minus all refund applications (see L<FS::cust_credit_refund>) and
337 applications to invoices (see L<FS::cust_credit_bill>).
343 my $amount = $self->amount;
344 $amount -= $_->amount foreach ( $self->cust_credit_refund );
345 $amount -= $_->amount foreach ( $self->cust_credit_bill );
346 sprintf( "%.2f", $amount );
351 Returns the customer (see L<FS::cust_main>) for this credit.
357 qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
363 Returns the text of the associated reason (see L<FS::reason>) for this credit.
368 my ($self, $value, %options) = @_;
371 my $typenum = $options{'reason_type'};
373 my $oldAutoCommit = $FS::UID::AutoCommit; # this should already be in
374 local $FS::UID::AutoCommit = 0; # a transaction if it matters
376 if ( defined( $value ) ) {
377 my $hashref = { 'reason' => $value };
378 $hashref->{'reason_type'} = $typenum if $typenum;
379 my $addl_from = "LEFT JOIN reason_type ON ( reason_type = typenum ) ";
380 my $extra_sql = " AND reason_type.class='R'";
382 $reason = qsearchs( { 'table' => 'reason',
383 'hashref' => $hashref,
384 'addl_from' => $addl_from,
385 'extra_sql' => $extra_sql,
388 if (!$reason && $typenum) {
389 $reason = new FS::reason( { 'reason_type' => $typenum,
393 $reason->insert and $reason = undef;
396 $self->reasonnum($reason ? $reason->reasonnum : '') ;
397 warn "$me reason used in set mode with non-existant reason -- clearing"
400 $reason = qsearchs( 'reason', { 'reasonnum' => $self->reasonnum } );
402 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
404 $reason ? $reason->reason : '';
409 # Used by FS::Upgrade to migrate to a new database.
413 sub _upgrade_data { # class method
414 my ($class, %opts) = @_;
416 warn "$me upgrading $class\n" if $DEBUG;
418 if (defined dbdef->table($class->table)->column('reason')) {
420 warn "$me Checking for unmigrated reasons\n" if $DEBUG;
422 my @cust_credits = qsearch({ 'table' => $class->table,
424 'extrasql' => 'WHERE reason IS NOT NULL',
427 if (scalar(grep { $_->getfield('reason') =~ /\S/ } @cust_credits)) {
428 warn "$me Found unmigrated reasons\n" if $DEBUG;
429 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
430 my $reason_type = qsearchs( 'reason_type', $hashref );
431 unless ($reason_type) {
432 $reason_type = new FS::reason_type( $hashref );
433 my $error = $reason_type->insert();
434 die "$class had error inserting FS::reason_type into database: $error\n"
438 $hashref = { 'reason_type' => $reason_type->typenum,
441 my $noreason = qsearchs( 'reason', $hashref );
443 $hashref->{'disabled'} = 'Y';
444 $noreason = new FS::reason( $hashref );
445 my $error = $noreason->insert();
446 die "can't insert legacy reason '(none)' into database: $error\n"
450 foreach my $cust_credit ( @cust_credits ) {
451 my $reason = $cust_credit->getfield('reason');
452 warn "Contemplating reason $reason\n" if $DEBUG > 1;
453 if ($reason =~ /\S/) {
454 $cust_credit->reason($reason, 'reason_type' => $reason_type->typenum)
455 or die "can't insert legacy reason $reason into database\n";
457 $cust_credit->reasonnum($noreason->reasonnum);
460 $cust_credit->setfield('reason', '');
461 my $error = $cust_credit->replace;
463 warn "*** WARNING: error replacing reason in $class ".
464 $cust_credit->crednum. ": $error ***\n"
469 warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
471 foreach ( keys %reasontype_map ) {
472 unless ($conf->config($_)) { # hmmmm
473 # warn "$me Found $_ reason type lacking\n" if $DEBUG;
474 # my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
475 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
476 my $reason_type = qsearchs( 'reason_type', $hashref );
477 unless ($reason_type) {
478 $reason_type = new FS::reason_type( $hashref );
479 my $error = $reason_type->insert();
480 die "$class had error inserting FS::reason_type into database: $error\n"
483 # or clause for 1.7.x
484 $conf->set($_, $reason_type->typenum) or die "failed setting config";
488 warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
490 my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
491 my $reason_type = qsearchs( 'reason_type', $hashref );
492 unless ($reason_type) {
493 $reason_type = new FS::reason_type( $hashref );
494 my $error = $reason_type->insert();
495 die "$class had error inserting FS::reason_type into database: $error\n"
499 my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
500 foreach my $plan ( @plans ) {
501 foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
502 unless ($pkg->option('reason_type', 1) ) {
503 my $plandata = $pkg->plandata.
504 "reason_type=". $reason_type->typenum. "\n";
505 $pkg->plandata($plandata);
507 $pkg->replace( undef,
508 'pkg_svc' => { map { $_->svcpart => $_->quantity }
511 'primary_svc' => $pkg->svcpart,
513 die "failed setting reason_type option: $error"
532 Returns an SQL fragment to retreive the unapplied amount.
541 ( SELECT SUM(amount) FROM cust_credit_refund
542 WHERE cust_credit.crednum = cust_credit_refund.crednum )
546 ( SELECT SUM(amount) FROM cust_credit_bill
547 WHERE cust_credit.crednum = cust_credit_bill.crednum )
558 The delete method. The replace method.
560 B<credited> and B<credited_sql> should probably be called B<unapplied> and
565 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
566 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base