fix discounts vs. quantities for prorate packages, RT#23530
[freeside.git] / FS / FS / part_pkg / cdr_termination.pm
1 package FS::part_pkg::cdr_termination;
2
3 use strict;
4 use base qw( FS::part_pkg::recur_Common );
5 use vars qw( $DEBUG %info );
6 use Tie::IxHash;
7 use FS::Record qw( qsearch ); #qsearchs );
8 use FS::cdr;
9 use FS::cdr_termination;
10
11 tie my %temporalities, 'Tie::IxHash',
12   'upcoming'  => "Upcoming (future)",
13   'preceding' => "Preceding (past)",
14 ;
15
16 %info = (
17   'name' => 'VoIP rating of CDR records for termination partners.',
18   'shortname' => 'VoIP/telco CDR termination',
19   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
20   'fields' => {
21     #'cdr_column'    => { 'name' => 'Column from CDR records',
22     #                     'type' => 'select',
23     #                     'select_enum' => [qw(
24     #                       dcontext
25     #                       channel
26     #                       dstchannel
27     #                       lastapp
28     #                       lastdata
29     #                       accountcode
30     #                       userfield
31     #                       cdrtypenum
32     #                       calltypenum
33     #                       description
34     #                       carrierid
35     #                       upstream_rateid
36     #                     )],
37     #                   },
38
39     #false laziness w/flat.pm
40     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
41                              'type' => 'select',
42                              'select_options' => \%temporalities,
43                            },
44
45     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
46                                    'subscription',
47                          'default' => '1',
48                        },
49     'recur_method'  => { 'name' => 'Recurring fee method',
50                          #'type' => 'radio',
51                          #'options' => \%recur_method,
52                          'type' => 'select',
53                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
54                        },
55
56     #false laziness w/voip_cdr.pm
57     'output_format' => { 'name' => 'CDR invoice display format',
58                          'type' => 'select',
59                          'select_options' => { FS::cdr::invoice_formats() },
60                          'default'        => 'simple2', #XXX test
61                        },
62
63     'usage_section' => { 'name' => 'Section in which to place separate usage charges',
64                        },
65
66     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
67                           'type' => 'checkbox',
68                         },
69
70     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
71                           'type' => 'checkbox',
72                        },
73     #eofalse
74
75   },
76                        #cdr_column
77   'fieldorder' => [qw( recur_temporality recur_method cutoff_day ),
78                        FS::part_pkg::prorate_Mixin::fieldorder, 
79                        qw(
80                        output_format usage_section summarize_usage usage_mandate
81                      )
82                   ],
83
84   'weight' => 48,
85
86 );
87
88 sub calc_recur {
89   my $self = shift;
90   my($cust_pkg, $sdate, $details, $param ) = @_;
91
92   #my $last_bill = $cust_pkg->last_bill;
93   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
94
95   return 0
96     if $self->recur_temporality eq 'preceding'
97     && ( $last_bill eq '' || $last_bill == 0 );
98
99   # termination calculations
100
101   my $term_percent = $cust_pkg->cust_main->cdr_termination_percentage;
102   die "no customer termination percentage" unless $term_percent;
103
104   my $output_format = $self->option('output_format', 'Hush!') || 'simple2';
105
106   my $charges = 0;
107
108   #find an svc_external record
109   my @svc_external = map  { $_->svc_x }
110                      grep { $_->part_svc->svcdb eq 'svc_external' }
111                      $cust_pkg->cust_svc;
112
113   die "cdr_termination package has no svc_external service"
114     unless @svc_external;
115   die "cdr_termination package has multiple svc_external services"
116     if scalar(@svc_external) > 1;
117
118   my $svc_external = $svc_external[0];
119
120   # find CDRs:
121   # - matching our customer via svc_external.id/title?  (and via what field?)
122
123   #let's try carrierid for now, can always make it configurable or rewrite
124   my $cdr_column = 'carrierid';
125
126   my %hashref = ( 'freesidestatus' => 'done' );
127
128   # try matching on svc_external.id for now... (or title?  if ints don't cut it)
129   $hashref{$cdr_column} = $svc_external[0]->id; 
130
131   # - with no cdr_termination.status
132
133   my $termpart = 1; #or from an option
134
135   #false lazienss w/search/cdr.html (i should be a part_termination method)
136   my $where_term =
137     "( cdr.acctid = cdr_termination.acctid AND termpart = $termpart ) ";
138   #my $join_term = "LEFT JOIN cdr_termination ON ( $where_term )";
139   my $extra_sql =
140     "AND NOT EXISTS ( SELECT 1 FROM cdr_termination WHERE $where_term )";
141
142   #may need to process in batches if there's waaay too many
143   my @cdrs = qsearch({
144     'table'     => 'cdr',
145     #'addl_from' => $join_term,
146     'hashref'   => \%hashref,
147     'extra_sql' => "$extra_sql FOR UPDATE",
148   });
149
150   foreach my $cdr (@cdrs) {
151
152     #add a cdr_termination record and the charges
153
154     # XXX config?
155     #my $term_price = sprintf('%.2f', $cdr->rated_price * $term_percent / 100 );
156     my $term_price = sprintf('%.4f', $cdr->rated_price * $term_percent / 100 );
157
158     my $cdr_termination = new FS::cdr_termination {
159       'acctid'      => $cdr->acctid,
160       'termpart'    => $termpart,
161       'rated_price' => $term_price,
162       'status'      => 'done',
163     };
164
165     my $error = $cdr_termination->insert;
166     die $error if $error; #next if $error; #or just skip this one???  why?
167
168     $charges += $term_price;
169
170     # and add a line to the invoice
171
172     my $call_details = $cdr->downstream_csv( 'format' => $output_format,
173                                              'charge' => $term_price,
174                                            );
175
176     my $classnum = ''; #usage class?
177
178     #option to turn off?  or just use squelch_cdr for the customer probably
179     push @$details, [ 'C', $call_details, $term_price, $classnum ];
180
181   }
182     
183   # eotermiation calculation
184
185   $charges += ($cust_pkg->quantity || 1) * $self->calc_recur_Common(@_);
186
187   $charges;
188 }
189
190 sub is_free {
191   0;
192 }
193
194 1;