invoice formatting: add sections for usage, add sections per svc_phone, add folding...
[freeside.git] / FS / FS / cust_bill_pkg_detail.pm
1 package FS::cust_bill_pkg_detail;
2
3 use strict;
4 use vars qw( @ISA $me $DEBUG %GetInfoType );
5 use HTML::Entities;
6 use FS::Record qw( qsearch qsearchs dbdef dbh );
7 use FS::cust_bill_pkg;
8 use FS::Conf;
9
10 @ISA = qw(FS::Record);
11 $me = '[ FS::cust_bill_pkg_detail ]';
12 $DEBUG = 0;
13
14 =head1 NAME
15
16 FS::cust_bill_pkg_detail - Object methods for cust_bill_pkg_detail records
17
18 =head1 SYNOPSIS
19
20   use FS::cust_bill_pkg_detail;
21
22   $record = new FS::cust_bill_pkg_detail \%hash;
23   $record = new FS::cust_bill_pkg_detail { 'column' => 'value' };
24
25   $error = $record->insert;
26
27   $error = $new_record->replace($old_record);
28
29   $error = $record->delete;
30
31   $error = $record->check;
32
33 =head1 DESCRIPTION
34
35 An FS::cust_bill_pkg_detail object represents additional detail information for
36 an invoice line item (see L<FS::cust_bill_pkg>).  FS::cust_bill_pkg_detail
37 inherits from FS::Record.  The following fields are currently supported:
38
39 =over 4
40
41 =item detailnum - primary key
42
43 =item billpkgnum - link to cust_bill_pkg
44
45 =item amount - price of this line item detail
46
47 =item format - '' for straight text and 'C' for CSV in detail
48
49 =item classnum - link to usage_class
50
51 =item duration - granularized number of seconds for this call
52
53 =item regionname -
54
55 =item phonenum -
56
57 =item detail - detail description
58
59 =back
60
61 =head1 METHODS
62
63 =over 4
64
65 =item new HASHREF
66
67 Creates a new line item detail.  To add the line item detail to the database,
68 see L<"insert">.
69
70 Note that this stores the hash reference, not a distinct copy of the hash it
71 points to.  You can ask the object for a copy with the I<hash> method.
72
73 =cut
74
75 # the new method can be inherited from FS::Record, if a table method is defined
76
77 sub table { 'cust_bill_pkg_detail'; }
78
79 =item insert
80
81 Adds this record to the database.  If there is an error, returns the error,
82 otherwise returns false.
83
84 =cut
85
86 # the insert method can be inherited from FS::Record
87
88 =item delete
89
90 Delete this record from the database.
91
92 =cut
93
94 # the delete method can be inherited from FS::Record
95
96 =item replace OLD_RECORD
97
98 Replaces the OLD_RECORD with this one in the database.  If there is an error,
99 returns the error, otherwise returns false.
100
101 =cut
102
103 # the replace method can be inherited from FS::Record
104
105 =item check
106
107 Checks all fields to make sure this is a valid line item detail.  If there is
108 an error, returns the error, otherwise returns false.  Called by the insert
109 and replace methods.
110
111 =cut
112
113 # the check method should currently be supplied - FS::Record contains some
114 # data checking routines
115
116 sub check {
117   my $self = shift;
118
119   my $conf = new FS::Conf;
120
121   my $phonenum = $self->phonenum;
122   my $phonenum_check_method;
123   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
124     $phonenum =~ s/\W//g;
125     $phonenum_check_method = 'ut_alphan';
126   } else {
127     $phonenum =~ s/\D//g;
128     $phonenum_check_method = 'ut_numbern';
129   }
130   $self->phonenum($phonenum);
131
132   $self->ut_numbern('detailnum')
133     || $self->ut_foreign_key('billpkgnum', 'cust_bill_pkg', 'billpkgnum')
134     #|| $self->ut_moneyn('amount')
135     || $self->ut_floatn('amount')
136     || $self->ut_enum('format', [ '', 'C' ] )
137     || $self->ut_numbern('duration')
138     || $self->ut_textn('regionname')
139     || $self->ut_text('detail')
140     || $self->ut_foreign_keyn('classnum', 'usage_class', 'classnum')
141     || $self->$phonenum_check_method('phonenum')
142     || $self->SUPER::check
143     ;
144
145 }
146
147 =item formatted [ OPTION => VALUE ... ]
148
149 Returns detail information for the invoice line item detail formatted for
150 display.
151
152 Currently available options are: I<format> I<escape_function>
153
154 If I<format> is set to html or latex then the format is improved
155 for tabular appearance in those environments if possible.
156
157 If I<escape_function> is set then the format is processed by this
158 function before being returned.
159
160 If I<format_function> is set then the detail is handed to this callback
161 for processing.
162
163 =cut
164
165 sub formatted {
166   my ( $self, %opt ) = @_;
167   my $format = $opt{format} || '';
168   return () unless defined dbdef->table('cust_bill_pkg_detail');
169
170   eval "use Text::CSV_XS;";
171   die $@ if $@;
172   my $csv = new Text::CSV_XS;
173
174   my $escape_function = sub { shift };
175
176   $escape_function = \&encode_entities
177     if $format eq 'html';
178
179   $escape_function =
180     sub {
181       my $value = shift;
182       $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
183       $value =~ s/([<>])/\$$1\$/g;
184       $value;
185     }
186   if $format eq 'latex';
187
188   $escape_function = $opt{escape_function} if $opt{escape_function};
189
190   my $format_sub = sub { my $detail = shift;
191                          $csv->parse($detail) or return "can't parse $detail";
192                          join(' - ', map { &$escape_function($_) }
193                                      $csv->fields
194                              );
195                        };
196
197   $format_sub = sub { my $detail = shift;
198                       $csv->parse($detail) or return "can't parse $detail";
199                       join('</TD><TD>', map { &$escape_function($_) }
200                                         $csv->fields
201                           );
202                     }
203     if $format eq 'html';
204
205   $format_sub = sub { my $detail = shift;
206                       $csv->parse($detail) or return "can't parse $detail";
207                       #join(' & ', map { '\small{'. &$escape_function($_). '}' }                      #            $csv->fields );
208                       my $result = '';
209                       my $column = 1;
210                       foreach ($csv->fields) {
211                         $result .= ' & ' if $column > 1;
212                         if ($column > 6) {                     # KLUDGE ALERT!
213                           $result .= '\multicolumn{1}{l}{\scriptsize{'.
214                                      &$escape_function($_). '}}';
215                         }else{
216                           $result .= '\scriptsize{'.  &$escape_function($_). '}';
217                         }
218                         $column++;
219                       }
220                       $result;
221                     }
222     if $format eq 'latex';
223
224   $format_sub = $opt{format_function} if $opt{format_function};
225
226   $self->format eq 'C'
227     ? &{$format_sub}( $self->detail, $self )
228     : &{$escape_function}( $self->detail )
229   ;
230 }
231
232
233 # _upgrade_data
234 #
235 # Used by FS::Upgrade to migrate to a new database.
236
237 sub _upgrade_data { # class method
238
239   my ($class, %opts) = @_;
240
241   warn "$me upgrading $class\n" if $DEBUG;
242
243   my $columndef = dbdef->table($class->table)->column('classnum');
244   unless ($columndef->type eq 'int4') {
245
246     my $dbh = dbh;
247     if ( $dbh->{Driver}->{Name} eq 'Pg' ) {
248
249       eval "use DBI::Const::GetInfoType;";
250       die $@ if $@;
251
252       my $major_version = 0;
253       $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ) =~ /^(\d{2})/
254         && ( $major_version = sprintf("%d", $1) );
255
256       if ( $major_version > 7 ) {
257
258         # ideally this would be supported in DBIx-DBSchema and friends
259
260         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
261
262           warn "updating $table column classnum to integer\n" if $DEBUG;
263           my $sql = "ALTER TABLE $table ALTER classnum TYPE int USING ".
264             "int4(classnum)";
265           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
266           $sth->execute or die $sth->errstr;
267
268         }
269
270       } elsif ( $dbh->{pg_server_version} =~ /^704/ ) {  # earlier?
271
272         # ideally this would be supported in DBIx-DBSchema and friends
273
274         #  XXX_FIXME better locking
275
276         foreach my $table ( qw( cust_bill_pkg_detail h_cust_bill_pkg_detail ) ){
277
278           warn "updating $table column classnum to integer\n" if $DEBUG;
279
280           my $sql = "ALTER TABLE $table RENAME classnum TO old_classnum";
281           my $sth = $dbh->prepare($sql) or die $dbh->errstr;
282           $sth->execute or die $sth->errstr;
283
284           my $def = dbdef->table($table)->column('classnum');
285           $def->type('integer');
286           $def->length(''); 
287           $sql = "ALTER TABLE $table ADD COLUMN ". $def->line($dbh);
288           $sth = $dbh->prepare($sql) or die $dbh->errstr;
289           $sth->execute or die $sth->errstr;
290
291           $sql = "UPDATE $table SET classnum = int4( text( old_classnum ) )";
292           $sth = $dbh->prepare($sql) or die $dbh->errstr;
293           $sth->execute or die $sth->errstr;
294
295           $sql = "ALTER TABLE $table DROP old_classnum";
296           $sth = $dbh->prepare($sql) or die $dbh->errstr;
297           $sth->execute or die $sth->errstr;
298
299         }
300
301       } else {
302
303         die "cust_bill_pkg_detail classnum upgrade unsupported for this Pg version\n";
304
305       }
306
307     } else {
308
309       die "cust_bill_pkg_detail classnum upgrade only supported for Pg 8+\n";
310
311     }
312
313   }
314
315
316   if ( defined( dbdef->table($class->table)->column('billpkgnum') ) &&
317        defined( dbdef->table($class->table)->column('invnum') ) &&
318        defined( dbdef->table($class->table)->column('pkgnum') ) 
319   ) {
320
321     warn "$me Checking for unmigrated invoice line item details\n" if $DEBUG;
322
323     my @cbpd = qsearch({ 'table'   => $class->table,
324                          'hashref' => {},
325                          'extra_sql' => 'WHERE invnum IS NOT NULL AND '.
326                                         'pkgnum IS NOT NULL',
327                       });
328
329     if (scalar(@cbpd)) {
330       warn "$me Found unmigrated invoice line item details\n" if $DEBUG;
331
332       foreach my $cbpd ( @cbpd ) {
333         my $detailnum = $cbpd->detailnum;
334         warn "$me Contemplating detail $detailnum\n" if $DEBUG > 1;
335         my $cust_bill_pkg =
336           qsearchs({ 'table' => 'cust_bill_pkg',
337                      'hashref' => { 'invnum' => $cbpd->invnum,
338                                     'pkgnum' => $cbpd->pkgnum,
339                                   },
340                      'order_by' => 'ORDER BY billpkgnum LIMIT 1',
341                   });
342         if ($cust_bill_pkg) {
343           $cbpd->billpkgnum($cust_bill_pkg->billpkgnum);
344           $cbpd->invnum('');
345           $cbpd->pkgnum('');
346           my $error = $cbpd->replace;
347
348           warn "*** WARNING: error replacing line item detail ".
349                "(cust_bill_pkg_detail) $detailnum: $error ***\n"
350             if $error;
351         } else {
352           warn "Found orphaned line item detail $detailnum during upgrade.\n";
353         }
354
355       } # foreach $cbpd
356
357     } # if @cbpd
358
359   } # if billpkgnum, invnum, and pkgnum columns defined
360
361   '';
362
363 }                         
364
365 =back
366
367 =head1 BUGS
368
369 =head1 SEE ALSO
370
371 L<FS::cust_bill_pkg>, L<FS::Record>, schema.html from the base documentation.
372
373 =cut
374
375 1;
376