Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / FS / FS / cust_credit.pm
1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
3              FS::Record );
4
5 use strict;
6 use vars qw( $conf $unsuspendauto $me $DEBUG
7              $otaker_upgrade_kludge $ignore_empty_reasonnum
8            );
9 use List::Util qw( min );
10 use Date::Format;
11 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs dbdef );
13 use FS::CurrentUser;
14 use FS::cust_pkg;
15 use FS::cust_refund;
16 use FS::cust_credit_bill;
17 use FS::part_pkg;
18 use FS::reason_type;
19 use FS::reason;
20 use FS::cust_event;
21 use FS::agent;
22 use FS::sales;
23 use FS::cust_credit_void;
24 use FS::cust_bill_pkg;
25 use FS::upgrade_journal;
26
27 $me = '[ FS::cust_credit ]';
28 $DEBUG = 0;
29
30 $otaker_upgrade_kludge = 0;
31 $ignore_empty_reasonnum = 0;
32
33 #ask FS::UID to run this stuff for us later
34 $FS::UID::callback{'FS::cust_credit'} = sub { 
35
36   $conf = new FS::Conf;
37   $unsuspendauto = $conf->exists('unsuspendauto');
38
39 };
40
41 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
42                         'cancel_credit_type'   => 'Cancellation Credit',
43                         'signup_credit_type'   => 'Self-Service Credit',
44                       );
45
46 =head1 NAME
47
48 FS::cust_credit - Object methods for cust_credit records
49
50 =head1 SYNOPSIS
51
52   use FS::cust_credit;
53
54   $record = new FS::cust_credit \%hash;
55   $record = new FS::cust_credit { 'column' => 'value' };
56
57   $error = $record->insert;
58
59   $error = $new_record->replace($old_record);
60
61   $error = $record->delete;
62
63   $error = $record->check;
64
65 =head1 DESCRIPTION
66
67 An FS::cust_credit object represents a credit; the equivalent of a negative
68 B<cust_bill> record (see L<FS::cust_bill>).  FS::cust_credit inherits from
69 FS::Record.  The following fields are currently supported:
70
71 =over 4
72
73 =item crednum
74
75 Primary key (assigned automatically for new credits)
76
77 =item custnum
78
79 Customer (see L<FS::cust_main>)
80
81 =item amount
82
83 Amount of the credit
84
85 =item _date
86
87 Specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
89
90 =item usernum
91
92 Order taker (see L<FS::access_user>)
93
94 =item reason
95
96 Text ( deprecated )
97
98 =item reasonnum
99
100 Reason (see L<FS::reason>)
101
102 =item addlinfo
103
104 Text
105
106 =item closed
107
108 Books closed flag, empty or `Y'
109
110 =item pkgnum
111
112 Desired pkgnum when using experimental package balances.
113
114 =back
115
116 =head1 METHODS
117
118 =over 4
119
120 =item new HASHREF
121
122 Creates a new credit.  To add the credit to the database, see L<"insert">.
123
124 =cut
125
126 sub table { 'cust_credit'; }
127 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
128 sub cust_unlinked_msg {
129   my $self = shift;
130   "WARNING: can't find cust_main.custnum ". $self->custnum.
131   ' (cust_credit.crednum '. $self->crednum. ')';
132 }
133
134 =item insert [ OPTION => VALUE ... ]
135
136 Adds this credit to the database ("Posts" the credit).  If there is an error,
137 returns the error, otherwise returns false.
138
139 Ooptions are passed as a list of keys and values.  Available options:
140
141 =over 4
142
143 =item reason_type
144
145 L<FS::reason_type|Reason> type for newly-inserted reason
146
147 =item cust_credit_source_bill_pkg
148
149 An arrayref of
150 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bilL_pkg> objects.
151 They will have their crednum set and will be inserted along with this credit.
152
153 =back
154
155 =cut
156
157 sub insert {
158   my ($self, %options) = @_;
159
160   local $SIG{HUP} = 'IGNORE';
161   local $SIG{INT} = 'IGNORE';
162   local $SIG{QUIT} = 'IGNORE';
163   local $SIG{TERM} = 'IGNORE';
164   local $SIG{TSTP} = 'IGNORE';
165   local $SIG{PIPE} = 'IGNORE';
166
167   my $oldAutoCommit = $FS::UID::AutoCommit;
168   local $FS::UID::AutoCommit = 0;
169   my $dbh = dbh;
170
171   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
172   my $old_balance = $cust_main->balance;
173
174   if (!$self->reasonnum) {
175     my $reason_text = $self->get('reason')
176       or return "reason text or existing reason required";
177     my $reason_type = $options{'reason_type'}
178       or return "reason type required";
179
180     local $@;
181     my $reason = FS::reason->new_or_existing(
182       reason => $reason_text,
183       type   => $reason_type,
184       class  => 'R',
185     );
186     if ($@) {
187       $dbh->rollback if $oldAutoCommit;
188       return "failed to set credit reason: $@";
189     }
190     $self->set('reasonnum', $reason->reasonnum);
191   }
192
193   $self->setfield('reason', '');
194
195   my $error = $self->SUPER::insert;
196   if ( $error ) {
197     $dbh->rollback if $oldAutoCommit;
198     return "error inserting $self: $error";
199   }
200
201   if ( $options{'cust_credit_source_bill_pkg'} ) {
202     foreach my $ccsbr ( @{ $options{'cust_credit_source_bill_pkg'} } ) {
203       $ccsbr->crednum( $self->crednum );
204       $error = $ccsbr->insert;
205       if ( $error ) {
206         $dbh->rollback if $oldAutoCommit;
207         return "error inserting $ccsbr: $error";
208       }
209     }
210   }
211
212   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
213
214   #false laziness w/ cust_pay::insert
215   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
216     my @errors = $cust_main->unsuspend;
217     #return 
218     # side-fx with nested transactions?  upstack rolls back?
219     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
220          join(' / ', @errors)
221       if @errors;
222   }
223   #eslaf
224
225   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
226
227   '';
228
229 }
230
231 =item delete
232
233 Unless the closed flag is set, deletes this credit and all associated
234 applications (see L<FS::cust_credit_bill>).  In most cases, you want to use
235 the void method instead to leave a record of the deleted credit.
236
237 =cut
238
239 # very similar to FS::cust_pay::delete
240 sub delete {
241   my $self = shift;
242   my %opt = @_;
243
244   return "Can't delete closed credit" if $self->closed =~ /^Y/i;
245
246   local $SIG{HUP} = 'IGNORE';
247   local $SIG{INT} = 'IGNORE';
248   local $SIG{QUIT} = 'IGNORE';
249   local $SIG{TERM} = 'IGNORE';
250   local $SIG{TSTP} = 'IGNORE';
251   local $SIG{PIPE} = 'IGNORE';
252
253   my $oldAutoCommit = $FS::UID::AutoCommit;
254   local $FS::UID::AutoCommit = 0;
255   my $dbh = dbh;
256
257   foreach my $cust_credit_bill ( $self->cust_credit_bill ) {
258     my $error = $cust_credit_bill->delete;
259     if ( $error ) {
260       $dbh->rollback if $oldAutoCommit;
261       return $error;
262     }
263   }
264
265   foreach my $cust_credit_refund ( $self->cust_credit_refund ) {
266     my $error = $cust_credit_refund->delete;
267     if ( $error ) {
268       $dbh->rollback if $oldAutoCommit;
269       return $error;
270     }
271   }
272
273   my $error = $self->SUPER::delete(@_);
274   if ( $error ) {
275     $dbh->rollback if $oldAutoCommit;
276     return $error;
277   }
278
279   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280
281   '';
282
283 }
284
285 =item replace [ OLD_RECORD ]
286
287 You can, but probably shouldn't modify credits... 
288
289 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
290 supplied, replaces this record.  If there is an error, returns the error,
291 otherwise returns false.
292
293 =cut
294
295 sub replace {
296   my $self = shift;
297   return "Can't modify closed credit" if $self->closed =~ /^Y/i;
298   $self->SUPER::replace(@_);
299 }
300
301 =item check
302
303 Checks all fields to make sure this is a valid credit.  If there is an error,
304 returns the error, otherwise returns false.  Called by the insert and replace
305 methods.
306
307 =cut
308
309 sub check {
310   my $self = shift;
311
312   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
313
314   my $error =
315     $self->ut_numbern('crednum')
316     || $self->ut_number('custnum')
317     || $self->ut_numbern('_date')
318     || $self->ut_money('amount')
319     || $self->ut_alphan('otaker')
320     || $self->ut_textn('reason')
321     || $self->ut_textn('addlinfo')
322     || $self->ut_enum('closed', [ '', 'Y' ])
323     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
324     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
325     || $self->ut_foreign_keyn('commission_agentnum',  'agent', 'agentnum')
326     || $self->ut_foreign_keyn('commission_salesnum',  'sales', 'salesnum')
327     || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
328   ;
329   return $error if $error;
330
331   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
332   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
333   return $error if $error;
334
335   return "amount must be > 0 " if $self->amount <= 0;
336
337   return "amount must be greater or equal to amount applied"
338     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
339
340   return "Unknown customer"
341     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
342
343   $self->_date(time) unless $self->_date;
344
345   $self->SUPER::check;
346 }
347
348 =item void [ REASON ]
349
350 Voids this credit: deletes the credit and all associated applications and 
351 adds a record of the voided credit to the cust_credit_void table.
352
353 =cut
354
355 sub void {
356   my $self = shift;
357   my $reason = shift;
358
359   unless (ref($reason) || !$reason) {
360     $reason = FS::reason->new_or_existing(
361       'class'  => 'X',
362       'type'   => 'Void credit',
363       'reason' => $reason
364     );
365   }
366
367   local $SIG{HUP} = 'IGNORE';
368   local $SIG{INT} = 'IGNORE';
369   local $SIG{QUIT} = 'IGNORE';
370   local $SIG{TERM} = 'IGNORE';
371   local $SIG{TSTP} = 'IGNORE';
372   local $SIG{PIPE} = 'IGNORE';
373
374   my $oldAutoCommit = $FS::UID::AutoCommit;
375   local $FS::UID::AutoCommit = 0;
376   my $dbh = dbh;
377
378   my $cust_credit_void = new FS::cust_credit_void ( {
379       map { $_ => $self->get($_) } $self->fields
380     } );
381   $cust_credit_void->set('void_reasonnum', $reason->reasonnum);
382   my $error = $cust_credit_void->insert;
383   if ( $error ) {
384     $dbh->rollback if $oldAutoCommit;
385     return $error;
386   }
387
388   $error = $self->delete();
389   if ( $error ) {
390     $dbh->rollback if $oldAutoCommit;
391     return $error;
392   }
393
394   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
395
396   '';
397
398 }
399
400 =item cust_credit_refund
401
402 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
403
404 =cut
405
406 sub cust_credit_refund {
407   my $self = shift;
408   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
409   sort { $a->_date <=> $b->_date }
410     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
411   ;
412 }
413
414 =item cust_credit_bill
415
416 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
417 credit.
418
419 =cut
420
421 sub cust_credit_bill {
422   my $self = shift;
423   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
424   sort { $a->_date <=> $b->_date }
425     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
426   ;
427 }
428
429 =item unapplied
430
431 Returns the amount of this credit that is still unapplied/outstanding; 
432 amount minus all refund applications (see L<FS::cust_credit_refund>) and
433 applications to invoices (see L<FS::cust_credit_bill>).
434
435 =cut
436
437 sub unapplied {
438   my $self = shift;
439   my $amount = $self->amount;
440   $amount -= $_->amount foreach ( $self->cust_credit_refund );
441   $amount -= $_->amount foreach ( $self->cust_credit_bill );
442   sprintf( "%.2f", $amount );
443 }
444
445 =item credited
446
447 Deprecated name for the unapplied method.
448
449 =cut
450
451 sub credited {
452   my $self = shift;
453   #carp "cust_credit->credited deprecated; use ->unapplied";
454   $self->unapplied(@_);
455 }
456
457 =item cust_main
458
459 Returns the customer (see L<FS::cust_main>) for this credit.
460
461 =cut
462
463 # _upgrade_data
464 #
465 # Used by FS::Upgrade to migrate to a new database.
466
467 sub _upgrade_data {  # class method
468   my ($class, %opts) = @_;
469
470   warn "$me upgrading $class\n" if $DEBUG;
471
472   $class->_upgrade_reasonnum(%opts);
473
474   if (defined dbdef->table($class->table)->column('reason')) {
475
476     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
477
478     foreach ( keys %reasontype_map ) {
479       unless ($conf->config($_)) {       # hmmmm
480 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
481 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
482         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
483         my $reason_type = qsearchs( 'reason_type', $hashref );
484         unless ($reason_type) {
485           $reason_type  = new FS::reason_type( $hashref );
486           my $error   = $reason_type->insert();
487           die "$class had error inserting FS::reason_type into database: $error\n"
488             if $error;
489         }
490         $conf->set($_, $reason_type->typenum);
491       }
492     }
493
494     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
495
496     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
497     my $reason_type = qsearchs( 'reason_type', $hashref );
498     unless ($reason_type) {
499       $reason_type  = new FS::reason_type( $hashref );
500       my $error   = $reason_type->insert();
501       die "$class had error inserting FS::reason_type into database: $error\n"
502         if $error;
503     }
504
505     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
506     foreach my $plan ( @plans ) {
507       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
508         unless ($pkg->option('reason_type', 1) ) { 
509           my $plandata = $pkg->plandata.
510                         "reason_type=". $reason_type->typenum. "\n";
511           $pkg->plandata($plandata);
512           my $error =
513             $pkg->replace( undef,
514                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
515                                           $pkg->pkg_svc
516                                         },
517                            'primary_svc' => $pkg->svcpart,
518                          );
519             die "failed setting reason_type option: $error"
520               if $error;
521         }
522       }
523     }
524   }
525
526   local($otaker_upgrade_kludge) = 1;
527   local($ignore_empty_reasonnum) = 1;
528   $class->_upgrade_otaker(%opts);
529
530   if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
531       and !$conf->config('tax_data_vendor') ) {
532     # RT#25458: fix credit line item applications that should refer to a 
533     # specific tax allocation
534     my @cust_credit_bill_pkg = qsearch({
535         table     => 'cust_credit_bill_pkg',
536         select    => 'cust_credit_bill_pkg.*',
537         addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
538         extra_sql =>
539           'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
540           'AND cust_bill_pkg.pkgnum = 0', # is a tax
541     });
542     my %tax_items;
543     my %credits;
544     foreach (@cust_credit_bill_pkg) {
545       my $billpkgnum = $_->billpkgnum;
546       $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
547       $credits{$billpkgnum} ||= [];
548       push @{ $credits{$billpkgnum} }, $_;
549     }
550     TAX_ITEM: foreach my $tax_item (values %tax_items) {
551       my $billpkgnum = $tax_item->billpkgnum;
552       # get all pkg/location/taxrate allocations of this tax line item
553       my @allocations = sort {$b->amount <=> $a->amount}
554                         qsearch('cust_bill_pkg_tax_location', {
555                             billpkgnum => $billpkgnum
556                         });
557       # and these are all credit applications to it
558       my @credits = sort {$b->amount <=> $a->amount}
559                     @{ $credits{$billpkgnum} };
560       my $c = shift @credits;
561       my $a = shift @allocations; # we will NOT modify these
562       while ($c and $a) {
563         if ( abs($c->amount - $a->amount) < 0.005 ) {
564           # by far the most common case: the tax line item is for a single
565           # tax, so we just fill in the billpkgtaxlocationnum
566           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
567           my $error = $c->replace;
568           if ($error) {
569             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
570             next TAX_ITEM;
571           }
572           $c = shift @credits;
573           $a = shift @allocations;
574         } elsif ( $c->amount > $a->amount ) {
575           # fairly common: the tax line contains tax for multiple packages
576           # (or multiple taxes) but the credit isn't divided up
577           my $new_link = FS::cust_credit_bill_pkg->new({
578               creditbillnum         => $c->creditbillnum,
579               billpkgnum            => $c->billpkgnum,
580               billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
581               amount                => $a->amount,
582               setuprecur            => 'setup',
583           });
584           my $error = $new_link->insert;
585           if ($error) {
586             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
587             next TAX_ITEM;
588           }
589           $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
590           $a = shift @allocations;
591         } elsif ( $c->amount < 0.005 ) {
592           # also fairly common; we can delete these with no harm
593           my $error = $c->delete;
594           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
595           $c = shift @credits;
596         } elsif ( $c->amount < $a->amount ) {
597           # should never happen, but if it does, handle it gracefully
598           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
599           my $error = $c->replace;
600           if ($error) {
601             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
602             next TAX_ITEM;
603           }
604           $a->set(amount => $a->amount - $c->amount);
605           $c = shift @credits;
606         }
607       } # while $c and $a
608       if ( $c ) {
609         if ( $c->amount < 0.005 ) {
610           my $error = $c->delete;
611           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
612         } elsif ( $c->modified ) {
613           # then we've allocated part of it, so reduce the nonspecific 
614           # application by that much
615           my $error = $c->replace;
616           warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
617         }
618         # else there are probably no allocations, i.e. this is a pre-3.x 
619         # record that was never migrated over, so leave it alone
620       } # if $c
621     } # foreach $tax_item
622     FS::upgrade_journal->set_done('cust_credit__tax_link');
623   }
624 }
625
626 =back
627
628 =head1 CLASS METHODS
629
630 =over 4
631
632 =item unapplied_sql
633
634 Returns an SQL fragment to retreive the unapplied amount.
635
636 =cut
637
638 sub unapplied_sql {
639   my ($class, $start, $end) = @_;
640
641   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
642   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
643   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
644   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
645
646   "amount
647         - COALESCE(
648                     ( SELECT SUM(amount) FROM cust_credit_refund
649                         WHERE cust_credit.crednum = cust_credit_refund.crednum
650                         $refund_start $refund_end )
651                     ,0
652                   )
653         - COALESCE(
654                     ( SELECT SUM(amount) FROM cust_credit_bill
655                         WHERE cust_credit.crednum = cust_credit_bill.crednum
656                         $bill_start $bill_end )
657                     ,0
658                   )
659   ";
660
661 }
662
663 =item credited_sql
664
665 Deprecated name for the unapplied_sql method.
666
667 =cut
668
669 sub credited_sql {
670   #my $class = shift;
671
672   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
673
674   #$class->unapplied_sql(@_);
675   unapplied_sql();
676 }
677
678 =item calculate_tax_adjustment PARAMS
679
680 Calculate the amount of tax that needs to be credited as part of a lineitem
681 credit.
682
683 PARAMS must include:
684
685 - billpkgnums: arrayref identifying the line items to credit
686 - setuprecurs: arrayref of 'setup' or 'recur', indicating which part of
687   the lineitem charge is being credited
688 - amounts: arrayref of the amounts to credit on each line item
689 - custnum: the customer all of these invoices belong to, for error checking
690
691 Returns a hash containing:
692 - subtotal: the total non-tax amount to be credited (the sum of the 'amounts')
693 - taxtotal: the total tax amount to be credited
694 - taxlines: an arrayref of hashrefs for each tax line to be credited, each with:
695   - table: "cust_bill_pkg_tax_location" or "cust_bill_pkg_tax_rate_location"
696   - num: the key within that table
697   - credit: the credit amount to apply to that line
698
699 =cut
700
701 sub calculate_tax_adjustment {
702   my ($class, %arg) = @_;
703
704   my $error;
705   my @taxlines;
706   my $subtotal = 0;
707   my $taxtotal = 0;
708
709   my (%cust_bill_pkg, %cust_bill);
710
711   for (my $i = 0; ; $i++) {
712     my $billpkgnum = $arg{billpkgnums}[$i]
713       or last;
714     my $setuprecur = $arg{setuprecurs}[$i];
715     my $amount = $arg{amounts}[$i];
716     next if $amount == 0;
717     $subtotal += $amount;
718     my $cust_bill_pkg = $cust_bill_pkg{$billpkgnum}
719                     ||= FS::cust_bill_pkg->by_key($billpkgnum)
720       or die "lineitem #$billpkgnum not found\n";
721
722     my $invnum = $cust_bill_pkg->invnum;
723     $cust_bill{ $invnum } ||= FS::cust_bill->by_key($invnum);
724     $cust_bill{ $invnum}->custnum == $arg{custnum}
725       or die "lineitem #$billpkgnum not found\n";
726
727     # calculate credit ratio.
728     # (First deduct any existing credits applied to this line item, to avoid
729     # rounding errors.)
730     my $charged = $cust_bill_pkg->get($setuprecur);
731     my $previously_credited =
732       $cust_bill_pkg->credited( '', '', setuprecur => $setuprecur) || 0;
733
734     $charged -= $previously_credited;
735     if ($charged < $amount) {
736       $error = "invoice #$invnum: tried to credit $amount, but only $charged was charged";
737       last;
738     }
739     my $ratio = $amount / $charged;
740
741     # gather taxes that apply to the selected item
742     foreach my $table (
743       qw(cust_bill_pkg_tax_location cust_bill_pkg_tax_rate_location)
744     ) {
745       foreach my $tax_link (
746         qsearch($table, { taxable_billpkgnum => $billpkgnum })
747       ) {
748         my $tax_amount = $tax_link->amount;
749         # deduct existing credits applied to the tax, for the same reason as
750         # above
751         foreach ($tax_link->cust_credit_bill_pkg) {
752           $tax_amount -= $_->amount;
753         }
754         my $tax_credit = sprintf('%.2f', $tax_amount * $ratio);
755         my $pkey = $tax_link->get($tax_link->primary_key);
756         push @taxlines, {
757           table   => $table,
758           num     => $pkey,
759           credit  => $tax_credit,
760         };
761         $taxtotal += $tax_credit;
762
763       } #foreach cust_bill_pkg_tax_(rate_)?location
764     }
765   } # foreach $billpkgnum
766
767   return (
768     subtotal => sprintf('%.2f', $subtotal),
769     taxtotal => sprintf('%.2f', $taxtotal),
770     taxlines => \@taxlines,
771   );
772 }
773
774 =item credit_lineitems
775
776 Example:
777
778   my $error = FS::cust_credit->credit_lineitems(
779
780     #the lineitems to credit
781     'billpkgnums'       => \@billpkgnums,
782     'setuprecurs'       => \@setuprecurs,
783     'amounts'           => \@amounts,
784     'apply'             => 1, #0 leaves the credit unapplied
785
786     #the credit
787     map { $_ => scalar($cgi->param($_)) }
788       #fields('cust_credit')  
789       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
790
791   );
792
793 =cut
794
795 #maybe i should just be an insert with extra args instead of a class method
796 sub credit_lineitems {
797   my( $class, %arg ) = @_;
798   my $curuser = $FS::CurrentUser::CurrentUser;
799
800   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
801
802   my $cust_main = qsearchs({
803     'table'     => 'cust_main',
804     'hashref'   => { 'custnum' => $arg{custnum} },
805     'extra_sql' => ' AND '. $curuser->agentnums_sql,
806   }) or return 'unknown customer';
807
808
809   local $SIG{HUP} = 'IGNORE';
810   local $SIG{INT} = 'IGNORE';
811   local $SIG{QUIT} = 'IGNORE';
812   local $SIG{TERM} = 'IGNORE';
813   local $SIG{TSTP} = 'IGNORE';
814   local $SIG{PIPE} = 'IGNORE';
815
816   my $oldAutoCommit = $FS::UID::AutoCommit;
817   local $FS::UID::AutoCommit = 0;
818   my $dbh = dbh;
819
820   #my @cust_bill_pkg = qsearch({
821   #  'select'    => 'cust_bill_pkg.*',
822   #  'table'     => 'cust_bill_pkg',
823   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
824   #                 ' LEFT JOIN cust_main USING (custnum) ',
825   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
826   #                     join( ',', @{$arg{billpkgnums}} ). ')',
827   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
828   #});
829
830   my $error = '';
831
832   my $cust_credit = new FS::cust_credit ( {
833     map { $_ => $arg{$_} }
834       #fields('cust_credit')
835       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
836   } );
837   $error = $cust_credit->insert;
838   if ( $error ) {
839     $dbh->rollback if $oldAutoCommit;
840     return "Error inserting credit: $error";
841   }
842
843   unless ( $arg{'apply'} ) {
844     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
845     return '';
846   }
847
848   #my $subtotal = 0;
849   # keys in all of these are invoice numbers
850   my %cust_credit_bill = ();
851   my %cust_bill_pkg = ();
852   my %cust_credit_bill_pkg = ();
853   my %unapplied_payments = (); #invoice numbers, and then billpaynums
854
855   # determine the tax adjustments
856   my %tax_adjust = $class->calculate_tax_adjustment(%arg);
857
858   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
859     my $setuprecur = shift @{$arg{setuprecurs}};
860     my $amount = shift @{$arg{amounts}};
861
862     my $cust_bill_pkg = qsearchs({
863       'table'     => 'cust_bill_pkg',
864       'hashref'   => { 'billpkgnum' => $billpkgnum },
865       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
866       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
867     }) or die "unknown billpkgnum $billpkgnum";
868   
869     my $invnum = $cust_bill_pkg->invnum;
870
871     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
872
873     $cust_credit_bill{$invnum} += $amount;
874     push @{ $cust_credit_bill_pkg{$invnum} },
875       new FS::cust_credit_bill_pkg {
876         'billpkgnum' => $billpkgnum,
877         'amount'     => sprintf('%.2f',$amount),
878         'setuprecur' => $setuprecur,
879         'sdate'      => $cust_bill_pkg->sdate,
880         'edate'      => $cust_bill_pkg->edate,
881       };
882     # unapply payments (but not other credits) from this line item
883     foreach my $cust_bill_pay_pkg (
884       $cust_bill_pkg->cust_bill_pay_pkg($setuprecur)
885     ) {
886       $error = $cust_bill_pay_pkg->delete;
887       if ( $error ) {
888         $dbh->rollback if $oldAutoCommit;
889         return "Error unapplying payment: $error";
890       }
891       $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
892         += $cust_bill_pay_pkg->amount;
893     }
894   }
895
896   # do the same for taxes
897   foreach my $tax_credit ( @{ $tax_adjust{taxlines} } ) {
898     my $table = $tax_credit->{table};
899     my $tax_link = "FS::$table"->by_key( $tax_credit->{num} )
900       or die "tried to credit $table #$tax_credit->{num} but it doesn't exist";
901
902     my $billpkgnum = $tax_link->billpkgnum;
903     my $cust_bill_pkg = qsearchs({
904       'table'     => 'cust_bill_pkg',
905       'hashref'   => { 'billpkgnum' => $billpkgnum },
906       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
907       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
908     }) or die "unknown billpkgnum $billpkgnum";
909     
910     my $invnum = $cust_bill_pkg->invnum;
911     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
912
913     my $amount = $tax_credit->{credit};
914     $cust_credit_bill{$invnum} += $amount;
915
916     # create a credit application record to the tax line item, earmarked
917     # to the specific cust_bill_pkg_Xlocation
918     push @{ $cust_credit_bill_pkg{$invnum} },
919       new FS::cust_credit_bill_pkg {
920         'billpkgnum' => $billpkgnum,
921         'amount'     => sprintf('%.2f', $amount),
922         'setuprecur' => 'setup',
923         $tax_link->primary_key, $tax_credit->{num}
924       };
925     # unapply any payments from the tax
926     foreach my $cust_bill_pay_pkg (
927       $cust_bill_pkg->cust_bill_pay_pkg('setup')
928     ) {
929       $error = $cust_bill_pay_pkg->delete;
930       if ( $error ) {
931         $dbh->rollback if $oldAutoCommit;
932         return "Error unapplying payment: $error";
933       }
934       $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
935         += $cust_bill_pay_pkg->amount;
936     }
937   }
938
939   ###
940   # now loop through %cust_credit_bill and insert those
941   ###
942
943   # (hack to prevent cust_credit_bill_pkg insertion)
944   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
945
946   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
947
948     # if we unapplied any payments from line items, also unapply that 
949     # amount from the invoice
950     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
951       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
952         or die "broken payment application $billpaynum";
953       my @subapps = $cust_bill_pay->lineitem_applications;
954       $error = $cust_bill_pay->delete; # can't replace
955
956       my $new_cust_bill_pay = FS::cust_bill_pay->new({
957           $cust_bill_pay->hash,
958           billpaynum => '',
959           amount => sprintf('%.2f', 
960               $cust_bill_pay->amount 
961               - $unapplied_payments{$invnum}{$billpaynum}),
962       });
963
964       if ( $new_cust_bill_pay->amount > 0 ) {
965         $error ||= $new_cust_bill_pay->insert;
966         # Also reapply it to everything it was applied to before.
967         # Note that we've already deleted cust_bill_pay_pkg records for the
968         # items we're crediting, so they aren't on this list.
969         foreach my $cust_bill_pay_pkg (@subapps) {
970           $cust_bill_pay_pkg->billpaypkgnum('');
971           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
972           $error ||= $cust_bill_pay_pkg->insert;
973         }
974       }
975       if ( $error ) {
976         $dbh->rollback if $oldAutoCommit;
977         return "Error unapplying payment: $error";
978       }
979     }
980     #insert cust_credit_bill
981
982     my $cust_credit_bill = new FS::cust_credit_bill {
983       'crednum' => $cust_credit->crednum,
984       'invnum'  => $invnum,
985       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
986     };
987     $error = $cust_credit_bill->insert;
988     if ( $error ) {
989       $dbh->rollback if $oldAutoCommit;
990       return "Error applying credit of $cust_credit_bill{$invnum} ".
991              " to invoice $invnum: $error";
992     }
993
994     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
995     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
996       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
997       $error = $cust_credit_bill_pkg->insert;
998       if ( $error ) {
999         $dbh->rollback if $oldAutoCommit;
1000         return "Error applying credit to line item: $error";
1001       }
1002     }
1003
1004   }
1005
1006   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1007   '';
1008
1009 }
1010
1011 =back
1012
1013 =head1 SUBROUTINES
1014
1015 =over 4
1016
1017 =item process_batch_import
1018
1019 =cut
1020
1021 use List::Util qw( min );
1022 use FS::cust_bill;
1023 use FS::cust_credit_bill;
1024 sub process_batch_import {
1025   my $job = shift;
1026
1027   my $opt = { 'table'   => 'cust_credit',
1028               'params'  => [ '_date', 'credbatch' ],
1029               'formats' => { 'simple' =>
1030                                [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1031                            },
1032               'default_csv' => 1,
1033               'postinsert_callback' => sub {
1034                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1035
1036                 if ( $cust_credit->invnum ) {
1037
1038                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1039                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1040     
1041                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1042                     'crednum' => $cust_credit->crednum,
1043                     'invnum'  => $cust_bill->invnum,
1044                     'amount'  => $amount,
1045                   } );
1046                   my $error = $cust_credit_bill->insert;
1047                   return '' unless $error;
1048
1049                 }
1050
1051                 #apply_payments_and_credits ?
1052                 $cust_credit->cust_main->apply_credits;
1053
1054                 return '';
1055
1056               },
1057             };
1058
1059   FS::Record::process_batch_import( $job, $opt, @_ );
1060
1061 }
1062
1063 =back
1064
1065 =head1 BUGS
1066
1067 The delete method.  The replace method.
1068
1069 B<credited> and B<credited_sql> are now called B<unapplied> and
1070 B<unapplied_sql>.  The old method names should start to give warnings.
1071
1072 =head1 SEE ALSO
1073
1074 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1075 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1076 documentation.
1077
1078 =cut
1079
1080 1;
1081