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