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