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