very basic start at adding quantities
[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 (currentlty used only when pkgnum is 0 or -1)
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       'pkgnum' => $self->pkgnum,
120       'invnum' => $self->invnum,
121       'format' => (ref($detail) ? $detail->[0] : '' ),
122       'detail' => (ref($detail) ? $detail->[1] : $detail ),
123     };
124     $error = $cust_bill_pkg_detail->insert;
125     if ( $error ) {
126       $dbh->rollback if $oldAutoCommit;
127       return $error;
128     }
129   }
130
131   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
132   '';
133
134 }
135
136 =item delete
137
138 Currently unimplemented.  I don't remove line items because there would then be
139 no record the items ever existed (which is bad, no?)
140
141 =cut
142
143 sub delete {
144   return "Can't delete cust_bill_pkg records!";
145 }
146
147 =item replace OLD_RECORD
148
149 Currently unimplemented.  This would be even more of an accounting nightmare
150 than deleteing the items.  Just don't do it.
151
152 =cut
153
154 sub replace {
155   return "Can't modify cust_bill_pkg records!";
156 }
157
158 =item check
159
160 Checks all fields to make sure this is a valid line item.  If there is an
161 error, returns the error, otherwise returns false.  Called by the insert
162 method.
163
164 =cut
165
166 sub check {
167   my $self = shift;
168
169   my $error =
170          $self->ut_numbern('billpkgnum')
171       || $self->ut_snumber('pkgnum')
172       || $self->ut_number('invnum')
173       || $self->ut_money('setup')
174       || $self->ut_money('recur')
175       || $self->ut_numbern('sdate')
176       || $self->ut_numbern('edate')
177       || $self->ut_textn('itemdesc')
178   ;
179   return $error if $error;
180
181   #if ( $self->pkgnum != 0 ) { #allow unchecked pkgnum 0 for tax! (add to part_pkg?)
182   if ( $self->pkgnum > 0 ) { #allow -1 for non-pkg line items and 0 for tax (add to part_pkg?)
183     return "Unknown pkgnum ". $self->pkgnum
184       unless qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
185   }
186
187   return "Unknown invnum"
188     unless qsearchs( 'cust_bill' ,{ 'invnum' => $self->invnum } );
189
190   $self->SUPER::check;
191 }
192
193 =item cust_pkg
194
195 Returns the package (see L<FS::cust_pkg>) for this invoice line item.
196
197 =cut
198
199 sub cust_pkg {
200   my $self = shift;
201   qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
202 }
203
204 =item part_pkg
205
206 Returns the package definition for this invoice line item.
207
208 =cut
209
210 sub part_pkg {
211   my $self = shift;
212   if ( $self->pkgpart_override ) {
213     qsearchs('part_pkg', { 'pkgpart' => $self->pkgpart_override } );
214   } else {
215     $self->cust_pkg->part_pkg;
216   }
217 }
218
219 =item cust_bill
220
221 Returns the invoice (see L<FS::cust_bill>) for this invoice line item.
222
223 =cut
224
225 sub cust_bill {
226   my $self = shift;
227   qsearchs( 'cust_bill', { 'invnum' => $self->invnum } );
228 }
229
230 =item details [ OPTION => VALUE ... ]
231
232 Returns an array of detail information for the invoice line item.
233
234 Currently available options are: I<format> I<escape_function>
235
236 If I<format> is set to html or latex then the array members are improved
237 for tabular appearance in those environments if possible.
238
239 If I<escape_function> is set then the array members are processed by this
240 function before being returned.
241
242 =cut
243
244 sub details {
245   my ( $self, %opt ) = @_;
246   my $format = $opt{format} || '';
247   my $escape_function = $opt{escape_function} || sub { shift };
248   return () unless defined dbdef->table('cust_bill_pkg_detail');
249
250   eval "use Text::CSV_XS;";
251   die $@ if $@;
252   my $csv = new Text::CSV_XS;
253
254   my $format_sub = sub { my $detail = shift;
255                          $csv->parse($detail) or return "can't parse $detail";
256                          join(' - ', map { &$escape_function($_) }
257                                      $csv->fields
258                              );
259                        };
260
261   $format_sub = sub { my $detail = shift;
262                       $csv->parse($detail) or return "can't parse $detail";
263                       join('</TD><TD>', map { &$escape_function($_) }
264                                         $csv->fields
265                           );
266                     }
267     if $format eq 'html';
268
269   $format_sub = sub { my $detail = shift;
270                       $csv->parse($detail) or return "can't parse $detail";
271                       join(' & ', map { '\small{'. &$escape_function($_). '}' }
272                                   $csv->fields );
273                     }
274     if $format eq 'latex';
275
276   map { ( $_->format eq 'C'
277           ? &{$format_sub}( $_->detail )
278           : &{$escape_function}( $_->detail )
279         )
280       }
281     qsearch ({ 'table'    => 'cust_bill_pkg_detail',
282                'hashref'  => { 'pkgnum' => $self->pkgnum,
283                                'invnum' => $self->invnum,
284                              },
285                'order_by' => 'ORDER BY detailnum',
286             });
287     #qsearch ( 'cust_bill_pkg_detail', { 'lineitemnum' => $self->lineitemnum });
288 }
289
290 =item desc
291
292 Returns a description for this line item.  For typical line items, this is the
293 I<pkg> field of the corresponding B<FS::part_pkg> object (see L<FS::part_pkg>).
294 For one-shot line items and named taxes, it is the I<itemdesc> field of this
295 line item, and for generic taxes, simply returns "Tax".
296
297 =cut
298
299 sub desc {
300   my $self = shift;
301
302   if ( $self->pkgnum > 0 ) {
303     $self->part_pkg->pkg;
304   } else {
305     $self->itemdesc || 'Tax';
306   }
307 }
308
309 =item owed_setup
310
311 Returns the amount owed (still outstanding) on this line item's setup fee,
312 which is the amount of the line item minus all payment applications (see
313 L<FS::cust_bill_pay_pkg> and credit applications (see
314 L<FS::cust_credit_bill_pkg>).
315
316 =cut
317
318 sub owed_setup {
319   my $self = shift;
320   $self->owed('setup', @_);
321 }
322
323 =item owed_recur
324
325 Returns the amount owed (still outstanding) on this line item's recurring fee,
326 which is the amount of the line item minus all payment applications (see
327 L<FS::cust_bill_pay_pkg> and credit applications (see
328 L<FS::cust_credit_bill_pkg>).
329
330 =cut
331
332 sub owed_recur {
333   my $self = shift;
334   $self->owed('recur', @_);
335 }
336
337 # modeled after cust_bill::owed...
338 sub owed {
339   my( $self, $field ) = @_;
340   my $balance = $self->$field();
341   $balance -= $_->amount foreach ( $self->cust_bill_pay_pkg($field) );
342   $balance -= $_->amount foreach ( $self->cust_credit_bill_pkg($field) );
343   $balance = sprintf( '%.2f', $balance );
344   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
345   $balance;
346 }
347
348 sub cust_bill_pay_pkg {
349   my( $self, $field ) = @_;
350   qsearch( 'cust_bill_pay_pkg', { 'billpkgnum' => $self->billpkgnum,
351                                   'setuprecur' => $field,
352                                 }
353          );
354 }
355
356 sub cust_credit_bill_pkg {
357   my( $self, $field ) = @_;
358   qsearch( 'cust_credit_bill_pkg', { 'billpkgnum' => $self->billpkgnum,
359                                      'setuprecur' => $field,
360                                    }
361          );
362 }
363
364 =item units
365
366 Returns the number of billing units (for tax purposes) represented by this,
367 line item.
368
369 =cut
370
371 sub units {
372   my $self = shift;
373   $self->part_pkg->calc_units($self->cust_pkg);
374 }
375
376 =item quantity
377
378 =cut
379
380 sub quantity {
381   my( $self, $value ) = @_;
382   if ( defined($value) ) {
383     $self->setfield('quantity', $value);
384   }
385   $self->getfield('quantity') || 1;
386 }
387
388 =item unitsetup
389
390 =cut
391
392 sub unitsetup {
393   my( $self, $value ) = @_;
394   if ( defined($value) ) {
395     $self->setfield('unitsetup', $value);
396   }
397   $self->getfield('unitsetup') eq ''
398     ? $self->getfield('setup')
399     : $self->getfield('unitsetup');
400 }
401
402 =item unitrecur
403
404 =cut
405
406 sub unitrecur {
407   my( $self, $value ) = @_;
408   if ( defined($value) ) {
409     $self->setfield('unitrecur', $value);
410   }
411   $self->getfield('unitrecur') eq ''
412     ? $self->getfield('recur')
413     : $self->getfield('unitrecur');
414 }
415
416 =back
417
418 =head1 BUGS
419
420 setup and recur shouldn't be separate fields.  There should be one "amount"
421 field and a flag to tell you if it is a setup/one-time fee or a recurring fee.
422
423 A line item with both should really be two separate records (preserving
424 sdate and edate for setup fees for recurring packages - that information may
425 be valuable later).  Invoice generation (cust_main::bill), invoice printing
426 (cust_bill), tax reports (report_tax.cgi) and line item reports 
427 (cust_bill_pkg.cgi) would need to be updated.
428
429 owed_setup and owed_recur could then be repaced by just owed, and
430 cust_bill::open_cust_bill_pkg and
431 cust_bill_ApplicationCommon::apply_to_lineitems could be simplified.
432
433 =head1 SEE ALSO
434
435 L<FS::Record>, L<FS::cust_bill>, L<FS::cust_pkg>, L<FS::cust_main>, schema.html
436 from the base documentation.
437
438 =cut
439
440 1;
441