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