Merge branch 'master' of https://github.com/jgoodman/Freeside
[freeside.git] / FS / FS / cust_credit.pm
1 package FS::cust_credit;
2 use base qw( FS::otaker_Mixin FS::cust_main_Mixin FS::reason_Mixin
3              FS::Record );
4
5 use strict;
6 use vars qw( $conf $unsuspendauto $me $DEBUG
7              $otaker_upgrade_kludge $ignore_empty_reasonnum
8            );
9 use List::Util qw( min );
10 use Date::Format;
11 use FS::UID qw( dbh );
12 use FS::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::upgrade_journal;
26
27 $me = '[ FS::cust_credit ]';
28 $DEBUG = 0;
29
30 $otaker_upgrade_kludge = 0;
31 $ignore_empty_reasonnum = 0;
32
33 #ask FS::UID to run this stuff for us later
34 $FS::UID::callback{'FS::cust_credit'} = sub { 
35
36   $conf = new FS::Conf;
37   $unsuspendauto = $conf->exists('unsuspendauto');
38
39 };
40
41 our %reasontype_map = ( 'referral_credit_type' => 'Referral Credit',
42                         'cancel_credit_type'   => 'Cancellation Credit',
43                         'signup_credit_type'   => 'Self-Service Credit',
44                       );
45
46 =head1 NAME
47
48 FS::cust_credit - Object methods for cust_credit records
49
50 =head1 SYNOPSIS
51
52   use FS::cust_credit;
53
54   $record = new FS::cust_credit \%hash;
55   $record = new FS::cust_credit { 'column' => 'value' };
56
57   $error = $record->insert;
58
59   $error = $new_record->replace($old_record);
60
61   $error = $record->delete;
62
63   $error = $record->check;
64
65 =head1 DESCRIPTION
66
67 An FS::cust_credit object represents a credit; the equivalent of a negative
68 B<cust_bill> record (see L<FS::cust_bill>).  FS::cust_credit inherits from
69 FS::Record.  The following fields are currently supported:
70
71 =over 4
72
73 =item crednum
74
75 Primary key (assigned automatically for new credits)
76
77 =item custnum
78
79 Customer (see L<FS::cust_main>)
80
81 =item amount
82
83 Amount of the credit
84
85 =item _date
86
87 Specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
89
90 =item usernum
91
92 Order taker (see L<FS::access_user>)
93
94 =item reason
95
96 Text ( deprecated )
97
98 =item reasonnum
99
100 Reason (see L<FS::reason>)
101
102 =item addlinfo
103
104 Text
105
106 =item closed
107
108 Books closed flag, empty or `Y'
109
110 =item pkgnum
111
112 Desired pkgnum when using experimental package balances.
113
114 =back
115
116 =head1 METHODS
117
118 =over 4
119
120 =item new HASHREF
121
122 Creates a new credit.  To add the credit to the database, see L<"insert">.
123
124 =cut
125
126 sub table { 'cust_credit'; }
127 sub cust_linked { $_[0]->cust_main_custnum || $_[0]->custnum } 
128 sub cust_unlinked_msg {
129   my $self = shift;
130   "WARNING: can't find cust_main.custnum ". $self->custnum.
131   ' (cust_credit.crednum '. $self->crednum. ')';
132 }
133
134 =item insert
135
136 Adds this credit to the database ("Posts" the credit).  If there is an error,
137 returns the error, otherwise returns false.
138
139 =cut
140
141 sub insert {
142   my ($self, %options) = @_;
143
144   local $SIG{HUP} = 'IGNORE';
145   local $SIG{INT} = 'IGNORE';
146   local $SIG{QUIT} = 'IGNORE';
147   local $SIG{TERM} = 'IGNORE';
148   local $SIG{TSTP} = 'IGNORE';
149   local $SIG{PIPE} = 'IGNORE';
150
151   my $oldAutoCommit = $FS::UID::AutoCommit;
152   local $FS::UID::AutoCommit = 0;
153   my $dbh = dbh;
154
155   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
156   my $old_balance = $cust_main->balance;
157
158   unless ($self->reasonnum) {
159     my $result = $self->reason( $self->getfield('reason'),
160                                 exists($options{ 'reason_type' })
161                                   ? ('reason_type' => $options{ 'reason_type' })
162                                   : (),
163                               );
164     unless($result) {
165       $dbh->rollback if $oldAutoCommit;
166       return "failed to set reason for $me"; #: ". $dbh->errstr;
167     }
168   }
169
170   $self->setfield('reason', '');
171
172   my $error = $self->SUPER::insert;
173   if ( $error ) {
174     $dbh->rollback if $oldAutoCommit;
175     return "error inserting $self: $error";
176   }
177
178   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
179
180   #false laziness w/ cust_pay::insert
181   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
182     my @errors = $cust_main->unsuspend;
183     #return 
184     # side-fx with nested transactions?  upstack rolls back?
185     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
186          join(' / ', @errors)
187       if @errors;
188   }
189   #eslaf
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->config('invoice_from', $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 # yes, false laziness with cust_pay and cust_bill
351 # but frankly I don't have time to fix it now
352
353 sub void {
354   my $self = shift;
355   my $reason = shift;
356
357   local $SIG{HUP} = 'IGNORE';
358   local $SIG{INT} = 'IGNORE';
359   local $SIG{QUIT} = 'IGNORE';
360   local $SIG{TERM} = 'IGNORE';
361   local $SIG{TSTP} = 'IGNORE';
362   local $SIG{PIPE} = 'IGNORE';
363
364   my $oldAutoCommit = $FS::UID::AutoCommit;
365   local $FS::UID::AutoCommit = 0;
366   my $dbh = dbh;
367
368   my $cust_credit_void = new FS::cust_credit_void ( {
369       map { $_ => $self->get($_) } $self->fields
370     } );
371   $cust_credit_void->set('void_reason', $reason);
372   my $error = $cust_credit_void->insert;
373   if ( $error ) {
374     $dbh->rollback if $oldAutoCommit;
375     return $error;
376   }
377
378   $error = $self->delete(void => 1); # suppress deletecredits warning
379   if ( $error ) {
380     $dbh->rollback if $oldAutoCommit;
381     return $error;
382   }
383
384   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
385
386   '';
387
388 }
389
390 =item cust_credit_refund
391
392 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
393
394 =cut
395
396 sub cust_credit_refund {
397   my $self = shift;
398   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
399   sort { $a->_date <=> $b->_date }
400     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
401   ;
402 }
403
404 =item cust_credit_bill
405
406 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
407 credit.
408
409 =cut
410
411 sub cust_credit_bill {
412   my $self = shift;
413   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
414   sort { $a->_date <=> $b->_date }
415     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
416   ;
417 }
418
419 =item unapplied
420
421 Returns the amount of this credit that is still unapplied/outstanding; 
422 amount minus all refund applications (see L<FS::cust_credit_refund>) and
423 applications to invoices (see L<FS::cust_credit_bill>).
424
425 =cut
426
427 sub unapplied {
428   my $self = shift;
429   my $amount = $self->amount;
430   $amount -= $_->amount foreach ( $self->cust_credit_refund );
431   $amount -= $_->amount foreach ( $self->cust_credit_bill );
432   sprintf( "%.2f", $amount );
433 }
434
435 =item credited
436
437 Deprecated name for the unapplied method.
438
439 =cut
440
441 sub credited {
442   my $self = shift;
443   #carp "cust_credit->credited deprecated; use ->unapplied";
444   $self->unapplied(@_);
445 }
446
447 =item cust_main
448
449 Returns the customer (see L<FS::cust_main>) for this credit.
450
451 =cut
452
453 # _upgrade_data
454 #
455 # Used by FS::Upgrade to migrate to a new database.
456
457 sub _upgrade_data {  # class method
458   my ($class, %opts) = @_;
459
460   warn "$me upgrading $class\n" if $DEBUG;
461
462   $class->_upgrade_reasonnum(%opts);
463
464   if (defined dbdef->table($class->table)->column('reason')) {
465
466     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
467
468     foreach ( keys %reasontype_map ) {
469       unless ($conf->config($_)) {       # hmmmm
470 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
471 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
472         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
473         my $reason_type = qsearchs( 'reason_type', $hashref );
474         unless ($reason_type) {
475           $reason_type  = new FS::reason_type( $hashref );
476           my $error   = $reason_type->insert();
477           die "$class had error inserting FS::reason_type into database: $error\n"
478             if $error;
479         }
480         $conf->set($_, $reason_type->typenum);
481       }
482     }
483
484     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
485
486     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
487     my $reason_type = qsearchs( 'reason_type', $hashref );
488     unless ($reason_type) {
489       $reason_type  = new FS::reason_type( $hashref );
490       my $error   = $reason_type->insert();
491       die "$class had error inserting FS::reason_type into database: $error\n"
492         if $error;
493     }
494
495     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
496     foreach my $plan ( @plans ) {
497       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
498         unless ($pkg->option('reason_type', 1) ) { 
499           my $plandata = $pkg->plandata.
500                         "reason_type=". $reason_type->typenum. "\n";
501           $pkg->plandata($plandata);
502           my $error =
503             $pkg->replace( undef,
504                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
505                                           $pkg->pkg_svc
506                                         },
507                            'primary_svc' => $pkg->svcpart,
508                          );
509             die "failed setting reason_type option: $error"
510               if $error;
511         }
512       }
513     }
514   }
515
516   local($otaker_upgrade_kludge) = 1;
517   local($ignore_empty_reasonnum) = 1;
518   $class->_upgrade_otaker(%opts);
519
520   if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
521       and !$conf->exists('enable_taxproducts') ) {
522     # RT#25458: fix credit line item applications that should refer to a 
523     # specific tax allocation
524     my @cust_credit_bill_pkg = qsearch({
525         table     => 'cust_credit_bill_pkg',
526         select    => 'cust_credit_bill_pkg.*',
527         addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
528         extra_sql =>
529           'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
530           'AND cust_bill_pkg.pkgnum = 0', # is a tax
531     });
532     my %tax_items;
533     my %credits;
534     foreach (@cust_credit_bill_pkg) {
535       my $billpkgnum = $_->billpkgnum;
536       $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
537       $credits{$billpkgnum} ||= [];
538       push @{ $credits{$billpkgnum} }, $_;
539     }
540     TAX_ITEM: foreach my $tax_item (values %tax_items) {
541       my $billpkgnum = $tax_item->billpkgnum;
542       # get all pkg/location/taxrate allocations of this tax line item
543       my @allocations = sort {$b->amount <=> $a->amount}
544                         qsearch('cust_bill_pkg_tax_location', {
545                             billpkgnum => $billpkgnum
546                         });
547       # and these are all credit applications to it
548       my @credits = sort {$b->amount <=> $a->amount}
549                     @{ $credits{$billpkgnum} };
550       my $c = shift @credits;
551       my $a = shift @allocations; # we will NOT modify these
552       while ($c and $a) {
553         if ( abs($c->amount - $a->amount) < 0.005 ) {
554           # by far the most common case: the tax line item is for a single
555           # tax, so we just fill in the billpkgtaxlocationnum
556           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
557           my $error = $c->replace;
558           if ($error) {
559             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
560             next TAX_ITEM;
561           }
562           $c = shift @credits;
563           $a = shift @allocations;
564         } elsif ( $c->amount > $a->amount ) {
565           # fairly common: the tax line contains tax for multiple packages
566           # (or multiple taxes) but the credit isn't divided up
567           my $new_link = FS::cust_credit_bill_pkg->new({
568               creditbillnum         => $c->creditbillnum,
569               billpkgnum            => $c->billpkgnum,
570               billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
571               amount                => $a->amount,
572               setuprecur            => 'setup',
573           });
574           my $error = $new_link->insert;
575           if ($error) {
576             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
577             next TAX_ITEM;
578           }
579           $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
580           $a = shift @allocations;
581         } elsif ( $c->amount < 0.005 ) {
582           # also fairly common; we can delete these with no harm
583           my $error = $c->delete;
584           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
585           $c = shift @credits;
586         } elsif ( $c->amount < $a->amount ) {
587           # should never happen, but if it does, handle it gracefully
588           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
589           my $error = $c->replace;
590           if ($error) {
591             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
592             next TAX_ITEM;
593           }
594           $a->set(amount => $a->amount - $c->amount);
595           $c = shift @credits;
596         }
597       } # while $c and $a
598       if ( $c ) {
599         if ( $c->amount < 0.005 ) {
600           my $error = $c->delete;
601           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
602         } elsif ( $c->modified ) {
603           # then we've allocated part of it, so reduce the nonspecific 
604           # application by that much
605           my $error = $c->replace;
606           warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
607         }
608         # else there are probably no allocations, i.e. this is a pre-3.x 
609         # record that was never migrated over, so leave it alone
610       } # if $c
611     } # foreach $tax_item
612     FS::upgrade_journal->set_done('cust_credit__tax_link');
613   }
614 }
615
616 =back
617
618 =head1 CLASS METHODS
619
620 =over 4
621
622 =item unapplied_sql
623
624 Returns an SQL fragment to retreive the unapplied amount.
625
626 =cut
627
628 sub unapplied_sql {
629   my ($class, $start, $end) = @_;
630
631   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
632   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
633   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
634   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
635
636   "amount
637         - COALESCE(
638                     ( SELECT SUM(amount) FROM cust_credit_refund
639                         WHERE cust_credit.crednum = cust_credit_refund.crednum
640                         $refund_start $refund_end )
641                     ,0
642                   )
643         - COALESCE(
644                     ( SELECT SUM(amount) FROM cust_credit_bill
645                         WHERE cust_credit.crednum = cust_credit_bill.crednum
646                         $bill_start $bill_end )
647                     ,0
648                   )
649   ";
650
651 }
652
653 =item credited_sql
654
655 Deprecated name for the unapplied_sql method.
656
657 =cut
658
659 sub credited_sql {
660   #my $class = shift;
661
662   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
663
664   #$class->unapplied_sql(@_);
665   unapplied_sql();
666 }
667
668 =item credit_lineitems
669
670 Example:
671
672   my $error = FS::cust_credit->credit_lineitems(
673
674     #the lineitems to credit
675     'billpkgnums'       => \@billpkgnums,
676     'setuprecurs'       => \@setuprecurs,
677     'amounts'           => \@amounts,
678     'apply'             => 1, #0 leaves the credit unapplied
679
680     #the credit
681     'newreasonnum'      => scalar($cgi->param('newreasonnum')),
682     'newreasonnum_type' => scalar($cgi->param('newreasonnumT')),
683     map { $_ => scalar($cgi->param($_)) }
684       #fields('cust_credit')  
685       qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
686
687   );
688
689 =cut
690
691 #maybe i should just be an insert with extra args instead of a class method
692 use FS::cust_bill_pkg;
693 sub credit_lineitems {
694   my( $class, %arg ) = @_;
695   my $curuser = $FS::CurrentUser::CurrentUser;
696
697   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
698
699   my $cust_main = qsearchs({
700     'table'     => 'cust_main',
701     'hashref'   => { 'custnum' => $arg{custnum} },
702     'extra_sql' => ' AND '. $curuser->agentnums_sql,
703   }) or return 'unknown customer';
704
705
706   local $SIG{HUP} = 'IGNORE';
707   local $SIG{INT} = 'IGNORE';
708   local $SIG{QUIT} = 'IGNORE';
709   local $SIG{TERM} = 'IGNORE';
710   local $SIG{TSTP} = 'IGNORE';
711   local $SIG{PIPE} = 'IGNORE';
712
713   my $oldAutoCommit = $FS::UID::AutoCommit;
714   local $FS::UID::AutoCommit = 0;
715   my $dbh = dbh;
716
717   #my @cust_bill_pkg = qsearch({
718   #  'select'    => 'cust_bill_pkg.*',
719   #  'table'     => 'cust_bill_pkg',
720   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
721   #                 ' LEFT JOIN cust_main USING (custnum) ',
722   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
723   #                     join( ',', @{$arg{billpkgnums}} ). ')',
724   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
725   #});
726
727   my $error = '';
728   if ($arg{reasonnum} == -1) {
729
730     $error = 'Enter a new reason (or select an existing one)'
731       unless $arg{newreasonnum} !~ /^\s*$/;
732     my $reason = new FS::reason {
733                    'reason'      => $arg{newreasonnum},
734                    'reason_type' => $arg{newreasonnum_type},
735                  };
736     $error ||= $reason->insert;
737     if ( $error ) {
738       $dbh->rollback if $oldAutoCommit;
739       return "Error inserting reason: $error";
740     }
741     $arg{reasonnum} = $reason->reasonnum;
742   }
743
744   my $cust_credit = new FS::cust_credit ( {
745     map { $_ => $arg{$_} }
746       #fields('cust_credit')
747       qw( custnum _date amount reason reasonnum addlinfo ), #pkgnum eventnum
748   } );
749   $error = $cust_credit->insert;
750   if ( $error ) {
751     $dbh->rollback if $oldAutoCommit;
752     return "Error inserting credit: $error";
753   }
754
755   unless ( $arg{'apply'} ) {
756     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
757     return '';
758   }
759
760   #my $subtotal = 0;
761   # keys in all of these are invoice numbers
762   my %cust_credit_bill = ();
763   my %cust_bill_pkg = ();
764   my %cust_credit_bill_pkg = ();
765   my %taxlisthash = ();
766   my %unapplied_payments = (); #invoice numbers, and then billpaynums
767   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
768     my $setuprecur = shift @{$arg{setuprecurs}};
769     my $amount = shift @{$arg{amounts}};
770
771     my $cust_bill_pkg = qsearchs({
772       'table'     => 'cust_bill_pkg',
773       'hashref'   => { 'billpkgnum' => $billpkgnum },
774       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
775       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
776     }) or die "unknown billpkgnum $billpkgnum";
777   
778     my $invnum = $cust_bill_pkg->invnum;
779
780     if ( $setuprecur eq 'setup' ) {
781       $cust_bill_pkg->setup($amount);
782       $cust_bill_pkg->recur(0);
783       $cust_bill_pkg->unitrecur(0);
784       $cust_bill_pkg->type('');
785     } else {
786       $setuprecur = 'recur'; #in case its a usage classnum?
787       $cust_bill_pkg->recur($amount);
788       $cust_bill_pkg->setup(0);
789       $cust_bill_pkg->unitsetup(0);
790     }
791
792     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
793
794     #unapply any payments applied to this line item (other credits too?)
795     foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
796       $error = $cust_bill_pay_pkg->delete;
797       if ( $error ) {
798         $dbh->rollback if $oldAutoCommit;
799         return "Error unapplying payment: $error";
800       }
801       $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
802         += $cust_bill_pay_pkg->amount;
803     }
804
805     #$subtotal += $amount;
806     $cust_credit_bill{$invnum} += $amount;
807     push @{ $cust_credit_bill_pkg{$invnum} },
808       new FS::cust_credit_bill_pkg {
809         'billpkgnum' => $cust_bill_pkg->billpkgnum,
810         'amount'     => sprintf('%.2f',$amount),
811         'setuprecur' => $setuprecur,
812         'sdate'      => $cust_bill_pkg->sdate,
813         'edate'      => $cust_bill_pkg->edate,
814       };
815
816     # recalculate taxes with new amounts
817     $taxlisthash{$invnum} ||= {};
818     my $part_pkg = $cust_bill_pkg->part_pkg
819       if $cust_bill_pkg->pkgpart_override;
820     $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
821   }
822
823   ###
824   # now loop through %cust_credit_bill and insert those
825   ###
826
827   # (hack to prevent cust_credit_bill_pkg insertion)
828   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
829
830   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
831
832     my $arrayref_or_error =
833       $cust_main->calculate_taxes(
834         $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
835         $taxlisthash{$invnum},   # list of tax-item bindings
836         $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
837       );
838
839     unless ( ref( $arrayref_or_error ) ) {
840       $dbh->rollback if $oldAutoCommit;
841       return "Error calculating taxes: $arrayref_or_error";
842     }
843     
844     my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
845
846     #taxes
847     foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
848       my $billpkgnum = $cust_bill_pkg->billpkgnum;
849       my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
850       # gather up existing tax links (we need their billpkgtaxlocationnums)
851       my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
852                       qsearch('cust_bill_pkg_tax_rate_location', \%hash);
853
854       foreach ( @tax_links ) {
855         $tax_links{$_->billpkgnum} ||= {};
856         $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
857       }
858     }
859
860     foreach my $taxline ( @$arrayref_or_error ) {
861
862       my $amount = $taxline->setup;
863
864       # find equivalent tax line item on the existing invoice
865       my $tax_item = qsearchs('cust_bill_pkg', {
866           'invnum'    => $invnum,
867           'pkgnum'    => 0,
868           'itemdesc'  => $taxline->desc,
869       });
870       if (!$tax_item) {
871         # or should we just exit if this happens?
872         $cust_credit->set('amount', 
873           sprintf('%.2f', $cust_credit->get('amount') - $amount)
874         );
875         my $error = $cust_credit->replace;
876         if ( $error ) {
877           $dbh->rollback if $oldAutoCommit;
878           return "error correcting credit for missing tax line: $error";
879         }
880       }
881
882       # but in the new era, we no longer have the problem of uniquely
883       # identifying the tax_Xlocation record.  The billpkgnums of the 
884       # tax and the taxed item are known.
885       foreach my $new_loc
886         ( @{ $taxline->get('cust_bill_pkg_tax_location') },
887           @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
888       {
889         # the existing tax_Xlocation object
890         my $old_loc =
891           $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
892
893         next if !$old_loc; # apply the leftover amount nonspecifically
894
895         #support partial credits: use $amount if smaller
896         # (so just distribute to the first location?   perhaps should
897         #  do so evenly...)
898         my $loc_amount = min( $amount, $new_loc->amount);
899
900         $amount -= $loc_amount;
901
902         $cust_credit_bill{$invnum} += $loc_amount;
903         push @{ $cust_credit_bill_pkg{$invnum} },
904           new FS::cust_credit_bill_pkg {
905             'billpkgnum'                => $tax_item->billpkgnum,
906             'amount'                    => $loc_amount,
907             'setuprecur'                => 'setup',
908             'billpkgtaxlocationnum'     => $old_loc->billpkgtaxlocationnum,
909             'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
910           };
911
912       } #foreach my $new_loc
913
914       # we still have to deal with the possibility that the tax links don't
915       # cover the whole amount of tax because of an incomplete upgrade...
916       if ($amount > 0.005) {
917         $cust_credit_bill{$invnum} += $amount;
918         push @{ $cust_credit_bill_pkg{$invnum} },
919           new FS::cust_credit_bill_pkg {
920             'billpkgnum' => $tax_item->billpkgnum,
921             'amount'     => sprintf('%.2f', $amount),
922             'setuprecur' => 'setup',
923           };
924
925       } # if $amount > 0
926
927       #unapply any payments applied to the tax
928       foreach my $cust_bill_pay_pkg
929         ( $tax_item->cust_bill_pay_pkg('setup') )
930       {
931         $error = $cust_bill_pay_pkg->delete;
932         if ( $error ) {
933           $dbh->rollback if $oldAutoCommit;
934           return "Error unapplying payment: $error";
935         }
936         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
937           += $cust_bill_pay_pkg->amount;
938       }
939     } #foreach $taxline
940
941     # if we unapplied any payments from line items, also unapply that 
942     # amount from the invoice
943     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
944       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
945         or die "broken payment application $billpaynum";
946       my @subapps = $cust_bill_pay->lineitem_applications;
947       $error = $cust_bill_pay->delete; # can't replace
948
949       my $new_cust_bill_pay = FS::cust_bill_pay->new({
950           $cust_bill_pay->hash,
951           billpaynum => '',
952           amount => sprintf('%.2f', 
953               $cust_bill_pay->amount 
954               - $unapplied_payments{$invnum}{$billpaynum}),
955       });
956
957       if ( $new_cust_bill_pay->amount > 0 ) {
958         $error ||= $new_cust_bill_pay->insert;
959         # Also reapply it to everything it was applied to before.
960         # Note that we've already deleted cust_bill_pay_pkg records for the
961         # items we're crediting, so they aren't on this list.
962         foreach my $cust_bill_pay_pkg (@subapps) {
963           $cust_bill_pay_pkg->billpaypkgnum('');
964           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
965           $error ||= $cust_bill_pay_pkg->insert;
966         }
967       }
968       if ( $error ) {
969         $dbh->rollback if $oldAutoCommit;
970         return "Error unapplying payment: $error";
971       }
972     }
973     #insert cust_credit_bill
974
975     my $cust_credit_bill = new FS::cust_credit_bill {
976       'crednum' => $cust_credit->crednum,
977       'invnum'  => $invnum,
978       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
979     };
980     $error = $cust_credit_bill->insert;
981     if ( $error ) {
982       $dbh->rollback if $oldAutoCommit;
983       return "Error applying credit of $cust_credit_bill{$invnum} ".
984              " to invoice $invnum: $error";
985     }
986
987     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
988     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
989       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
990       $error = $cust_credit_bill_pkg->insert;
991       if ( $error ) {
992         $dbh->rollback if $oldAutoCommit;
993         return "Error applying credit to line item: $error";
994       }
995     }
996
997   }
998
999   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1000   '';
1001
1002 }
1003
1004 =back
1005
1006 =head1 SUBROUTINES
1007
1008 =over 4
1009
1010 =item process_batch_import
1011
1012 =cut
1013
1014 use List::Util qw( min );
1015 use FS::cust_bill;
1016 use FS::cust_credit_bill;
1017 sub process_batch_import {
1018   my $job = shift;
1019
1020   my $opt = { 'table'   => 'cust_credit',
1021               'params'  => [ '_date', 'credbatch' ],
1022               'formats' => { 'simple' =>
1023                                [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1024                            },
1025               'default_csv' => 1,
1026               'postinsert_callback' => sub {
1027                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1028
1029                 if ( $cust_credit->invnum ) {
1030
1031                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1032                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1033     
1034                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1035                     'crednum' => $cust_credit->crednum,
1036                     'invnum'  => $cust_bill->invnum,
1037                     'amount'  => $amount,
1038                   } );
1039                   my $error = $cust_credit_bill->insert;
1040                   return '' unless $error;
1041
1042                 }
1043
1044                 #apply_payments_and_credits ?
1045                 $cust_credit->cust_main->apply_credits;
1046
1047                 return '';
1048
1049               },
1050             };
1051
1052   FS::Record::process_batch_import( $job, $opt, @_ );
1053
1054 }
1055
1056 =back
1057
1058 =head1 BUGS
1059
1060 The delete method.  The replace method.
1061
1062 B<credited> and B<credited_sql> are now called B<unapplied> and
1063 B<unapplied_sql>.  The old method names should start to give warnings.
1064
1065 =head1 SEE ALSO
1066
1067 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1068 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1069 documentation.
1070
1071 =cut
1072
1073 1;
1074