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