improve CDR usage presentation
[freeside.git] / FS / FS / cust_bill_pkg.pm
1 package FS::cust_bill_pkg;
2
3 use strict;
4 use vars qw( @ISA );
5 use FS::Record qw( qsearch qsearchs dbdef dbh );
6 use FS::cust_main_Mixin;
7 use FS::cust_pkg;
8 use FS::part_pkg;
9 use FS::cust_bill;
10 use FS::cust_bill_pkg_detail;
11 use FS::cust_bill_pay_pkg;
12 use FS::cust_credit_bill_pkg;
13
14 @ISA = qw( FS::cust_main_Mixin FS::Record );
15
16 =head1 NAME
17
18 FS::cust_bill_pkg - Object methods for cust_bill_pkg records
19
20 =head1 SYNOPSIS
21
22   use FS::cust_bill_pkg;
23
24   $record = new FS::cust_bill_pkg \%hash;
25   $record = new FS::cust_bill_pkg { 'column' => 'value' };
26
27   $error = $record->insert;
28
29   $error = $new_record->replace($old_record);
30
31   $error = $record->delete;
32
33   $error = $record->check;
34
35 =head1 DESCRIPTION
36
37 An FS::cust_bill_pkg object represents an invoice line item.
38 FS::cust_bill_pkg inherits from FS::Record.  The following fields are currently
39 supported:
40
41 =over 4
42
43 =item billpkgnum - primary key
44
45 =item invnum - invoice (see L<FS::cust_bill>)
46
47 =item pkgnum - package (see L<FS::cust_pkg>) or 0 for the special virtual sales tax package, or -1 for the virtual line item (itemdesc is used for the line)
48
49 =item pkgpart_override - optional package definition (see L<FS::part_pkg>) override
50 =item setup - setup fee
51
52 =item recur - recurring fee
53
54 =item sdate - starting date of recurring fee
55
56 =item edate - ending date of recurring fee
57
58 =item itemdesc - Line item description (overrides normal package description)
59
60 =item quantity - If not set, defaults to 1
61
62 =item unitsetup - If not set, defaults to setup
63
64 =item unitrecur - If not set, defaults to recur
65
66 =back
67
68 sdate and edate are specified as UNIX timestamps; see L<perlfunc/"time">.  Also
69 see L<Time::Local> and L<Date::Parse> for conversion functions.
70
71 =head1 METHODS
72
73 =over 4
74
75 =item new HASHREF
76
77 Creates a new line item.  To add the line item to the database, see
78 L<"insert">.  Line items are normally created by calling the bill method of a
79 customer object (see L<FS::cust_main>).
80
81 =cut
82
83 sub table { 'cust_bill_pkg'; }
84
85 =item insert
86
87 Adds this line item to the database.  If there is an error, returns the error,
88 otherwise returns false.
89
90 =cut
91
92 sub insert {
93   my $self = shift;
94
95   local $SIG{HUP} = 'IGNORE';
96   local $SIG{INT} = 'IGNORE';
97   local $SIG{QUIT} = 'IGNORE';
98   local $SIG{TERM} = 'IGNORE';
99   local $SIG{TSTP} = 'IGNORE';
100   local $SIG{PIPE} = 'IGNORE';
101
102   my $oldAutoCommit = $FS::UID::AutoCommit;
103   local $FS::UID::AutoCommit = 0;
104   my $dbh = dbh;
105
106   my $error = $self->SUPER::insert;
107   if ( $error ) {
108     $dbh->rollback if $oldAutoCommit;
109     return $error;
110   }
111
112   unless ( defined dbdef->table('cust_bill_pkg_detail') && $self->get('details') ) {
113     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
114     return '';
115   }
116
117   foreach my $detail ( @{$self->get('details')} ) {
118     my $cust_bill_pkg_detail = new FS::cust_bill_pkg_detail {
119       'billpkgnum' => $self->billpkgnum,
120       'format'     => (ref($detail) ? $detail->[0] : '' ),
121       'detail'     => (ref($detail) ? $detail->[1] : $detail ),
122     };
123     $error = $cust_bill_pkg_detail->insert;
124     if ( $error ) {
125       $dbh->rollback if $oldAutoCommit;
126       return $error;
127     }
128   }
129
130   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
131   '';
132
133 }
134
135 =item delete
136
137 Currently unimplemented.  I don't remove line items because there would then be
138 no record the items ever existed (which is bad, no?)
139
140 =cut
141
142 sub delete {
143   return "Can't delete cust_bill_pkg records!";
144 }
145
146 =item replace OLD_RECORD
147
148 Currently unimplemented.  This would be even more of an accounting nightmare
149 than deleteing the items.  Just don't do it.
150
151 =cut
152
153 sub replace {
154   return "Can't modify cust_bill_pkg records!";
155 }
156
157 =item check
158
159 Checks all fields to make sure this is a valid line item.  If there is an
160 error, returns the error, otherwise returns false.  Called by the insert
161 method.
162
163 =cut
164
165 sub check {
166   my $self = shift;
167
168   my $error =
169          $self->ut_numbern('billpkgnum')
170       || $self->ut_snumber('pkgnum')
171       || $self->ut_number('invnum')
172       || $self->ut_money('setup')
173       || $self->ut_money('recur')
174       || $self->ut_numbern('sdate')
175       || $self->ut_numbern('edate')
176       || $self->ut_textn('itemdesc')
177   ;
178   return $error if $error;
179
180   #if ( $self->pkgnum != 0 ) { #allow unchecked pkgnum 0 for tax! (add to part_pkg?)
181   if ( $self->pkgnum > 0 ) { #allow -1 for non-pkg line items and 0 for tax (add to part_pkg?)
182     return "Unknown pkgnum ". $self->pkgnum
183       unless qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
184   }
185
186   return "Unknown invnum"
187     unless qsearchs( 'cust_bill' ,{ 'invnum' => $self->invnum } );
188
189   $self->SUPER::check;
190 }
191
192 =item cust_pkg
193
194 Returns the package (see L<FS::cust_pkg>) for this invoice line item.
195
196 =cut
197
198 sub cust_pkg {
199   my $self = shift;
200   qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
201 }
202
203 =item part_pkg
204
205 Returns the package definition for this invoice line item.
206
207 =cut
208
209 sub part_pkg {
210   my $self = shift;
211   if ( $self->pkgpart_override ) {
212     qsearchs('part_pkg', { 'pkgpart' => $self->pkgpart_override } );
213   } else {
214     $self->cust_pkg->part_pkg;
215   }
216 }
217
218 =item cust_bill
219
220 Returns the invoice (see L<FS::cust_bill>) for this invoice line item.
221
222 =cut
223
224 sub cust_bill {
225   my $self = shift;
226   qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
227 }
228
229 =item details [ OPTION => VALUE ... ]
230
231 Returns an array of detail information for the invoice line item.
232
233 Currently available options are: I<format> I<escape_function>
234
235 If I<format> is set to html or latex then the array members are improved
236 for tabular appearance in those environments if possible.
237
238 If I<escape_function> is set then the array members are processed by this
239 function before being returned.
240
241 =cut
242
243 sub details {
244   my ( $self, %opt ) = @_;
245   my $format = $opt{format} || '';
246   my $escape_function = $opt{escape_function} || sub { shift };
247   return () unless defined dbdef->table('cust_bill_pkg_detail');
248
249   eval "use Text::CSV_XS;";
250   die $@ if $@;
251   my $csv = new Text::CSV_XS;
252
253   my $format_sub = sub { my $detail = shift;
254                          $csv->parse($detail) or return "can't parse $detail";
255                          join(' - ', map { &$escape_function($_) }
256                                      $csv->fields
257                              );
258                        };
259
260   $format_sub = sub { my $detail = shift;
261                       $csv->parse($detail) or return "can't parse $detail";
262                       join('</TD><TD>', map { &$escape_function($_) }
263                                         $csv->fields
264                           );
265                     }
266     if $format eq 'html';
267
268   $format_sub = sub { my $detail = shift;
269                       $csv->parse($detail) or return "can't parse $detail";
270                       #join(' & ', map { '\small{'. &$escape_function($_). '}' }
271                       #            $csv->fields );
272                       my $result = '';
273                       my $column = 1;
274                       foreach ($csv->fields) {
275                         $result .= ' & ' if $column > 1;
276                         if ($column > 6) {                     # KLUDGE ALERT!
277                           $result .= '\multicolumn{1}{l}{\small{'.
278                                      &$escape_function($_). '}}';
279                         }else{
280                           $result .= '\small{'.  &$escape_function($_). '}';
281                         }
282                         $column++;
283                       }
284                       $result;
285                     }
286     if $format eq 'latex';
287
288   map { ( $_->format eq 'C'
289           ? &{$format_sub}( $_->detail )
290           : &{$escape_function}( $_->detail )
291         )
292       }
293     qsearch ({ 'table'    => 'cust_bill_pkg_detail',
294                'hashref'  => { 'billpkgnum' => $self->billpkgnum },
295                'order_by' => 'ORDER BY detailnum',
296             });
297     #qsearch ( 'cust_bill_pkg_detail', { 'lineitemnum' => $self->lineitemnum });
298 }
299
300 =item desc
301
302 Returns a description for this line item.  For typical line items, this is the
303 I<pkg> field of the corresponding B<FS::part_pkg> object (see L<FS::part_pkg>).
304 For one-shot line items and named taxes, it is the I<itemdesc> field of this
305 line item, and for generic taxes, simply returns "Tax".
306
307 =cut
308
309 sub desc {
310   my $self = shift;
311
312   if ( $self->pkgnum > 0 ) {
313     $self->itemdesc || $self->part_pkg->pkg;
314   } else {
315     $self->itemdesc || 'Tax';
316   }
317 }
318
319 =item owed_setup
320
321 Returns the amount owed (still outstanding) on this line item's setup fee,
322 which is the amount of the line item minus all payment applications (see
323 L<FS::cust_bill_pay_pkg> and credit applications (see
324 L<FS::cust_credit_bill_pkg>).
325
326 =cut
327
328 sub owed_setup {
329   my $self = shift;
330   $self->owed('setup', @_);
331 }
332
333 =item owed_recur
334
335 Returns the amount owed (still outstanding) on this line item's recurring fee,
336 which is the amount of the line item minus all payment applications (see
337 L<FS::cust_bill_pay_pkg> and credit applications (see
338 L<FS::cust_credit_bill_pkg>).
339
340 =cut
341
342 sub owed_recur {
343   my $self = shift;
344   $self->owed('recur', @_);
345 }
346
347 # modeled after cust_bill::owed...
348 sub owed {
349   my( $self, $field ) = @_;
350   my $balance = $self->$field();
351   $balance -= $_->amount foreach ( $self->cust_bill_pay_pkg($field) );
352   $balance -= $_->amount foreach ( $self->cust_credit_bill_pkg($field) );
353   $balance = sprintf( '%.2f', $balance );
354   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
355   $balance;
356 }
357
358 sub cust_bill_pay_pkg {
359   my( $self, $field ) = @_;
360   qsearch( 'cust_bill_pay_pkg', { 'billpkgnum' => $self->billpkgnum,
361                                   'setuprecur' => $field,
362                                 }
363          );
364 }
365
366 sub cust_credit_bill_pkg {
367   my( $self, $field ) = @_;
368   qsearch( 'cust_credit_bill_pkg', { 'billpkgnum' => $self->billpkgnum,
369                                      'setuprecur' => $field,
370                                    }
371          );
372 }
373
374 =item units
375
376 Returns the number of billing units (for tax purposes) represented by this,
377 line item.
378
379 =cut
380
381 sub units {
382   my $self = shift;
383   $self->part_pkg->calc_units($self->cust_pkg);
384 }
385
386 =item quantity
387
388 =cut
389
390 sub quantity {
391   my( $self, $value ) = @_;
392   if ( defined($value) ) {
393     $self->setfield('quantity', $value);
394   }
395   $self->getfield('quantity') || 1;
396 }
397
398 =item unitsetup
399
400 =cut
401
402 sub unitsetup {
403   my( $self, $value ) = @_;
404   if ( defined($value) ) {
405     $self->setfield('unitsetup', $value);
406   }
407   $self->getfield('unitsetup') eq ''
408     ? $self->getfield('setup')
409     : $self->getfield('unitsetup');
410 }
411
412 =item unitrecur
413
414 =cut
415
416 sub unitrecur {
417   my( $self, $value ) = @_;
418   if ( defined($value) ) {
419     $self->setfield('unitrecur', $value);
420   }
421   $self->getfield('unitrecur') eq ''
422     ? $self->getfield('recur')
423     : $self->getfield('unitrecur');
424 }
425
426 =back
427
428 =head1 BUGS
429
430 setup and recur shouldn't be separate fields.  There should be one "amount"
431 field and a flag to tell you if it is a setup/one-time fee or a recurring fee.
432
433 A line item with both should really be two separate records (preserving
434 sdate and edate for setup fees for recurring packages - that information may
435 be valuable later).  Invoice generation (cust_main::bill), invoice printing
436 (cust_bill), tax reports (report_tax.cgi) and line item reports 
437 (cust_bill_pkg.cgi) would need to be updated.
438
439 owed_setup and owed_recur could then be repaced by just owed, and
440 cust_bill::open_cust_bill_pkg and
441 cust_bill_ApplicationCommon::apply_to_lineitems could be simplified.
442
443 =head1 SEE ALSO
444
445 L<FS::Record>, L<FS::cust_bill>, L<FS::cust_pkg>, L<FS::cust_main>, schema.html
446 from the base documentation.
447
448 =cut
449
450 1;
451