fix invoice for cust_bill_pkg missing cust_pkg, RT#27745
[freeside.git] / FS / FS / TemplateItem_Mixin.pm
1 package FS::TemplateItem_Mixin;
2
3 use strict;
4 use vars qw( $DEBUG $me $conf $date_format );
5 use Carp;
6 use Date::Format;
7 use FS::UID;
8 use FS::Record qw( qsearch qsearchs dbh );
9 use FS::Conf;
10 use FS::part_pkg;
11 use FS::cust_pkg;
12
13 $DEBUG = 0;
14 $me = '[FS::TemplateItem_Mixin]';
15 FS::UID->install_callback( sub { 
16   $conf = new FS::Conf;
17   $date_format      = $conf->config('date_format')      || '%x'; #/YY
18 } );
19
20 =item cust_pkg
21
22 Returns the package (see L<FS::cust_pkg>) for this invoice line item.
23
24 =cut
25
26 sub cust_pkg {
27   my $self = shift;
28   carp "$me $self -> cust_pkg" if $DEBUG;
29   qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
30 }
31
32 =item part_pkg
33
34 Returns the package definition for this invoice line item.
35
36 =cut
37
38 sub part_pkg {
39   my $self = shift;
40   if ( $self->pkgpart_override ) {
41     qsearchs('part_pkg', { 'pkgpart' => $self->pkgpart_override } );
42   } else {
43     my $part_pkg;
44     my $cust_pkg = $self->cust_pkg;
45     $part_pkg = $cust_pkg->part_pkg if $cust_pkg;
46     $part_pkg;
47   }
48
49 }
50
51 =item desc LOCALE
52
53 Returns a description for this line item.  For typical line items, this is the
54 I<pkg> field of the corresponding B<FS::part_pkg> object (see L<FS::part_pkg>).
55 For one-shot line items and named taxes, it is the I<itemdesc> field of this
56 line item, and for generic taxes, simply returns "Tax".
57
58 =cut
59
60 sub desc {
61   my( $self, $locale ) = @_;
62
63   if ( $self->pkgnum > 0 ) {
64     return $self->itemdesc if $self->itemdesc;
65     my $part_pkg = $self->part_pkg or return 'UNKNOWN';
66     return $part_pkg->pkg_locale($locale);
67
68   } elsif ( $self->feepart ) {
69     return $self->part_fee->itemdesc_locale($locale);
70
71   } else { # by the process of elimination it must be a tax
72     my $desc = $self->itemdesc || 'Tax';
73     $desc .= ' '. $self->itemcomment if $self->itemcomment =~ /\S/;
74     return $desc;
75   }
76
77 }
78
79 =item time_period_pretty PART_PKG, AGENTNUM
80
81 Returns a formatted time period for this line item.
82
83 =cut
84
85 sub time_period_pretty {
86   my( $self, $part_pkg, $agentnum ) = @_;
87
88   #more efficient to look some of this conf stuff up outside the
89   # invoice/template display loop we're called from
90   # (Template_Mixin::_invoice_cust_bill_pkg) and pass them in as options
91
92   return '' if $conf->exists('disable_line_item_date_ranges')
93             || $part_pkg->option('disable_line_item_date_ranges',1)
94             || ! $self->sdate
95             || ! $self->edate;
96
97   my $date_style = '';
98   $date_style = $conf->config( 'cust_bill-line_item-date_style-non_monhtly',
99                                $agentnum
100                              )
101     if $part_pkg && $part_pkg->freq !~ /^1m?$/;
102   $date_style ||= $conf->config( 'cust_bill-line_item-date_style',
103                                   $agentnum
104                                );
105
106   my $time_period;
107   if ( defined($date_style) && $date_style eq 'month_of' ) {
108     # (now watch, someone's going to make us do Chinese)
109     $time_period = $self->mt('The month of [_1]',
110                       $self->time2str_local('%B', $self->sdate)
111                    );
112   } elsif ( defined($date_style) && $date_style eq 'X_month' ) {
113     my $desc = $conf->config( 'cust_bill-line_item-date_description',
114                                $agentnum
115                             );
116     $desc .= ' ' unless $desc =~ /\s$/;
117     $time_period = $desc. $self->time2str_local('%B', $self->sdate);
118   } else {
119     $time_period =      $self->time2str_local($date_format, $self->sdate).
120                  " - ". $self->time2str_local($date_format, $self->edate);
121   }
122
123   " ($time_period)";
124
125 }
126
127 =item details [ OPTION => VALUE ... ]
128
129 Returns an array of detail information for the invoice line item.
130
131 Currently available options are: I<format>, I<escape_function> and
132 I<format_function>.
133
134 If I<format> is set to html or latex then the array members are improved
135 for tabular appearance in those environments if possible.
136
137 If I<escape_function> is set then the array members are processed by this
138 function before being returned.
139
140 I<format_function> overrides the normal HTML or LaTeX function for returning
141 formatted CDRs.  It can be set to a subroutine which returns an empty list
142 to skip usage detail:
143
144   'format_function' => sub { () },
145
146 =cut
147
148 sub details {
149   my ( $self, %opt ) = @_;
150   my $escape_function = $opt{escape_function} || sub { shift };
151
152   my $csv = new Text::CSV_XS;
153
154   if ( $opt{format_function} ) {
155
156     #this still expects to be passed a cust_bill_pkg_detail object as the
157     #second argument, which is expensive
158     carp "deprecated format_function passed to cust_bill_pkg->details";
159     my $format_sub = $opt{format_function} if $opt{format_function};
160
161     map { ( $_->format eq 'C'
162               ? &{$format_sub}( $_->detail, $_ )
163               : &{$escape_function}( $_->detail )
164           )
165         }
166       qsearch ({ 'table'    => $self->detail_table,
167                  'hashref'  => { 'billpkgnum' => $self->billpkgnum },
168                  'order_by' => 'ORDER BY detailnum',
169               });
170
171   } elsif ( $opt{'no_usage'} ) {
172
173     my $sql = "SELECT detail FROM ". $self->detail_table.
174               "  WHERE billpkgnum = ". $self->billpkgnum.
175               "    AND ( format IS NULL OR format != 'C' ) ".
176               "  ORDER BY detailnum";
177     my $sth = dbh->prepare($sql) or die dbh->errstr;
178     $sth->execute or die $sth->errstr;
179
180     map &{$escape_function}( $_->[0] ), @{ $sth->fetchall_arrayref };
181
182   } else {
183
184     my $format_sub;
185     my $format = $opt{format} || '';
186     if ( $format eq 'html' ) {
187
188       $format_sub = sub { my $detail = shift;
189                           $csv->parse($detail) or return "can't parse $detail";
190                           join('</TD><TD>', map { &$escape_function($_) }
191                                             $csv->fields
192                               );
193                         };
194
195     } elsif ( $format eq 'latex' ) {
196
197       $format_sub = sub {
198         my $detail = shift;
199         $csv->parse($detail) or return "can't parse $detail";
200         #join(' & ', map { '\small{'. &$escape_function($_). '}' }
201         #            $csv->fields );
202         my $result = '';
203         my $column = 1;
204         foreach ($csv->fields) {
205           $result .= ' & ' if $column > 1;
206           if ($column > 6) {                     # KLUDGE ALERT!
207             $result .= '\multicolumn{1}{l}{\scriptsize{'.
208                        &$escape_function($_). '}}';
209           }else{
210             $result .= '\scriptsize{'.  &$escape_function($_). '}';
211           }
212           $column++;
213         }
214         $result;
215       };
216
217     } else {
218
219       $format_sub = sub { my $detail = shift;
220                           $csv->parse($detail) or return "can't parse $detail";
221                           join(' - ', map { &$escape_function($_) }
222                                       $csv->fields
223                               );
224                         };
225
226     }
227
228     my $sql = "SELECT format, detail FROM ". $self->detail_table.
229               "  WHERE billpkgnum = ". $self->billpkgnum.
230               "  ORDER BY detailnum";
231     my $sth = dbh->prepare($sql) or die dbh->errstr;
232     $sth->execute or die $sth->errstr;
233
234     #avoid the fetchall_arrayref and loop for less memory usage?
235
236     map { (defined($_->[0]) && $_->[0] eq 'C')
237             ? &{$format_sub}(      $_->[1] )
238             : &{$escape_function}( $_->[1] );
239         }
240       @{ $sth->fetchall_arrayref };
241
242   }
243
244 }
245
246 =item details_header [ OPTION => VALUE ... ]
247
248 Returns a list representing an invoice line item detail header, if any.
249 This relies on the behavior of voip_cdr in that it expects the header
250 to be the first CSV formatted detail (as is expected by invoice generation
251 routines).  Returns the empty list otherwise.
252
253 =cut
254
255 sub details_header {
256   my $self = shift;
257
258   my $csv = new Text::CSV_XS;
259
260   my @detail = 
261     qsearch ({ 'table'    => $self->detail_table,
262                'hashref'  => { 'billpkgnum' => $self->billpkgnum,
263                                'format'     => 'C',
264                              },
265                'order_by' => 'ORDER BY detailnum LIMIT 1',
266             });
267   return() unless scalar(@detail);
268   $csv->parse($detail[0]->detail) or return ();
269   $csv->fields;
270 }
271
272 =item quantity
273
274 =cut
275
276 sub quantity {
277   my( $self, $value ) = @_;
278   if ( defined($value) ) {
279     $self->setfield('quantity', $value);
280   }
281   $self->getfield('quantity') || 1;
282 }
283
284 =item unitsetup
285
286 =cut
287
288 sub unitsetup {
289   my( $self, $value ) = @_;
290   if ( defined($value) ) {
291     $self->setfield('unitsetup', $value);
292   }
293   $self->getfield('unitsetup') eq ''
294     ? $self->getfield('setup')
295     : $self->getfield('unitsetup');
296 }
297
298 =item unitrecur
299
300 =cut
301
302 sub unitrecur {
303   my( $self, $value ) = @_;
304   if ( defined($value) ) {
305     $self->setfield('unitrecur', $value);
306   }
307   $self->getfield('unitrecur') eq ''
308     ? $self->getfield('recur')
309     : $self->getfield('unitrecur');
310 }
311
312 =item cust_bill_pkg_display [ type => TYPE ]
313
314 Returns an array of display information for the invoice line item optionally
315 limited to 'TYPE'.
316
317 =cut
318
319 sub cust_bill_pkg_display {
320   my ( $self, %opt ) = @_;
321
322   my $class = 'FS::'. $self->display_table;
323
324   my $default = $class->new( { billpkgnum =>$self->billpkgnum } );
325
326   my $type = $opt{type} if exists $opt{type};
327   my @result;
328
329   if ( $self->get('display') ) {
330     @result = grep { defined($type) ? ($type eq $_->type) : 1 }
331               @{ $self->get('display') };
332   } else {
333     my $hashref = { 'billpkgnum' => $self->billpkgnum };
334     $hashref->{type} = $type if defined($type);
335
336     my $order_by = $self->display_table_orderby || 'billpkgdisplaynum';
337     
338     @result = qsearch ({ 'table'    => $self->display_table,
339                          'hashref'  => $hashref,
340                          'order_by' => "ORDER BY $order_by",
341                       });
342   }
343
344   push @result, $default unless ( scalar(@result) || $type );
345
346   @result;
347
348 }
349
350 =item cust_bill_pkg_detail [ CLASSNUM ]
351
352 Returns the list of associated cust_bill_pkg_detail objects
353 The optional CLASSNUM argument will limit the details to the specified usage
354 class.
355
356 =cut
357
358 sub cust_bill_pkg_detail {
359   my $self = shift;
360   my $classnum = shift || '';
361
362   my %hash = ( 'billpkgnum' => $self->billpkgnum );
363   $hash{classnum} = $classnum if $classnum;
364
365   qsearch( $self->detail_table, \%hash ),
366
367 }
368
369 =item cust_bill_pkg_discount 
370
371 Returns the list of associated cust_bill_pkg_discount objects.
372
373 =cut
374
375 sub cust_bill_pkg_discount {
376   my $self = shift;
377   qsearch( $self->discount_table, { 'billpkgnum' => $self->billpkgnum } );
378 }
379
380 1;