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