Ticket #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->config('invoice_from_name', $self->cust_main->agentnum) ?
286                    $conf->config('invoice_from_name', $self->cust_main->agentnum) . ' <' .
287                    $conf->config('invoice_from', $self->cust_main->agentnum) . '>' :
288                    $conf->config('invoice_from', $self->cust_main->agentnum),
289                                  #invoice_from??? well as good as any
290       'to'      => $conf->config('deletecredits'),
291       'subject' => 'FREESIDE NOTIFICATION: Credit deleted',
292       'body'    => [
293         "This is an automatic message from your Freeside installation\n",
294         "informing you that the following credit has been deleted:\n",
295         "\n",
296         'crednum: '. $self->crednum. "\n",
297         'custnum: '. $self->custnum.
298           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
299         'amount: $'. sprintf("%.2f", $self->amount). "\n",
300         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
301         'reason: '. $self->reason. "\n",
302       ],
303     );
304
305     if ( $error ) {
306       $dbh->rollback if $oldAutoCommit;
307       return "can't send credit deletion notification: $error";
308     }
309
310   }
311
312   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
313
314   '';
315
316 }
317
318 =item replace [ OLD_RECORD ]
319
320 You can, but probably shouldn't modify credits... 
321
322 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
323 supplied, replaces this record.  If there is an error, returns the error,
324 otherwise returns false.
325
326 =cut
327
328 sub replace {
329   my $self = shift;
330   return "Can't modify closed credit" if $self->closed =~ /^Y/i;
331   $self->SUPER::replace(@_);
332 }
333
334 =item check
335
336 Checks all fields to make sure this is a valid credit.  If there is an error,
337 returns the error, otherwise returns false.  Called by the insert and replace
338 methods.
339
340 =cut
341
342 sub check {
343   my $self = shift;
344
345   $self->usernum($FS::CurrentUser::CurrentUser->usernum) unless $self->usernum;
346
347   my $error =
348     $self->ut_numbern('crednum')
349     || $self->ut_number('custnum')
350     || $self->ut_numbern('_date')
351     || $self->ut_money('amount')
352     || $self->ut_alphan('otaker')
353     || $self->ut_textn('reason')
354     || $self->ut_textn('addlinfo')
355     || $self->ut_enum('closed', [ '', 'Y' ])
356     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
357     || $self->ut_foreign_keyn('eventnum', 'cust_event', 'eventnum')
358     || $self->ut_foreign_keyn('commission_agentnum',  'agent', 'agentnum')
359     || $self->ut_foreign_keyn('commission_salesnum',  'sales', 'salesnum')
360     || $self->ut_foreign_keyn('commission_pkgnum', 'cust_pkg', 'pkgnum')
361   ;
362   return $error if $error;
363
364   my $method = $ignore_empty_reasonnum ? 'ut_foreign_keyn' : 'ut_foreign_key';
365   $error = $self->$method('reasonnum', 'reason', 'reasonnum');
366   return $error if $error;
367
368   return "amount must be > 0 " if $self->amount <= 0;
369
370   return "amount must be greater or equal to amount applied"
371     if $self->unapplied < 0 && ! $otaker_upgrade_kludge;
372
373   return "Unknown customer"
374     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
375
376   $self->_date(time) unless $self->_date;
377
378   $self->SUPER::check;
379 }
380
381 =item void [ REASON ]
382
383 Voids this credit: deletes the credit and all associated applications and 
384 adds a record of the voided credit to the cust_credit_void table.
385
386 =cut
387
388 # yes, false laziness with cust_pay and cust_bill
389 # but frankly I don't have time to fix it now
390
391 sub void {
392   my $self = shift;
393   my $reason = shift;
394
395   local $SIG{HUP} = 'IGNORE';
396   local $SIG{INT} = 'IGNORE';
397   local $SIG{QUIT} = 'IGNORE';
398   local $SIG{TERM} = 'IGNORE';
399   local $SIG{TSTP} = 'IGNORE';
400   local $SIG{PIPE} = 'IGNORE';
401
402   my $oldAutoCommit = $FS::UID::AutoCommit;
403   local $FS::UID::AutoCommit = 0;
404   my $dbh = dbh;
405
406   my $cust_credit_void = new FS::cust_credit_void ( {
407       map { $_ => $self->get($_) } $self->fields
408     } );
409   $cust_credit_void->set('void_reason', $reason);
410   my $error = $cust_credit_void->insert;
411   if ( $error ) {
412     $dbh->rollback if $oldAutoCommit;
413     return $error;
414   }
415
416   $error = $self->delete(void => 1); # suppress deletecredits warning
417   if ( $error ) {
418     $dbh->rollback if $oldAutoCommit;
419     return $error;
420   }
421
422   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
423
424   '';
425
426 }
427
428 =item cust_credit_refund
429
430 Returns all refund applications (see L<FS::cust_credit_refund>) for this credit.
431
432 =cut
433
434 sub cust_credit_refund {
435   my $self = shift;
436   map { $_ } #return $self->num_cust_credit_refund unless wantarray;
437   sort { $a->_date <=> $b->_date }
438     qsearch( 'cust_credit_refund', { 'crednum' => $self->crednum } )
439   ;
440 }
441
442 =item cust_credit_bill
443
444 Returns all application to invoices (see L<FS::cust_credit_bill>) for this
445 credit.
446
447 =cut
448
449 sub cust_credit_bill {
450   my $self = shift;
451   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
452   sort { $a->_date <=> $b->_date }
453     qsearch( 'cust_credit_bill', { 'crednum' => $self->crednum } )
454   ;
455 }
456
457 =item unapplied
458
459 Returns the amount of this credit that is still unapplied/outstanding; 
460 amount minus all refund applications (see L<FS::cust_credit_refund>) and
461 applications to invoices (see L<FS::cust_credit_bill>).
462
463 =cut
464
465 sub unapplied {
466   my $self = shift;
467   my $amount = $self->amount;
468   $amount -= $_->amount foreach ( $self->cust_credit_refund );
469   $amount -= $_->amount foreach ( $self->cust_credit_bill );
470   sprintf( "%.2f", $amount );
471 }
472
473 =item credited
474
475 Deprecated name for the unapplied method.
476
477 =cut
478
479 sub credited {
480   my $self = shift;
481   #carp "cust_credit->credited deprecated; use ->unapplied";
482   $self->unapplied(@_);
483 }
484
485 =item cust_main
486
487 Returns the customer (see L<FS::cust_main>) for this credit.
488
489 =cut
490
491 # _upgrade_data
492 #
493 # Used by FS::Upgrade to migrate to a new database.
494
495 sub _upgrade_data {  # class method
496   my ($class, %opts) = @_;
497
498   warn "$me upgrading $class\n" if $DEBUG;
499
500   $class->_upgrade_reasonnum(%opts);
501
502   if (defined dbdef->table($class->table)->column('reason')) {
503
504     warn "$me Ensuring existance of auto reasons\n" if $DEBUG;
505
506     foreach ( keys %reasontype_map ) {
507       unless ($conf->config($_)) {       # hmmmm
508 #       warn "$me Found $_ reason type lacking\n" if $DEBUG;
509 #       my $hashref = { 'class' => 'R', 'type' => $reasontype_map{$_} };
510         my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
511         my $reason_type = qsearchs( 'reason_type', $hashref );
512         unless ($reason_type) {
513           $reason_type  = new FS::reason_type( $hashref );
514           my $error   = $reason_type->insert();
515           die "$class had error inserting FS::reason_type into database: $error\n"
516             if $error;
517         }
518         $conf->set($_, $reason_type->typenum);
519       }
520     }
521
522     warn "$me Ensuring commission packages have a reason type\n" if $DEBUG;
523
524     my $hashref = { 'class' => 'R', 'type' => 'Legacy' };
525     my $reason_type = qsearchs( 'reason_type', $hashref );
526     unless ($reason_type) {
527       $reason_type  = new FS::reason_type( $hashref );
528       my $error   = $reason_type->insert();
529       die "$class had error inserting FS::reason_type into database: $error\n"
530         if $error;
531     }
532
533     my @plans = qw( flat_comission flat_comission_cust flat_comission_pkg );
534     foreach my $plan ( @plans ) {
535       foreach my $pkg ( qsearch('part_pkg', { 'plan' => $plan } ) ) {
536         unless ($pkg->option('reason_type', 1) ) { 
537           my $plandata = $pkg->plandata.
538                         "reason_type=". $reason_type->typenum. "\n";
539           $pkg->plandata($plandata);
540           my $error =
541             $pkg->replace( undef,
542                            'pkg_svc' => { map { $_->svcpart => $_->quantity }
543                                           $pkg->pkg_svc
544                                         },
545                            'primary_svc' => $pkg->svcpart,
546                          );
547             die "failed setting reason_type option: $error"
548               if $error;
549         }
550       }
551     }
552   }
553
554   local($otaker_upgrade_kludge) = 1;
555   local($ignore_empty_reasonnum) = 1;
556   $class->_upgrade_otaker(%opts);
557
558   if ( !FS::upgrade_journal->is_done('cust_credit__tax_link')
559       and !$conf->exists('enable_taxproducts') ) {
560     # RT#25458: fix credit line item applications that should refer to a 
561     # specific tax allocation
562     my @cust_credit_bill_pkg = qsearch({
563         table     => 'cust_credit_bill_pkg',
564         select    => 'cust_credit_bill_pkg.*',
565         addl_from => ' LEFT JOIN cust_bill_pkg USING (billpkgnum)',
566         extra_sql =>
567           'WHERE cust_credit_bill_pkg.billpkgtaxlocationnum IS NULL '.
568           'AND cust_bill_pkg.pkgnum = 0', # is a tax
569     });
570     my %tax_items;
571     my %credits;
572     foreach (@cust_credit_bill_pkg) {
573       my $billpkgnum = $_->billpkgnum;
574       $tax_items{$billpkgnum} ||= FS::cust_bill_pkg->by_key($billpkgnum);
575       $credits{$billpkgnum} ||= [];
576       push @{ $credits{$billpkgnum} }, $_;
577     }
578     TAX_ITEM: foreach my $tax_item (values %tax_items) {
579       my $billpkgnum = $tax_item->billpkgnum;
580       # get all pkg/location/taxrate allocations of this tax line item
581       my @allocations = sort {$b->amount <=> $a->amount}
582                         qsearch('cust_bill_pkg_tax_location', {
583                             billpkgnum => $billpkgnum
584                         });
585       # and these are all credit applications to it
586       my @credits = sort {$b->amount <=> $a->amount}
587                     @{ $credits{$billpkgnum} };
588       my $c = shift @credits;
589       my $a = shift @allocations; # we will NOT modify these
590       while ($c and $a) {
591         if ( abs($c->amount - $a->amount) < 0.005 ) {
592           # by far the most common case: the tax line item is for a single
593           # tax, so we just fill in the billpkgtaxlocationnum
594           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
595           my $error = $c->replace;
596           if ($error) {
597             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
598             next TAX_ITEM;
599           }
600           $c = shift @credits;
601           $a = shift @allocations;
602         } elsif ( $c->amount > $a->amount ) {
603           # fairly common: the tax line contains tax for multiple packages
604           # (or multiple taxes) but the credit isn't divided up
605           my $new_link = FS::cust_credit_bill_pkg->new({
606               creditbillnum         => $c->creditbillnum,
607               billpkgnum            => $c->billpkgnum,
608               billpkgtaxlocationnum => $a->billpkgtaxlocationnum,
609               amount                => $a->amount,
610               setuprecur            => 'setup',
611           });
612           my $error = $new_link->insert;
613           if ($error) {
614             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
615             next TAX_ITEM;
616           }
617           $c->set(amount => sprintf('%.2f', $c->amount - $a->amount));
618           $a = shift @allocations;
619         } elsif ( $c->amount < 0.005 ) {
620           # also fairly common; we can delete these with no harm
621           my $error = $c->delete;
622           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
623           $c = shift @credits;
624         } elsif ( $c->amount < $a->amount ) {
625           # should never happen, but if it does, handle it gracefully
626           $c->set('billpkgtaxlocationnum', $a->billpkgtaxlocationnum);
627           my $error = $c->replace;
628           if ($error) {
629             warn "error fixing credit application to tax item #$billpkgnum:\n$error\n";
630             next TAX_ITEM;
631           }
632           $a->set(amount => $a->amount - $c->amount);
633           $c = shift @credits;
634         }
635       } # while $c and $a
636       if ( $c ) {
637         if ( $c->amount < 0.005 ) {
638           my $error = $c->delete;
639           warn "error removing zero-amount credit application (probably harmless):\n$error\n" if $error;
640         } elsif ( $c->modified ) {
641           # then we've allocated part of it, so reduce the nonspecific 
642           # application by that much
643           my $error = $c->replace;
644           warn "error fixing credit application to tax item #$billpkgnum:\n$error\n" if $error;
645         }
646         # else there are probably no allocations, i.e. this is a pre-3.x 
647         # record that was never migrated over, so leave it alone
648       } # if $c
649     } # foreach $tax_item
650     FS::upgrade_journal->set_done('cust_credit__tax_link');
651   }
652 }
653
654 =back
655
656 =head1 CLASS METHODS
657
658 =over 4
659
660 =item unapplied_sql
661
662 Returns an SQL fragment to retreive the unapplied amount.
663
664 =cut
665
666 sub unapplied_sql {
667   my ($class, $start, $end) = @_;
668
669   my $bill_start   = $start ? "AND cust_credit_bill._date <= $start"   : '';
670   my $bill_end     = $end   ? "AND cust_credit_bill._date > $end"     : '';
671   my $refund_start = $start ? "AND cust_credit_refund._date <= $start" : '';
672   my $refund_end   = $end   ? "AND cust_credit_refund._date > $end"   : '';
673
674   "amount
675         - COALESCE(
676                     ( SELECT SUM(amount) FROM cust_credit_refund
677                         WHERE cust_credit.crednum = cust_credit_refund.crednum
678                         $refund_start $refund_end )
679                     ,0
680                   )
681         - COALESCE(
682                     ( SELECT SUM(amount) FROM cust_credit_bill
683                         WHERE cust_credit.crednum = cust_credit_bill.crednum
684                         $bill_start $bill_end )
685                     ,0
686                   )
687   ";
688
689 }
690
691 =item credited_sql
692
693 Deprecated name for the unapplied_sql method.
694
695 =cut
696
697 sub credited_sql {
698   #my $class = shift;
699
700   #carp "cust_credit->credited_sql deprecated; use ->unapplied_sql";
701
702   #$class->unapplied_sql(@_);
703   unapplied_sql();
704 }
705
706 =item credit_lineitems
707
708 Example:
709
710   my $error = FS::cust_credit->credit_lineitems(
711
712     #the lineitems to credit
713     'billpkgnums'       => \@billpkgnums,
714     'setuprecurs'       => \@setuprecurs,
715     'amounts'           => \@amounts,
716     'apply'             => 1, #0 leaves the credit unapplied
717
718     #the credit
719     map { $_ => scalar($cgi->param($_)) }
720       #fields('cust_credit')  
721       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
722
723   );
724
725 =cut
726
727 #maybe i should just be an insert with extra args instead of a class method
728 sub credit_lineitems {
729   my( $class, %arg ) = @_;
730   my $curuser = $FS::CurrentUser::CurrentUser;
731
732   #some false laziness w/misc/xmlhttp-cust_bill_pkg-calculate_taxes.html
733
734   my $cust_main = qsearchs({
735     'table'     => 'cust_main',
736     'hashref'   => { 'custnum' => $arg{custnum} },
737     'extra_sql' => ' AND '. $curuser->agentnums_sql,
738   }) or return 'unknown customer';
739
740
741   local $SIG{HUP} = 'IGNORE';
742   local $SIG{INT} = 'IGNORE';
743   local $SIG{QUIT} = 'IGNORE';
744   local $SIG{TERM} = 'IGNORE';
745   local $SIG{TSTP} = 'IGNORE';
746   local $SIG{PIPE} = 'IGNORE';
747
748   my $oldAutoCommit = $FS::UID::AutoCommit;
749   local $FS::UID::AutoCommit = 0;
750   my $dbh = dbh;
751
752   #my @cust_bill_pkg = qsearch({
753   #  'select'    => 'cust_bill_pkg.*',
754   #  'table'     => 'cust_bill_pkg',
755   #  'addl_from' => ' LEFT JOIN cust_bill USING (invnum)  '.
756   #                 ' LEFT JOIN cust_main USING (custnum) ',
757   #  'extra_sql' => ' WHERE custnum = $custnum AND billpkgnum IN ('.
758   #                     join( ',', @{$arg{billpkgnums}} ). ')',
759   #  'order_by'  => 'ORDER BY invnum ASC, billpkgnum ASC',
760   #});
761
762   my $error = '';
763
764   my $cust_credit = new FS::cust_credit ( {
765     map { $_ => $arg{$_} }
766       #fields('cust_credit')
767       qw( custnum _date amount reasonnum addlinfo ), #pkgnum eventnum
768   } );
769   $error = $cust_credit->insert;
770   if ( $error ) {
771     $dbh->rollback if $oldAutoCommit;
772     return "Error inserting credit: $error";
773   }
774
775   unless ( $arg{'apply'} ) {
776     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
777     return '';
778   }
779
780   #my $subtotal = 0;
781   # keys in all of these are invoice numbers
782   my %cust_credit_bill = ();
783   my %cust_bill_pkg = ();
784   my %cust_credit_bill_pkg = ();
785   my %taxlisthash = ();
786   my %unapplied_payments = (); #invoice numbers, and then billpaynums
787   foreach my $billpkgnum ( @{$arg{billpkgnums}} ) {
788     my $setuprecur = shift @{$arg{setuprecurs}};
789     my $amount = shift @{$arg{amounts}};
790
791     my $cust_bill_pkg = qsearchs({
792       'table'     => 'cust_bill_pkg',
793       'hashref'   => { 'billpkgnum' => $billpkgnum },
794       'addl_from' => 'LEFT JOIN cust_bill USING (invnum)',
795       'extra_sql' => 'AND custnum = '. $cust_main->custnum,
796     }) or die "unknown billpkgnum $billpkgnum";
797   
798     my $invnum = $cust_bill_pkg->invnum;
799
800     if ( $setuprecur eq 'setup' ) {
801       $cust_bill_pkg->setup($amount);
802       $cust_bill_pkg->recur(0);
803       $cust_bill_pkg->unitrecur(0);
804       $cust_bill_pkg->type('');
805     } else {
806       $setuprecur = 'recur'; #in case its a usage classnum?
807       $cust_bill_pkg->recur($amount);
808       $cust_bill_pkg->setup(0);
809       $cust_bill_pkg->unitsetup(0);
810     }
811
812     push @{$cust_bill_pkg{$invnum}}, $cust_bill_pkg;
813
814     #unapply any payments applied to this line item (other credits too?)
815     foreach my $cust_bill_pay_pkg ( $cust_bill_pkg->cust_bill_pay_pkg($setuprecur) ) {
816       $error = $cust_bill_pay_pkg->delete;
817       if ( $error ) {
818         $dbh->rollback if $oldAutoCommit;
819         return "Error unapplying payment: $error";
820       }
821       $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
822         += $cust_bill_pay_pkg->amount;
823     }
824
825     #$subtotal += $amount;
826     $cust_credit_bill{$invnum} += $amount;
827     push @{ $cust_credit_bill_pkg{$invnum} },
828       new FS::cust_credit_bill_pkg {
829         'billpkgnum' => $cust_bill_pkg->billpkgnum,
830         'amount'     => sprintf('%.2f',$amount),
831         'setuprecur' => $setuprecur,
832         'sdate'      => $cust_bill_pkg->sdate,
833         'edate'      => $cust_bill_pkg->edate,
834       };
835
836     # recalculate taxes with new amounts
837     $taxlisthash{$invnum} ||= {};
838     if ( $cust_bill_pkg->pkgnum or $cust_bill_pkg->feepart ) {
839       $cust_main->_handle_taxes( $taxlisthash{$invnum}, $cust_bill_pkg );
840     } # otherwise the item itself is a tax, and assume the caller knows
841       # what they're doing
842   }
843
844   ###
845   # now loop through %cust_credit_bill and insert those
846   ###
847
848   # (hack to prevent cust_credit_bill_pkg insertion)
849   local($FS::cust_bill_ApplicationCommon::skip_apply_to_lineitems_hack) = 1;
850
851   foreach my $invnum ( sort { $a <=> $b } keys %cust_credit_bill ) {
852
853     my $arrayref_or_error =
854       $cust_main->calculate_taxes(
855         $cust_bill_pkg{$invnum}, # list of taxable items that we're crediting
856         $taxlisthash{$invnum},   # list of tax-item bindings
857         $cust_bill_pkg{$invnum}->[0]->cust_bill->_date, # invoice time
858       );
859
860     unless ( ref( $arrayref_or_error ) ) {
861       $dbh->rollback if $oldAutoCommit;
862       return "Error calculating taxes: $arrayref_or_error";
863     }
864     
865     my %tax_links; # {tax billpkgnum}{nontax billpkgnum}
866
867     #taxes
868     foreach my $cust_bill_pkg ( @{ $cust_bill_pkg{$invnum} } ) {
869       my $billpkgnum = $cust_bill_pkg->billpkgnum;
870       my %hash = ( 'taxable_billpkgnum' => $billpkgnum );
871       # gather up existing tax links (we need their billpkgtaxlocationnums)
872       my @tax_links = qsearch('cust_bill_pkg_tax_location', \%hash),
873                       qsearch('cust_bill_pkg_tax_rate_location', \%hash);
874
875       foreach ( @tax_links ) {
876         $tax_links{$_->billpkgnum} ||= {};
877         $tax_links{$_->billpkgnum}{$_->taxable_billpkgnum} = $_;
878       }
879     }
880
881     foreach my $taxline ( @$arrayref_or_error ) {
882
883       my $amount = $taxline->setup;
884
885       # find equivalent tax line item on the existing invoice
886       my $tax_item = qsearchs('cust_bill_pkg', {
887           'invnum'    => $invnum,
888           'pkgnum'    => 0,
889           'itemdesc'  => $taxline->desc,
890       });
891       if (!$tax_item) {
892         # or should we just exit if this happens?
893         $cust_credit->set('amount', 
894           sprintf('%.2f', $cust_credit->get('amount') - $amount)
895         );
896         my $error = $cust_credit->replace;
897         if ( $error ) {
898           $dbh->rollback if $oldAutoCommit;
899           return "error correcting credit for missing tax line: $error";
900         }
901       }
902
903       # but in the new era, we no longer have the problem of uniquely
904       # identifying the tax_Xlocation record.  The billpkgnums of the 
905       # tax and the taxed item are known.
906       foreach my $new_loc
907         ( @{ $taxline->get('cust_bill_pkg_tax_location') },
908           @{ $taxline->get('cust_bill_pkg_tax_rate_location') } )
909       {
910         # the existing tax_Xlocation object
911         my $old_loc =
912           $tax_links{$tax_item->billpkgnum}{$new_loc->taxable_cust_bill_pkg->billpkgnum};
913
914         next if !$old_loc; # apply the leftover amount nonspecifically
915
916         #support partial credits: use $amount if smaller
917         # (so just distribute to the first location?   perhaps should
918         #  do so evenly...)
919         my $loc_amount = min( $amount, $new_loc->amount);
920
921         $amount -= $loc_amount;
922
923         $cust_credit_bill{$invnum} += $loc_amount;
924         push @{ $cust_credit_bill_pkg{$invnum} },
925           new FS::cust_credit_bill_pkg {
926             'billpkgnum'                => $tax_item->billpkgnum,
927             'amount'                    => $loc_amount,
928             'setuprecur'                => 'setup',
929             'billpkgtaxlocationnum'     => $old_loc->billpkgtaxlocationnum,
930             'billpkgtaxratelocationnum' => $old_loc->billpkgtaxratelocationnum,
931           };
932
933       } #foreach my $new_loc
934
935       # we still have to deal with the possibility that the tax links don't
936       # cover the whole amount of tax because of an incomplete upgrade...
937       if ($amount > 0.005) {
938         $cust_credit_bill{$invnum} += $amount;
939         push @{ $cust_credit_bill_pkg{$invnum} },
940           new FS::cust_credit_bill_pkg {
941             'billpkgnum' => $tax_item->billpkgnum,
942             'amount'     => sprintf('%.2f', $amount),
943             'setuprecur' => 'setup',
944           };
945
946       } # if $amount > 0
947
948       #unapply any payments applied to the tax
949       foreach my $cust_bill_pay_pkg
950         ( $tax_item->cust_bill_pay_pkg('setup') )
951       {
952         $error = $cust_bill_pay_pkg->delete;
953         if ( $error ) {
954           $dbh->rollback if $oldAutoCommit;
955           return "Error unapplying payment: $error";
956         }
957         $unapplied_payments{$invnum}{$cust_bill_pay_pkg->billpaynum}
958           += $cust_bill_pay_pkg->amount;
959       }
960     } #foreach $taxline
961
962     # if we unapplied any payments from line items, also unapply that 
963     # amount from the invoice
964     foreach my $billpaynum (keys %{$unapplied_payments{$invnum}}) {
965       my $cust_bill_pay = FS::cust_bill_pay->by_key($billpaynum)
966         or die "broken payment application $billpaynum";
967       my @subapps = $cust_bill_pay->lineitem_applications;
968       $error = $cust_bill_pay->delete; # can't replace
969
970       my $new_cust_bill_pay = FS::cust_bill_pay->new({
971           $cust_bill_pay->hash,
972           billpaynum => '',
973           amount => sprintf('%.2f', 
974               $cust_bill_pay->amount 
975               - $unapplied_payments{$invnum}{$billpaynum}),
976       });
977
978       if ( $new_cust_bill_pay->amount > 0 ) {
979         $error ||= $new_cust_bill_pay->insert;
980         # Also reapply it to everything it was applied to before.
981         # Note that we've already deleted cust_bill_pay_pkg records for the
982         # items we're crediting, so they aren't on this list.
983         foreach my $cust_bill_pay_pkg (@subapps) {
984           $cust_bill_pay_pkg->billpaypkgnum('');
985           $cust_bill_pay_pkg->billpaynum($new_cust_bill_pay->billpaynum);
986           $error ||= $cust_bill_pay_pkg->insert;
987         }
988       }
989       if ( $error ) {
990         $dbh->rollback if $oldAutoCommit;
991         return "Error unapplying payment: $error";
992       }
993     }
994     #insert cust_credit_bill
995
996     my $cust_credit_bill = new FS::cust_credit_bill {
997       'crednum' => $cust_credit->crednum,
998       'invnum'  => $invnum,
999       'amount'  => sprintf('%.2f', $cust_credit_bill{$invnum}),
1000     };
1001     $error = $cust_credit_bill->insert;
1002     if ( $error ) {
1003       $dbh->rollback if $oldAutoCommit;
1004       return "Error applying credit of $cust_credit_bill{$invnum} ".
1005              " to invoice $invnum: $error";
1006     }
1007
1008     #and then insert cust_credit_bill_pkg for each cust_bill_pkg
1009     foreach my $cust_credit_bill_pkg ( @{$cust_credit_bill_pkg{$invnum}} ) {
1010       $cust_credit_bill_pkg->creditbillnum( $cust_credit_bill->creditbillnum );
1011       $error = $cust_credit_bill_pkg->insert;
1012       if ( $error ) {
1013         $dbh->rollback if $oldAutoCommit;
1014         return "Error applying credit to line item: $error";
1015       }
1016     }
1017
1018   }
1019
1020   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1021   '';
1022
1023 }
1024
1025 =back
1026
1027 =head1 SUBROUTINES
1028
1029 =over 4
1030
1031 =item process_batch_import
1032
1033 =cut
1034
1035 use List::Util qw( min );
1036 use FS::cust_bill;
1037 use FS::cust_credit_bill;
1038 sub process_batch_import {
1039   my $job = shift;
1040
1041   my $opt = { 'table'   => 'cust_credit',
1042               'params'  => [ '_date', 'credbatch' ],
1043               'formats' => { 'simple' =>
1044                                [ 'custnum', 'amount', 'reasonnum', 'invnum' ],
1045                            },
1046               'default_csv' => 1,
1047               'postinsert_callback' => sub {
1048                 my $cust_credit = shift; #my ($cust_credit, $param ) = @_;
1049
1050                 if ( $cust_credit->invnum ) {
1051
1052                   my $cust_bill = qsearchs('cust_bill', { invnum=>$cust_credit->invnum } );
1053                   my $amount = min( $cust_credit->credited, $cust_bill->owed );
1054     
1055                   my $cust_credit_bill = new FS::cust_credit_bill ( {
1056                     'crednum' => $cust_credit->crednum,
1057                     'invnum'  => $cust_bill->invnum,
1058                     'amount'  => $amount,
1059                   } );
1060                   my $error = $cust_credit_bill->insert;
1061                   return '' unless $error;
1062
1063                 }
1064
1065                 #apply_payments_and_credits ?
1066                 $cust_credit->cust_main->apply_credits;
1067
1068                 return '';
1069
1070               },
1071             };
1072
1073   FS::Record::process_batch_import( $job, $opt, @_ );
1074
1075 }
1076
1077 =back
1078
1079 =head1 BUGS
1080
1081 The delete method.  The replace method.
1082
1083 B<credited> and B<credited_sql> are now called B<unapplied> and
1084 B<unapplied_sql>.  The old method names should start to give warnings.
1085
1086 =head1 SEE ALSO
1087
1088 L<FS::Record>, L<FS::cust_credit_refund>, L<FS::cust_refund>,
1089 L<FS::cust_credit_bill> L<FS::cust_bill>, schema.html from the base
1090 documentation.
1091
1092 =cut
1093
1094 1;
1095