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